Skip to content

Commit

Permalink
Add logging support
Browse files Browse the repository at this point in the history
  • Loading branch information
Morea committed Dec 3, 2023
1 parent e77ece6 commit 5ef29b2
Show file tree
Hide file tree
Showing 9 changed files with 156 additions and 43 deletions.
6 changes: 2 additions & 4 deletions Find Unique Titles/config/webpack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,8 @@ const config: webpack.Configuration = {
new WebpackUserscript({
headers: scriptHeaders,
proxyScript: {
baseURL: url
.pathToFileURL(outputPath)
.toString()
.replace("http", "https"),
baseURL: `http://127.0.0.1:${port}`,
filename: "[basename].proxy.user.js",
},
}),
],
Expand Down
105 changes: 73 additions & 32 deletions Find Unique Titles/dist/find.unique.titles.user.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// ==UserScript==
// @name Find Unique Titles
// @description Find unique titles to cross seed
// @version 0.0.5
// @version 0.0.6
// @author Mea01
// @match https://cinemageddon.net/browse.php*
// @match https://karagarga.in/browse.php*
Expand Down Expand Up @@ -51,30 +51,36 @@
"./src/index.ts": (module, __unused_webpack___webpack_exports__, __webpack_require__) => {
__webpack_require__.a(module, (async (__webpack_handle_async_dependencies__, __webpack_async_result__) => {
try {
var _trackers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./src/trackers/index.ts");
var _utils_cache__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("./src/utils/cache.ts");
var _utils_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./src/utils/dom.ts");
var _settings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/settings.ts");
var common_dom__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__("../common/dist/dom/index.mjs");
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([ _trackers__WEBPACK_IMPORTED_MODULE_1__, _utils_cache__WEBPACK_IMPORTED_MODULE_3__ ]);
[_trackers__WEBPACK_IMPORTED_MODULE_1__, _utils_cache__WEBPACK_IMPORTED_MODULE_3__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__;
var _trackers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./src/trackers/index.ts");
var _utils_cache__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__("./src/utils/cache.ts");
var _utils_dom__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("./src/utils/dom.ts");
var _settings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./src/settings.ts");
var common_dom__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("../common/dist/dom/index.mjs");
var common_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("../common/dist/logger/index.mjs");
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([ _trackers__WEBPACK_IMPORTED_MODULE_2__, _utils_cache__WEBPACK_IMPORTED_MODULE_4__ ]);
[_trackers__WEBPACK_IMPORTED_MODULE_2__, _utils_cache__WEBPACK_IMPORTED_MODULE_4__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__;
function hideTorrents(request) {
for (let element of request.dom) element.style.display = "none";
for (let torrent of request.torrents) torrent.dom.style.display = "none";
}
const setUpLogger = debugMode => {
common_logger__WEBPACK_IMPORTED_MODULE_0__.logger.setPrefix("[Find Unique Titles]");
if (debugMode) common_logger__WEBPACK_IMPORTED_MODULE_0__.logger.setLevel(common_logger__WEBPACK_IMPORTED_MODULE_0__.LEVEL.DEBUG);
};
const main = async function() {
console.log("Init User script");
const settings = (0, _settings__WEBPACK_IMPORTED_MODULE_0__.getSettings)();
const settings = (0, _settings__WEBPACK_IMPORTED_MODULE_1__.getSettings)();
setUpLogger(settings.debug);
common_logger__WEBPACK_IMPORTED_MODULE_0__.logger.info("Init User script");
if (document.getElementById("tracker-select")) return;
const url = window.location.href;
let sourceTracker = null;
let targetTrackers = [];
Object.keys(_trackers__WEBPACK_IMPORTED_MODULE_1__).forEach((trackerName => {
const trackerImplementation = new _trackers__WEBPACK_IMPORTED_MODULE_1__[trackerName];
Object.keys(_trackers__WEBPACK_IMPORTED_MODULE_2__).forEach((trackerName => {
const trackerImplementation = new _trackers__WEBPACK_IMPORTED_MODULE_2__[trackerName];
if (trackerImplementation.canRun(url)) sourceTracker = trackerImplementation; else if (trackerImplementation.canBeUsedAsTarget()) targetTrackers.push(trackerImplementation);
}));
if (null == sourceTracker) return;
const select = (0, _utils_dom__WEBPACK_IMPORTED_MODULE_2__.createTrackersSelect)(targetTrackers.map((tracker => tracker.name())));
const select = (0, _utils_dom__WEBPACK_IMPORTED_MODULE_3__.createTrackersSelect)(targetTrackers.map((tracker => tracker.name())));
select.addEventListener("change", (async () => {
let answer = confirm("Start searching new content for: " + select.value);
if (answer) {
Expand All @@ -83,33 +89,33 @@
let newContent = 0;
let requestGenerator = sourceTracker.getSearchRequest();
const metadata = (await requestGenerator.next()).value;
(0, _utils_dom__WEBPACK_IMPORTED_MODULE_2__.addCounter)();
(0, _utils_dom__WEBPACK_IMPORTED_MODULE_2__.updateTotalCount)(metadata.total);
(0, _utils_dom__WEBPACK_IMPORTED_MODULE_3__.addCounter)();
(0, _utils_dom__WEBPACK_IMPORTED_MODULE_3__.updateTotalCount)(metadata.total);
for await (const item of requestGenerator) {
const request = item;
if (settings.useCache && request.imdbId && (0, _utils_cache__WEBPACK_IMPORTED_MODULE_3__.existsInCache)(targetTracker.name(), request.imdbId)) {
if (settings.useCache && request.imdbId && (0, _utils_cache__WEBPACK_IMPORTED_MODULE_4__.existsInCache)(targetTracker.name(), request.imdbId)) {
hideTorrents(request);
(0, _utils_dom__WEBPACK_IMPORTED_MODULE_2__.updateCount)(i++);
(0, _utils_dom__WEBPACK_IMPORTED_MODULE_3__.updateCount)(i++);
continue;
}
const response = await targetTracker.canUpload(request, settings.onlyNewTitles);
(0, _utils_dom__WEBPACK_IMPORTED_MODULE_2__.updateCount)(i++);
(0, _utils_dom__WEBPACK_IMPORTED_MODULE_3__.updateCount)(i++);
if (!response) {
if (request.imdbId) await (0, _utils_cache__WEBPACK_IMPORTED_MODULE_3__.addToCache)(targetTracker.name(), request.imdbId);
if (request.imdbId) await (0, _utils_cache__WEBPACK_IMPORTED_MODULE_4__.addToCache)(targetTracker.name(), request.imdbId);
hideTorrents(request);
} else {
newContent++;
(0, _utils_dom__WEBPACK_IMPORTED_MODULE_2__.updateNewContent)(newContent);
(0, _utils_dom__WEBPACK_IMPORTED_MODULE_3__.updateNewContent)(newContent);
}
}
(0, _utils_cache__WEBPACK_IMPORTED_MODULE_3__.clearMemoryCache)();
(0, _utils_cache__WEBPACK_IMPORTED_MODULE_4__.clearMemoryCache)();
}
}));
sourceTracker.insertTrackersSelect(select);
};
(0, common_dom__WEBPACK_IMPORTED_MODULE_4__.appendErrorMessage)();
(0, common_dom__WEBPACK_IMPORTED_MODULE_5__.appendErrorMessage)();
main().catch((e => {
(0, common_dom__WEBPACK_IMPORTED_MODULE_4__.showError)(e.message);
(0, common_dom__WEBPACK_IMPORTED_MODULE_5__.showError)(e.message);
}));
let currentUrl = document.location.href;
const observer = new MutationObserver((async () => {
Expand All @@ -136,6 +142,7 @@
const defaultConfig = {
onlyNewTitles: false,
useCache: true,
debug: false,
sizeDifferenceThreshold: 1.2
};
GM_config.init({
Expand All @@ -156,6 +163,11 @@
label: "Size Difference Threshold",
type: "float",
default: defaultConfig.sizeDifferenceThreshold
},
debug: {
label: "Debug mode",
type: "checkbox",
default: defaultConfig.debug
}
},
css: "\n #find-unique-titles-settings {\n }\n #find-unique-titles-settings .config_var {\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n ",
Expand All @@ -177,6 +189,7 @@
const getSettings = () => ({
onlyNewTitles: GM_config.get("onlyNewTitles"),
useCache: GM_config.get("useCache"),
debug: GM_config.get("debug"),
sizeDifferenceThreshold: GM_config.get("sizeDifferenceThreshold")
});
},
Expand Down Expand Up @@ -2289,7 +2302,8 @@
"../common/dist/http/index.mjs": (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
__webpack_require__.d(__webpack_exports__, {
fetchAndParseHtml: () => fetchAndParseHtml,
fetchUrl: () => fetchUrl
fetchUrl: () => fetchUrl,
sleep: () => sleep
});
var _trim21_gm_fetch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("../node_modules/@trim21/gm-fetch/dist/index.mjs");
const parser = new DOMParser;
Expand All @@ -2304,6 +2318,33 @@
};
const sleep = ms => new Promise((resolve => setTimeout(resolve, ms)));
},
"../common/dist/logger/index.mjs": (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
__webpack_require__.d(__webpack_exports__, {
LEVEL: () => LEVEL,
logger: () => logger
});
var LEVEL;
!function(LEVEL) {
LEVEL[LEVEL.DEBUG = 0] = "DEBUG";
LEVEL[LEVEL.INFO = 1] = "INFO";
}(LEVEL || (LEVEL = {}));
const logger = {
level: LEVEL.INFO,
prefix: "",
setLevel: level => {
logger.level = level;
},
setPrefix: prefix => {
logger.prefix = prefix;
},
info: message => {
if (logger.level <= LEVEL.INFO) console.log(`${logger.prefix} [INFO] ${message}`);
},
debug: message => {
if (logger.level <= LEVEL.DEBUG) console.log(`${logger.prefix} [DEBUG] ${message}`);
}
};
},
"../common/dist/searcher/index.mjs": (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
__webpack_require__.d(__webpack_exports__, {
SearchResult: () => SearchResult,
Expand All @@ -2318,9 +2359,12 @@
SearchResult[SearchResult.ERROR = 3] = "ERROR";
}(SearchResult || (SearchResult = {}));
const search = async (tracker, options) => {
"rateLimit" in tracker && tracker.rateLimit;
tracker.searchUrl.split("/")[2];
(new Date).getTime();
const rate = "rateLimit" in tracker ? tracker.rateLimit : 200;
const domain = tracker.searchUrl.split("/")[2];
const now = (new Date).getTime();
let lastLoaded = window.localStorage[domain + "_lastLoaded"];
if (!lastLoaded) lastLoaded = now - 5e4; else lastLoaded = parseInt(lastLoaded);
if (now - lastLoaded < rate) await (0, _http_index_mjs__WEBPACK_IMPORTED_MODULE_0__.sleep)(now - lastLoaded); else window.localStorage[domain + "_lastLoaded"] = (new Date).getTime();
const success_match = "positiveMatch" in tracker ? tracker.positiveMatch : false;
const searchUrl = await replaceSearchUrlParams(tracker, options);
if (searchUrl.indexOf("=00000000") > -1 || searchUrl.indexOf("=undefined") > -1) return SearchResult.ERROR;
Expand Down Expand Up @@ -2423,7 +2467,6 @@
TSeeds: () => TSeeds
});
const KG = {
TV: false,
name: "KG",
searchUrl: "https://karagarga.in/browse.php?sort=added&search=%nott%&search_type=imdb&d=DESC",
loggedOutRegex: /Cloudflare|Ray ID|Not logged in!/,
Expand All @@ -2432,7 +2475,6 @@
both: true
};
const MTV = {
TV: false,
name: "MTV",
searchUrl: "https://www.morethantv.me/torrents.php?filter_cat[1]=1&filter_cat[2]=1&title=+%2B%search_string%+%2B%year%",
loggedOutRegex: /Cloudflare|Ray ID|forgotten password/,
Expand All @@ -2441,16 +2483,15 @@
positiveMatch: true
};
const MTV_TV = {
TV: true,
name: "MTV",
searchUrl: "https://www.morethantv.me/torrents.php?filter_cat[3]=1&filter_cat[5]=1&filter_cat[4]=1&filter_cat[6]=1&title=+%2B%search_string%",
loggedOutRegex: /Cloudflare|Ray ID|forgotten password/,
spaceEncode: "+%2B",
matchRegex: /action=download/,
positiveMatch: true
positiveMatch: true,
TV: true
};
const TSeeds = {
TV: false,
name: "TSeeds",
searchUrl: "https://www.torrentseeds.org/torrents?tmdbId=%tmdbid%",
loggedOutRegex: /Cloudflare|Forgot Your Password|Service Unavailable/,
Expand Down
2 changes: 1 addition & 1 deletion Find Unique Titles/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
"webpack": "^5.78.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.13.2",
"webpack-userscript": "^3.1.0"
"webpack-userscript": "^3.2.2"
},
"browserslist": [
"last 1 chrome version",
Expand Down
15 changes: 12 additions & 3 deletions Find Unique Titles/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import "./settings";
import { getSettings } from "./settings";
import { appendErrorMessage, showError } from "common/dom";
import { logger, LEVEL } from "common/logger"

function hideTorrents(request: Request) {
for (let element of request.dom) {
Expand All @@ -21,14 +22,22 @@ function hideTorrents(request: Request) {
}
}

const setUpLogger = (debugMode: boolean) => {
logger.setPrefix("[Find Unique Titles]")
if (debugMode){
logger.setLevel(LEVEL.DEBUG)
}
}

const main = async function () {
"use strict";

console.log("Init User script");
/******************************************************************************/
const settings = getSettings();

/******************************************************************************/
setUpLogger(settings.debug)

logger.info("Init User script");

if (document.getElementById("tracker-select")) return;
const url = window.location.href;
let sourceTracker: tracker | null = null;
Expand Down
8 changes: 8 additions & 0 deletions Find Unique Titles/src/settings.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const defaultConfig: Settings = {
onlyNewTitles: false,
useCache: true,
debug: false,
sizeDifferenceThreshold: 1.2,
};

Expand All @@ -24,6 +25,11 @@ GM_config.init({
type: "float",
default: defaultConfig.sizeDifferenceThreshold,
},
debug: {
label: "Debug mode",
type: "checkbox",
default: defaultConfig.debug,
},
},
css: `
#find-unique-titles-settings {
Expand Down Expand Up @@ -56,12 +62,14 @@ export const getSettings = (): Settings => {
return {
onlyNewTitles: GM_config.get("onlyNewTitles"),
useCache: GM_config.get("useCache"),
debug: GM_config.get("debug"),
sizeDifferenceThreshold: GM_config.get("sizeDifferenceThreshold"),
};
};

interface Settings {
useCache: boolean;
onlyNewTitles: boolean;
debug: boolean;
sizeDifferenceThreshold: number;
}
4 changes: 4 additions & 0 deletions common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@
"./searcher": {
"types": "./dist/types/src/searcher/index.d.ts",
"import": "./dist/searcher/index.mjs"
},
"./logger": {
"types": "./dist/types/src/logger/index.d.ts",
"import": "./dist/logger/index.mjs"
}
},
"type": "module",
Expand Down
1 change: 1 addition & 0 deletions common/rollup.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ module.exports = {
'dom/index': 'src/dom/index.ts',
'trackers/index': 'src/trackers/index.ts',
'searcher/index': 'src/searcher/index.ts',
'logger/index': 'src/logger/index.ts',
},
plugins: [
typescript({
Expand Down
52 changes: 52 additions & 0 deletions common/src/logger/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
export enum LEVEL {
DEBUG,
INFO,
}

export const logger = {
level: LEVEL.INFO,
prefix: "",

setLevel: (level: LEVEL) => {
logger.level = level;
},

setPrefix: (prefix: string) => {
logger.prefix = prefix;
},

info: (message: string, ...args: Array<any>) => {
if (logger.level <= LEVEL.INFO) {
console.log(formatMessage(logger.level, message, args));
}
},

debug: (message: string, ...args: Array<any>) => {
// Log debug messages if level is 'debug'
if (logger.level <= LEVEL.DEBUG) {
console.log(formatMessage(logger.level, message, args));
}
},
};

const formatMessage = (level: LEVEL, message: string, args: any[]): string => {
let levelPrefix = "";
if (level == LEVEL.INFO) {
levelPrefix = "[INFO]";
} else if (level == LEVEL.DEBUG) {
levelPrefix = "[DEBUG]";
}
return (
`${logger.prefix} ${levelPrefix} "` +
message
.replace(/{(\d+)}/g, (match, index) => {
const argIndex = parseInt(index, 10);
const argValue = args[argIndex];

// Stringify objects and arrays
return typeof argValue === 'object' ? JSON.stringify(argValue) : argValue;

})
.trim()
);
};
Loading

0 comments on commit 5ef29b2

Please sign in to comment.