hlongtran959 / (V).Tool Tải Manga Bản ĐTs

// ==UserScript==
// @name            (V).Tool Tải Manga Bản ĐTs
// @namespace       https://baivong.github.io
// @description     Tải truyện tranh từ các trang chia sẻ ở Việt Nam. Nhấn Alt+Y để tải toàn bộ.
// @version         3.4.6
// @icon            https://raw.githubusercontent.com/lelinhtinh/Userscript/master/manga_comic_downloader/icon.png
// @author          Zzbaivong
// @license         MIT; https://baivong.mit-license.org/license.txt
// @match           https://*.nettruyen.com/*
// @match           https://*.nettruyen.com/*
// @match           https://*.nettruyentop.com/*
// @match           https://*.nettruyentop.com/*
// @match           http://*.nettruyenonline.com/*
// @match           https://*.nettruyenonline.com/*
// @match           https://*.nettruyenapp.com/*
// @match           https://*.nettruyenapp.com/*
// @match           https://*.nettruyenpro.com/*
// @match           https://*.nettruyenpro.com/*
// @match           https://nettruyenok.com/*
// @match           https://nettruyenww.com/*
// @match           https://thanvuc.com/*
// @match           https://nettruyen.life/*
// @match           https://*.nettruyenup.com/*
// @match           https://nettruyenqqviet.com/*
// @match           https://tutientruyen4.fun/*
// @match           https://tutientruyen6.xyz/*
// @match           https://truyenqq.com/*
// @match           https://truyenqq.net/*
// @match           https://truyenqqto.com/*
// @match           https://truyenqq5.com/*
// @require         https://code.jquery.com/jquery-3.6.0.min.js
// @require         https://greasyfork.org/scripts/442805-fflate-umd/code/fflateumd.js?version=1036436
// @require         https://unpkg.com/file-saver@2.0.5/dist/FileSaver.min.js
// @require         https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js?v=a834d46
// @require         https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
// @resource        success https://unpkg.com/facebook-sound-kit@2.0.0/Low_Volume_-20dB/Complete_and_Success/Success_2.m4a
// @resource        error https://unpkg.com/facebook-sound-kit@2.0.0/Low_Volume_-20dB/Errors_and_Cancel/Error_2.m4a
// @noframes
// @connect         *
// @supportURL      https://github.com/lelinhtinh/Userscript/issues
// @run-at          document-start
// @grant           GM_addStyle
// @grant           GM_xmlhttpRequest
// @grant           GM.xmlHttpRequest
// @grant           GM.getResourceUrl
// @grant           GM_getResourceURL
// @grant           GM_registerMenuCommand
// ==/UserScript==

/* global fflate, CryptoJS */
window._URL = window.URL || window.webkitURL;

jQuery(function ($) {
  /**
   * Output extension
   * @type {String} zip
   *                cbz
   *
   * Tips: Convert .zip to .cbz
   * Windows
   * $ ren *.zip *.cbz
   * Linux
   * $ rename 's/\.zip$/\.cbz/' *.zip
   */
  var outputExt = 'zip'; // or 'zip'

  /**
   * Multithreading
   * @type {Number} [1 -> 32]
   */
  var threading = 4;

  /**
   * The number of times the download may be attempted.
   * @type {Number}
   */
  var tries = 5;

  /**
   * Enable audio cues.
   * @type {Boolean}
   */
  var audioCues = true;

  /**
   * Image list will be ignored
   * @type {Array} url
   */
  var ignoreList = [
    'https://truyentranhtam.net/templates/main/images/gioithieubanbe3.png',
    'https://1.bp.blogspot.com/-U1SdU4_52Xs/WvLvn1OjvHI/AAAAAAAEugM/dLBgVGSeUN0bVy-FoFfIZvrCJ07YQew7wCHMYCw/s0/haybaoloi.png',
    '/public/images/loading.gif',
    'https://truyentranhlh.net/wp-content/uploads/2015/10/lhmanga.png',
    '/Content/Img/1eeef5d2-b936-496d-ba41-df1b21d0166a.jpg',
    '/Content/Img/d79886b3-3699-47b2-bbf4-af6149c2e8fb.jpg',
    'https://st.beeng.net/files/uploads/images/21/c8/21c8d2c3599c485e31f270675bc57e4c.jpeg',
    '00k9jbV.gif',
  ];

  /**
   * Keep the original url
   * @type {Array} key
   */
  var keepOriginal = [
    'proxy.truyen.cloud',
    '.ttmanga.com',
    '.fbcdn.net',
    'mangaqq.net',
    'mangaqq.com',
    'truyenqqvn.net',
    'truyenqqvn.com',
     'truyenqq5.com',
    'truyenqqtop.com',
    'truyenqqpro.com',
    '.upanhmoi.net',
    'qqtaku.com',
    'qqtaku.net',
    'trangshop.net',
    '.beeng.net',
    '.beeng.org',
    'forumnt.com',
    'hoitruyentranh.com',
    'hoihentai.com',
    'i02.hentaivn.net',
    'truyentop1.com',
    'anhnhanh.org',
    'truyenvua.xyz',
    'hamtruyen.vn',
    '.xem-truyen.com',
    'p.ntcdntempv26.com',
    'cdn.ntcdntempv26.com',
    'i221.ntcdntempv3.com',
    'p1.ntcdntempv26.com',
    'p2.ntcdntempv26.com',
    'p3.ntcdntempv26.com',
    'p4.ntcdntempv26.com',
    'p5.ntcdntempv26.com',
    'p6.ntcdntempv26.com',
    'p7.ntcdntempv26.com',
    'p8.ntcdntempv26.com',
    'doctruyen5s.net',
    's3.mideman.com',
    'dtcdnyacd.com',
    'nchcccl.pro',
    'cmnvymn.com',
    'dtcdnyacd.com',
    'nettruyenhq.com',
    'cdn-vn2.hnmxntgn.com',
    'cmangaog.com',
    'salt.tikicdn.com',
    'i10-1.bumcheo4.info',
    'ads.mxhnkn.pro',
    's2.anhvip.xyz',
    's11.anhvip.xyz',
    'kcgsbok.com',
    'ddntcthcd.com',
    'ccmmh.biz',
    'kcgsbok.com',
    'img.truyenvua.com',
    'hinhhinh.com',
    's135.hinhhinh.com',
    'img.nettruyenqqviet.com',
    'storage.truyengpt.com',
    'image1.truyengpt.com',
    'xfs-n08.xfsbb.com',
    'cdn.truyentutien.site',
    'i2.netcdn.one',
    'minio.tienlv.com',
    'truyentutien.site',
    'image1.ddntcthcd.com',
    'storage.nettruyen3q.com',
    'cdn1.cloud-zzz.com',
    's1.nettruyen3q.com',
    'cdn-vn2.hnmxntgn.com',
  ];

  /**
   * HTTP referer
   * @param {Object} hostname
   */
  var referer = {
    'ddntcthcd.com': 'https://nettruyen.life',
    'nchcccl.pro': 'https://nettruyen.life',
    'ccmmh.biz': 'https://nettruyen.life',
    'cmnvymn.com': 'https://nettruyen.life',
    'cmangaog.com': 'https://nettruyen.life',
    'kcgsbok.com': 'https://nettruyen.life',
    'cdn-vn2.hnmxntgn.com': 'https://nettruyen.life',
    'image1.ddntcthcd.com': 'https://nettruyenviet.com',
    'img.nettruyenqqviet.com': 'https://nettruyenqqviet.com/',
    'storage.ddntcthcd.com': 'https://nettruyenviet.com',
    'storage.anhvip.xyz': 'https://nettruyen3q.com/',
    's1.nettruyen3q.com': 'https://nettruyen3q.com/',
   'xfs-n08.xfsbb.com': 'https://truyenqqto.com',
    'img.truyenvua.com': 'https://truyenqqto.com',
     'truyenvua.com': 'https://truyenqqto.com/',
      'storage.truyengpt.com': 'https://truyenqqto.com',
     'image1.truyengpt.com': 'https://truyenqqto.com',
     'storage.hinhhinh.com': 'https://truyenqqto.com',
     's135.hinhhinh.com': 'https://truyenqqto.com',
     'hinhhinh.com': 'https://truyenqqto.com',
      'cdn-vn2.hnmxntgn.com': 'https://truyenqqto.com',
     'xfs-n08.xfsbb.com': 'https://truyenqq5.com',
     'img.truyenvua.com': 'https://truyenqq5.com',
     'truyenvua.com': 'https://truyenqq5.com/',
     'storage.truyengpt.com': 'https://truyenqq5.com',
     'image1.truyengpt.com': 'https://truyenqq5.com',
     'storage.hinhhinh.com': 'https://truyenqq5.com',
     's135.hinhhinh.com': 'https://truyenqq5.com',
    'hinhhinh.com': 'https://truyenqq5.com',
    'cdn-vn2.hnmxntgn.com': 'https://truyenqq5.com',
     'mangaqq.net': 'https://truyenqqto.com/',
    'mangaqq.com': 'https://truyenqqto.com/',
    'truyenqq.net': 'https://truyenqqto.com/',
    'truyenvua.xyz': 'https://truyenqqto.com/',
     'mangaqq.net': 'https://truyenqq5.com/',
    'mangaqq.com': 'https://truyenqq5.com/',
    'truyenqq.net': 'https://truyenqq5.com/',
    'truyenvua.xyz': 'https://truyenqq5.com/',
    'ads.mxhnkn.pro': 'https://truyenqq5.com/',
    'ads.mxhnkn.pro': 'https://truyenqqto.com/',
    'truyentutien.site': 'https://tutientruyen6.xyz',
    'cdn.truyentutien.site': 'https://tutientruyen6.xyz',
    'truyentutien.site': 'https://tutientruyen4.fun',
    'cdn.truyentutien.site': 'https://tutientruyen4.fun',
    'i2.netcdn.one': 'https://nettruyenok.com',
    'minio.tienlv.com': 'https://thanvuc.com/',
    'truyen.cloud': 'http://www.nettruyen.com',
    'proxy.truyen.cloud': 'http://www.nettruyen.com',
    'i.netsnippet.com': 'http://www.nettruyen.com/',
    'forumnt.com': 'http://www.nettruyen.com/',
    'upload.forumnt.com': 'http://www.nettruyen.com/',
    'upload2.forumnt.com': 'http://www.nettruyen.com/',
    'upload.upanhmoi.net': 'https://upanhmoi.net',
    'upload2.upanhmoi.net': 'https://upanhmoi.net',
    'upload3.upanhmoi.net': 'https://upanhmoi.net',
    'upload4.upanhmoi.com': 'https://upanhmoi.com',
    'upload5.upanhmoi.com': 'https://upanhmoi.com',
    'upload6.upanhmoi.com': 'https://upanhmoi.com',
    'upload7.upanhmoi.com': 'https://upanhmoi.com',
    'upload8.upanhmoi.com': 'https://upanhmoi.com',
    'upload9.upanhmoi.com': 'https://upanhmoi.com',
    'img1.upanhmoi.net': 'https://upanhmoi.net',
    'img2.upanhmoi.net': 'https://upanhmoi.net',
  };

  /* === DO NOT CHANGE === */

  window.URL = window._URL;

  var successSound, errorSound;
  if (audioCues) {
    GM.getResourceUrl('success').then(function (url) {
      successSound = new Audio(url);
    });
    GM.getResourceUrl('error').then(function (url) {
      errorSound = new Audio(url);
    });
  }

  function getImageType(arrayBuffer) {
    if (!arrayBuffer.byteLength)
      return {
        mime: null,
        ext: null,
      };

    var ext = '',
      mime = '',
      dv = new DataView(arrayBuffer, 0, 5),
      numE1 = dv.getUint8(0, true),
      numE2 = dv.getUint8(1, true),
      hex = numE1.toString(16) + numE2.toString(16);

    switch (hex) {
      case '8950':
        ext = 'png';
        mime = 'image/png';
        break;
      case '4749':
        ext = 'gif';
        mime = 'image/gif';
        break;
      case 'ffd8':
        ext = 'jpg';
        mime = 'image/jpeg';
        break;
      case '424d':
        ext = 'bmp';
        mime = 'image/bmp';
        break;
      case '5249':
        ext = 'webp';
        mime = 'image/webp';
        break;
      default:
        ext = null;
        mime = null;
        break;
    }

    return {
      mime: mime,
      ext: ext,
    };
  }

  var notyTimeout;
  function noty(txt, status) {
    function destroy() {
      var $noty = $doc.find('#mcd_noty_wrap');
      if (!$noty.length) return;
      $noty.fadeOut(300, function () {
        $noty.remove();
        $noty = [];
      });
      clearTimeout(notyTimeout);
    }

    function autoHide() {
      notyTimeout = setTimeout(function () {
        destroy();
      }, 2000);
    }

    var $noty = $doc.find('#mcd_noty_wrap');
    if (!$noty.length) {
      var $wrap = $('<div>', {
          id: 'mcd_noty_wrap',
        }),
        $content = $('<div>', {
          id: 'mcd_noty_content',
          class: 'mcd_' + status,
          html: txt,
        }),
        $close = $('<div>', {
          id: 'mcd_noty_close',
          html: '&times;',
        });

      $noty = $wrap.append($content).append($close);
      $noty.appendTo('body');
    }

    $noty
      .find('#mcd_noty_content')
      .attr('class', 'mcd_' + status)
      .html(txt);

    $noty.fadeIn(300);
    clearTimeout(notyTimeout);

    $doc
      .on('click', '#mcd_noty_wrap', function () {
        destroy();
      })
      .on('mouseenter', '#mcd_noty_wrap', function () {
        clearTimeout(notyTimeout);
      })
      .on('mouseleave', '#mcd_noty_wrap', autoHide);

    if (status !== 'warning' && status !== 'success') autoHide();
  }

  function targetLink(selector) {
    return configs.link
      .split(/\s*,\s*/)
      .map(function (i) {
        return i + selector;
      })
      .join(',');
  }

  function linkError() {
    $(targetLink('[href="' + configs.href + '"]')).css({
      color: 'red',
      textShadow: '0 0 1px red, 0 0 1px red, 0 0 1px red',
    });
    hasDownloadError = true;
  }

  function linkSuccess() {
    var $currLink = $(targetLink('[href="' + configs.href + '"]'));
    if (!hasDownloadError)
      $currLink.css({
        color: 'green',
        textShadow: '0 0 1px green, 0 0 1px green, 0 0 1px green',
      });
  }

  function beforeleaving(e) {
    e.preventDefault();
    e.returnValue = '';
  }

  function cancelProgress() {
    linkError();
    inProgress = false;
    window.removeEventListener('beforeunload', beforeleaving);
    setTimeout(() => {
      if (dlAll.length || inProgress || !errorSound) return;
      errorSound.play();
    }, 0);
  }

  function notyError() {
    noty('Lỗi! Không tải được <strong>' + chapName + '</strong>', 'error');
    cancelProgress();
  }

  function notyImages() {
    noty('Lỗi! <strong>' + chapName + '</strong> không có dữ liệu', 'error');
    cancelProgress();
  }

  function notySuccess(source) {
    if (threading < 1) threading = 1;
    if (threading > 32) threading = 32;

    dlImages = source.map(function (url) {
      return {
        url: url,
        attempt: tries,
      };
    });
    dlTotal = dlImages.length;
    addZip();

    noty('Bắt đầu tải <strong>' + chapName + '</strong>', 'warning');
    window.addEventListener('beforeunload', beforeleaving);
  }

  function notyWait() {
    document.title = '[…] ' + tit;

    noty('<strong>' + chapName + '</strong> đang lấy dữ liệu...', 'warning');

    dlAll = dlAll.filter(function (l) {
      return configs.href.indexOf(l) === -1;
    });

    $(targetLink('[href="' + configs.href + '"]')).css({
      color: 'orange',
      fontWeight: 'bold',
      fontStyle: 'italic',
      textDecoration: 'underline',
      textShadow: '0 0 1px orange, 0 0 1px orange, 0 0 1px orange',
    });
  }

  function dlAllGen() {
    dlAll = [];
    $(configs.link).each(function (i, el) {
      dlAll[i] = $(el).attr('href');
    });
    if (configs.reverse) dlAll.reverse();
  }

  function notyReady() {
    noty('Script đã <strong>sẵn sàng</strong> làm việc', 'info');

    dlAllGen();

    $doc
      .on('click', configs.link, function (e) {
        if (!e.ctrlKey && !e.shiftKey) return;

        e.preventDefault();
        var _link = $(this).attr('href');

        if (e.ctrlKey && e.shiftKey) {
          dlAll = dlAll.filter(function (l) {
            return _link.indexOf(l) === -1;
          });

          $(targetLink('[href="' + _link + '"]')).css({
            color: 'gray',
            fontWeight: 'bold',
            fontStyle: 'italic',
            textDecoration: 'line-through',
            textShadow: '0 0 1px gray, 0 0 1px gray, 0 0 1px gray',
          });
        } else {
          if (!inCustom) {
            dlAll = [];
            inCustom = true;
          }

          dlAll.push(_link);

          var color = e.shiftKey ? 'violet' : 'purple';
          $(targetLink('[href="' + _link + '"]')).css({
            color: color,
            textDecoration: 'overline',
            textShadow: '0 0 1px ' + color + ', 0 0 1px ' + color + ', 0 0 1px ' + color,
          });
        }
      })
      .on('keyup', function (e) {
        if (e.key === 'Control' || e.key === 'Shift') {
          e.preventDefault();

          if (dlAll.length && inCustom) {
            if (e.key === 'Shift') inMerge = true;
            downloadAll();
          }
        }
      });
  }

  function downloadAll() {
    if (inProgress || inAuto) return;
    if (!inCustom && !dlAll.length) dlAllGen();
    if (!dlAll.length) return;
    inAuto = true;
    $(targetLink('[href$="' + dlAll[0] + '"]')).trigger('contextmenu');
  }

  function downloadAllOne() {
    inMerge = true;
    downloadAll();
  }

  function genFileName() {
    chapName = chapName
      .replace(/\s+/g, '_')
      .replace(/・/g, '·')
      .replace(/(^_+|_+$)/, '');
    if (hasDownloadError) chapName = '__ERROR__' + chapName;
    return chapName;
  }

  function endZip() {
    if (!inMerge) {
      zipObj = {};
      if (recentZip) URL.revokeObjectURL(recentZip);
      recentZip = null;
    }

    dlCurrent = 0;
    dlFinal = 0;
    dlTotal = 0;
    dlImages = [];

    hasDownloadError = false;
    inProgress = false;

    if (inAuto) {
      if (dlAll.length) {
        $(targetLink('[href$="' + dlAll[0] + '"]')).trigger('contextmenu');
      } else {
        inAuto = false;
        inCustom = false;
      }
    }

    setTimeout(() => {
      if (dlAll.length || inProgress || !successSound) return;
      successSound.play();
    }, 0);
  }

  function genZip() {
    noty('Tạo file nén của <strong>' + chapName + '</strong>', 'warning');

    fflate.zip(
      zipObj,
      {
        level: 0,
      },
      function (err, out) {
        if (err) {
          noty('Lỗi tạo file nén của <strong>' + chapName + '</strong>', 'error');
          cancelProgress();

          document.title = '[x] ' + tit;
          endZip();
        } else {
          var zipName = genFileName() + '.' + outputExt;
          var zipFile = new File([out], zipName, {
            type: outputExt === 'cbz' ? 'application/vnd.comicbook+zip' : 'application/zip',
          });

          if (recentZip) URL.revokeObjectURL(recentZip);
          recentZip = zipFile;

          noty(
            '<a href="' +
              URL.createObjectURL(zipFile) +
              '" download="' +
              zipName +
              '"><strong>Click vào đây</strong></a> nếu trình duyệt không tự tải xuống',
            'success',
          );
          linkSuccess();

          window.removeEventListener('beforeunload', beforeleaving);
          saveAs(zipFile, zipName);

          document.title = '[⇓] ' + tit;
          endZip();
        }
      },
    );
  }

  function dlImgError(current, success, error, err, filename) {
    if (dlImages[current].attempt <= 0) {
      dlFinal++;
      error(err, filename);
      return;
    }

    setTimeout(function () {
      dlImg(current, success, error);
      dlImages[current].attempt--;
    }, 2000);
  }

  function dlImg(current, success, error) {
    var url = dlImages[current].url,
      filename = ('0000' + dlCurrent).slice(-4),
      urlObj,
      urlHost,
      headers = {};

    if (url.indexOf('//') === 0) url = location.protocol + url;
    urlObj = new URL(url);
    urlHost = urlObj.hostname;

    if (referer[urlHost]) {
      headers.referer = referer[urlHost];
      headers.origin = referer[urlHost];
    } else {
      headers.referer = location.origin;
      headers.origin = location.origin;
    }

    GM.xmlHttpRequest({
      method: 'GET',
      url: url,
      responseType: 'arraybuffer',
      headers: headers,
      onload: function (response) {
        var imgExt = getImageType(response.response).ext;

        if (imgExt === 'gif') {
          dlFinal++;
          next();
          return;
        }

        if (
          !imgExt ||
          response.response.byteLength < 100 ||
          (response.statusText !== 'OK' && response.statusText !== '')
        ) {
          dlImgError(current, success, error, response, filename);
        } else {
          filename = filename + '.' + imgExt;
          dlFinal++;
          success(response, filename);
        }
      },
      onerror: function (err) {
        dlImgError(current, success, error, err, filename);
      },
    });
  }

  function next() {
    noty('Đang tải xuống <strong>' + dlFinal + '/' + dlTotal + '</strong>', 'warning');
    if (dlFinal < dlCurrent) return;

    if (dlFinal < dlTotal) {
      addZip();
    } else {
      if (inMerge) {
        if (dlAll.length) {
          linkSuccess();
          endZip();
        } else {
          inMerge = false;
          genZip();
        }
      } else {
        genZip();
      }
    }
  }

  function addZip() {
    var max = dlCurrent + threading,
      path = '';

    if (max > dlTotal) max = dlTotal;
    if (inMerge) path = genFileName() + '/';

    for (dlCurrent; dlCurrent < max; dlCurrent++) {
      dlImg(
        dlCurrent,
        function (response, filename) {
          zipObj[path + filename] = [
            new Uint8Array(response.response),
            {
              level: 0,
            },
          ];

          next();
        },
        function (err, filename) {
          zipObj[path + filename + '_error.txt'] = [
            fflate.strToU8(err.statusText + '\r\n' + err.finalUrl),
            {
              level: 6,
            },
          ];

          noty(err.statusText, 'error');
          linkError();

          next();
        },
      );
    }
  }

  function imageIgnore(url) {
    return ignoreList.some(function (v) {
      return url.indexOf(v) !== -1;
    });
  }

  function protocolUrl(url) {
    if (url.indexOf('//') === 0) url = location.protocol + url;
    if (url.search(/https?:\/\//) !== 0) url = 'http://' + url;
    return url;
  }

  function redirectSSL(url) {
    if (
      url.search(/(i\.imgur\.com|\.blogspot\.com|\.fbcdn\.net|storage\.fshare\.vn)/i) !== -1 &&
      url.indexOf('http://') === 0
    )
      url = url.replace(/^http:\/\//, 'https://');

    return url;
  }

  function decodeUrl(url) {
    var parser = new DOMParser(),
      dom = parser.parseFromString('<!doctype html><body>' + url, 'text/html');

    return decodeURIComponent(dom.body.textContent);
  }

  function imageFilter(url) {
    url = decodeUrl(url);
    url = url.trim();
    url = url.replace(/^.+(&|\?)url=/, '');
    url = url.replace(/(https?:\/\/)lh(\d)(\.bp\.blogspot\.com)/, '$1$2$3');
    url = url.replace(/(https?:\/\/)lh\d\.(googleusercontent|ggpht)\.com/, '$14.bp.blogspot.com');
    url = url.replace(/\?.+$/, '');
    if (url.indexOf('imgur.com') !== -1) {
      url = url.replace(/(\/)(\w{5}|\w{7})(s|b|t|m|l|h)(\.(jpe?g|png|webp))$/, '$1$2$4');
    } else if (url.indexOf('blogspot.com') !== -1) {
      url = url.replace(/\/([^/]+-)?(Ic42)(-[^/]+)?\//, '/$2/');
      url = url.replace(/\/(((s|w|h)\d+|(w|h)\d+-(w|h)\d+))?-?(c|d|g)?\/(?=[^/]+$)/, '/');
      url += '?imgmax=16383';
    } else {
      url = url.replace(/(\?|&).+/, '');
    }
    url = encodeURI(url);
    url = protocolUrl(url);
    url = redirectSSL(url);

    return url;
  }

  function checkImages(images) {
    var source = [];

    if (!images.length) {
      notyImages();
    } else {
      $.each(images, function (i, v) {
        v = v.replace(/^[\s\n]+|[\s\n]+$/g, '');

        var keep = keepOriginal.some(function (key) {
          return v.indexOf(key) !== -1;
        });
        if (keep) {
          source.push(v);
          return;
        }

        if (imageIgnore(v) || typeof v === 'undefined') return;
        if (/[><"']/.test(v)) return;

        if (
          (v.indexOf(location.origin) === 0 || (v.indexOf('/') === 0 && v.indexOf('//') !== 0)) &&
          !/^(\.(jpg|png)|webp|jpeg)$/.test(v.slice(-4))
        ) {
          return;
        } else if (v.indexOf('http') !== 0 && v.indexOf('//') !== 0) {
          v = location.origin + (v.indexOf('/') === 0 ? '' : '/') + v;
        } else if (v.indexOf('http') === 0 || v.indexOf('//') === 0) {
          v = imageFilter(v);
        } else {
          return;
        }

        source.push(v);
      });

      notySuccess(source);
    }
  }

  function getImages($contents) {
    var images = [];
    $contents.each(function (i, v) {
      var $img = $(v);
      images[i] =
        (!configs.imgSrc ? $img.data('src') || $img.data('original') : $img.attr(configs.imgSrc)) || $img.attr('src');
    });

    checkImages(images);
  }

  function getContents($source) {
    var method = 'find';
    if (configs.filter) method = 'filter';

    var $entry = $source[method](configs.contents).find('img');
    if (!$entry.length) {
      notyImages();
    } else {
      getImages($entry);
    }
  }

  function cleanSource(response) {
    var responseText = response.responseText;
    if (!configs.imgSrc) {
      responseText = responseText.replace(/[\s\n]+src[\s\n]*=[\s\n]*/gi, ' data-src=');
    }
    responseText = responseText.replace(/^[^<]*/, '');

    if (configs.imgSrc) return $(responseText);
    return $(responseText);
  }

  function rightClickEvent(_this, callback) {
    var $this = $(_this),
      name = configs.name;

    configs.href = $this.attr('href');
    chapName = $this.text().trim();

    if (typeof name === 'function') {
      chapName = name(_this, chapName);
    } else if (typeof name === 'string') {
      chapName = $(name).text().trim() + ' ' + chapName;
    }

    notyWait();

    GM.xmlHttpRequest({
      method: 'GET',
      url: configs.href,
      onload: function (response) {
        var $data = cleanSource(response);
        if (typeof callback === 'function') {
          callback($data);
        } else {
          getContents($data);
        }
      },
      onerror: function () {
        notyError();
      },
    });
  }

  function oneProgress() {
    if (inProgress) {
      noty('Chỉ được phép <strong>tải một truyện</strong> mỗi lần', 'error');
      return false;
    }
    inProgress = true;
    return true;
  }

  function getSource(callback) {
    var $link = $(configs.link);
    if (!$link.length) return;

    $doc.on('contextmenu', configs.link, function (e) {
      e.preventDefault();
      hasDownloadError = false;
      if (!oneProgress()) return;

      rightClickEvent(e.currentTarget, callback);
    });

    notyReady();
  }

  
  function getTruyenVn() {
    getSource(function ($data) {
      var chapId = $data.find('[name="p"]:first').val();
      $.ajax({
        type: 'POST',
        url: '/wp-admin/admin-ajax.php',
        data: {
          action: 'z_do_ajax',
          _action: 'load_imgs_for_chapter',
          p: chapId,
        },
        dataType: 'json',
      })
        .done(function (res) {
          if (res.mes != '-1') {
            if (res.mes.length > 1) {
              checkImages(
                res.mes.map(function (img) {
                  return img.url;
                }),
              );
            } else {
              notyImages();
            }
          } else {
            notyImages();
          }
        })
        .fail(function () {
          notyError();
        });
    });
  }

  var configsDefault = {
      reverse: true,
      link: '',
      name: '',
      contents: '',
      imgSrc: '',
      filter: false,
      init: getSource,
    },
    configs,
    chapName,
    domainName = location.host,
    tit = document.title,
    $doc = $(document),
    zipObj = {},
    recentZip = null,
    dlCurrent = 0,
    dlFinal = 0,
    dlTotal = 0,
    dlImages = [],
    dlAll = [],
    hasDownloadError = false,
    inProgress = false,
    inAuto = false,
    inCustom = false,
    inMerge = false;

  GM_registerMenuCommand('Download All Chapters', downloadAll);
  GM_registerMenuCommand('Download All To One File', downloadAllOne);

  $doc.on('keydown', function (e) {
    if (e.code === 'KeyY' && e.altKey) {
      // Alt+Y
      e.preventDefault();
      e.shiftKey ? downloadAllOne() : downloadAll();
    }
  });

  GM_addStyle(
    '#mcd_noty_wrap{background:#fff;position:fixed;z-index:2147483647;right:20px;top:20px;min-width:150px;max-width:100%;padding:15px 25px;border:1px solid #ddd;border-radius:2px;box-shadow:0 0 0 1px rgba(0,0,0,.1),0 1px 10px rgba(0,0,0,.35);cursor:pointer}#mcd_noty_content{color:#444}#mcd_noty_content strong{font-weight:700}#mcd_noty_content.mcd_info strong{color:#2196f3}#mcd_noty_content.mcd_success strong{color:#4caf50}#mcd_noty_content.mcd_warning strong{color:#ffc107}#mcd_noty_content.mcd_error strong{color:#f44336}#mcd_noty_content strong.centered{display:block;text-align:center}#mcd_noty_close{position:absolute;right:0;top:0;font-size:18px;color:#ddd;height:20px;width:20px;line-height:20px;text-align:center}#mcd_noty_wrap:hover #mcd_noty_close{color:#333}',
  );

  switch (domainName) {
    case 'www.nettruyen.com':
    case 'tutientruyen4.fun':
    case 'tutientruyen6.xyz':
    case 'nettruyenok.com':
    case 'nettruyen3q.com':
    case 'nettruyen.life':
    case 'thanvuc.com':
    case 'www.nettruyenapp.com':
    case 'www.nettruyenpro.com':
    case 'www.nettruyengo.com':
    case 'www.nettruyenmoi.com':
    case 'nettruyenqqviet.com':
      configs = {
        link: '#nt_listchapter .chapter a',
        name: '.title-detail',
        contents: '.reading-detail.box_doc',
        imgSrc: 'data-original',
      };
      break;
    case 'www.nettruyentop.com':
    case 'www.nettruyenonline.com':
    case 'www.nettruyenbb.com':
    case 'kingtruyen.com':
      configs = {
        link: '#nt_listchapter .chapter a',
        name: '.title-detail',
        contents: '.readimg,.reading-detail.box_doc',
      };
      break;
    case 'blogtruyen.com':
    case 'blogtruyen.vn':
    case 'blogtruyen.top':
    case 'www.blogtruyen.com':
    case 'www.blogtruyen.vn':
    case 'www.blogtruyen.top':
      configs = {
        link: '#list-chapters .title a',
        contents: '#content',
      };
      break;
    case 'm.blogtruyen.com':
    case 'm.blogtruyen.vn':
    case 'm.blogtruyen.top':
      configs = {
        link: '.list-chapter a',
        name: function (_this) {
          return $('h1.title').text().trim() + ' ' + $(_this).find('span').text().trim();
        },
        contents: '.content',
      };
      break;
    case 'nettruyetviet.com':
      configs = {
        link: '.works-chapter-list a',
        name: 'h1',
        contents: '.chapter_content',
      };
      break;
    case 'truyenqq.net':
    case 'truyenqq.com':
    case 'truyenqqto.com':
    case 'truyenqq5.com':
      configs = {
        link: '.works-chapter-list a',
        name: 'h1',
        contents: '.chapter_content',
      };
      break;
  }

  if (Array.isArray(configs)) {
    var isMobile = /mobi|android|touch|mini/i.test(navigator.userAgent.toLowerCase());
    configs = configs[isMobile ? 1 : 0];
  }
  if (!configs) return;

  configs = $.extend(configsDefault, configs);
  configs.init();
});