Merge pull request #20828 from Chocobo1/js_quotes

WebUI: enforce coding styles
This commit is contained in:
Chocobo1 2024-05-29 01:39:13 +08:00 committed by GitHub
commit d52995015e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
58 changed files with 3768 additions and 3724 deletions

View file

@ -1,8 +1,8 @@
import Globals from 'globals';
import Html from 'eslint-plugin-html';
import Js from '@eslint/js';
import Stylistic from '@stylistic/eslint-plugin';
import * as RegexpPlugin from 'eslint-plugin-regexp';
import Globals from "globals";
import Html from "eslint-plugin-html";
import Js from "@eslint/js";
import Stylistic from "@stylistic/eslint-plugin";
import * as RegexpPlugin from "eslint-plugin-regexp";
export default [
Js.configs.recommended,
@ -27,8 +27,14 @@ export default [
},
rules: {
"eqeqeq": "error",
"guard-for-in": "error",
"no-undef": "off",
"no-unused-vars": "off",
"no-var": "error",
"operator-assignment": "error",
"prefer-arrow-callback": "error",
"prefer-const": "error",
"radix": "error",
"Stylistic/no-mixed-operators": [
"error",
{
@ -38,6 +44,14 @@ export default [
}
],
"Stylistic/nonblock-statement-body-position": ["error", "below"],
"Stylistic/quotes": [
"error",
"double",
{
"avoidEscape": true,
"allowTemplateLiterals": true
}
],
"Stylistic/semi": "error"
}
}

View file

@ -7,8 +7,8 @@
},
"scripts": {
"extract_translation": "i18next -c public/i18next-parser.config.mjs public/index.html public/scripts/login.js",
"format": "js-beautify -r private/*.html private/scripts/*.js private/views/*.html public/*.html public/scripts/*.js && prettier --write **.css",
"lint": "eslint private/*.html private/scripts/*.js private/views/*.html public/*.html public/scripts/*.js && stylelint **/*.css && html-validate private public"
"format": "js-beautify -r *.mjs private/*.html private/scripts/*.js private/views/*.html public/*.html public/scripts/*.js && prettier --write **.css",
"lint": "eslint *.mjs private/*.html private/scripts/*.js private/views/*.html public/*.html public/scripts/*.js && stylelint **/*.css && html-validate private public"
},
"devDependencies": {
"@stylistic/eslint-plugin": "*",

View file

@ -8,42 +8,42 @@
<script src="scripts/lib/MooTools-Core-1.6.0-compat-compressed.js"></script>
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', function() {
const hash = new URI().getData('hash');
window.addEvent("domready", () => {
const hash = new URI().getData("hash");
if (!hash)
return false;
$('peers').focus();
$("peers").focus();
$('addPeersOk').addEvent('click', function(e) {
$("addPeersOk").addEvent("click", (e) => {
new Event(e).stop();
const peers = $('peers').get('value').trim().split(/[\r\n]+/);
const peers = $("peers").get("value").trim().split(/[\r\n]+/);
if (peers.length === 0)
return;
new Request({
url: 'api/v2/torrents/addPeers',
method: 'post',
url: "api/v2/torrents/addPeers",
method: "post",
data: {
hashes: hash,
peers: peers.join('|')
peers: peers.join("|")
},
onFailure: function() {
alert("QBT_TR(Unable to add peers. Please ensure you are adhering to the IP:port format.)QBT_TR[CONTEXT=HttpServer]");

View file

@ -8,33 +8,33 @@
<script src="scripts/lib/MooTools-Core-1.6.0-compat-compressed.js"></script>
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script>
'use strict';
"use strict";
window.addEvent('domready', function() {
window.addEvent("domready", () => {
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
$('trackersUrls').focus();
$('addTrackersButton').addEvent('click', function(e) {
$("trackersUrls").focus();
$("addTrackersButton").addEvent("click", (e) => {
new Event(e).stop();
const hash = new URI().getData('hash');
const hash = new URI().getData("hash");
new Request({
url: 'api/v2/torrents/addTrackers',
method: 'post',
url: "api/v2/torrents/addTrackers",
method: "post",
data: {
hash: hash,
urls: $('trackersUrls').value
urls: $("trackersUrls").value
},
onComplete: function() {
window.parent.qBittorrent.Client.closeWindows();

View file

@ -8,73 +8,73 @@
<script src="scripts/lib/MooTools-Core-1.6.0-compat-compressed.js"></script>
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script>
'use strict';
"use strict";
function setRememberBtnEnabled(enable) {
const btn = $('rememberBtn');
const btn = $("rememberBtn");
btn.disabled = !enable;
const icon = btn.getElementsByTagName('path')[0];
const icon = btn.getElementsByTagName("path")[0];
if (enable)
icon.style.removeProperty('fill');
icon.style.removeProperty("fill");
else
icon.style.fill = "var(--color-border-default)";
}
window.addEvent('domready', function() {
window.addEvent("domready", () => {
new Request({
url: 'images/object-locked.svg',
method: 'get',
url: "images/object-locked.svg",
method: "get",
onSuccess: function(text, xml) {
const newIcon = xml.childNodes[0];
newIcon.style.height = '24px';
newIcon.style.width = '24px';
$('rememberBtn').appendChild(newIcon);
newIcon.style.height = "24px";
newIcon.style.width = "24px";
$("rememberBtn").appendChild(newIcon);
setRememberBtnEnabled(false);
}
}).send();
const isDeletingFiles = (new URI().getData('deleteFiles') === "true");
$('deleteFromDiskCB').checked = isDeletingFiles;
const isDeletingFiles = (new URI().getData("deleteFiles") === "true");
$("deleteFromDiskCB").checked = isDeletingFiles;
const prefCache = window.parent.qBittorrent.Cache.preferences.get();
let prefDeleteContentFiles = prefCache.delete_torrent_content_files;
$('deleteFromDiskCB').checked ||= prefDeleteContentFiles;
$('deleteFromDiskCB').addEvent('click', function(e) {
setRememberBtnEnabled($('deleteFromDiskCB').checked !== prefDeleteContentFiles);
$("deleteFromDiskCB").checked ||= prefDeleteContentFiles;
$("deleteFromDiskCB").addEvent("click", (e) => {
setRememberBtnEnabled($("deleteFromDiskCB").checked !== prefDeleteContentFiles);
});
// Set current "Delete files" choice as the default
$('rememberBtn').addEvent('click', function(e) {
$("rememberBtn").addEvent("click", (e) => {
window.parent.qBittorrent.Cache.preferences.set({
data: {
'delete_torrent_content_files': $('deleteFromDiskCB').checked
"delete_torrent_content_files": $("deleteFromDiskCB").checked
},
onSuccess: function() {
prefDeleteContentFiles = $('deleteFromDiskCB').checked;
prefDeleteContentFiles = $("deleteFromDiskCB").checked;
setRememberBtnEnabled(false);
}
});
});
const hashes = new URI().getData('hashes').split('|');
$('cancelBtn').focus();
$('cancelBtn').addEvent('click', function(e) {
const hashes = new URI().getData("hashes").split("|");
$("cancelBtn").focus();
$("cancelBtn").addEvent("click", (e) => {
new Event(e).stop();
window.parent.qBittorrent.Client.closeWindows();
});
$('confirmBtn').addEvent('click', function(e) {
$("confirmBtn").addEvent("click", (e) => {
parent.torrentsTable.deselectAll();
new Event(e).stop();
const cmd = 'api/v2/torrents/delete';
const deleteFiles = $('deleteFromDiskCB').get('checked');
const cmd = "api/v2/torrents/delete";
const deleteFiles = $("deleteFromDiskCB").get("checked");
new Request({
url: cmd,
method: 'post',
method: "post",
data: {
'hashes': hashes.join('|'),
'deleteFiles': deleteFiles
"hashes": hashes.join("|"),
"deleteFiles": deleteFiles
},
onComplete: function() {
window.parent.qBittorrent.Client.closeWindows();

View file

@ -8,22 +8,22 @@
<script src="scripts/lib/MooTools-Core-1.6.0-compat-compressed.js"></script>
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script>
'use strict';
"use strict";
window.addEvent('domready', () => {
const paths = new URI().getData('paths').split('|');
$('cancelBtn').focus();
$('cancelBtn').addEvent('click', (e) => {
window.addEvent("domready", () => {
const paths = new URI().getData("paths").split("|");
$("cancelBtn").focus();
$("cancelBtn").addEvent("click", (e) => {
new Event(e).stop();
window.parent.qBittorrent.Client.closeWindows();
});
$('confirmBtn').addEvent('click', (e) => {
$("confirmBtn").addEvent("click", (e) => {
new Event(e).stop();
let completionCount = 0;
paths.forEach((path) => {
new Request({
url: 'api/v2/rss/removeItem',
method: 'post',
url: "api/v2/rss/removeItem",
method: "post",
data: {
path: decodeURIComponent(path)
},

View file

@ -8,25 +8,25 @@
<script src="scripts/lib/MooTools-Core-1.6.0-compat-compressed.js"></script>
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script>
'use strict';
"use strict";
window.addEvent('domready', () => {
const rules = new URI().getData('rules').split('|');
window.addEvent("domready", () => {
const rules = new URI().getData("rules").split("|");
$('cancelBtn').focus();
$('cancelBtn').addEvent('click', (e) => {
$("cancelBtn").focus();
$("cancelBtn").addEvent("click", (e) => {
new Event(e).stop();
window.parent.MochaUI.closeWindow(window.parent.$('clearRulesPage'));
window.parent.MochaUI.closeWindow(window.parent.$("clearRulesPage"));
});
$('confirmBtn').addEvent('click', (e) => {
$("confirmBtn").addEvent("click", (e) => {
new Event(e).stop();
let completionCount = 0;
rules.forEach((rule) => {
window.parent.qBittorrent.RssDownloader.modifyRuleState(decodeURIComponent(rule), 'previouslyMatchedEpisodes', [], () => {
window.parent.qBittorrent.RssDownloader.modifyRuleState(decodeURIComponent(rule), "previouslyMatchedEpisodes", [], () => {
++completionCount;
if (completionCount === rules.length) {
window.parent.qBittorrent.RssDownloader.updateRulesList();
window.parent.MochaUI.closeWindow(window.parent.$('clearRulesPage'));
window.parent.MochaUI.closeWindow(window.parent.$("clearRulesPage"));
}
});
});

View file

@ -8,23 +8,23 @@
<script src="scripts/lib/MooTools-Core-1.6.0-compat-compressed.js"></script>
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script>
'use strict';
"use strict";
window.addEvent('domready', () => {
const rules = new URI().getData('rules').split('|');
window.addEvent("domready", () => {
const rules = new URI().getData("rules").split("|");
$('cancelBtn').focus();
$('cancelBtn').addEvent('click', (e) => {
$("cancelBtn").focus();
$("cancelBtn").addEvent("click", (e) => {
new Event(e).stop();
window.parent.MochaUI.closeWindow(window.parent.$('removeRulePage'));
window.parent.MochaUI.closeWindow(window.parent.$("removeRulePage"));
});
$('confirmBtn').addEvent('click', (e) => {
$("confirmBtn").addEvent("click", (e) => {
new Event(e).stop();
let completionCount = 0;
rules.forEach((rule) => {
new Request({
url: 'api/v2/rss/removeRule',
method: 'post',
url: "api/v2/rss/removeRule",
method: "post",
data: {
ruleName: decodeURIComponent(rule)
},
@ -32,7 +32,7 @@
++completionCount;
if (completionCount === rules.length) {
window.parent.qBittorrent.RssDownloader.updateRulesList();
window.parent.MochaUI.closeWindow(window.parent.$('removeRulePage'));
window.parent.MochaUI.closeWindow(window.parent.$("removeRulePage"));
}
}
}).send();

View file

@ -163,31 +163,31 @@
<div id="download_spinner" class="mochaSpinner"></div>
<script>
'use strict';
"use strict";
const encodedUrls = new URI().getData('urls');
const encodedUrls = new URI().getData("urls");
if (encodedUrls) {
const urls = encodedUrls.split('|').map(function(url) {
const urls = encodedUrls.split("|").map((url) => {
return decodeURIComponent(url);
});
if (urls.length)
$('urls').set('value', urls.join("\n"));
$("urls").set("value", urls.join("\n"));
}
let submitted = false;
$('downloadForm').addEventListener("submit", function() {
$('startTorrentHidden').value = $('startTorrent').checked ? 'false' : 'true';
$("downloadForm").addEventListener("submit", () => {
$("startTorrentHidden").value = $("startTorrent").checked ? "false" : "true";
$('dlLimitHidden').value = $('dlLimitText').value.toInt() * 1024;
$('upLimitHidden').value = $('upLimitText').value.toInt() * 1024;
$("dlLimitHidden").value = $("dlLimitText").value.toInt() * 1024;
$("upLimitHidden").value = $("upLimitText").value.toInt() * 1024;
$('download_spinner').style.display = "block";
$("download_spinner").style.display = "block";
submitted = true;
});
$('download_frame').addEventListener("load", function() {
$("download_frame").addEventListener("load", () => {
if (submitted)
window.parent.qBittorrent.Client.closeWindows();
});

View file

@ -25,17 +25,17 @@
</div>
<script>
'use strict';
"use strict";
const hashes = new URI().getData('hashes').split('|');
const hashes = new URI().getData("hashes").split("|");
const setDlLimit = function() {
const limit = $("dllimitUpdatevalue").value.toInt() * 1024;
if (hashes[0] === "global") {
new Request({
url: 'api/v2/transfer/setDownloadLimit',
method: 'post',
url: "api/v2/transfer/setDownloadLimit",
method: "post",
data: {
'limit': limit
"limit": limit
},
onComplete: function() {
window.parent.updateMainData();
@ -45,11 +45,11 @@
}
else {
new Request({
url: 'api/v2/torrents/setDownloadLimit',
method: 'post',
url: "api/v2/torrents/setDownloadLimit",
method: "post",
data: {
'hashes': hashes.join('|'),
'limit': limit
"hashes": hashes.join("|"),
"limit": limit
},
onComplete: function() {
window.parent.qBittorrent.Client.closeWindows();
@ -59,24 +59,24 @@
};
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(event) {
$('applyButton').click();
"Enter": function(event) {
$("applyButton").click();
event.preventDefault();
},
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
$('dllimitUpdatevalue').focus();
$("dllimitUpdatevalue").focus();
MochaUI.addDlLimitSlider(hashes);
</script>

View file

@ -8,44 +8,44 @@
<script src="scripts/lib/MooTools-Core-1.6.0-compat-compressed.js"></script>
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script>
'use strict';
"use strict";
window.addEvent('domready', function() {
window.addEvent("domready", () => {
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(event) {
$('editTrackerButton').click();
"Enter": function(event) {
$("editTrackerButton").click();
event.preventDefault();
},
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
const currentUrl = new URI().getData('url');
const currentUrl = new URI().getData("url");
if (!currentUrl)
return false;
$('trackerUrl').value = currentUrl;
$('trackerUrl').focus();
$("trackerUrl").value = currentUrl;
$("trackerUrl").focus();
$('editTrackerButton').addEvent('click', function(e) {
$("editTrackerButton").addEvent("click", (e) => {
new Event(e).stop();
const hash = new URI().getData('hash');
const hash = new URI().getData("hash");
new Request({
url: 'api/v2/torrents/editTracker',
method: 'post',
url: "api/v2/torrents/editTracker",
method: "post",
data: {
hash: hash,
origUrl: currentUrl,
newUrl: $('trackerUrl').value
newUrl: $("trackerUrl").value
},
onComplete: function() {
window.parent.qBittorrent.Client.closeWindows();

View file

@ -9,54 +9,54 @@
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(event) {
$('categoryNameButton').click();
"Enter": function(event) {
$("categoryNameButton").click();
event.preventDefault();
},
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', function() {
const uriAction = window.qBittorrent.Misc.safeTrim(new URI().getData('action'));
const uriHashes = window.qBittorrent.Misc.safeTrim(new URI().getData('hashes'));
const uriCategoryName = window.qBittorrent.Misc.safeTrim(new URI().getData('categoryName'));
const uriSavePath = window.qBittorrent.Misc.safeTrim(new URI().getData('savePath'));
window.addEvent("domready", () => {
const uriAction = window.qBittorrent.Misc.safeTrim(new URI().getData("action"));
const uriHashes = window.qBittorrent.Misc.safeTrim(new URI().getData("hashes"));
const uriCategoryName = window.qBittorrent.Misc.safeTrim(new URI().getData("categoryName"));
const uriSavePath = window.qBittorrent.Misc.safeTrim(new URI().getData("savePath"));
if (uriAction === "edit") {
if (!uriCategoryName)
return false;
$('categoryName').set('disabled', true);
$('categoryName').set('value', window.qBittorrent.Misc.escapeHtml(uriCategoryName));
$('savePath').set('value', window.qBittorrent.Misc.escapeHtml(uriSavePath));
$('savePath').focus();
$("categoryName").set("disabled", true);
$("categoryName").set("value", window.qBittorrent.Misc.escapeHtml(uriCategoryName));
$("savePath").set("value", window.qBittorrent.Misc.escapeHtml(uriSavePath));
$("savePath").focus();
}
else if (uriAction === "createSubcategory") {
$('categoryName').set('value', window.qBittorrent.Misc.escapeHtml(uriCategoryName));
$('categoryName').focus();
$("categoryName").set("value", window.qBittorrent.Misc.escapeHtml(uriCategoryName));
$("categoryName").focus();
}
else {
$('categoryName').focus();
$("categoryName").focus();
}
$('categoryNameButton').addEvent('click', function(e) {
$("categoryNameButton").addEvent("click", (e) => {
new Event(e).stop();
const savePath = $('savePath').value.trim();
const categoryName = $('categoryName').value.trim();
const savePath = $("savePath").value.trim();
const categoryName = $("categoryName").value.trim();
const verifyCategoryName = function(name) {
if ((name === null) || (name === ""))
@ -74,16 +74,16 @@
return;
new Request({
url: 'api/v2/torrents/createCategory',
method: 'post',
url: "api/v2/torrents/createCategory",
method: "post",
data: {
category: categoryName,
savePath: savePath
},
onSuccess: function() {
new Request({
url: 'api/v2/torrents/setCategory',
method: 'post',
url: "api/v2/torrents/setCategory",
method: "post",
data: {
hashes: uriHashes,
category: categoryName
@ -104,8 +104,8 @@
return;
new Request({
url: 'api/v2/torrents/createCategory',
method: 'post',
url: "api/v2/torrents/createCategory",
method: "post",
data: {
category: categoryName,
savePath: savePath
@ -117,8 +117,8 @@
break;
case "edit":
new Request({
url: 'api/v2/torrents/editCategory',
method: 'post',
url: "api/v2/torrents/editCategory",
method: "post",
data: {
category: uriCategoryName, // category name can't be changed
savePath: savePath

View file

@ -9,45 +9,45 @@
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': (event) => {
$('submitButton').click();
"Enter": (event) => {
$("submitButton").click();
event.preventDefault();
},
'Escape': (event) => {
"Escape": (event) => {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': (event) => {
"Esc": (event) => {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', () => {
$('feedURL').focus();
const path = new URI().getData('path');
$('submitButton').addEvent('click', (e) => {
window.addEvent("domready", () => {
$("feedURL").focus();
const path = new URI().getData("path");
$("submitButton").addEvent("click", (e) => {
new Event(e).stop();
// check field
const feedURL = $('feedURL').value.trim();
if (feedURL === '') {
alert('QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]');
const feedURL = $("feedURL").value.trim();
if (feedURL === "") {
alert("QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]");
return;
}
$('submitButton').disabled = true;
$("submitButton").disabled = true;
new Request({
url: 'api/v2/rss/addFeed',
method: 'post',
url: "api/v2/rss/addFeed",
method: "post",
data: {
url: feedURL,
path: path ? (path + '\\' + feedURL) : ''
path: path ? (path + "\\" + feedURL) : ""
},
onSuccess: (response) => {
window.parent.qBittorrent.Rss.updateRssFeedList();
@ -56,7 +56,7 @@
onFailure: (response) => {
if (response.status === 409)
alert(response.responseText);
$('submitButton').disabled = false;
$("submitButton").disabled = false;
}
}).send();
});

View file

@ -9,44 +9,44 @@
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': (event) => {
$('submitButton').click();
"Enter": (event) => {
$("submitButton").click();
event.preventDefault();
},
'Escape': (event) => {
"Escape": (event) => {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': (event) => {
"Esc": (event) => {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', () => {
$('folderName').focus();
const path = new URI().getData('path');
$('submitButton').addEvent('click', (e) => {
window.addEvent("domready", () => {
$("folderName").focus();
const path = new URI().getData("path");
$("submitButton").addEvent("click", (e) => {
new Event(e).stop();
// check field
const folderName = $('folderName').value.trim();
if (folderName === '') {
alert('QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]');
const folderName = $("folderName").value.trim();
if (folderName === "") {
alert("QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]");
return;
}
$('submitButton').disabled = true;
$("submitButton").disabled = true;
new Request({
url: 'api/v2/rss/addFolder',
method: 'post',
url: "api/v2/rss/addFolder",
method: "post",
data: {
path: path ? (path + '\\' + folderName) : folderName
path: path ? (path + "\\" + folderName) : folderName
},
onSuccess: (response) => {
window.parent.qBittorrent.Rss.updateRssFeedList();
@ -55,7 +55,7 @@
onFailure: (response) => {
if (response.status === 409)
alert(response.responseText);
$('submitButton').disabled = false;
$("submitButton").disabled = false;
}
}).send();
});

View file

@ -9,46 +9,46 @@
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': (event) => {
$('submitButton').click();
"Enter": (event) => {
$("submitButton").click();
event.preventDefault();
},
'Escape': (event) => {
window.parent.MochaUI.closeWindow(window.parent.$('newRulePage'));
"Escape": (event) => {
window.parent.MochaUI.closeWindow(window.parent.$("newRulePage"));
event.preventDefault();
},
'Esc': (event) => {
window.parent.MochaUI.closeWindow(window.parent.$('newRulePage'));
"Esc": (event) => {
window.parent.MochaUI.closeWindow(window.parent.$("newRulePage"));
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', () => {
$('name').focus();
$('submitButton').addEvent('click', (e) => {
window.addEvent("domready", () => {
$("name").focus();
$("submitButton").addEvent("click", (e) => {
new Event(e).stop();
// check field
const name = $('name').value.trim();
if (name === '') {
alert('QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]');
const name = $("name").value.trim();
if (name === "") {
alert("QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]");
return;
}
$('submitButton').disabled = true;
$("submitButton").disabled = true;
new Request({
url: 'api/v2/rss/setRule',
method: 'post',
url: "api/v2/rss/setRule",
method: "post",
data: {
ruleName: name,
ruleDef: '{}'
ruleDef: "{}"
},
onSuccess: (response) => {
window.parent.qBittorrent.RssDownloader.updateRulesList();
window.parent.MochaUI.closeWindow(window.parent.$('newRulePage'));
window.parent.MochaUI.closeWindow(window.parent.$("newRulePage"));
}
}).send();
});

View file

@ -9,39 +9,39 @@
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(event) {
$('tagNameButton').click();
"Enter": function(event) {
$("tagNameButton").click();
event.preventDefault();
},
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', function() {
const uriAction = window.qBittorrent.Misc.safeTrim(new URI().getData('action'));
const uriHashes = window.qBittorrent.Misc.safeTrim(new URI().getData('hashes'));
window.addEvent("domready", () => {
const uriAction = window.qBittorrent.Misc.safeTrim(new URI().getData("action"));
const uriHashes = window.qBittorrent.Misc.safeTrim(new URI().getData("hashes"));
if (uriAction === 'create')
$('legendText').innerText = 'QBT_TR(Tag:)QBT_TR[CONTEXT=TagFilterWidget]';
if (uriAction === "create")
$("legendText").innerText = "QBT_TR(Tag:)QBT_TR[CONTEXT=TagFilterWidget]";
$('tagName').focus();
$("tagName").focus();
$('tagNameButton').addEvent('click', function(e) {
$("tagNameButton").addEvent("click", (e) => {
new Event(e).stop();
const tagName = $('tagName').value.trim();
const tagName = $("tagName").value.trim();
const verifyTagName = function(name) {
if ((name === null) || (name === ""))
@ -59,8 +59,8 @@
return;
new Request({
url: 'api/v2/torrents/addTags',
method: 'post',
url: "api/v2/torrents/addTags",
method: "post",
data: {
hashes: uriHashes,
tags: tagName,
@ -76,8 +76,8 @@
return;
new Request({
url: 'api/v2/torrents/createTags',
method: 'post',
url: "api/v2/torrents/createTags",
method: "post",
data: {
tags: tagName,
},

View file

@ -9,45 +9,45 @@
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(event) {
$('renameButton').click();
"Enter": function(event) {
$("renameButton").click();
event.preventDefault();
},
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', function() {
const name = new URI().getData('name');
window.addEvent("domready", () => {
const name = new URI().getData("name");
// set text field to current value
if (name)
$('rename').value = name;
$("rename").value = name;
$('rename').focus();
$('renameButton').addEvent('click', function(e) {
$("rename").focus();
$("renameButton").addEvent("click", (e) => {
new Event(e).stop();
// check field
const name = $('rename').value.trim();
const name = $("rename").value.trim();
if ((name === null) || (name === ""))
return false;
const hash = new URI().getData('hash');
const hash = new URI().getData("hash");
if (hash) {
new Request({
url: 'api/v2/torrents/rename',
method: 'post',
url: "api/v2/torrents/rename",
method: "post",
data: {
hash: hash,
name: name

View file

@ -9,51 +9,51 @@
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': (event) => {
$('renameButton').click();
"Enter": (event) => {
$("renameButton").click();
event.preventDefault();
},
'Escape': (event) => {
"Escape": (event) => {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': (event) => {
"Esc": (event) => {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', () => {
const oldPath = new URI().getData('oldPath');
window.addEvent("domready", () => {
const oldPath = new URI().getData("oldPath");
$('rename').value = oldPath;
$('rename').focus();
$('rename').setSelectionRange(0, oldPath.length);
$("rename").value = oldPath;
$("rename").focus();
$("rename").setSelectionRange(0, oldPath.length);
$('renameButton').addEvent('click', (e) => {
$("renameButton").addEvent("click", (e) => {
new Event(e).stop();
// check field
const newPath = $('rename').value.trim();
if (newPath === '') {
alert('QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]');
const newPath = $("rename").value.trim();
if (newPath === "") {
alert("QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]");
return;
}
if (newPath === oldPath) {
alert('QBT_TR(Name is unchanged)QBT_TR[CONTEXT=HttpServer]');
alert("QBT_TR(Name is unchanged)QBT_TR[CONTEXT=HttpServer]");
return;
}
$('renameButton').disabled = true;
$("renameButton").disabled = true;
new Request({
url: 'api/v2/rss/moveItem',
method: 'post',
url: "api/v2/rss/moveItem",
method: "post",
data: {
itemPath: oldPath,
destPath: newPath
@ -66,7 +66,7 @@
if (response.status === 409) {
alert(response.responseText);
}
$('renameButton').disabled = false;
$("renameButton").disabled = false;
}
}).send();
});

View file

@ -10,60 +10,60 @@
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script src="scripts/filesystem.js?v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(event) {
$('renameButton').click();
"Enter": function(event) {
$("renameButton").click();
event.preventDefault();
},
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', function() {
const hash = new URI().getData('hash');
const oldPath = new URI().getData('path');
const isFolder = ((new URI().getData('isFolder')) === 'true');
window.addEvent("domready", () => {
const hash = new URI().getData("hash");
const oldPath = new URI().getData("path");
const isFolder = ((new URI().getData("isFolder")) === "true");
const oldName = window.qBittorrent.Filesystem.fileName(oldPath);
$('rename').value = oldName;
$('rename').focus();
$("rename").value = oldName;
$("rename").focus();
if (!isFolder)
$('rename').setSelectionRange(0, oldName.lastIndexOf('.'));
$("rename").setSelectionRange(0, oldName.lastIndexOf("."));
$('renameButton').addEvent('click', function(e) {
$("renameButton").addEvent("click", (e) => {
new Event(e).stop();
// check field
const newName = $('rename').value.trim();
if (newName === '') {
alert('QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]');
const newName = $("rename").value.trim();
if (newName === "") {
alert("QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]");
return;
}
if (newName === oldName) {
alert('QBT_TR(Name is unchanged)QBT_TR[CONTEXT=HttpServer]');
alert("QBT_TR(Name is unchanged)QBT_TR[CONTEXT=HttpServer]");
return;
}
$('renameButton').disabled = true;
$("renameButton").disabled = true;
const parentPath = window.qBittorrent.Filesystem.folderName(oldPath);
const newPath = parentPath
? parentPath + window.qBittorrent.Filesystem.PathSeparator + newName
: newName;
new Request({
url: isFolder ? 'api/v2/torrents/renameFolder' : 'api/v2/torrents/renameFile',
method: 'post',
url: isFolder ? "api/v2/torrents/renameFolder" : "api/v2/torrents/renameFile",
method: "post",
data: {
hash: hash,
oldPath: oldPath,
@ -73,8 +73,8 @@
window.parent.qBittorrent.Client.closeWindows();
},
onFailure: function() {
alert('QBT_TR(Failed to update name)QBT_TR[CONTEXT=HttpServer]');
$('renameButton').disabled = false;
alert("QBT_TR(Failed to update name)QBT_TR[CONTEXT=HttpServer]");
$("renameButton").disabled = false;
}
}).send();
});

View file

@ -12,23 +12,23 @@
<script src="scripts/dynamicTable.js?locale=${LANG}&v=${CACHEID}"></script>
<script src="scripts/rename-files.js?v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
if (window.parent.qBittorrent !== undefined) {
window.qBittorrent = window.parent.qBittorrent;
}
window.qBittorrent = window.parent.qBittorrent;
var TriState = window.qBittorrent.FileTree.TriState;
var data = window.MUI.Windows.instances['multiRenamePage'].options.data;
var bulkRenameFilesContextMenu;
const TriState = window.qBittorrent.FileTree.TriState;
const data = window.MUI.Windows.instances["multiRenamePage"].options.data;
let bulkRenameFilesContextMenu;
if (!bulkRenameFilesContextMenu) {
bulkRenameFilesContextMenu = new window.qBittorrent.ContextMenu.ContextMenu({
targets: '#bulkRenameFilesTableDiv tr',
menu: 'multiRenameFilesMenu',
targets: "#bulkRenameFilesTableDiv tr",
menu: "multiRenameFilesMenu",
actions: {
ToggleSelection: function(element, ref) {
const rowId = parseInt(element.get('data-row-id'));
const rowId = parseInt(element.get("data-row-id"), 10);
const row = bulkRenameFilesTable.getNode(rowId);
const checkState = (row.checked === 1) ? 0 : 1;
bulkRenameFilesTable.toggleNodeTreeCheckbox(rowId, checkState);
@ -44,20 +44,20 @@
}
// Setup the dynamic table for bulk renaming
var bulkRenameFilesTable = new window.qBittorrent.DynamicTable.BulkRenameTorrentFilesTable();
bulkRenameFilesTable.setup('bulkRenameFilesTableDiv', 'bulkRenameFilesTableFixedHeaderDiv', bulkRenameFilesContextMenu);
const bulkRenameFilesTable = new window.qBittorrent.DynamicTable.BulkRenameTorrentFilesTable();
bulkRenameFilesTable.setup("bulkRenameFilesTableDiv", "bulkRenameFilesTableFixedHeaderDiv", bulkRenameFilesContextMenu);
// Inject checkbox into the first column of the table header
var tableHeaders = $$('#bulkRenameFilesTableFixedHeaderDiv .dynamicTableHeader th');
var checkboxHeader;
const tableHeaders = $$("#bulkRenameFilesTableFixedHeaderDiv .dynamicTableHeader th");
let checkboxHeader;
if (tableHeaders.length > 0) {
if (checkboxHeader) {
checkboxHeader.remove();
}
checkboxHeader = new Element('input');
checkboxHeader.set('type', 'checkbox');
checkboxHeader.set('id', 'rootMultiRename_cb');
checkboxHeader.addEvent('click', function(e) {
checkboxHeader = new Element("input");
checkboxHeader.set("type", "checkbox");
checkboxHeader.set("id", "rootMultiRename_cb");
checkboxHeader.addEvent("click", (e) => {
bulkRenameFilesTable.toggleGlobalCheckbox();
fileRenamer.selectedFiles = bulkRenameFilesTable.getSelectedRows();
fileRenamer.update();
@ -69,16 +69,16 @@
// Register keyboard events to modal window
// https://github.com/qbittorrent/qBittorrent/pull/18687#discussion_r1135045726
var keyboard;
let keyboard;
if (!keyboard) {
keyboard = new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
@ -87,55 +87,55 @@
keyboard.activate();
}
var fileRenamer = new window.qBittorrent.MultiRename.RenameFiles();
const fileRenamer = new window.qBittorrent.MultiRename.RenameFiles();
fileRenamer.hash = data.hash;
// Load Multi Rename Preferences
var multiRenamePrefChecked = LocalPreferences.get('multirename_rememberPreferences', "true") === "true";
$('multirename_rememberprefs_checkbox').setProperty('checked', multiRenamePrefChecked);
const multiRenamePrefChecked = LocalPreferences.get("multirename_rememberPreferences", "true") === "true";
$("multirename_rememberprefs_checkbox").setProperty("checked", multiRenamePrefChecked);
if (multiRenamePrefChecked) {
var multirename_search = LocalPreferences.get('multirename_search', '');
const multirename_search = LocalPreferences.get("multirename_search", "");
fileRenamer.setSearch(multirename_search);
$('multiRenameSearch').set('value', multirename_search);
$("multiRenameSearch").set("value", multirename_search);
var multirename_useRegex = LocalPreferences.get('multirename_useRegex', false);
fileRenamer.useRegex = multirename_useRegex === 'true';
$('use_regex_search').checked = fileRenamer.useRegex;
const multirename_useRegex = LocalPreferences.get("multirename_useRegex", false);
fileRenamer.useRegex = multirename_useRegex === "true";
$("use_regex_search").checked = fileRenamer.useRegex;
var multirename_matchAllOccurrences = LocalPreferences.get('multirename_matchAllOccurrences', false);
fileRenamer.matchAllOccurrences = multirename_matchAllOccurrences === 'true';
$('match_all_occurrences').checked = fileRenamer.matchAllOccurrences;
const multirename_matchAllOccurrences = LocalPreferences.get("multirename_matchAllOccurrences", false);
fileRenamer.matchAllOccurrences = multirename_matchAllOccurrences === "true";
$("match_all_occurrences").checked = fileRenamer.matchAllOccurrences;
var multirename_caseSensitive = LocalPreferences.get('multirename_caseSensitive', false);
fileRenamer.caseSensitive = multirename_caseSensitive === 'true';
$('case_sensitive').checked = fileRenamer.caseSensitive;
const multirename_caseSensitive = LocalPreferences.get("multirename_caseSensitive", false);
fileRenamer.caseSensitive = multirename_caseSensitive === "true";
$("case_sensitive").checked = fileRenamer.caseSensitive;
var multirename_replace = LocalPreferences.get('multirename_replace', '');
const multirename_replace = LocalPreferences.get("multirename_replace", "");
fileRenamer.setReplacement(multirename_replace);
$('multiRenameReplace').set('value', multirename_replace);
$("multiRenameReplace").set("value", multirename_replace);
var multirename_appliesTo = LocalPreferences.get('multirename_appliesTo', window.qBittorrent.MultiRename.AppliesTo.FilenameExtension);
const multirename_appliesTo = LocalPreferences.get("multirename_appliesTo", window.qBittorrent.MultiRename.AppliesTo.FilenameExtension);
fileRenamer.appliesTo = window.qBittorrent.MultiRename.AppliesTo[multirename_appliesTo];
$('applies_to_option').set('value', fileRenamer.appliesTo);
$("applies_to_option").set("value", fileRenamer.appliesTo);
var multirename_includeFiles = LocalPreferences.get('multirename_includeFiles', true);
fileRenamer.includeFiles = multirename_includeFiles === 'true';
$('include_files').checked = fileRenamer.includeFiles;
const multirename_includeFiles = LocalPreferences.get("multirename_includeFiles", true);
fileRenamer.includeFiles = multirename_includeFiles === "true";
$("include_files").checked = fileRenamer.includeFiles;
var multirename_includeFolders = LocalPreferences.get('multirename_includeFolders', false);
fileRenamer.includeFolders = multirename_includeFolders === 'true';
$('include_folders').checked = fileRenamer.includeFolders;
const multirename_includeFolders = LocalPreferences.get("multirename_includeFolders", false);
fileRenamer.includeFolders = multirename_includeFolders === "true";
$("include_folders").checked = fileRenamer.includeFolders;
var multirename_fileEnumerationStart = LocalPreferences.get('multirename_fileEnumerationStart', 0);
fileRenamer.fileEnumerationStart = parseInt(multirename_fileEnumerationStart);
$('file_counter').set('value', fileRenamer.fileEnumerationStart);
const multirename_fileEnumerationStart = LocalPreferences.get("multirename_fileEnumerationStart", 0);
fileRenamer.fileEnumerationStart = parseInt(multirename_fileEnumerationStart, 10);
$("file_counter").set("value", fileRenamer.fileEnumerationStart);
var multirename_replaceAll = LocalPreferences.get('multirename_replaceAll', false);
fileRenamer.replaceAll = multirename_replaceAll === 'true';
var renameButtonValue = fileRenamer.replaceAll ? 'Replace All' : 'Replace';
$('renameOptions').set('value', renameButtonValue);
$('renameButton').set('value', renameButtonValue);
const multirename_replaceAll = LocalPreferences.get("multirename_replaceAll", false);
fileRenamer.replaceAll = multirename_replaceAll === "true";
const renameButtonValue = fileRenamer.replaceAll ? "Replace All" : "Replace";
$("renameOptions").set("value", renameButtonValue);
$("renameButton").set("value", renameButtonValue);
}
// Fires every time a row's selection changes
@ -145,28 +145,28 @@
};
// Setup Search Events that control renaming
$('multiRenameSearch').addEvent('input', function(e) {
let sanitized = e.target.value.replace(/\n/g, '');
$('multiRenameSearch').set('value', sanitized);
$("multiRenameSearch").addEvent("input", (e) => {
const sanitized = e.target.value.replace(/\n/g, "");
$("multiRenameSearch").set("value", sanitized);
// Search input has changed
$('multiRenameSearch').style['border-color'] = '';
LocalPreferences.set('multirename_search', sanitized);
$("multiRenameSearch").style["border-color"] = "";
LocalPreferences.set("multirename_search", sanitized);
fileRenamer.setSearch(sanitized);
});
$('use_regex_search').addEvent('change', function(e) {
$("use_regex_search").addEvent("change", (e) => {
fileRenamer.useRegex = e.target.checked;
LocalPreferences.set('multirename_useRegex', e.target.checked);
LocalPreferences.set("multirename_useRegex", e.target.checked);
fileRenamer.update();
});
$('match_all_occurrences').addEvent('change', function(e) {
$("match_all_occurrences").addEvent("change", (e) => {
fileRenamer.matchAllOccurrences = e.target.checked;
LocalPreferences.set('multirename_matchAllOccurrences', e.target.checked);
LocalPreferences.set("multirename_matchAllOccurrences", e.target.checked);
fileRenamer.update();
});
$('case_sensitive').addEvent('change', function(e) {
$("case_sensitive").addEvent("change", (e) => {
fileRenamer.caseSensitive = e.target.checked;
LocalPreferences.set('multirename_caseSensitive', e.target.checked);
LocalPreferences.set("multirename_caseSensitive", e.target.checked);
fileRenamer.update();
});
@ -177,95 +177,95 @@
// Clear renamed column
document
.querySelectorAll("span[id^='filesTablefileRenamed']")
.forEach(function(span) {
span.set('text', "");
.forEach((span) => {
span.set("text", "");
});
// Update renamed column for matched rows
for (let i = 0; i < matchedRows.length; ++i) {
const row = matchedRows[i];
$('filesTablefileRenamed' + row.rowId).set('text', row.renamed);
$("filesTablefileRenamed" + row.rowId).set("text", row.renamed);
}
};
fileRenamer.onInvalidRegex = function(err) {
$('multiRenameSearch').style['border-color'] = '#CC0033';
$("multiRenameSearch").style["border-color"] = "#CC0033";
};
// Setup Replace Events that control renaming
$('multiRenameReplace').addEvent('input', function(e) {
let sanitized = e.target.value.replace(/\n/g, '');
$('multiRenameReplace').set('value', sanitized);
$("multiRenameReplace").addEvent("input", (e) => {
const sanitized = e.target.value.replace(/\n/g, "");
$("multiRenameReplace").set("value", sanitized);
// Replace input has changed
$('multiRenameReplace').style['border-color'] = '';
LocalPreferences.set('multirename_replace', sanitized);
$("multiRenameReplace").style["border-color"] = "";
LocalPreferences.set("multirename_replace", sanitized);
fileRenamer.setReplacement(sanitized);
});
$('applies_to_option').addEvent('change', function(e) {
$("applies_to_option").addEvent("change", (e) => {
fileRenamer.appliesTo = e.target.value;
LocalPreferences.set('multirename_appliesTo', e.target.value);
LocalPreferences.set("multirename_appliesTo", e.target.value);
fileRenamer.update();
});
$('include_files').addEvent('change', function(e) {
$("include_files").addEvent("change", (e) => {
fileRenamer.includeFiles = e.target.checked;
LocalPreferences.set('multirename_includeFiles', e.target.checked);
LocalPreferences.set("multirename_includeFiles", e.target.checked);
fileRenamer.update();
});
$('include_folders').addEvent('change', function(e) {
$("include_folders").addEvent("change", (e) => {
fileRenamer.includeFolders = e.target.checked;
LocalPreferences.set('multirename_includeFolders', e.target.checked);
LocalPreferences.set("multirename_includeFolders", e.target.checked);
fileRenamer.update();
});
$('file_counter').addEvent('input', function(e) {
$("file_counter").addEvent("input", (e) => {
let value = e.target.valueAsNumber;
if (!value) { value = 0; }
if (value < 0) { value = 0; }
if (value > 99999999) { value = 99999999; }
fileRenamer.fileEnumerationStart = value;
$('file_counter').set('value', value);
LocalPreferences.set('multirename_fileEnumerationStart', value);
$("file_counter").set("value", value);
LocalPreferences.set("multirename_fileEnumerationStart", value);
fileRenamer.update();
});
// Setup Rename Operation Events
$('renameButton').addEvent('click', function(e) {
$("renameButton").addEvent("click", (e) => {
// Disable Search Options
$('multiRenameSearch').disabled = true;
$('use_regex_search').disabled = true;
$('match_all_occurrences').disabled = true;
$('case_sensitive').disabled = true;
$("multiRenameSearch").disabled = true;
$("use_regex_search").disabled = true;
$("match_all_occurrences").disabled = true;
$("case_sensitive").disabled = true;
// Disable Replace Options
$('multiRenameReplace').disabled = true;
$('applies_to_option').disabled = true;
$('include_files').disabled = true;
$('include_folders').disabled = true;
$('file_counter').disabled = true;
$("multiRenameReplace").disabled = true;
$("applies_to_option").disabled = true;
$("include_files").disabled = true;
$("include_folders").disabled = true;
$("file_counter").disabled = true;
// Disable Rename Buttons
$('renameButton').disabled = true;
$('renameOptions').disabled = true;
$("renameButton").disabled = true;
$("renameOptions").disabled = true;
// Clear error text
$('rename_error').set('text', '');
$("rename_error").set("text", "");
fileRenamer.rename();
});
fileRenamer.onRenamed = function(rows) {
// Disable Search Options
$('multiRenameSearch').disabled = false;
$('use_regex_search').disabled = false;
$('match_all_occurrences').disabled = false;
$('case_sensitive').disabled = false;
$("multiRenameSearch").disabled = false;
$("use_regex_search").disabled = false;
$("match_all_occurrences").disabled = false;
$("case_sensitive").disabled = false;
// Disable Replace Options
$('multiRenameReplace').disabled = false;
$('applies_to_option').disabled = false;
$('include_files').disabled = false;
$('include_folders').disabled = false;
$('file_counter').disabled = false;
$("multiRenameReplace").disabled = false;
$("applies_to_option").disabled = false;
$("include_files").disabled = false;
$("include_folders").disabled = false;
$("file_counter").disabled = false;
// Disable Rename Buttons
$('renameButton').disabled = false;
$('renameOptions').disabled = false;
$("renameButton").disabled = false;
$("renameOptions").disabled = false;
// Recreate table
let selectedRows = bulkRenameFilesTable.getSelectedRows().map(row => row.rowId.toString());
for (let renamedRow of rows) {
for (const renamedRow of rows) {
selectedRows = selectedRows.filter(selectedRow => selectedRow !== renamedRow.rowId.toString());
}
bulkRenameFilesTable.clear();
@ -273,16 +273,16 @@
// Adjust file enumeration count by 1 when replacing single files to prevent naming conflicts
if (!fileRenamer.replaceAll) {
fileRenamer.fileEnumerationStart++;
$('file_counter').set('value', fileRenamer.fileEnumerationStart);
$("file_counter").set("value", fileRenamer.fileEnumerationStart);
}
setupTable(selectedRows);
};
fileRenamer.onRenameError = function(err, row) {
if (err.xhr.status === 409) {
$('rename_error').set('text', `QBT_TR(Rename failed: file or folder already exists)QBT_TR[CONTEXT=PropertiesWidget] \`${row.renamed}\``);
$("rename_error").set("text", `QBT_TR(Rename failed: file or folder already exists)QBT_TR[CONTEXT=PropertiesWidget] \`${row.renamed}\``);
}
};
$('renameOptions').addEvent('change', function(e) {
$("renameOptions").addEvent("change", (e) => {
const combobox = e.target;
const replaceOperation = combobox.value;
if (replaceOperation === "Replace") {
@ -294,21 +294,21 @@
else {
fileRenamer.replaceAll = false;
}
LocalPreferences.set('multirename_replaceAll', fileRenamer.replaceAll);
$('renameButton').set('value', replaceOperation);
LocalPreferences.set("multirename_replaceAll", fileRenamer.replaceAll);
$("renameButton").set("value", replaceOperation);
});
$('closeButton').addEvent('click', function() {
$("closeButton").addEvent("click", () => {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
});
// synchronize header scrolling to table body
$('bulkRenameFilesTableDiv').onscroll = function() {
$("bulkRenameFilesTableDiv").onscroll = function() {
const length = $(this).scrollLeft;
$('bulkRenameFilesTableFixedHeaderDiv').scrollLeft = length;
$("bulkRenameFilesTableFixedHeaderDiv").scrollLeft = length;
};
var handleTorrentFiles = function(files, selectedRows) {
const rows = files.map(function(file, index) {
const handleTorrentFiles = function(files, selectedRows) {
const rows = files.map((file, index) => {
const row = {
fileId: index,
@ -325,18 +325,18 @@
addRowsToTable(rows, selectedRows);
};
var addRowsToTable = function(rows, selectedRows) {
const addRowsToTable = function(rows, selectedRows) {
let rowId = 0;
const rootNode = new window.qBittorrent.FileTree.FolderNode();
rootNode.autoCheckFolders = false;
rows.forEach(function(row) {
rows.forEach((row) => {
const pathItems = row.path.split(window.qBittorrent.Filesystem.PathSeparator);
pathItems.pop(); // remove last item (i.e. file name)
let parent = rootNode;
pathItems.forEach(function(folderName) {
if (folderName === '.unwanted') {
pathItems.forEach((folderName) => {
if (folderName === ".unwanted") {
return;
}
@ -394,11 +394,11 @@
fileRenamer.update();
};
var setupTable = function(selectedRows) {
const setupTable = function(selectedRows) {
new Request.JSON({
url: new URI('api/v2/torrents/files?hash=' + data.hash),
url: new URI("api/v2/torrents/files?hash=" + data.hash),
noCache: true,
method: 'get',
method: "get",
onSuccess: function(files) {
if (files.length === 0) {
bulkRenameFilesTable.clear();

View file

@ -9,57 +9,57 @@
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': (event) => {
$('renameButton').click();
"Enter": (event) => {
$("renameButton").click();
event.preventDefault();
},
'Escape': (event) => {
window.parent.MochaUI.closeWindow(window.parent.$('renameRulePage'));
"Escape": (event) => {
window.parent.MochaUI.closeWindow(window.parent.$("renameRulePage"));
event.preventDefault();
},
'Esc': (event) => {
window.parent.MochaUI.closeWindow(window.parent.$('renameRulePage'));
"Esc": (event) => {
window.parent.MochaUI.closeWindow(window.parent.$("renameRulePage"));
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', () => {
const oldName = new URI().getData('rule');
window.addEvent("domready", () => {
const oldName = new URI().getData("rule");
$('rename').value = oldName;
$('rename').focus();
$('rename').setSelectionRange(0, oldName.length);
$("rename").value = oldName;
$("rename").focus();
$("rename").setSelectionRange(0, oldName.length);
$('renameButton').addEvent('click', (e) => {
$("renameButton").addEvent("click", (e) => {
new Event(e).stop();
// check field
const newName = $('rename').value.trim();
if (newName === '') {
alert('QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]');
const newName = $("rename").value.trim();
if (newName === "") {
alert("QBT_TR(Name cannot be empty)QBT_TR[CONTEXT=HttpServer]");
return;
}
if (newName === oldName) {
alert('QBT_TR(Name is unchanged)QBT_TR[CONTEXT=HttpServer]');
alert("QBT_TR(Name is unchanged)QBT_TR[CONTEXT=HttpServer]");
return;
}
$('renameButton').disabled = true;
$("renameButton").disabled = true;
new Request({
url: 'api/v2/rss/renameRule',
method: 'post',
url: "api/v2/rss/renameRule",
method: "post",
data: {
ruleName: oldName,
newRuleName: newName
},
onSuccess: (response) => {
window.parent.qBittorrent.RssDownloader.updateRulesList();
window.parent.MochaUI.closeWindow(window.parent.$('renameRulePage'));
window.parent.MochaUI.closeWindow(window.parent.$("renameRulePage"));
}
}).send();
});

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined)
window.qBittorrent = {};
@ -46,7 +46,7 @@ window.qBittorrent.Cache = (() => {
const keys = Reflect.ownKeys(obj);
for (const key of keys) {
const value = obj[key];
if ((value && (typeof value === 'object')) || (typeof value === 'function'))
if ((value && (typeof value === "object")) || (typeof value === "function"))
deepFreeze(value);
}
Object.freeze(obj);
@ -57,8 +57,8 @@ window.qBittorrent.Cache = (() => {
init() {
new Request.JSON({
url: 'api/v2/app/buildInfo',
method: 'get',
url: "api/v2/app/buildInfo",
method: "get",
noCache: true,
onSuccess: (responseJSON) => {
if (!responseJSON)
@ -84,11 +84,11 @@ window.qBittorrent.Cache = (() => {
// }
init(obj = {}) {
new Request.JSON({
url: 'api/v2/app/preferences',
method: 'get',
url: "api/v2/app/preferences",
method: "get",
noCache: true,
onFailure: (xhr) => {
if (typeof obj.onFailure === 'function')
if (typeof obj.onFailure === "function")
obj.onFailure(xhr);
},
onSuccess: (responseJSON, responseText) => {
@ -98,7 +98,7 @@ window.qBittorrent.Cache = (() => {
deepFreeze(responseJSON);
this.#m_store = responseJSON;
if (typeof obj.onSuccess === 'function')
if (typeof obj.onSuccess === "function")
obj.onSuccess(responseJSON, responseText);
}
}).send();
@ -114,19 +114,19 @@ window.qBittorrent.Cache = (() => {
// onSuccess: () => {}
// }
set(obj) {
if (typeof obj !== 'object')
throw new Error('`obj` is not an object.');
if (typeof obj.data !== 'object')
throw new Error('`data` is not an object.');
if (typeof obj !== "object")
throw new Error("`obj` is not an object.");
if (typeof obj.data !== "object")
throw new Error("`data` is not an object.");
new Request({
url: 'api/v2/app/setPreferences',
method: 'post',
url: "api/v2/app/setPreferences",
method: "post",
data: {
'json': JSON.stringify(obj.data)
"json": JSON.stringify(obj.data)
},
onFailure: (xhr) => {
if (typeof obj.onFailure === 'function')
if (typeof obj.onFailure === "function")
obj.onFailure(xhr);
},
onSuccess: (responseText, responseXML) => {
@ -140,7 +140,7 @@ window.qBittorrent.Cache = (() => {
}
deepFreeze(this.#m_store);
if (typeof obj.onSuccess === 'function')
if (typeof obj.onSuccess === "function")
obj.onSuccess(responseText, responseXML);
}
}).send();
@ -148,12 +148,12 @@ window.qBittorrent.Cache = (() => {
}
class QbtVersionCache {
#m_store = '';
#m_store = "";
init() {
new Request({
url: 'api/v2/app/version',
method: 'get',
url: "api/v2/app/version",
method: "get",
noCache: true,
onSuccess: (responseText) => {
if (!responseText)

File diff suppressed because it is too large Load diff

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -54,9 +54,9 @@ window.qBittorrent.ContextMenu = (function() {
//options
options: {
actions: {},
menu: 'menu_id',
menu: "menu_id",
stopEvent: true,
targets: 'body',
targets: "body",
offsets: {
x: 0,
y: 0
@ -79,14 +79,14 @@ window.qBittorrent.ContextMenu = (function() {
//fx
this.fx = new Fx.Tween(this.menu, {
property: 'opacity',
property: "opacity",
duration: this.options.fadeSpeed,
onComplete: function() {
if (this.getStyle('opacity')) {
this.setStyle('visibility', 'visible');
if (this.getStyle("opacity")) {
this.setStyle("visibility", "visible");
}
else {
this.setStyle('visibility', 'hidden');
this.setStyle("visibility", "hidden");
}
}.bind(this.menu)
});
@ -96,9 +96,9 @@ window.qBittorrent.ContextMenu = (function() {
//hide the menu
this.menu.setStyles({
'position': 'absolute',
'top': '-900000px',
'display': 'block'
"position": "absolute",
"top": "-900000px",
"display": "block"
});
},
@ -107,13 +107,13 @@ window.qBittorrent.ContextMenu = (function() {
const scrollableMenuMaxHeight = document.documentElement.clientHeight * 0.75;
if (this.menu.hasClass('scrollableMenu'))
this.menu.setStyle('max-height', scrollableMenuMaxHeight);
if (this.menu.hasClass("scrollableMenu"))
this.menu.setStyle("max-height", scrollableMenuMaxHeight);
// draw the menu off-screen to know the menu dimensions
this.menu.setStyles({
left: '-999em',
top: '-999em'
left: "-999em",
top: "-999em"
});
// position the menu
@ -130,16 +130,16 @@ window.qBittorrent.ContextMenu = (function() {
this.menu.setStyles({
left: xPosMenu,
top: yPosMenu,
position: 'absolute',
'z-index': '2000'
position: "absolute",
"z-index": "2000"
});
// position the sub-menu
const uls = this.menu.getElementsByTagName('ul');
const uls = this.menu.getElementsByTagName("ul");
for (let i = 0; i < uls.length; ++i) {
const ul = uls[i];
if (ul.hasClass('scrollableMenu'))
ul.setStyle('max-height', scrollableMenuMaxHeight);
if (ul.hasClass("scrollableMenu"))
ul.setStyle("max-height", scrollableMenuMaxHeight);
const rectParent = ul.parentNode.getBoundingClientRect();
const xPosOrigin = rectParent.left;
const yPosOrigin = rectParent.bottom;
@ -154,26 +154,26 @@ window.qBittorrent.ContextMenu = (function() {
if (yPos < 0)
yPos = 0;
ul.setStyles({
'margin-left': xPos - xPosOrigin,
'margin-top': yPos - yPosOrigin
"margin-left": xPos - xPosOrigin,
"margin-top": yPos - yPosOrigin
});
}
},
setupEventListeners: function(elem) {
elem.addEvent('contextmenu', function(e) {
elem.addEvent("contextmenu", (e) => {
this.triggerMenu(e, elem);
}.bind(this));
elem.addEvent('click', function(e) {
});
elem.addEvent("click", (e) => {
this.hide();
}.bind(this));
});
elem.addEvent('touchstart', function(e) {
elem.addEvent("touchstart", (e) => {
this.hide();
this.touchStartAt = performance.now();
this.touchStartEvent = e;
}.bind(this));
elem.addEvent('touchend', function(e) {
});
elem.addEvent("touchend", (e) => {
const now = performance.now();
const touchStartAt = this.touchStartAt;
const touchStartEvent = this.touchStartEvent;
@ -185,13 +185,13 @@ window.qBittorrent.ContextMenu = (function() {
if (((now - touchStartAt) >= this.options.touchTimer) && isTargetUnchanged) {
this.triggerMenu(touchStartEvent, elem);
}
}.bind(this));
});
},
addTarget: function(t) {
// prevent long press from selecting this text
t.style.setProperty('user-select', 'none');
t.style.setProperty('-webkit-user-select', 'none');
t.style.setProperty("user-select", "none");
t.style.setProperty("-webkit-user-select", "none");
this.targets[this.targets.length] = t;
this.setupEventListeners(t);
@ -215,25 +215,25 @@ window.qBittorrent.ContextMenu = (function() {
//get things started
startListener: function() {
/* all elements */
this.targets.each(function(el) {
this.targets.each((el) => {
this.setupEventListeners(el);
}.bind(this), this);
}, this);
/* menu items */
this.menu.getElements('a').each(function(item) {
item.addEvent('click', function(e) {
this.menu.getElements("a").each(function(item) {
item.addEvent("click", (e) => {
e.preventDefault();
if (!item.hasClass('disabled')) {
this.execute(item.get('href').split('#')[1], $(this.options.element));
this.fireEvent('click', [item, e]);
if (!item.hasClass("disabled")) {
this.execute(item.get("href").split("#")[1], $(this.options.element));
this.fireEvent("click", [item, e]);
}
}.bind(this));
});
}, this);
//hide on body click
$(document.body).addEvent('click', function() {
$(document.body).addEvent("click", () => {
this.hide();
}.bind(this));
});
},
updateMenuItems: function() {},
@ -243,40 +243,40 @@ window.qBittorrent.ContextMenu = (function() {
if (lastShownContextMenu && (lastShownContextMenu !== this))
lastShownContextMenu.hide();
this.fx.start(1);
this.fireEvent('show');
this.fireEvent("show");
lastShownContextMenu = this;
return this;
},
//hide the menu
hide: function(trigger) {
if (lastShownContextMenu && (lastShownContextMenu.menu.style.visibility !== 'hidden')) {
if (lastShownContextMenu && (lastShownContextMenu.menu.style.visibility !== "hidden")) {
this.fx.start(0);
//this.menu.fade('out');
this.fireEvent('hide');
this.fireEvent("hide");
}
return this;
},
setItemChecked: function(item, checked) {
this.menu.getElement('a[href$=' + item + ']').firstChild.style.opacity =
checked ? '1' : '0';
this.menu.getElement("a[href$=" + item + "]").firstChild.style.opacity =
checked ? "1" : "0";
return this;
},
getItemChecked: function(item) {
return this.menu.getElement('a[href$=' + item + ']').firstChild.style.opacity !== '0';
return this.menu.getElement("a[href$=" + item + "]").firstChild.style.opacity !== "0";
},
//hide an item
hideItem: function(item) {
this.menu.getElement('a[href$=' + item + ']').parentNode.addClass('invisible');
this.menu.getElement("a[href$=" + item + "]").parentNode.addClass("invisible");
return this;
},
//show an item
showItem: function(item) {
this.menu.getElement('a[href$=' + item + ']').parentNode.removeClass('invisible');
this.menu.getElement("a[href$=" + item + "]").parentNode.removeClass("invisible");
return this;
},
@ -323,37 +323,37 @@ window.qBittorrent.ContextMenu = (function() {
selectedRows.forEach((item, index) => {
const data = torrentsTable.rows.get(item).full_data;
if (data['seq_dl'] !== true)
if (data["seq_dl"] !== true)
all_are_seq_dl = false;
else
there_are_seq_dl = true;
if (data['f_l_piece_prio'] !== true)
if (data["f_l_piece_prio"] !== true)
all_are_f_l_piece_prio = false;
else
there_are_f_l_piece_prio = true;
if (data['progress'] !== 1.0) // not downloaded
if (data["progress"] !== 1.0) // not downloaded
all_are_downloaded = false;
else if (data['super_seeding'] !== true)
else if (data["super_seeding"] !== true)
all_are_super_seeding = false;
if ((data['state'] !== 'stoppedUP') && (data['state'] !== 'stoppedDL'))
if ((data["state"] !== "stoppedUP") && (data["state"] !== "stoppedDL"))
all_are_stopped = false;
else
there_are_stopped = true;
if (data['force_start'] !== true)
if (data["force_start"] !== true)
all_are_force_start = false;
else
there_are_force_start = true;
if (data['auto_tmm'] === true)
if (data["auto_tmm"] === true)
there_are_auto_tmm = true;
else
all_are_auto_tmm = false;
const torrentTags = data['tags'].split(', ');
const torrentTags = data["tags"].split(", ");
for (const tag of torrentTags) {
const count = tagCount.get(tag);
tagCount.set(tag, ((count !== undefined) ? (count + 1) : 1));
@ -363,71 +363,71 @@ window.qBittorrent.ContextMenu = (function() {
// hide renameFiles when more than 1 torrent is selected
if (selectedRows.length === 1) {
const data = torrentsTable.rows.get(selectedRows[0]).full_data;
let metadata_downloaded = !((data['state'] === 'metaDL') || (data['state'] === 'forcedMetaDL') || (data['total_size'] === -1));
const metadata_downloaded = !((data["state"] === "metaDL") || (data["state"] === "forcedMetaDL") || (data["total_size"] === -1));
// hide renameFiles when metadata hasn't been downloaded yet
metadata_downloaded
? this.showItem('renameFiles')
: this.hideItem('renameFiles');
? this.showItem("renameFiles")
: this.hideItem("renameFiles");
}
else {
this.hideItem('renameFiles');
this.hideItem("renameFiles");
}
if (all_are_downloaded) {
this.hideItem('downloadLimit');
this.menu.getElement('a[href$=uploadLimit]').parentNode.addClass('separator');
this.hideItem('sequentialDownload');
this.hideItem('firstLastPiecePrio');
this.showItem('superSeeding');
this.setItemChecked('superSeeding', all_are_super_seeding);
this.hideItem("downloadLimit");
this.menu.getElement("a[href$=uploadLimit]").parentNode.addClass("separator");
this.hideItem("sequentialDownload");
this.hideItem("firstLastPiecePrio");
this.showItem("superSeeding");
this.setItemChecked("superSeeding", all_are_super_seeding);
}
else {
const show_seq_dl = (all_are_seq_dl || !there_are_seq_dl);
const show_f_l_piece_prio = (all_are_f_l_piece_prio || !there_are_f_l_piece_prio);
if (!show_seq_dl && show_f_l_piece_prio)
this.menu.getElement('a[href$=firstLastPiecePrio]').parentNode.addClass('separator');
this.menu.getElement("a[href$=firstLastPiecePrio]").parentNode.addClass("separator");
else
this.menu.getElement('a[href$=firstLastPiecePrio]').parentNode.removeClass('separator');
this.menu.getElement("a[href$=firstLastPiecePrio]").parentNode.removeClass("separator");
if (show_seq_dl)
this.showItem('sequentialDownload');
this.showItem("sequentialDownload");
else
this.hideItem('sequentialDownload');
this.hideItem("sequentialDownload");
if (show_f_l_piece_prio)
this.showItem('firstLastPiecePrio');
this.showItem("firstLastPiecePrio");
else
this.hideItem('firstLastPiecePrio');
this.hideItem("firstLastPiecePrio");
this.setItemChecked('sequentialDownload', all_are_seq_dl);
this.setItemChecked('firstLastPiecePrio', all_are_f_l_piece_prio);
this.setItemChecked("sequentialDownload", all_are_seq_dl);
this.setItemChecked("firstLastPiecePrio", all_are_f_l_piece_prio);
this.showItem('downloadLimit');
this.menu.getElement('a[href$=uploadLimit]').parentNode.removeClass('separator');
this.hideItem('superSeeding');
this.showItem("downloadLimit");
this.menu.getElement("a[href$=uploadLimit]").parentNode.removeClass("separator");
this.hideItem("superSeeding");
}
this.showItem('start');
this.showItem('stop');
this.showItem('forceStart');
this.showItem("start");
this.showItem("stop");
this.showItem("forceStart");
if (all_are_stopped)
this.hideItem('stop');
this.hideItem("stop");
else if (all_are_force_start)
this.hideItem('forceStart');
this.hideItem("forceStart");
else if (!there_are_stopped && !there_are_force_start)
this.hideItem('start');
this.hideItem("start");
if (!all_are_auto_tmm && there_are_auto_tmm) {
this.hideItem('autoTorrentManagement');
this.hideItem("autoTorrentManagement");
}
else {
this.showItem('autoTorrentManagement');
this.setItemChecked('autoTorrentManagement', all_are_auto_tmm);
this.showItem("autoTorrentManagement");
this.setItemChecked("autoTorrentManagement", all_are_auto_tmm);
}
const contextTagList = $('contextTagList');
const contextTagList = $("contextTagList");
tagList.forEach((tag, tagHash) => {
const checkbox = contextTagList.getElement(`a[href="#Tag/${tagHash}"] input[type="checkbox"]`);
const count = tagCount.get(tag.name);
@ -439,12 +439,12 @@ window.qBittorrent.ContextMenu = (function() {
},
updateCategoriesSubMenu: function(categoryList) {
const contextCategoryList = $('contextCategoryList');
const contextCategoryList = $("contextCategoryList");
contextCategoryList.getChildren().each(c => c.destroy());
contextCategoryList.appendChild(new Element('li', {
contextCategoryList.appendChild(new Element("li", {
html: '<a href="javascript:torrentNewCategoryFN();"><img src="images/list-add.svg" alt="QBT_TR(New...)QBT_TR[CONTEXT=TransferListWidget]"/> QBT_TR(New...)QBT_TR[CONTEXT=TransferListWidget]</a>'
}));
contextCategoryList.appendChild(new Element('li', {
contextCategoryList.appendChild(new Element("li", {
html: '<a href="javascript:torrentSetCategoryFN(0);"><img src="images/edit-clear.svg" alt="QBT_TR(Reset)QBT_TR[CONTEXT=TransferListWidget]"/> QBT_TR(Reset)QBT_TR[CONTEXT=TransferListWidget]</a>'
}));
@ -458,11 +458,11 @@ window.qBittorrent.ContextMenu = (function() {
let first = true;
for (const { categoryName, categoryHash } of sortedCategories) {
const el = new Element('li', {
const el = new Element("li", {
html: `<a href="javascript:torrentSetCategoryFN(${categoryHash});"><img src="images/view-categories.svg"/>${window.qBittorrent.Misc.escapeHtml(categoryName)}</a>`
});
if (first) {
el.addClass('separator');
el.addClass("separator");
first = false;
}
contextCategoryList.appendChild(el);
@ -470,21 +470,21 @@ window.qBittorrent.ContextMenu = (function() {
},
updateTagsSubMenu: function(tagList) {
const contextTagList = $('contextTagList');
const contextTagList = $("contextTagList");
while (contextTagList.firstChild !== null)
contextTagList.removeChild(contextTagList.firstChild);
contextTagList.appendChild(new Element('li', {
contextTagList.appendChild(new Element("li", {
html: '<a href="javascript:torrentAddTagsFN();">'
+ '<img src="images/list-add.svg" alt="QBT_TR(Add...)QBT_TR[CONTEXT=TransferListWidget]"/>'
+ ' QBT_TR(Add...)QBT_TR[CONTEXT=TransferListWidget]'
+ '</a>'
+ " QBT_TR(Add...)QBT_TR[CONTEXT=TransferListWidget]"
+ "</a>"
}));
contextTagList.appendChild(new Element('li', {
contextTagList.appendChild(new Element("li", {
html: '<a href="javascript:torrentRemoveAllTagsFN();">'
+ '<img src="images/edit-clear.svg" alt="QBT_TR(Remove All)QBT_TR[CONTEXT=TransferListWidget]"/>'
+ ' QBT_TR(Remove All)QBT_TR[CONTEXT=TransferListWidget]'
+ '</a>'
+ " QBT_TR(Remove All)QBT_TR[CONTEXT=TransferListWidget]"
+ "</a>"
}));
const sortedTags = [];
@ -496,13 +496,13 @@ window.qBittorrent.ContextMenu = (function() {
for (let i = 0; i < sortedTags.length; ++i) {
const { tagName, tagHash } = sortedTags[i];
const el = new Element('li', {
const el = new Element("li", {
html: `<a href="#Tag/${tagHash}" onclick="event.preventDefault(); torrentSetTagsFN(${tagHash}, !event.currentTarget.getElement('input[type=checkbox]').checked);">`
+ '<input type="checkbox" onclick="this.checked = !this.checked;"> ' + window.qBittorrent.Misc.escapeHtml(tagName)
+ '</a>'
+ "</a>"
});
if (i === 0)
el.addClass('separator');
el.addClass("separator");
contextTagList.appendChild(el);
}
}
@ -513,19 +513,19 @@ window.qBittorrent.ContextMenu = (function() {
updateMenuItems: function() {
const id = Number(this.options.element.id);
if ((id !== CATEGORIES_ALL) && (id !== CATEGORIES_UNCATEGORIZED)) {
this.showItem('editCategory');
this.showItem('deleteCategory');
this.showItem("editCategory");
this.showItem("deleteCategory");
if (useSubcategories) {
this.showItem('createSubcategory');
this.showItem("createSubcategory");
}
else {
this.hideItem('createSubcategory');
this.hideItem("createSubcategory");
}
}
else {
this.hideItem('editCategory');
this.hideItem('deleteCategory');
this.hideItem('createSubcategory');
this.hideItem("editCategory");
this.hideItem("deleteCategory");
this.hideItem("createSubcategory");
}
}
});
@ -535,9 +535,9 @@ window.qBittorrent.ContextMenu = (function() {
updateMenuItems: function() {
const id = Number(this.options.element.id);
if ((id !== TAGS_ALL) && (id !== TAGS_UNTAGGED))
this.showItem('deleteTag');
this.showItem("deleteTag");
else
this.hideItem('deleteTag');
this.hideItem("deleteTag");
}
});
@ -552,77 +552,77 @@ window.qBittorrent.ContextMenu = (function() {
return i;
};
this.showItem('Enabled');
this.setItemChecked('Enabled', this.options.element.getChildren("td")[enabledColumnIndex()].get("html") === "Yes");
this.showItem("Enabled");
this.setItemChecked("Enabled", this.options.element.getChildren("td")[enabledColumnIndex()].get("html") === "Yes");
this.showItem('Uninstall');
this.showItem("Uninstall");
}
});
const RssFeedContextMenu = new Class({
Extends: ContextMenu,
updateMenuItems: function() {
let selectedRows = window.qBittorrent.Rss.rssFeedTable.selectedRowsIds();
this.menu.getElement('a[href$=newSubscription]').parentNode.addClass('separator');
const selectedRows = window.qBittorrent.Rss.rssFeedTable.selectedRowsIds();
this.menu.getElement("a[href$=newSubscription]").parentNode.addClass("separator");
switch (selectedRows.length) {
case 0:
// remove separator on top of newSubscription entry to avoid double line
this.menu.getElement('a[href$=newSubscription]').parentNode.removeClass('separator');
this.menu.getElement("a[href$=newSubscription]").parentNode.removeClass("separator");
// menu when nothing selected
this.hideItem('update');
this.hideItem('markRead');
this.hideItem('rename');
this.hideItem('delete');
this.showItem('newSubscription');
this.showItem('newFolder');
this.showItem('updateAll');
this.hideItem('copyFeedURL');
this.hideItem("update");
this.hideItem("markRead");
this.hideItem("rename");
this.hideItem("delete");
this.showItem("newSubscription");
this.showItem("newFolder");
this.showItem("updateAll");
this.hideItem("copyFeedURL");
break;
case 1:
if (selectedRows[0] === 0) {
// menu when "unread" feed selected
this.showItem('update');
this.showItem('markRead');
this.hideItem('rename');
this.hideItem('delete');
this.showItem('newSubscription');
this.hideItem('newFolder');
this.hideItem('updateAll');
this.hideItem('copyFeedURL');
this.showItem("update");
this.showItem("markRead");
this.hideItem("rename");
this.hideItem("delete");
this.showItem("newSubscription");
this.hideItem("newFolder");
this.hideItem("updateAll");
this.hideItem("copyFeedURL");
}
else if (window.qBittorrent.Rss.rssFeedTable.rows[selectedRows[0]].full_data.dataUid === '') {
else if (window.qBittorrent.Rss.rssFeedTable.rows[selectedRows[0]].full_data.dataUid === "") {
// menu when single folder selected
this.showItem('update');
this.showItem('markRead');
this.showItem('rename');
this.showItem('delete');
this.showItem('newSubscription');
this.showItem('newFolder');
this.hideItem('updateAll');
this.hideItem('copyFeedURL');
this.showItem("update");
this.showItem("markRead");
this.showItem("rename");
this.showItem("delete");
this.showItem("newSubscription");
this.showItem("newFolder");
this.hideItem("updateAll");
this.hideItem("copyFeedURL");
}
else {
// menu when single feed selected
this.showItem('update');
this.showItem('markRead');
this.showItem('rename');
this.showItem('delete');
this.showItem('newSubscription');
this.hideItem('newFolder');
this.hideItem('updateAll');
this.showItem('copyFeedURL');
this.showItem("update");
this.showItem("markRead");
this.showItem("rename");
this.showItem("delete");
this.showItem("newSubscription");
this.hideItem("newFolder");
this.hideItem("updateAll");
this.showItem("copyFeedURL");
}
break;
default:
// menu when multiple items selected
this.showItem('update');
this.showItem('markRead');
this.hideItem('rename');
this.showItem('delete');
this.hideItem('newSubscription');
this.hideItem('newFolder');
this.hideItem('updateAll');
this.showItem('copyFeedURL');
this.showItem("update");
this.showItem("markRead");
this.hideItem("rename");
this.showItem("delete");
this.hideItem("newSubscription");
this.hideItem("newFolder");
this.hideItem("updateAll");
this.showItem("copyFeedURL");
break;
}
}
@ -639,12 +639,12 @@ window.qBittorrent.ContextMenu = (function() {
// draw the menu off-screen to know the menu dimensions
this.menu.setStyles({
left: '-999em',
top: '-999em'
left: "-999em",
top: "-999em"
});
// position the menu
let xPosMenu = e.page.x + this.options.offsets.x - $('rssdownloaderpage').offsetLeft;
let yPosMenu = e.page.y + this.options.offsets.y - $('rssdownloaderpage').offsetTop;
let xPosMenu = e.page.x + this.options.offsets.x - $("rssdownloaderpage").offsetLeft;
let yPosMenu = e.page.y + this.options.offsets.y - $("rssdownloaderpage").offsetTop;
if ((xPosMenu + this.menu.offsetWidth) > document.documentElement.clientWidth)
xPosMenu -= this.menu.offsetWidth;
if ((yPosMenu + this.menu.offsetHeight) > document.documentElement.clientHeight)
@ -655,31 +655,31 @@ window.qBittorrent.ContextMenu = (function() {
this.menu.setStyles({
left: xPosMenu,
top: yPosMenu,
position: 'absolute',
'z-index': '2000'
position: "absolute",
"z-index": "2000"
});
},
updateMenuItems: function() {
let selectedRows = window.qBittorrent.RssDownloader.rssDownloaderRulesTable.selectedRowsIds();
this.showItem('addRule');
const selectedRows = window.qBittorrent.RssDownloader.rssDownloaderRulesTable.selectedRowsIds();
this.showItem("addRule");
switch (selectedRows.length) {
case 0:
// menu when nothing selected
this.hideItem('deleteRule');
this.hideItem('renameRule');
this.hideItem('clearDownloadedEpisodes');
this.hideItem("deleteRule");
this.hideItem("renameRule");
this.hideItem("clearDownloadedEpisodes");
break;
case 1:
// menu when single item selected
this.showItem('deleteRule');
this.showItem('renameRule');
this.showItem('clearDownloadedEpisodes');
this.showItem("deleteRule");
this.showItem("renameRule");
this.showItem("clearDownloadedEpisodes");
break;
default:
// menu when multiple items selected
this.showItem('deleteRule');
this.hideItem('renameRule');
this.showItem('clearDownloadedEpisodes');
this.showItem("deleteRule");
this.hideItem("renameRule");
this.showItem("clearDownloadedEpisodes");
break;
}
}

View file

@ -21,7 +21,7 @@
* THE SOFTWARE.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -40,18 +40,21 @@ window.qBittorrent.Download = (function() {
const getCategories = function() {
new Request.JSON({
url: 'api/v2/torrents/categories',
method: 'get',
url: "api/v2/torrents/categories",
method: "get",
noCache: true,
onSuccess: function(data) {
if (data) {
categories = data;
for (const i in data) {
if (!Object.hasOwn(data, i))
continue;
const category = data[i];
const option = new Element("option");
option.set('value', category.name);
option.set('html', category.name);
$('categorySelect').appendChild(option);
option.set("value", category.name);
option.set("html", category.name);
$("categorySelect").appendChild(option);
}
}
}
@ -62,36 +65,36 @@ window.qBittorrent.Download = (function() {
const pref = window.parent.qBittorrent.Cache.preferences.get();
defaultSavePath = pref.save_path;
$('savepath').setProperty('value', defaultSavePath);
$('startTorrent').checked = !pref.add_stopped_enabled;
$('addToTopOfQueue').checked = pref.add_to_top_of_queue;
$("savepath").setProperty("value", defaultSavePath);
$("startTorrent").checked = !pref.add_stopped_enabled;
$("addToTopOfQueue").checked = pref.add_to_top_of_queue;
if (pref.auto_tmm_enabled === 1) {
$('autoTMM').selectedIndex = 1;
$('savepath').disabled = true;
$("autoTMM").selectedIndex = 1;
$("savepath").disabled = true;
}
else {
$('autoTMM').selectedIndex = 0;
$("autoTMM").selectedIndex = 0;
}
if (pref.torrent_stop_condition === "MetadataReceived") {
$('stopCondition').selectedIndex = 1;
$("stopCondition").selectedIndex = 1;
}
else if (pref.torrent_stop_condition === "FilesChecked") {
$('stopCondition').selectedIndex = 2;
$("stopCondition").selectedIndex = 2;
}
else {
$('stopCondition').selectedIndex = 0;
$("stopCondition").selectedIndex = 0;
}
if (pref.torrent_content_layout === "Subfolder") {
$('contentLayout').selectedIndex = 1;
$("contentLayout").selectedIndex = 1;
}
else if (pref.torrent_content_layout === "NoSubfolder") {
$('contentLayout').selectedIndex = 2;
$("contentLayout").selectedIndex = 2;
}
else {
$('contentLayout').selectedIndex = 0;
$("contentLayout").selectedIndex = 0;
}
};
@ -101,41 +104,41 @@ window.qBittorrent.Download = (function() {
item.nextElementSibling.value = "";
item.nextElementSibling.select();
if ($('autoTMM').selectedIndex === 1)
$('savepath').value = defaultSavePath;
if ($("autoTMM").selectedIndex === 1)
$("savepath").value = defaultSavePath;
}
else {
item.nextElementSibling.hidden = true;
const text = item.options[item.selectedIndex].textContent;
item.nextElementSibling.value = text;
if ($('autoTMM').selectedIndex === 1) {
if ($("autoTMM").selectedIndex === 1) {
const categoryName = item.value;
const category = categories[categoryName];
let savePath = defaultSavePath;
if (category !== undefined)
savePath = (category['savePath'] !== "") ? category['savePath'] : `${defaultSavePath}/${categoryName}`;
$('savepath').value = savePath;
savePath = (category["savePath"] !== "") ? category["savePath"] : `${defaultSavePath}/${categoryName}`;
$("savepath").value = savePath;
}
}
};
const changeTMM = function(item) {
if (item.selectedIndex === 1) {
$('savepath').disabled = true;
$("savepath").disabled = true;
const categorySelect = $('categorySelect');
const categorySelect = $("categorySelect");
const categoryName = categorySelect.options[categorySelect.selectedIndex].value;
const category = categories[categoryName];
$('savepath').value = (category === undefined) ? "" : category['savePath'];
$("savepath").value = (category === undefined) ? "" : category["savePath"];
}
else {
$('savepath').disabled = false;
$('savepath').value = defaultSavePath;
$("savepath").disabled = false;
$("savepath").value = defaultSavePath;
}
};
$(window).addEventListener("load", function() {
$(window).addEventListener("load", () => {
getPreferences();
getCategories();
});

File diff suppressed because it is too large Load diff

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -81,9 +81,9 @@ window.qBittorrent.FileTree = (function() {
this.nodeMap[node.rowId] = node;
}
node.children.each(function(child) {
node.children.each((child) => {
this.generateNodeMap(child);
}.bind(this));
});
},
getNode: function(rowId) {
@ -101,17 +101,17 @@ window.qBittorrent.FileTree = (function() {
*/
toArray: function() {
const nodes = [];
this.root.children.each(function(node) {
this.root.children.each((node) => {
this._getArrayOfNodes(node, nodes);
}.bind(this));
});
return nodes;
},
_getArrayOfNodes: function(node, array) {
array.push(node);
node.children.each(function(child) {
node.children.each((child) => {
this._getArrayOfNodes(child, array);
}.bind(this));
});
}
});
@ -161,7 +161,7 @@ window.qBittorrent.FileTree = (function() {
let isFirstFile = true;
this.children.each(function(node) {
this.children.each((node) => {
if (node.isFolder)
node.calculateSize();
@ -185,7 +185,7 @@ window.qBittorrent.FileTree = (function() {
progress += (node.progress * node.size);
availability += (node.availability * node.size);
}
}.bind(this));
});
this.size = size;
this.remaining = remaining;

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
// This file is the JavaScript implementation of base/utils/fs.cpp
@ -44,15 +44,15 @@ window.qBittorrent.Filesystem = (function() {
};
};
const PathSeparator = '/';
const PathSeparator = "/";
/**
* Returns the file extension part of a file name.
*/
const fileExtension = function(filename) {
const pointIndex = filename.lastIndexOf('.');
const pointIndex = filename.lastIndexOf(".");
if (pointIndex === -1)
return '';
return "";
return filename.substring(pointIndex + 1);
};
@ -66,7 +66,7 @@ window.qBittorrent.Filesystem = (function() {
const folderName = function(filepath) {
const slashIndex = filepath.lastIndexOf(PathSeparator);
if (slashIndex === -1)
return '';
return "";
return filepath.substring(0, slashIndex);
};

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -112,18 +112,18 @@ window.qBittorrent.Misc = (function() {
return "QBT_TR(< 1m)QBT_TR[CONTEXT=misc]";
let minutes = seconds / 60;
if (minutes < 60)
return "QBT_TR(%1m)QBT_TR[CONTEXT=misc]".replace("%1", parseInt(minutes));
return "QBT_TR(%1m)QBT_TR[CONTEXT=misc]".replace("%1", Math.floor(minutes));
let hours = minutes / 60;
minutes = minutes % 60;
minutes %= 60;
if (hours < 24)
return "QBT_TR(%1h %2m)QBT_TR[CONTEXT=misc]".replace("%1", parseInt(hours)).replace("%2", parseInt(minutes));
return "QBT_TR(%1h %2m)QBT_TR[CONTEXT=misc]".replace("%1", Math.floor(hours)).replace("%2", Math.floor(minutes));
let days = hours / 24;
hours = hours % 24;
hours %= 24;
if (days < 365)
return "QBT_TR(%1d %2h)QBT_TR[CONTEXT=misc]".replace("%1", parseInt(days)).replace("%2", parseInt(hours));
return "QBT_TR(%1d %2h)QBT_TR[CONTEXT=misc]".replace("%1", Math.floor(days)).replace("%2", Math.floor(hours));
const years = days / 365;
days = days % 365;
return "QBT_TR(%1y %2d)QBT_TR[CONTEXT=misc]".replace("%1", parseInt(years)).replace("%2", parseInt(days));
days %= 365;
return "QBT_TR(%1y %2d)QBT_TR[CONTEXT=misc]".replace("%1", Math.floor(years)).replace("%2", Math.floor(days));
};
const friendlyPercentage = function(value) {
@ -152,7 +152,7 @@ window.qBittorrent.Misc = (function() {
valid: false
};
if (typeof versionString !== 'string')
if (typeof versionString !== "string")
return failure;
const tryToNumber = (str) => {
@ -160,7 +160,7 @@ window.qBittorrent.Misc = (function() {
return (isNaN(num) ? str : num);
};
const ver = versionString.split('.', 4).map(val => tryToNumber(val));
const ver = versionString.split(".", 4).map(val => tryToNumber(val));
return {
valid: true,
major: ver[0],
@ -171,7 +171,7 @@ window.qBittorrent.Misc = (function() {
};
const escapeHtml = function(str) {
const div = document.createElement('div');
const div = document.createElement("div");
div.appendChild(document.createTextNode(str));
const escapedString = div.innerHTML;
div.remove();
@ -179,7 +179,7 @@ window.qBittorrent.Misc = (function() {
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#parameters
const naturalSortCollator = new Intl.Collator(undefined, { numeric: true, usage: 'sort' });
const naturalSortCollator = new Intl.Collator(undefined, { numeric: true, usage: "sort" });
const safeTrim = function(value) {
try {
@ -206,9 +206,9 @@ window.qBittorrent.Misc = (function() {
*/
const containsAllTerms = function(text, terms) {
const textToSearch = text.toLowerCase();
return terms.every(function(term) {
const isTermRequired = (term[0] === '+');
const isTermExcluded = (term[0] === '-');
return terms.every((term) => {
const isTermRequired = (term[0] === "+");
const isTermExcluded = (term[0] === "-");
if (isTermRequired || isTermExcluded) {
// ignore lonely +/-
if (term.length === 1)

View file

@ -36,7 +36,7 @@
it in the onContentLoaded function of the new window.
----------------------------------------------------------------- */
'use strict';
"use strict";
const LocalPreferences = new window.qBittorrent.LocalPreferences.LocalPreferencesClass();
@ -96,34 +96,34 @@ let exportTorrentFN = function() {};
const initializeWindows = function() {
saveWindowSize = function(windowId) {
const size = $(windowId).getSize();
LocalPreferences.set('window_' + windowId + '_width', size.x);
LocalPreferences.set('window_' + windowId + '_height', size.y);
LocalPreferences.set("window_" + windowId + "_width", size.x);
LocalPreferences.set("window_" + windowId + "_height", size.y);
};
loadWindowWidth = function(windowId, defaultValue) {
return LocalPreferences.get('window_' + windowId + '_width', defaultValue);
return LocalPreferences.get("window_" + windowId + "_width", defaultValue);
};
loadWindowHeight = function(windowId, defaultValue) {
return LocalPreferences.get('window_' + windowId + '_height', defaultValue);
return LocalPreferences.get("window_" + windowId + "_height", defaultValue);
};
function addClickEvent(el, fn) {
['Link', 'Button'].each(function(item) {
["Link", "Button"].each((item) => {
if ($(el + item)) {
$(el + item).addEvent('click', fn);
$(el + item).addEvent("click", fn);
}
});
}
addClickEvent('download', function(e) {
addClickEvent("download", (e) => {
new Event(e).stop();
showDownloadPage();
});
showDownloadPage = function(urls) {
const id = 'downloadPage';
let contentUri = new URI('download.html');
const id = "downloadPage";
const contentUri = new URI("download.html");
if (urls && (urls.length > 0)) {
contentUri.setData("urls", urls.map(encodeURIComponent).join("|"));
@ -132,9 +132,9 @@ const initializeWindows = function() {
new MochaUI.Window({
id: id,
title: "QBT_TR(Download from URLs)QBT_TR[CONTEXT=downloadFromURL]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: contentUri.toString(),
addClass: 'windowFrame', // fixes iframe scrolling on iOS Safari
addClass: "windowFrame", // fixes iframe scrolling on iOS Safari
scrollbars: true,
maximizable: false,
closable: true,
@ -149,19 +149,19 @@ const initializeWindows = function() {
updateMainData();
};
addClickEvent('preferences', function(e) {
addClickEvent("preferences", (e) => {
new Event(e).stop();
const id = 'preferencesPage';
const id = "preferencesPage";
new MochaUI.Window({
id: id,
title: "QBT_TR(Options)QBT_TR[CONTEXT=OptionsDialog]",
loadMethod: 'xhr',
loadMethod: "xhr",
toolbar: true,
contentURL: new URI("views/preferences.html").toString(),
require: {
css: ['css/Tabs.css']
css: ["css/Tabs.css"]
},
toolbarURL: 'views/preferencesToolbar.html',
toolbarURL: "views/preferencesToolbar.html",
maximizable: false,
closable: true,
paddingVertical: 0,
@ -174,15 +174,15 @@ const initializeWindows = function() {
});
});
addClickEvent('upload', function(e) {
addClickEvent("upload", (e) => {
new Event(e).stop();
const id = 'uploadPage';
const id = "uploadPage";
new MochaUI.Window({
id: id,
title: "QBT_TR(Upload local torrent)QBT_TR[CONTEXT=HttpServer]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("upload.html").toString(),
addClass: 'windowFrame', // fixes iframe scrolling on iOS Safari
addClass: "windowFrame", // fixes iframe scrolling on iOS Safari
scrollbars: true,
maximizable: false,
paddingVertical: 0,
@ -198,9 +198,9 @@ const initializeWindows = function() {
globalUploadLimitFN = function() {
new MochaUI.Window({
id: 'uploadLimitPage',
id: "uploadLimitPage",
title: "QBT_TR(Global Upload Speed Limit)QBT_TR[CONTEXT=MainWindow]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("uploadlimit.html").setData("hashes", "global").toString(),
scrollbars: false,
resizable: false,
@ -216,9 +216,9 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new MochaUI.Window({
id: 'uploadLimitPage',
id: "uploadLimitPage",
title: "QBT_TR(Torrent Upload Speed Limiting)QBT_TR[CONTEXT=TransferListWidget]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("uploadlimit.html").setData("hashes", hashes.join("|")).toString(),
scrollbars: false,
resizable: false,
@ -257,9 +257,9 @@ const initializeWindows = function() {
// if all torrents have same share ratio, display that share ratio. else use the default
const orig = torrentsHaveSameShareRatio ? shareRatio : "";
new MochaUI.Window({
id: 'shareRatioPage',
id: "shareRatioPage",
title: "QBT_TR(Torrent Upload/Download Ratio Limiting)QBT_TR[CONTEXT=UpDownRatioDialog]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("shareratio.html").setData("hashes", hashes.join("|")).setData("orig", orig).toString(),
scrollbars: false,
maximizable: false,
@ -275,8 +275,8 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new Request({
url: 'api/v2/torrents/toggleSequentialDownload',
method: 'post',
url: "api/v2/torrents/toggleSequentialDownload",
method: "post",
data: {
hashes: hashes.join("|")
}
@ -289,8 +289,8 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new Request({
url: 'api/v2/torrents/toggleFirstLastPiecePrio',
method: 'post',
url: "api/v2/torrents/toggleFirstLastPiecePrio",
method: "post",
data: {
hashes: hashes.join("|")
}
@ -303,8 +303,8 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new Request({
url: 'api/v2/torrents/setSuperSeeding',
method: 'post',
url: "api/v2/torrents/setSuperSeeding",
method: "post",
data: {
value: val,
hashes: hashes.join("|")
@ -318,10 +318,10 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new Request({
url: 'api/v2/torrents/setForceStart',
method: 'post',
url: "api/v2/torrents/setForceStart",
method: "post",
data: {
value: 'true',
value: "true",
hashes: hashes.join("|")
}
}).send();
@ -331,9 +331,9 @@ const initializeWindows = function() {
globalDownloadLimitFN = function() {
new MochaUI.Window({
id: 'downloadLimitPage',
id: "downloadLimitPage",
title: "QBT_TR(Global Download Speed Limit)QBT_TR[CONTEXT=MainWindow]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("downloadlimit.html").setData("hashes", "global").toString(),
scrollbars: false,
resizable: false,
@ -346,11 +346,11 @@ const initializeWindows = function() {
};
StatisticsLinkFN = function() {
const id = 'statisticspage';
const id = "statisticspage";
new MochaUI.Window({
id: id,
title: 'QBT_TR(Statistics)QBT_TR[CONTEXT=StatsDialog]',
loadMethod: 'xhr',
title: "QBT_TR(Statistics)QBT_TR[CONTEXT=StatsDialog]",
loadMethod: "xhr",
contentURL: new URI("views/statistics.html").toString(),
maximizable: false,
padding: 10,
@ -366,9 +366,9 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new MochaUI.Window({
id: 'downloadLimitPage',
id: "downloadLimitPage",
title: "QBT_TR(Torrent Download Speed Limiting)QBT_TR[CONTEXT=TransferListWidget]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("downloadlimit.html").setData("hashes", hashes.join("|")).toString(),
scrollbars: false,
resizable: false,
@ -385,9 +385,9 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new MochaUI.Window({
id: 'confirmDeletionPage',
id: "confirmDeletionPage",
title: "QBT_TR(Remove torrent(s))QBT_TR[CONTEXT=confirmDeletionDlg]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("confirmdeletion.html").setData("hashes", hashes.join("|")).setData("deleteFiles", deleteFiles).toString(),
scrollbars: false,
resizable: true,
@ -400,7 +400,7 @@ const initializeWindows = function() {
}
};
addClickEvent('delete', function(e) {
addClickEvent("delete", (e) => {
new Event(e).stop();
deleteFN();
});
@ -409,8 +409,8 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new Request({
url: 'api/v2/torrents/stop',
method: 'post',
url: "api/v2/torrents/stop",
method: "post",
data: {
hashes: hashes.join("|")
}
@ -423,8 +423,8 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new Request({
url: 'api/v2/torrents/start',
method: 'post',
url: "api/v2/torrents/start",
method: "post",
data: {
hashes: hashes.join("|")
}
@ -437,14 +437,14 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
let enable = false;
hashes.each(function(hash, index) {
hashes.each((hash, index) => {
const row = torrentsTable.rows[hash];
if (!row.full_data.auto_tmm)
enable = true;
});
new Request({
url: 'api/v2/torrents/setAutoManagement',
method: 'post',
url: "api/v2/torrents/setAutoManagement",
method: "post",
data: {
hashes: hashes.join("|"),
enable: enable
@ -458,8 +458,8 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new Request({
url: 'api/v2/torrents/recheck',
method: 'post',
url: "api/v2/torrents/recheck",
method: "post",
data: {
hashes: hashes.join("|"),
}
@ -472,8 +472,8 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new Request({
url: 'api/v2/torrents/reannounce',
method: 'post',
url: "api/v2/torrents/reannounce",
method: "post",
data: {
hashes: hashes.join("|"),
}
@ -489,10 +489,10 @@ const initializeWindows = function() {
const row = torrentsTable.rows[hash];
new MochaUI.Window({
id: 'setLocationPage',
id: "setLocationPage",
title: "QBT_TR(Set location)QBT_TR[CONTEXT=TransferListWidget]",
loadMethod: 'iframe',
contentURL: new URI("setlocation.html").setData("hashes", hashes.join('|')).setData("path", encodeURIComponent(row.full_data.save_path)).toString(),
loadMethod: "iframe",
contentURL: new URI("setlocation.html").setData("hashes", hashes.join("|")).setData("path", encodeURIComponent(row.full_data.save_path)).toString(),
scrollbars: false,
resizable: true,
maximizable: false,
@ -511,9 +511,9 @@ const initializeWindows = function() {
const row = torrentsTable.rows[hash];
if (row) {
new MochaUI.Window({
id: 'renamePage',
id: "renamePage",
title: "QBT_TR(Rename)QBT_TR[CONTEXT=TransferListWidget]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("rename.html").setData("hash", hash).setData("name", row.full_data.name).toString(),
scrollbars: false,
resizable: true,
@ -534,11 +534,11 @@ const initializeWindows = function() {
const row = torrentsTable.rows[hash];
if (row) {
new MochaUI.Window({
id: 'multiRenamePage',
id: "multiRenamePage",
title: "QBT_TR(Renaming)QBT_TR[CONTEXT=TransferListWidget]",
data: { hash: hash, selectedRows: [] },
loadMethod: 'xhr',
contentURL: 'rename_files.html',
loadMethod: "xhr",
contentURL: "rename_files.html",
scrollbars: false,
resizable: true,
maximizable: false,
@ -546,7 +546,7 @@ const initializeWindows = function() {
paddingHorizontal: 0,
width: 800,
height: 420,
resizeLimit: { 'x': [800], 'y': [420] }
resizeLimit: { "x": [800], "y": [420] }
});
}
}
@ -557,10 +557,10 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new MochaUI.Window({
id: 'newCategoryPage',
id: "newCategoryPage",
title: "QBT_TR(New Category)QBT_TR[CONTEXT=TransferListWidget]",
loadMethod: 'iframe',
contentURL: new URI("newcategory.html").setData("action", action).setData("hashes", hashes.join('|')).toString(),
loadMethod: "iframe",
contentURL: new URI("newcategory.html").setData("action", action).setData("hashes", hashes.join("|")).toString(),
scrollbars: false,
resizable: true,
maximizable: false,
@ -579,10 +579,10 @@ const initializeWindows = function() {
const categoryName = category_list.has(categoryHash)
? category_list.get(categoryHash).name
: '';
: "";
new Request({
url: 'api/v2/torrents/setCategory',
method: 'post',
url: "api/v2/torrents/setCategory",
method: "post",
data: {
hashes: hashes.join("|"),
category: categoryName
@ -593,9 +593,9 @@ const initializeWindows = function() {
createCategoryFN = function() {
const action = "create";
new MochaUI.Window({
id: 'newCategoryPage',
id: "newCategoryPage",
title: "QBT_TR(New Category)QBT_TR[CONTEXT=CategoryFilterWidget]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("newcategory.html").setData("action", action).toString(),
scrollbars: false,
resizable: true,
@ -612,9 +612,9 @@ const initializeWindows = function() {
const action = "createSubcategory";
const categoryName = category_list.get(categoryHash).name + "/";
new MochaUI.Window({
id: 'newSubcategoryPage',
id: "newSubcategoryPage",
title: "QBT_TR(New Category)QBT_TR[CONTEXT=CategoryFilterWidget]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("newcategory.html").setData("action", action).setData("categoryName", categoryName).toString(),
scrollbars: false,
resizable: true,
@ -631,10 +631,10 @@ const initializeWindows = function() {
const action = "edit";
const category = category_list.get(categoryHash);
new MochaUI.Window({
id: 'editCategoryPage',
id: "editCategoryPage",
title: "QBT_TR(Edit Category)QBT_TR[CONTEXT=TransferListWidget]",
loadMethod: 'iframe',
contentURL: new URI('newcategory.html').setData("action", action).setData("categoryName", category.name).setData("savePath", category.savePath).toString(),
loadMethod: "iframe",
contentURL: new URI("newcategory.html").setData("action", action).setData("categoryName", category.name).setData("savePath", category.savePath).toString(),
scrollbars: false,
resizable: true,
maximizable: false,
@ -649,8 +649,8 @@ const initializeWindows = function() {
removeCategoryFN = function(categoryHash) {
const categoryName = category_list.get(categoryHash).name;
new Request({
url: 'api/v2/torrents/removeCategories',
method: 'post',
url: "api/v2/torrents/removeCategories",
method: "post",
data: {
categories: categoryName
}
@ -661,26 +661,26 @@ const initializeWindows = function() {
deleteUnusedCategoriesFN = function() {
const categories = [];
category_list.forEach((category, hash) => {
if (torrentsTable.getFilteredTorrentsNumber('all', hash, TAGS_ALL, TRACKERS_ALL) === 0)
if (torrentsTable.getFilteredTorrentsNumber("all", hash, TAGS_ALL, TRACKERS_ALL) === 0)
categories.push(category.name);
});
new Request({
url: 'api/v2/torrents/removeCategories',
method: 'post',
url: "api/v2/torrents/removeCategories",
method: "post",
data: {
categories: categories.join('\n')
categories: categories.join("\n")
}
}).send();
setCategoryFilter(CATEGORIES_ALL);
};
startTorrentsByCategoryFN = function(categoryHash) {
const hashes = torrentsTable.getFilteredTorrentsHashes('all', categoryHash, TAGS_ALL, TRACKERS_ALL);
const hashes = torrentsTable.getFilteredTorrentsHashes("all", categoryHash, TAGS_ALL, TRACKERS_ALL);
if (hashes.length) {
new Request({
url: 'api/v2/torrents/start',
method: 'post',
url: "api/v2/torrents/start",
method: "post",
data: {
hashes: hashes.join("|")
}
@ -690,11 +690,11 @@ const initializeWindows = function() {
};
stopTorrentsByCategoryFN = function(categoryHash) {
const hashes = torrentsTable.getFilteredTorrentsHashes('all', categoryHash, TAGS_ALL, TRACKERS_ALL);
const hashes = torrentsTable.getFilteredTorrentsHashes("all", categoryHash, TAGS_ALL, TRACKERS_ALL);
if (hashes.length) {
new Request({
url: 'api/v2/torrents/stop',
method: 'post',
url: "api/v2/torrents/stop",
method: "post",
data: {
hashes: hashes.join("|")
}
@ -704,12 +704,12 @@ const initializeWindows = function() {
};
deleteTorrentsByCategoryFN = function(categoryHash) {
const hashes = torrentsTable.getFilteredTorrentsHashes('all', categoryHash, TAGS_ALL, TRACKERS_ALL);
const hashes = torrentsTable.getFilteredTorrentsHashes("all", categoryHash, TAGS_ALL, TRACKERS_ALL);
if (hashes.length) {
new MochaUI.Window({
id: 'confirmDeletionPage',
id: "confirmDeletionPage",
title: "QBT_TR(Remove torrent(s))QBT_TR[CONTEXT=confirmDeletionDlg]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("confirmdeletion.html").setData("hashes", hashes.join("|")).toString(),
scrollbars: false,
resizable: true,
@ -727,9 +727,9 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new MochaUI.Window({
id: 'newTagPage',
id: "newTagPage",
title: "QBT_TR(Add Tags)QBT_TR[CONTEXT=TransferListWidget]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("newtag.html").setData("action", action).setData("hashes", hashes.join("|")).toString(),
scrollbars: false,
resizable: true,
@ -747,10 +747,10 @@ const initializeWindows = function() {
if (hashes.length <= 0)
return;
const tagName = tagList.has(tagHash) ? tagList.get(tagHash).name : '';
const tagName = tagList.has(tagHash) ? tagList.get(tagHash).name : "";
new Request({
url: (isSet ? 'api/v2/torrents/addTags' : 'api/v2/torrents/removeTags'),
method: 'post',
url: (isSet ? "api/v2/torrents/addTags" : "api/v2/torrents/removeTags"),
method: "post",
data: {
hashes: hashes.join("|"),
tags: tagName,
@ -762,8 +762,8 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new Request({
url: ('api/v2/torrents/removeTags'),
method: 'post',
url: ("api/v2/torrents/removeTags"),
method: "post",
data: {
hashes: hashes.join("|"),
}
@ -774,9 +774,9 @@ const initializeWindows = function() {
createTagFN = function() {
const action = "create";
new MochaUI.Window({
id: 'newTagPage',
id: "newTagPage",
title: "QBT_TR(New Tag)QBT_TR[CONTEXT=TagFilterWidget]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("newtag.html").setData("action", action).toString(),
scrollbars: false,
resizable: true,
@ -792,8 +792,8 @@ const initializeWindows = function() {
removeTagFN = function(tagHash) {
const tagName = tagList.get(tagHash).name;
new Request({
url: 'api/v2/torrents/deleteTags',
method: 'post',
url: "api/v2/torrents/deleteTags",
method: "post",
data: {
tags: tagName
}
@ -804,25 +804,25 @@ const initializeWindows = function() {
deleteUnusedTagsFN = function() {
const tags = [];
tagList.forEach((tag, hash) => {
if (torrentsTable.getFilteredTorrentsNumber('all', CATEGORIES_ALL, hash, TRACKERS_ALL) === 0)
if (torrentsTable.getFilteredTorrentsNumber("all", CATEGORIES_ALL, hash, TRACKERS_ALL) === 0)
tags.push(tag.name);
});
new Request({
url: 'api/v2/torrents/deleteTags',
method: 'post',
url: "api/v2/torrents/deleteTags",
method: "post",
data: {
tags: tags.join(',')
tags: tags.join(",")
}
}).send();
setTagFilter(TAGS_ALL);
};
startTorrentsByTagFN = function(tagHash) {
const hashes = torrentsTable.getFilteredTorrentsHashes('all', CATEGORIES_ALL, tagHash, TRACKERS_ALL);
const hashes = torrentsTable.getFilteredTorrentsHashes("all", CATEGORIES_ALL, tagHash, TRACKERS_ALL);
if (hashes.length) {
new Request({
url: 'api/v2/torrents/start',
method: 'post',
url: "api/v2/torrents/start",
method: "post",
data: {
hashes: hashes.join("|")
}
@ -832,11 +832,11 @@ const initializeWindows = function() {
};
stopTorrentsByTagFN = function(tagHash) {
const hashes = torrentsTable.getFilteredTorrentsHashes('all', CATEGORIES_ALL, tagHash, TRACKERS_ALL);
const hashes = torrentsTable.getFilteredTorrentsHashes("all", CATEGORIES_ALL, tagHash, TRACKERS_ALL);
if (hashes.length) {
new Request({
url: 'api/v2/torrents/stop',
method: 'post',
url: "api/v2/torrents/stop",
method: "post",
data: {
hashes: hashes.join("|")
}
@ -846,12 +846,12 @@ const initializeWindows = function() {
};
deleteTorrentsByTagFN = function(tagHash) {
const hashes = torrentsTable.getFilteredTorrentsHashes('all', CATEGORIES_ALL, tagHash, TRACKERS_ALL);
const hashes = torrentsTable.getFilteredTorrentsHashes("all", CATEGORIES_ALL, tagHash, TRACKERS_ALL);
if (hashes.length) {
new MochaUI.Window({
id: 'confirmDeletionPage',
id: "confirmDeletionPage",
title: "QBT_TR(Remove torrent(s))QBT_TR[CONTEXT=confirmDeletionDlg]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("confirmdeletion.html").setData("hashes", hashes.join("|")).toString(),
scrollbars: false,
resizable: true,
@ -869,10 +869,10 @@ const initializeWindows = function() {
let hashes = [];
switch (trackerHashInt) {
case TRACKERS_ALL:
hashes = torrentsTable.getFilteredTorrentsHashes('all', CATEGORIES_ALL, TAGS_ALL, TRACKERS_ALL);
hashes = torrentsTable.getFilteredTorrentsHashes("all", CATEGORIES_ALL, TAGS_ALL, TRACKERS_ALL);
break;
case TRACKERS_TRACKERLESS:
hashes = torrentsTable.getFilteredTorrentsHashes('all', CATEGORIES_ALL, TAGS_ALL, TRACKERS_TRACKERLESS);
hashes = torrentsTable.getFilteredTorrentsHashes("all", CATEGORIES_ALL, TAGS_ALL, TRACKERS_TRACKERLESS);
break;
default: {
const uniqueTorrents = new Set();
@ -888,8 +888,8 @@ const initializeWindows = function() {
if (hashes.length > 0) {
new Request({
url: 'api/v2/torrents/start',
method: 'post',
url: "api/v2/torrents/start",
method: "post",
data: {
hashes: hashes.join("|")
}
@ -903,10 +903,10 @@ const initializeWindows = function() {
let hashes = [];
switch (trackerHashInt) {
case TRACKERS_ALL:
hashes = torrentsTable.getFilteredTorrentsHashes('all', CATEGORIES_ALL, TAGS_ALL, TRACKERS_ALL);
hashes = torrentsTable.getFilteredTorrentsHashes("all", CATEGORIES_ALL, TAGS_ALL, TRACKERS_ALL);
break;
case TRACKERS_TRACKERLESS:
hashes = torrentsTable.getFilteredTorrentsHashes('all', CATEGORIES_ALL, TAGS_ALL, TRACKERS_TRACKERLESS);
hashes = torrentsTable.getFilteredTorrentsHashes("all", CATEGORIES_ALL, TAGS_ALL, TRACKERS_TRACKERLESS);
break;
default: {
const uniqueTorrents = new Set();
@ -922,8 +922,8 @@ const initializeWindows = function() {
if (hashes.length) {
new Request({
url: 'api/v2/torrents/stop',
method: 'post',
url: "api/v2/torrents/stop",
method: "post",
data: {
hashes: hashes.join("|")
}
@ -937,10 +937,10 @@ const initializeWindows = function() {
let hashes = [];
switch (trackerHashInt) {
case TRACKERS_ALL:
hashes = torrentsTable.getFilteredTorrentsHashes('all', CATEGORIES_ALL, TAGS_ALL, TRACKERS_ALL);
hashes = torrentsTable.getFilteredTorrentsHashes("all", CATEGORIES_ALL, TAGS_ALL, TRACKERS_ALL);
break;
case TRACKERS_TRACKERLESS:
hashes = torrentsTable.getFilteredTorrentsHashes('all', CATEGORIES_ALL, TAGS_ALL, TRACKERS_TRACKERLESS);
hashes = torrentsTable.getFilteredTorrentsHashes("all", CATEGORIES_ALL, TAGS_ALL, TRACKERS_TRACKERLESS);
break;
default: {
const uniqueTorrents = new Set();
@ -956,9 +956,9 @@ const initializeWindows = function() {
if (hashes.length) {
new MochaUI.Window({
id: 'confirmDeletionPage',
id: "confirmDeletionPage",
title: "QBT_TR(Remove torrent(s))QBT_TR[CONTEXT=confirmDeletionDlg]",
loadMethod: 'iframe',
loadMethod: "iframe",
contentURL: new URI("confirmdeletion.html").setData("hashes", hashes.join("|")).toString(),
scrollbars: false,
resizable: true,
@ -1068,13 +1068,13 @@ const initializeWindows = function() {
}
};
addClickEvent('stopAll', (e) => {
addClickEvent("stopAll", (e) => {
new Event(e).stop();
if (confirm('QBT_TR(Would you like to stop all torrents?)QBT_TR[CONTEXT=MainWindow]')) {
if (confirm("QBT_TR(Would you like to stop all torrents?)QBT_TR[CONTEXT=MainWindow]")) {
new Request({
url: 'api/v2/torrents/stop',
method: 'post',
url: "api/v2/torrents/stop",
method: "post",
data: {
hashes: "all"
}
@ -1083,13 +1083,13 @@ const initializeWindows = function() {
}
});
addClickEvent('startAll', (e) => {
addClickEvent("startAll", (e) => {
new Event(e).stop();
if (confirm('QBT_TR(Would you like to start all torrents?)QBT_TR[CONTEXT=MainWindow]')) {
if (confirm("QBT_TR(Would you like to start all torrents?)QBT_TR[CONTEXT=MainWindow]")) {
new Request({
url: 'api/v2/torrents/start',
method: 'post',
url: "api/v2/torrents/start",
method: "post",
data: {
hashes: "all"
}
@ -1098,15 +1098,15 @@ const initializeWindows = function() {
}
});
['stop', 'start', 'recheck'].each(function(item) {
addClickEvent(item, function(e) {
["stop", "start", "recheck"].each((item) => {
addClickEvent(item, (e) => {
new Event(e).stop();
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
hashes.each(function(hash, index) {
hashes.each((hash, index) => {
new Request({
url: 'api/v2/torrents/' + item,
method: 'post',
url: "api/v2/torrents/" + item,
method: "post",
data: {
hashes: hash
}
@ -1117,8 +1117,8 @@ const initializeWindows = function() {
});
});
['decreasePrio', 'increasePrio', 'topPrio', 'bottomPrio'].each(function(item) {
addClickEvent(item, function(e) {
["decreasePrio", "increasePrio", "topPrio", "bottomPrio"].each((item) => {
addClickEvent(item, (e) => {
new Event(e).stop();
setQueuePositionFN(item);
});
@ -1128,8 +1128,8 @@ const initializeWindows = function() {
const hashes = torrentsTable.selectedRowsIds();
if (hashes.length) {
new Request({
url: 'api/v2/torrents/' + cmd,
method: 'post',
url: "api/v2/torrents/" + cmd,
method: "post",
data: {
hashes: hashes.join("|")
}
@ -1138,19 +1138,19 @@ const initializeWindows = function() {
}
};
addClickEvent('about', function(e) {
addClickEvent("about", (e) => {
new Event(e).stop();
const id = 'aboutpage';
const id = "aboutpage";
new MochaUI.Window({
id: id,
title: 'QBT_TR(About qBittorrent)QBT_TR[CONTEXT=AboutDialog]',
loadMethod: 'xhr',
title: "QBT_TR(About qBittorrent)QBT_TR[CONTEXT=AboutDialog]",
loadMethod: "xhr",
contentURL: new URI("views/about.html").toString(),
require: {
css: ['css/Tabs.css']
css: ["css/Tabs.css"]
},
toolbar: true,
toolbarURL: 'views/aboutToolbar.html',
toolbarURL: "views/aboutToolbar.html",
padding: 10,
width: loadWindowWidth(id, 550),
height: loadWindowHeight(id, 360),
@ -1160,25 +1160,25 @@ const initializeWindows = function() {
});
});
addClickEvent('logout', function(e) {
addClickEvent("logout", (e) => {
new Event(e).stop();
new Request({
url: 'api/v2/auth/logout',
method: 'post',
url: "api/v2/auth/logout",
method: "post",
onSuccess: function() {
window.location.reload(true);
}
}).send();
});
addClickEvent('shutdown', function(e) {
addClickEvent("shutdown", (e) => {
new Event(e).stop();
if (confirm('QBT_TR(Are you sure you want to quit qBittorrent?)QBT_TR[CONTEXT=MainWindow]')) {
if (confirm("QBT_TR(Are you sure you want to quit qBittorrent?)QBT_TR[CONTEXT=MainWindow]")) {
new Request({
url: 'api/v2/app/shutdown',
method: 'post',
url: "api/v2/app/shutdown",
method: "post",
onSuccess: function() {
const shutdownMessage = 'QBT_TR(%1 has been shutdown)QBT_TR[CONTEXT=HttpServer]'.replace("%1", window.qBittorrent.Client.mainTitle());
const shutdownMessage = "QBT_TR(%1 has been shutdown)QBT_TR[CONTEXT=HttpServer]".replace("%1", window.qBittorrent.Client.mainTitle());
document.write(`<!doctype html><html lang="${LANG}"><head> <meta charset="UTF-8"> <meta name="color-scheme" content="light dark"> <title>${shutdownMessage}</title> <style>* {font-family: Arial, Helvetica, sans-serif;}</style></head><body> <h1 style="text-align: center;">${shutdownMessage}</h1></body></html>`);
document.close();
window.stop();
@ -1189,8 +1189,8 @@ const initializeWindows = function() {
});
// Deactivate menu header links
$$('a.returnFalse').each(function(el) {
el.addEvent('click', function(e) {
$$("a.returnFalse").each((el) => {
el.addEvent("click", (e) => {
new Event(e).stop();
});
});

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -51,35 +51,35 @@ window.qBittorrent.PiecesBar = (() => {
const PiecesBar = new Class({
initialize(pieces, parameters) {
const vals = {
'id': 'piecesbar_' + (piecesBarUniqueId++),
'width': 0,
'height': 0,
'downloadingColor': 'hsl(110deg 94% 27%)', // @TODO palette vars not supported for this value, apply average
'haveColor': 'hsl(210deg 55% 55%)', // @TODO palette vars not supported for this value, apply average
'borderSize': 1,
'borderColor': 'var(--color-border-default)'
"id": "piecesbar_" + (piecesBarUniqueId++),
"width": 0,
"height": 0,
"downloadingColor": "hsl(110deg 94% 27%)", // @TODO palette vars not supported for this value, apply average
"haveColor": "hsl(210deg 55% 55%)", // @TODO palette vars not supported for this value, apply average
"borderSize": 1,
"borderColor": "var(--color-border-default)"
};
if (parameters && (typeOf(parameters) === 'object'))
if (parameters && (typeOf(parameters) === "object"))
Object.append(vals, parameters);
vals.height = Math.max(vals.height, 12);
const obj = new Element('div', {
'id': vals.id,
'class': 'piecesbarWrapper',
'styles': {
'border': vals.borderSize.toString() + 'px solid ' + vals.borderColor,
'height': vals.height.toString() + 'px',
const obj = new Element("div", {
"id": vals.id,
"class": "piecesbarWrapper",
"styles": {
"border": vals.borderSize.toString() + "px solid " + vals.borderColor,
"height": vals.height.toString() + "px",
}
});
obj.vals = vals;
obj.vals.pieces = [pieces, []].pick();
obj.vals.canvas = new Element('canvas', {
'id': vals.id + '_canvas',
'class': 'piecesbarCanvas',
'width': (vals.width - (2 * vals.borderSize)).toString(),
'height': '1' // will stretch vertically to take up the height of the parent
obj.vals.canvas = new Element("canvas", {
"id": vals.id + "_canvas",
"class": "piecesbarCanvas",
"width": (vals.width - (2 * vals.borderSize)).toString(),
"height": "1" // will stretch vertically to take up the height of the parent
});
obj.appendChild(obj.vals.canvas);
@ -124,7 +124,7 @@ window.qBittorrent.PiecesBar = (() => {
this.vals.canvas.width = width - (2 * this.vals.borderSize);
const canvas = this.vals.canvas;
const ctx = canvas.getContext('2d');
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
const imageWidth = canvas.width;
@ -246,7 +246,7 @@ window.qBittorrent.PiecesBar = (() => {
function drawStatus(ctx, start, width, statusValues) {
// mix the colors by using transparency and a composite mode
ctx.globalCompositeOperation = 'lighten';
ctx.globalCompositeOperation = "lighten";
if (statusValues[STATUS_DOWNLOADING]) {
ctx.globalAlpha = statusValues[STATUS_DOWNLOADING];
@ -266,7 +266,7 @@ window.qBittorrent.PiecesBar = (() => {
if (!obj)
return;
if (!obj.parentNode)
return setTimeout(function() { checkForParent(id); }, 1);
return setTimeout(() => { checkForParent(id); }, 1);
obj.refresh();
}

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -43,60 +43,60 @@ window.qBittorrent.ProgressBar = (function() {
const ProgressBar = new Class({
initialize: function(value, parameters) {
const vals = {
'id': 'progressbar_' + (ProgressBars++),
'value': [value, 0].pick(),
'width': 0,
'height': 0,
'darkbg': 'var(--color-background-blue)',
'darkfg': 'var(--color-text-white)',
'lightbg': 'var(--color-background-default)',
'lightfg': 'var(--color-text-default)'
"id": "progressbar_" + (ProgressBars++),
"value": [value, 0].pick(),
"width": 0,
"height": 0,
"darkbg": "var(--color-background-blue)",
"darkfg": "var(--color-text-white)",
"lightbg": "var(--color-background-default)",
"lightfg": "var(--color-text-default)"
};
if (parameters && (typeOf(parameters) === 'object'))
if (parameters && (typeOf(parameters) === "object"))
Object.append(vals, parameters);
if (vals.height < 12)
vals.height = 12;
const obj = new Element('div', {
'id': vals.id,
'class': 'progressbar_wrapper',
'styles': {
'border': '1px solid var(--color-border-default)',
'width': vals.width,
'height': vals.height,
'position': 'relative',
'margin': '0 auto'
const obj = new Element("div", {
"id": vals.id,
"class": "progressbar_wrapper",
"styles": {
"border": "1px solid var(--color-border-default)",
"width": vals.width,
"height": vals.height,
"position": "relative",
"margin": "0 auto"
}
});
obj.vals = vals;
obj.vals.value = [value, 0].pick();
obj.vals.dark = new Element('div', {
'id': vals.id + '_dark',
'class': 'progressbar_dark',
'styles': {
'width': vals.width,
'height': vals.height,
'background': vals.darkbg,
'color': vals.darkfg,
'position': 'absolute',
'text-align': 'center',
'left': 0,
'top': 0,
'line-height': vals.height
obj.vals.dark = new Element("div", {
"id": vals.id + "_dark",
"class": "progressbar_dark",
"styles": {
"width": vals.width,
"height": vals.height,
"background": vals.darkbg,
"color": vals.darkfg,
"position": "absolute",
"text-align": "center",
"left": 0,
"top": 0,
"line-height": vals.height
}
});
obj.vals.light = new Element('div', {
'id': vals.id + '_light',
'class': 'progressbar_light',
'styles': {
'width': vals.width,
'height': vals.height,
'background': vals.lightbg,
'color': vals.lightfg,
'position': 'absolute',
'text-align': 'center',
'left': 0,
'top': 0,
'line-height': vals.height
obj.vals.light = new Element("div", {
"id": vals.id + "_light",
"class": "progressbar_light",
"styles": {
"width": vals.width,
"height": vals.height,
"background": vals.lightbg,
"color": vals.lightfg,
"position": "absolute",
"text-align": "center",
"left": 0,
"top": 0,
"line-height": vals.height
}
});
obj.appendChild(obj.vals.dark);
@ -120,26 +120,24 @@ window.qBittorrent.ProgressBar = (function() {
value = parseFloat(value);
if (isNaN(value))
value = 0;
if (value > 100)
value = 100;
if (value < 0)
value = 0;
value = Math.min(Math.max(value, 0), 100);
this.vals.value = value;
this.vals.dark.empty();
this.vals.light.empty();
this.vals.dark.appendText(value.round(1).toFixed(1) + '%');
this.vals.light.appendText(value.round(1).toFixed(1) + '%');
const r = parseInt(this.vals.width * (value / 100));
this.vals.dark.setStyle('clip', 'rect(0,' + r + 'px,' + this.vals.height + 'px,0)');
this.vals.light.setStyle('clip', 'rect(0,' + this.vals.width + 'px,' + this.vals.height + 'px,' + r + 'px)');
const displayedValue = `${value.round(1).toFixed(1)}%`;
this.vals.dark.textContent = displayedValue;
this.vals.light.textContent = displayedValue;
const r = parseInt((this.vals.width * (value / 100)), 10);
this.vals.dark.setStyle("clip", `rect(0, ${r}px, ${this.vals.height}px, 0)`);
this.vals.light.setStyle("clip", `rect(0, ${this.vals.width}px, ${this.vals.height}px, ${r}px)`);
}
function ProgressBar_setWidth(value) {
if (this.vals.width !== value) {
this.vals.width = value;
this.setStyle('width', value);
this.vals.dark.setStyle('width', value);
this.vals.light.setStyle('width', value);
this.setStyle("width", value);
this.vals.dark.setStyle("width", value);
this.vals.light.setStyle("width", value);
this.setValue(this.vals.value);
}
}
@ -150,10 +148,10 @@ window.qBittorrent.ProgressBar = (function() {
return;
if (!obj.parentNode)
return setTimeout('ProgressBar_checkForParent("' + id + '")', 1);
obj.setStyle('width', '100%');
obj.setStyle("width", "100%");
const w = obj.offsetWidth;
obj.vals.dark.setStyle('width', w);
obj.vals.light.setStyle('width', w);
obj.vals.dark.setStyle("width", w);
obj.vals.light.setStyle("width", w);
obj.vals.width = w;
obj.setValue(obj.vals.value);
}

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -82,7 +82,7 @@ window.qBittorrent.PropFiles = (function() {
const getChildFiles = function(node) {
if (node.isFolder) {
node.children.each(function(child) {
node.children.each((child) => {
getChildFiles(child);
});
}
@ -92,7 +92,7 @@ window.qBittorrent.PropFiles = (function() {
}
};
node.children.each(function(child) {
node.children.each((child) => {
getChildFiles(child);
});
@ -107,8 +107,8 @@ window.qBittorrent.PropFiles = (function() {
const checkbox = e.target;
const priority = checkbox.checked ? FilePriority.Normal : FilePriority.Ignored;
const id = checkbox.get('data-id');
const fileId = checkbox.get('data-file-id');
const id = checkbox.get("data-id");
const fileId = checkbox.get("data-file-id");
const rows = getAllChildren(id, fileId);
@ -119,8 +119,8 @@ window.qBittorrent.PropFiles = (function() {
const fileComboboxChanged = function(e) {
const combobox = e.target;
const priority = combobox.value;
const id = combobox.get('data-id');
const fileId = combobox.get('data-file-id');
const id = combobox.get("data-id");
const fileId = combobox.get("data-file-id");
const rows = getAllChildren(id, fileId);
@ -129,24 +129,24 @@ window.qBittorrent.PropFiles = (function() {
};
const isDownloadCheckboxExists = function(id) {
return ($('cbPrio' + id) !== null);
return ($("cbPrio" + id) !== null);
};
const createDownloadCheckbox = function(id, fileId, checked) {
const checkbox = new Element('input');
checkbox.set('type', 'checkbox');
checkbox.set('id', 'cbPrio' + id);
checkbox.set('data-id', id);
checkbox.set('data-file-id', fileId);
checkbox.set('class', 'DownloadedCB');
checkbox.addEvent('click', fileCheckboxClicked);
const checkbox = new Element("input");
checkbox.set("type", "checkbox");
checkbox.set("id", "cbPrio" + id);
checkbox.set("data-id", id);
checkbox.set("data-file-id", fileId);
checkbox.set("class", "DownloadedCB");
checkbox.addEvent("click", fileCheckboxClicked);
updateCheckbox(checkbox, checked);
return checkbox;
};
const updateDownloadCheckbox = function(id, checked) {
const checkbox = $('cbPrio' + id);
const checkbox = $("cbPrio" + id);
updateCheckbox(checkbox, checked);
};
@ -165,43 +165,42 @@ window.qBittorrent.PropFiles = (function() {
};
const isPriorityComboExists = function(id) {
return ($('comboPrio' + id) !== null);
return ($("comboPrio" + id) !== null);
};
const createPriorityOptionElement = function(priority, selected, html) {
const elem = new Element('option');
elem.set('value', priority.toString());
elem.set('html', html);
const elem = new Element("option");
elem.set("value", priority.toString());
elem.set("html", html);
if (selected)
elem.selected = true;
return elem;
};
const createPriorityCombo = function(id, fileId, selectedPriority) {
const select = new Element('select');
select.set('id', 'comboPrio' + id);
select.set('data-id', id);
select.set('data-file-id', fileId);
select.addClass('combo_priority');
select.addEvent('change', fileComboboxChanged);
const select = new Element("select");
select.set("id", "comboPrio" + id);
select.set("data-id", id);
select.set("data-file-id", fileId);
select.addClass("combo_priority");
select.addEvent("change", fileComboboxChanged);
createPriorityOptionElement(FilePriority.Ignored, (FilePriority.Ignored === selectedPriority), 'QBT_TR(Do not download)QBT_TR[CONTEXT=PropListDelegate]').injectInside(select);
createPriorityOptionElement(FilePriority.Normal, (FilePriority.Normal === selectedPriority), 'QBT_TR(Normal)QBT_TR[CONTEXT=PropListDelegate]').injectInside(select);
createPriorityOptionElement(FilePriority.High, (FilePriority.High === selectedPriority), 'QBT_TR(High)QBT_TR[CONTEXT=PropListDelegate]').injectInside(select);
createPriorityOptionElement(FilePriority.Maximum, (FilePriority.Maximum === selectedPriority), 'QBT_TR(Maximum)QBT_TR[CONTEXT=PropListDelegate]').injectInside(select);
createPriorityOptionElement(FilePriority.Ignored, (FilePriority.Ignored === selectedPriority), "QBT_TR(Do not download)QBT_TR[CONTEXT=PropListDelegate]").injectInside(select);
createPriorityOptionElement(FilePriority.Normal, (FilePriority.Normal === selectedPriority), "QBT_TR(Normal)QBT_TR[CONTEXT=PropListDelegate]").injectInside(select);
createPriorityOptionElement(FilePriority.High, (FilePriority.High === selectedPriority), "QBT_TR(High)QBT_TR[CONTEXT=PropListDelegate]").injectInside(select);
createPriorityOptionElement(FilePriority.Maximum, (FilePriority.Maximum === selectedPriority), "QBT_TR(Maximum)QBT_TR[CONTEXT=PropListDelegate]").injectInside(select);
// "Mixed" priority is for display only; it shouldn't be selectable
const mixedPriorityOption = createPriorityOptionElement(FilePriority.Mixed, (FilePriority.Mixed === selectedPriority), 'QBT_TR(Mixed)QBT_TR[CONTEXT=PropListDelegate]');
mixedPriorityOption.set('disabled', true);
const mixedPriorityOption = createPriorityOptionElement(FilePriority.Mixed, (FilePriority.Mixed === selectedPriority), "QBT_TR(Mixed)QBT_TR[CONTEXT=PropListDelegate]");
mixedPriorityOption.set("disabled", true);
mixedPriorityOption.injectInside(select);
return select;
};
const updatePriorityCombo = function(id, selectedPriority) {
const combobox = $('comboPrio' + id);
if (parseInt(combobox.value) !== selectedPriority)
const combobox = $("comboPrio" + id);
if (parseInt(combobox.value, 10) !== selectedPriority)
selectComboboxPriority(combobox, selectedPriority);
};
@ -209,7 +208,7 @@ window.qBittorrent.PropFiles = (function() {
const options = combobox.options;
for (let i = 0; i < options.length; ++i) {
const option = options[i];
if (parseInt(option.value) === priority)
if (parseInt(option.value, 10) === priority)
option.selected = true;
else
option.selected = false;
@ -224,12 +223,12 @@ window.qBittorrent.PropFiles = (function() {
const rowIds = [];
const fileIds = [];
let priority = FilePriority.Ignored;
const checkbox = $('tristate_cb');
const checkbox = $("tristate_cb");
if (checkbox.state === "checked") {
setCheckboxUnchecked(checkbox);
// set file priority for all checked to Ignored
torrentFilesTable.getFilteredAndSortedRows().forEach(function(row) {
torrentFilesTable.getFilteredAndSortedRows().forEach((row) => {
const rowId = row.rowId;
const fileId = row.full_data.fileId;
const isChecked = (row.full_data.checked === TriState.Checked);
@ -244,7 +243,7 @@ window.qBittorrent.PropFiles = (function() {
setCheckboxChecked(checkbox);
priority = FilePriority.Normal;
// set file priority for all unchecked to Normal
torrentFilesTable.getFilteredAndSortedRows().forEach(function(row) {
torrentFilesTable.getFilteredAndSortedRows().forEach((row) => {
const rowId = row.rowId;
const fileId = row.full_data.fileId;
const isUnchecked = (row.full_data.checked === TriState.Unchecked);
@ -261,7 +260,7 @@ window.qBittorrent.PropFiles = (function() {
};
const updateGlobalCheckbox = function() {
const checkbox = $('tristate_cb');
const checkbox = $("tristate_cb");
if (isAllCheckboxesChecked())
setCheckboxChecked(checkbox);
else if (isAllCheckboxesUnchecked())
@ -288,7 +287,7 @@ window.qBittorrent.PropFiles = (function() {
};
const isAllCheckboxesChecked = function() {
const checkboxes = $$('input.DownloadedCB');
const checkboxes = $$("input.DownloadedCB");
for (let i = 0; i < checkboxes.length; ++i) {
if (!checkboxes[i].checked)
return false;
@ -297,7 +296,7 @@ window.qBittorrent.PropFiles = (function() {
};
const isAllCheckboxesUnchecked = function() {
const checkboxes = $$('input.DownloadedCB');
const checkboxes = $$("input.DownloadedCB");
for (let i = 0; i < checkboxes.length; ++i) {
if (checkboxes[i].checked)
return false;
@ -311,12 +310,12 @@ window.qBittorrent.PropFiles = (function() {
clearTimeout(loadTorrentFilesDataTimer);
new Request({
url: 'api/v2/torrents/filePrio',
method: 'post',
url: "api/v2/torrents/filePrio",
method: "post",
data: {
'hash': current_hash,
'id': fileIds.join('|'),
'priority': priority
"hash": current_hash,
"id": fileIds.join("|"),
"priority": priority
},
onComplete: function() {
loadTorrentFilesDataTimer = loadTorrentFilesData.delay(1000);
@ -324,10 +323,10 @@ window.qBittorrent.PropFiles = (function() {
}).send();
const ignore = (priority === FilePriority.Ignored);
ids.forEach(function(_id) {
ids.forEach((_id) => {
torrentFilesTable.setIgnored(_id, ignore);
const combobox = $('comboPrio' + _id);
const combobox = $("comboPrio" + _id);
if (combobox !== null)
selectComboboxPriority(combobox, priority);
});
@ -337,8 +336,8 @@ window.qBittorrent.PropFiles = (function() {
let loadTorrentFilesDataTimer;
const loadTorrentFilesData = function() {
if ($('prop_files').hasClass('invisible')
|| $('propertiesPanel_collapseToggle').hasClass('panel-expand')) {
if ($("prop_files").hasClass("invisible")
|| $("propertiesPanel_collapseToggle").hasClass("panel-expand")) {
// Tab changed, don't do anything
return;
}
@ -355,10 +354,10 @@ window.qBittorrent.PropFiles = (function() {
current_hash = new_hash;
loadedNewTorrent = true;
}
const url = new URI('api/v2/torrents/files?hash=' + current_hash);
const url = new URI("api/v2/torrents/files?hash=" + current_hash);
new Request.JSON({
url: url,
method: 'get',
method: "get",
noCache: true,
onComplete: function() {
clearTimeout(loadTorrentFilesDataTimer);
@ -388,7 +387,7 @@ window.qBittorrent.PropFiles = (function() {
const handleNewTorrentFiles = function(files) {
is_seed = (files.length > 0) ? files[0].is_seed : true;
const rows = files.map(function(file, index) {
const rows = files.map((file, index) => {
let progress = (file.progress * 100).round(1);
if ((progress === 100) && (file.progress < 1))
progress = 99.9;
@ -421,13 +420,13 @@ window.qBittorrent.PropFiles = (function() {
const rootNode = new window.qBittorrent.FileTree.FolderNode();
rows.forEach(function(row) {
rows.forEach((row) => {
const pathItems = row.fileName.split(window.qBittorrent.Filesystem.PathSeparator);
pathItems.pop(); // remove last item (i.e. file name)
let parent = rootNode;
pathItems.forEach(function(folderName) {
if (folderName === '.unwanted')
pathItems.forEach((folderName) => {
if (folderName === ".unwanted")
return;
let folderNode = null;
@ -474,7 +473,7 @@ window.qBittorrent.PropFiles = (function() {
parent.addChild(childNode);
++rowId;
}.bind(this));
});
torrentFilesTable.populateTable(rootNode);
torrentFilesTable.updateTable(false);
@ -516,8 +515,8 @@ window.qBittorrent.PropFiles = (function() {
const rowIds = [];
const fileIds = [];
selectedRows.forEach(function(rowId) {
const elem = $('comboPrio' + rowId);
selectedRows.forEach((rowId) => {
const elem = $("comboPrio" + rowId);
rowIds.push(rowId);
fileIds.push(elem.get("data-file-id"));
});
@ -526,10 +525,10 @@ window.qBittorrent.PropFiles = (function() {
const uniqueFileIds = {};
for (let i = 0; i < rowIds.length; ++i) {
const rows = getAllChildren(rowIds[i], fileIds[i]);
rows.rowIds.forEach(function(rowId) {
rows.rowIds.forEach((rowId) => {
uniqueRowIds[rowId] = true;
});
rows.fileIds.forEach(function(fileId) {
rows.fileIds.forEach((fileId) => {
uniqueFileIds[fileId] = true;
});
}
@ -549,11 +548,11 @@ window.qBittorrent.PropFiles = (function() {
const path = node.path;
new MochaUI.Window({
id: 'renamePage',
id: "renamePage",
title: "QBT_TR(Renaming)QBT_TR[CONTEXT=TorrentContentTreeView]",
loadMethod: 'iframe',
contentURL: 'rename_file.html?hash=' + hash + '&isFolder=' + node.isFolder
+ '&path=' + encodeURIComponent(path),
loadMethod: "iframe",
contentURL: "rename_file.html?hash=" + hash + "&isFolder=" + node.isFolder
+ "&path=" + encodeURIComponent(path),
scrollbars: false,
resizable: true,
maximizable: false,
@ -566,11 +565,11 @@ window.qBittorrent.PropFiles = (function() {
const multiFileRename = function(hash) {
new MochaUI.Window({
id: 'multiRenamePage',
id: "multiRenamePage",
title: "QBT_TR(Renaming)QBT_TR[CONTEXT=TorrentContentTreeView]",
data: { hash: hash, selectedRows: torrentFilesTable.selectedRows },
loadMethod: 'xhr',
contentURL: 'rename_files.html',
loadMethod: "xhr",
contentURL: "rename_files.html",
scrollbars: false,
resizable: true,
maximizable: false,
@ -578,13 +577,13 @@ window.qBittorrent.PropFiles = (function() {
paddingHorizontal: 0,
width: 800,
height: 420,
resizeLimit: { 'x': [800], 'y': [420] }
resizeLimit: { "x": [800], "y": [420] }
});
};
const torrentFilesContextMenu = new window.qBittorrent.ContextMenu.ContextMenu({
targets: '#torrentFilesTableDiv tr',
menu: 'torrentFilesMenu',
targets: "#torrentFilesTableDiv tr",
menu: "torrentFilesMenu",
actions: {
Rename: function(element, ref) {
const hash = torrentsTable.getCurrentTorrentID();
@ -618,20 +617,20 @@ window.qBittorrent.PropFiles = (function() {
},
onShow: function() {
if (is_seed)
this.hideItem('FilePrio');
this.hideItem("FilePrio");
else
this.showItem('FilePrio');
this.showItem("FilePrio");
}
});
torrentFilesTable.setup('torrentFilesTableDiv', 'torrentFilesTableFixedHeaderDiv', torrentFilesContextMenu);
torrentFilesTable.setup("torrentFilesTableDiv", "torrentFilesTableFixedHeaderDiv", torrentFilesContextMenu);
// inject checkbox into table header
const tableHeaders = $$('#torrentFilesTableFixedHeaderDiv .dynamicTableHeader th');
const tableHeaders = $$("#torrentFilesTableFixedHeaderDiv .dynamicTableHeader th");
if (tableHeaders.length > 0) {
const checkbox = new Element('input');
checkbox.set('type', 'checkbox');
checkbox.set('id', 'tristate_cb');
checkbox.addEvent('click', switchCheckboxState);
const checkbox = new Element("input");
checkbox.set("type", "checkbox");
checkbox.set("id", "tristate_cb");
checkbox.addEvent("click", switchCheckboxState);
const checkboxTH = tableHeaders[0];
checkbox.injectInside(checkboxTH);
@ -639,14 +638,14 @@ window.qBittorrent.PropFiles = (function() {
// default sort by name column
if (torrentFilesTable.getSortedColumn() === null)
torrentFilesTable.setSortedColumn('name');
torrentFilesTable.setSortedColumn("name");
// listen for changes to torrentFilesFilterInput
let torrentFilesFilterInputTimer = -1;
$('torrentFilesFilterInput').addEvent('input', () => {
$("torrentFilesFilterInput").addEvent("input", () => {
clearTimeout(torrentFilesFilterInputTimer);
const value = $('torrentFilesFilterInput').get("value");
const value = $("torrentFilesFilterInput").get("value");
torrentFilesTable.setFilter(value);
torrentFilesFilterInputTimer = setTimeout(() => {
@ -668,7 +667,7 @@ window.qBittorrent.PropFiles = (function() {
* Show/hide a node's row
*/
const _hideNode = function(node, shouldHide) {
const span = $('filesTablefileName' + node.rowId);
const span = $("filesTablefileName" + node.rowId);
// span won't exist if row has been filtered out
if (span === null)
return;
@ -683,7 +682,7 @@ window.qBittorrent.PropFiles = (function() {
* Update a node's collapsed state and icon
*/
const _updateNodeState = function(node, isCollapsed) {
const span = $('filesTablefileName' + node.rowId);
const span = $("filesTablefileName" + node.rowId);
// span won't exist if row has been filtered out
if (span === null)
return;
@ -701,7 +700,7 @@ window.qBittorrent.PropFiles = (function() {
};
const _isCollapsed = function(node) {
const span = $('filesTablefileName' + node.rowId);
const span = $("filesTablefileName" + node.rowId);
if (span === null)
return true;
@ -721,8 +720,8 @@ window.qBittorrent.PropFiles = (function() {
const expandAllNodes = function() {
const root = torrentFilesTable.getRoot();
root.children.each(function(node) {
node.children.each(function(child) {
root.children.each((node) => {
node.children.each((child) => {
_collapseNode(child, false, true, false);
});
});
@ -731,8 +730,8 @@ window.qBittorrent.PropFiles = (function() {
const collapseAllNodes = function() {
const root = torrentFilesTable.getRoot();
root.children.each(function(node) {
node.children.each(function(child) {
root.children.each((node) => {
node.children.each((child) => {
_collapseNode(child, true, true, false);
});
});
@ -757,7 +756,7 @@ window.qBittorrent.PropFiles = (function() {
if (!isChildNode || applyToChildren || !canSkipNode)
_updateNodeState(node, shouldCollapse);
node.children.each(function(child) {
node.children.each((child) => {
_hideNode(child, shouldCollapse);
if (!child.isFolder)

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -42,42 +42,42 @@ window.qBittorrent.PropGeneral = (function() {
const piecesBar = new window.qBittorrent.PiecesBar.PiecesBar([], {
height: 16
});
$('progress').appendChild(piecesBar);
$("progress").appendChild(piecesBar);
const clearData = function() {
$('time_elapsed').set('html', '');
$('eta').set('html', '');
$('nb_connections').set('html', '');
$('total_downloaded').set('html', '');
$('total_uploaded').set('html', '');
$('dl_speed').set('html', '');
$('up_speed').set('html', '');
$('dl_limit').set('html', '');
$('up_limit').set('html', '');
$('total_wasted').set('html', '');
$('seeds').set('html', '');
$('peers').set('html', '');
$('share_ratio').set('html', '');
$('popularity').set('html', '');
$('reannounce').set('html', '');
$('last_seen').set('html', '');
$('total_size').set('html', '');
$('pieces').set('html', '');
$('created_by').set('html', '');
$('addition_date').set('html', '');
$('completion_date').set('html', '');
$('creation_date').set('html', '');
$('torrent_hash_v1').set('html', '');
$('torrent_hash_v2').set('html', '');
$('save_path').set('html', '');
$('comment').set('html', '');
$("time_elapsed").set("html", "");
$("eta").set("html", "");
$("nb_connections").set("html", "");
$("total_downloaded").set("html", "");
$("total_uploaded").set("html", "");
$("dl_speed").set("html", "");
$("up_speed").set("html", "");
$("dl_limit").set("html", "");
$("up_limit").set("html", "");
$("total_wasted").set("html", "");
$("seeds").set("html", "");
$("peers").set("html", "");
$("share_ratio").set("html", "");
$("popularity").set("html", "");
$("reannounce").set("html", "");
$("last_seen").set("html", "");
$("total_size").set("html", "");
$("pieces").set("html", "");
$("created_by").set("html", "");
$("addition_date").set("html", "");
$("completion_date").set("html", "");
$("creation_date").set("html", "");
$("torrent_hash_v1").set("html", "");
$("torrent_hash_v2").set("html", "");
$("save_path").set("html", "");
$("comment").set("html", "");
piecesBar.clear();
};
let loadTorrentDataTimer;
const loadTorrentData = function() {
if ($('prop_general').hasClass('invisible')
|| $('propertiesPanel_collapseToggle').hasClass('panel-expand')) {
if ($("prop_general").hasClass("invisible")
|| $("propertiesPanel_collapseToggle").hasClass("panel-expand")) {
// Tab changed, don't do anything
return;
}
@ -88,18 +88,18 @@ window.qBittorrent.PropGeneral = (function() {
loadTorrentDataTimer = loadTorrentData.delay(5000);
return;
}
const url = new URI('api/v2/torrents/properties?hash=' + current_id);
const url = new URI("api/v2/torrents/properties?hash=" + current_id);
new Request.JSON({
url: url,
method: 'get',
method: "get",
noCache: true,
onFailure: function() {
$('error_div').set('html', 'QBT_TR(qBittorrent client is not reachable)QBT_TR[CONTEXT=HttpServer]');
$("error_div").set("html", "QBT_TR(qBittorrent client is not reachable)QBT_TR[CONTEXT=HttpServer]");
clearTimeout(loadTorrentDataTimer);
loadTorrentDataTimer = loadTorrentData.delay(10000);
},
onSuccess: function(data) {
$('error_div').set('html', '');
$("error_div").set("html", "");
if (data) {
// Update Torrent data
@ -108,109 +108,109 @@ window.qBittorrent.PropGeneral = (function() {
.replace("%1", window.qBittorrent.Misc.friendlyDuration(data.time_elapsed))
.replace("%2", window.qBittorrent.Misc.friendlyDuration(data.seeding_time))
: window.qBittorrent.Misc.friendlyDuration(data.time_elapsed);
$('time_elapsed').set('html', timeElapsed);
$("time_elapsed").set("html", timeElapsed);
$('eta').set('html', window.qBittorrent.Misc.friendlyDuration(data.eta, window.qBittorrent.Misc.MAX_ETA));
$("eta").set("html", window.qBittorrent.Misc.friendlyDuration(data.eta, window.qBittorrent.Misc.MAX_ETA));
const nbConnections = "QBT_TR(%1 (%2 max))QBT_TR[CONTEXT=PropertiesWidget]"
.replace("%1", data.nb_connections)
.replace("%2", ((data.nb_connections_limit < 0) ? "∞" : data.nb_connections_limit));
$('nb_connections').set('html', nbConnections);
$("nb_connections").set("html", nbConnections);
const totalDownloaded = "QBT_TR(%1 (%2 this session))QBT_TR[CONTEXT=PropertiesWidget]"
.replace("%1", window.qBittorrent.Misc.friendlyUnit(data.total_downloaded))
.replace("%2", window.qBittorrent.Misc.friendlyUnit(data.total_downloaded_session));
$('total_downloaded').set('html', totalDownloaded);
$("total_downloaded").set("html", totalDownloaded);
const totalUploaded = "QBT_TR(%1 (%2 this session))QBT_TR[CONTEXT=PropertiesWidget]"
.replace("%1", window.qBittorrent.Misc.friendlyUnit(data.total_uploaded))
.replace("%2", window.qBittorrent.Misc.friendlyUnit(data.total_uploaded_session));
$('total_uploaded').set('html', totalUploaded);
$("total_uploaded").set("html", totalUploaded);
const dlSpeed = "QBT_TR(%1 (%2 avg.))QBT_TR[CONTEXT=PropertiesWidget]"
.replace("%1", window.qBittorrent.Misc.friendlyUnit(data.dl_speed, true))
.replace("%2", window.qBittorrent.Misc.friendlyUnit(data.dl_speed_avg, true));
$('dl_speed').set('html', dlSpeed);
$("dl_speed").set("html", dlSpeed);
const upSpeed = "QBT_TR(%1 (%2 avg.))QBT_TR[CONTEXT=PropertiesWidget]"
.replace("%1", window.qBittorrent.Misc.friendlyUnit(data.up_speed, true))
.replace("%2", window.qBittorrent.Misc.friendlyUnit(data.up_speed_avg, true));
$('up_speed').set('html', upSpeed);
$("up_speed").set("html", upSpeed);
const dlLimit = (data.dl_limit === -1)
? "∞"
: window.qBittorrent.Misc.friendlyUnit(data.dl_limit, true);
$('dl_limit').set('html', dlLimit);
$("dl_limit").set("html", dlLimit);
const upLimit = (data.up_limit === -1)
? "∞"
: window.qBittorrent.Misc.friendlyUnit(data.up_limit, true);
$('up_limit').set('html', upLimit);
$("up_limit").set("html", upLimit);
$('total_wasted').set('html', window.qBittorrent.Misc.friendlyUnit(data.total_wasted));
$("total_wasted").set("html", window.qBittorrent.Misc.friendlyUnit(data.total_wasted));
const seeds = "QBT_TR(%1 (%2 total))QBT_TR[CONTEXT=PropertiesWidget]"
.replace("%1", data.seeds)
.replace("%2", data.seeds_total);
$('seeds').set('html', seeds);
$("seeds").set("html", seeds);
const peers = "QBT_TR(%1 (%2 total))QBT_TR[CONTEXT=PropertiesWidget]"
.replace("%1", data.peers)
.replace("%2", data.peers_total);
$('peers').set('html', peers);
$("peers").set("html", peers);
$('share_ratio').set('html', data.share_ratio.toFixed(2));
$("share_ratio").set("html", data.share_ratio.toFixed(2));
$('popularity').set('html', data.popularity.toFixed(2));
$("popularity").set("html", data.popularity.toFixed(2));
$('reannounce').set('html', window.qBittorrent.Misc.friendlyDuration(data.reannounce));
$("reannounce").set("html", window.qBittorrent.Misc.friendlyDuration(data.reannounce));
const lastSeen = (data.last_seen >= 0)
? new Date(data.last_seen * 1000).toLocaleString()
: "QBT_TR(Never)QBT_TR[CONTEXT=PropertiesWidget]";
$('last_seen').set('html', lastSeen);
$("last_seen").set("html", lastSeen);
const totalSize = (data.total_size >= 0) ? window.qBittorrent.Misc.friendlyUnit(data.total_size) : "";
$('total_size').set('html', totalSize);
$("total_size").set("html", totalSize);
const pieces = (data.pieces_num >= 0)
? "QBT_TR(%1 x %2 (have %3))QBT_TR[CONTEXT=PropertiesWidget]"
.replace("%1", data.pieces_num)
.replace("%2", window.qBittorrent.Misc.friendlyUnit(data.piece_size))
.replace("%3", data.pieces_have)
: '';
$('pieces').set('html', pieces);
: "";
$("pieces").set("html", pieces);
$('created_by').set('text', data.created_by);
$("created_by").set("text", data.created_by);
const additionDate = (data.addition_date >= 0)
? new Date(data.addition_date * 1000).toLocaleString()
: "QBT_TR(Unknown)QBT_TR[CONTEXT=HttpServer]";
$('addition_date').set('html', additionDate);
$("addition_date").set("html", additionDate);
const completionDate = (data.completion_date >= 0)
? new Date(data.completion_date * 1000).toLocaleString()
: "";
$('completion_date').set('html', completionDate);
$("completion_date").set("html", completionDate);
const creationDate = (data.creation_date >= 0)
? new Date(data.creation_date * 1000).toLocaleString()
: "";
$('creation_date').set('html', creationDate);
$("creation_date").set("html", creationDate);
const torrentHashV1 = (data.infohash_v1 !== "")
? data.infohash_v1
: "QBT_TR(N/A)QBT_TR[CONTEXT=PropertiesWidget]";
$('torrent_hash_v1').set('html', torrentHashV1);
$("torrent_hash_v1").set("html", torrentHashV1);
const torrentHashV2 = (data.infohash_v2 !== "")
? data.infohash_v2
: "QBT_TR(N/A)QBT_TR[CONTEXT=PropertiesWidget]";
$('torrent_hash_v2').set('html', torrentHashV2);
$("torrent_hash_v2").set("html", torrentHashV2);
$('save_path').set('html', data.save_path);
$("save_path").set("html", data.save_path);
$('comment').set('html', window.qBittorrent.Misc.parseHtmlLinks(window.qBittorrent.Misc.escapeHtml(data.comment)));
$("comment").set("html", window.qBittorrent.Misc.parseHtmlLinks(window.qBittorrent.Misc.escapeHtml(data.comment)));
}
else {
clearData();
@ -220,18 +220,18 @@ window.qBittorrent.PropGeneral = (function() {
}
}).send();
const piecesUrl = new URI('api/v2/torrents/pieceStates?hash=' + current_id);
const piecesUrl = new URI("api/v2/torrents/pieceStates?hash=" + current_id);
new Request.JSON({
url: piecesUrl,
method: 'get',
method: "get",
noCache: true,
onFailure: function() {
$('error_div').set('html', 'QBT_TR(qBittorrent client is not reachable)QBT_TR[CONTEXT=HttpServer]');
$("error_div").set("html", "QBT_TR(qBittorrent client is not reachable)QBT_TR[CONTEXT=HttpServer]");
clearTimeout(loadTorrentDataTimer);
loadTorrentDataTimer = loadTorrentData.delay(10000);
},
onSuccess: function(data) {
$('error_div').set('html', '');
$("error_div").set("html", "");
if (data) {
piecesBar.setPieces(data);

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -45,8 +45,8 @@ window.qBittorrent.PropPeers = (function() {
let show_flags = true;
const loadTorrentPeersData = function() {
if ($('prop_peers').hasClass('invisible')
|| $('propertiesPanel_collapseToggle').hasClass('panel-expand')) {
if ($("prop_peers").hasClass("invisible")
|| $("propertiesPanel_collapseToggle").hasClass("panel-expand")) {
syncTorrentPeersLastResponseId = 0;
torrentPeersTable.clear();
return;
@ -59,45 +59,47 @@ window.qBittorrent.PropPeers = (function() {
loadTorrentPeersTimer = loadTorrentPeersData.delay(window.qBittorrent.Client.getSyncMainDataInterval());
return;
}
const url = new URI('api/v2/sync/torrentPeers');
url.setData('rid', syncTorrentPeersLastResponseId);
url.setData('hash', current_hash);
const url = new URI("api/v2/sync/torrentPeers");
url.setData("rid", syncTorrentPeersLastResponseId);
url.setData("hash", current_hash);
new Request.JSON({
url: url,
method: 'get',
method: "get",
noCache: true,
onComplete: function() {
clearTimeout(loadTorrentPeersTimer);
loadTorrentPeersTimer = loadTorrentPeersData.delay(window.qBittorrent.Client.getSyncMainDataInterval());
},
onSuccess: function(response) {
$('error_div').set('html', '');
$("error_div").set("html", "");
if (response) {
const full_update = (response['full_update'] === true);
const full_update = (response["full_update"] === true);
if (full_update)
torrentPeersTable.clear();
if (response['rid'])
syncTorrentPeersLastResponseId = response['rid'];
if (response['peers']) {
for (const key in response['peers']) {
response['peers'][key]['rowId'] = key;
if (response["rid"])
syncTorrentPeersLastResponseId = response["rid"];
if (response["peers"]) {
for (const key in response["peers"]) {
if (!Object.hasOwn(response["peers"], key))
continue;
torrentPeersTable.updateRowData(response['peers'][key]);
response["peers"][key]["rowId"] = key;
torrentPeersTable.updateRowData(response["peers"][key]);
}
}
if (response['peers_removed']) {
response['peers_removed'].each(function(hash) {
if (response["peers_removed"]) {
response["peers_removed"].each((hash) => {
torrentPeersTable.removeRow(hash);
});
}
torrentPeersTable.updateTable(full_update);
torrentPeersTable.altRow();
if (response['show_flags']) {
if (show_flags !== response['show_flags']) {
show_flags = response['show_flags'];
torrentPeersTable.columns['country'].force_hide = !show_flags;
torrentPeersTable.updateColumn('country');
if (response["show_flags"]) {
if (show_flags !== response["show_flags"]) {
show_flags = response["show_flags"];
torrentPeersTable.columns["country"].force_hide = !show_flags;
torrentPeersTable.updateColumn("country");
}
}
}
@ -114,8 +116,8 @@ window.qBittorrent.PropPeers = (function() {
};
const torrentPeersContextMenu = new window.qBittorrent.ContextMenu.ContextMenu({
targets: '#torrentPeersTableDiv',
menu: 'torrentPeersMenu',
targets: "#torrentPeersTableDiv",
menu: "torrentPeersMenu",
actions: {
addPeer: function(element, ref) {
const hash = torrentsTable.getCurrentTorrentID();
@ -123,10 +125,10 @@ window.qBittorrent.PropPeers = (function() {
return;
new MochaUI.Window({
id: 'addPeersPage',
id: "addPeersPage",
title: "QBT_TR(Add Peers)QBT_TR[CONTEXT=PeersAdditionDialog]",
loadMethod: 'iframe',
contentURL: 'addpeers.html?hash=' + hash,
loadMethod: "iframe",
contentURL: "addpeers.html?hash=" + hash,
scrollbars: false,
resizable: false,
maximizable: false,
@ -141,13 +143,13 @@ window.qBittorrent.PropPeers = (function() {
if (selectedPeers.length === 0)
return;
if (confirm('QBT_TR(Are you sure you want to permanently ban the selected peers?)QBT_TR[CONTEXT=PeerListWidget]')) {
if (confirm("QBT_TR(Are you sure you want to permanently ban the selected peers?)QBT_TR[CONTEXT=PeerListWidget]")) {
new Request({
url: 'api/v2/transfer/banPeers',
method: 'post',
url: "api/v2/transfer/banPeers",
method: "post",
data: {
hash: torrentsTable.getCurrentTorrentID(),
peers: selectedPeers.join('|')
peers: selectedPeers.join("|")
}
}).send();
}
@ -161,23 +163,23 @@ window.qBittorrent.PropPeers = (function() {
const selectedPeers = torrentPeersTable.selectedRowsIds();
if (selectedPeers.length >= 1) {
this.showItem('copyPeer');
this.showItem('banPeer');
this.showItem("copyPeer");
this.showItem("banPeer");
}
else {
this.hideItem('copyPeer');
this.hideItem('banPeer');
this.hideItem("copyPeer");
this.hideItem("banPeer");
}
}
});
new ClipboardJS('#CopyPeerInfo', {
new ClipboardJS("#CopyPeerInfo", {
text: function(trigger) {
return torrentPeersTable.selectedRowsIds().join("\n");
}
});
torrentPeersTable.setup('torrentPeersTableDiv', 'torrentPeersTableFixedHeaderDiv', torrentPeersContextMenu);
torrentPeersTable.setup("torrentPeersTableDiv", "torrentPeersTableFixedHeaderDiv", torrentPeersContextMenu);
return exports();
})();

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -45,8 +45,8 @@ window.qBittorrent.PropTrackers = (function() {
let loadTrackersDataTimer;
const loadTrackersData = function() {
if ($('prop_trackers').hasClass('invisible')
|| $('propertiesPanel_collapseToggle').hasClass('panel-expand')) {
if ($("prop_trackers").hasClass("invisible")
|| $("propertiesPanel_collapseToggle").hasClass("panel-expand")) {
// Tab changed, don't do anything
return;
}
@ -61,10 +61,10 @@ window.qBittorrent.PropTrackers = (function() {
torrentTrackersTable.clear();
current_hash = new_hash;
}
const url = new URI('api/v2/torrents/trackers?hash=' + current_hash);
const url = new URI("api/v2/torrents/trackers?hash=" + current_hash);
new Request.JSON({
url: url,
method: 'get',
method: "get",
noCache: true,
onComplete: function() {
clearTimeout(loadTrackersDataTimer);
@ -75,7 +75,7 @@ window.qBittorrent.PropTrackers = (function() {
torrentTrackersTable.clear();
if (trackers) {
trackers.each(function(tracker) {
trackers.each((tracker) => {
let status;
switch (tracker.status) {
case 0:
@ -126,8 +126,8 @@ window.qBittorrent.PropTrackers = (function() {
};
const torrentTrackersContextMenu = new window.qBittorrent.ContextMenu.ContextMenu({
targets: '#torrentTrackersTableDiv',
menu: 'torrentTrackersMenu',
targets: "#torrentTrackersTableDiv",
menu: "torrentTrackersMenu",
actions: {
AddTracker: function(element, ref) {
addTrackerFN();
@ -147,19 +147,19 @@ window.qBittorrent.PropTrackers = (function() {
},
onShow: function() {
const selectedTrackers = torrentTrackersTable.selectedRowsIds();
const containsStaticTracker = selectedTrackers.some(function(tracker) {
const containsStaticTracker = selectedTrackers.some((tracker) => {
return (tracker.indexOf("** [") === 0);
});
if (containsStaticTracker || (selectedTrackers.length === 0)) {
this.hideItem('EditTracker');
this.hideItem('RemoveTracker');
this.hideItem('CopyTrackerUrl');
this.hideItem("EditTracker");
this.hideItem("RemoveTracker");
this.hideItem("CopyTrackerUrl");
}
else {
this.showItem('EditTracker');
this.showItem('RemoveTracker');
this.showItem('CopyTrackerUrl');
this.showItem("EditTracker");
this.showItem("RemoveTracker");
this.showItem("CopyTrackerUrl");
}
}
});
@ -168,10 +168,10 @@ window.qBittorrent.PropTrackers = (function() {
if (current_hash.length === 0)
return;
new MochaUI.Window({
id: 'trackersPage',
id: "trackersPage",
title: "QBT_TR(Add trackers)QBT_TR[CONTEXT=TrackersAdditionDialog]",
loadMethod: 'iframe',
contentURL: 'addtrackers.html?hash=' + current_hash,
loadMethod: "iframe",
contentURL: "addtrackers.html?hash=" + current_hash,
scrollbars: true,
resizable: false,
maximizable: false,
@ -192,10 +192,10 @@ window.qBittorrent.PropTrackers = (function() {
const trackerUrl = encodeURIComponent(element.childNodes[1].innerText);
new MochaUI.Window({
id: 'trackersPage',
id: "trackersPage",
title: "QBT_TR(Tracker editing)QBT_TR[CONTEXT=TrackerListWidget]",
loadMethod: 'iframe',
contentURL: 'edittracker.html?hash=' + current_hash + '&url=' + trackerUrl,
loadMethod: "iframe",
contentURL: "edittracker.html?hash=" + current_hash + "&url=" + trackerUrl,
scrollbars: true,
resizable: false,
maximizable: false,
@ -216,8 +216,8 @@ window.qBittorrent.PropTrackers = (function() {
const selectedTrackers = torrentTrackersTable.selectedRowsIds();
new Request({
url: 'api/v2/torrents/removeTrackers',
method: 'post',
url: "api/v2/torrents/removeTrackers",
method: "post",
data: {
hash: current_hash,
urls: selectedTrackers.join("|")
@ -228,13 +228,13 @@ window.qBittorrent.PropTrackers = (function() {
}).send();
};
new ClipboardJS('#CopyTrackerUrl', {
new ClipboardJS("#CopyTrackerUrl", {
text: function(trigger) {
return torrentTrackersTable.selectedRowsIds().join("\n");
}
});
torrentTrackersTable.setup('torrentTrackersTableDiv', 'torrentTrackersTableFixedHeaderDiv', torrentTrackersContextMenu);
torrentTrackersTable.setup("torrentTrackersTableDiv", "torrentTrackersTableFixedHeaderDiv", torrentTrackersContextMenu);
return exports();
})();

View file

@ -26,7 +26,7 @@
* exception statement from your version.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -58,15 +58,15 @@ window.qBittorrent.PropWebseeds = (function() {
},
removeAllRows: function() {
this.rows.each(function(tr, url) {
this.rows.each((tr, url) => {
this.removeRow(url);
}.bind(this));
});
},
updateRow: function(tr, row) {
const tds = tr.getElements('td');
const tds = tr.getElements("td");
for (let i = 0; i < row.length; ++i) {
tds[i].set('html', row[i]);
tds[i].set("html", row[i]);
}
return true;
},
@ -79,11 +79,11 @@ window.qBittorrent.PropWebseeds = (function() {
return;
}
//this.removeRow(id);
const tr = new Element('tr');
const tr = new Element("tr");
this.rows.set(url, tr);
for (let i = 0; i < row.length; ++i) {
const td = new Element('td');
td.set('html', row[i]);
const td = new Element("td");
td.set("html", row[i]);
td.injectInside(tr);
}
tr.injectInside(this.table);
@ -94,8 +94,8 @@ window.qBittorrent.PropWebseeds = (function() {
let loadWebSeedsDataTimer;
const loadWebSeedsData = function() {
if ($('prop_webseeds').hasClass('invisible')
|| $('propertiesPanel_collapseToggle').hasClass('panel-expand')) {
if ($("prop_webseeds").hasClass("invisible")
|| $("propertiesPanel_collapseToggle").hasClass("panel-expand")) {
// Tab changed, don't do anything
return;
}
@ -110,21 +110,21 @@ window.qBittorrent.PropWebseeds = (function() {
wsTable.removeAllRows();
current_hash = new_hash;
}
const url = new URI('api/v2/torrents/webseeds?hash=' + current_hash);
const url = new URI("api/v2/torrents/webseeds?hash=" + current_hash);
new Request.JSON({
url: url,
method: 'get',
method: "get",
noCache: true,
onFailure: function() {
$('error_div').set('html', 'QBT_TR(qBittorrent client is not reachable)QBT_TR[CONTEXT=HttpServer]');
$("error_div").set("html", "QBT_TR(qBittorrent client is not reachable)QBT_TR[CONTEXT=HttpServer]");
clearTimeout(loadWebSeedsDataTimer);
loadWebSeedsDataTimer = loadWebSeedsData.delay(20000);
},
onSuccess: function(webseeds) {
$('error_div').set('html', '');
$("error_div").set("html", "");
if (webseeds) {
// Update WebSeeds data
webseeds.each(function(webseed) {
webseeds.each((webseed) => {
const row = [];
row.length = 1;
row[0] = webseed.url;
@ -146,7 +146,7 @@ window.qBittorrent.PropWebseeds = (function() {
};
const wsTable = new webseedsDynTable();
wsTable.setup($('webseedsTable'));
wsTable.setup($("webseedsTable"));
return exports();
})();

View file

@ -1,4 +1,4 @@
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -19,7 +19,7 @@ window.qBittorrent.MultiRename = (function() {
};
const RenameFiles = new Class({
hash: '',
hash: "",
selectedFiles: [],
matchedFiles: [],
@ -58,7 +58,7 @@ window.qBittorrent.MultiRename = (function() {
let count = 0;
let lastIndex = 0;
regex.lastIndex = 0;
let matches = [];
const matches = [];
do {
result = regex.exec(str);
if (result === null)
@ -86,7 +86,7 @@ window.qBittorrent.MultiRename = (function() {
return input.substring(0, start) + replacement + input.substring(end);
};
const replaceGroup = (input, search, replacement, escape, stripEscape = true) => {
let result = '';
let result = "";
let i = 0;
while (i < input.length) {
// Check if the current index contains the escape string
@ -135,7 +135,7 @@ window.qBittorrent.MultiRename = (function() {
// Setup regex search
const regexEscapeExp = new RegExp(/[/\-\\^$*+?.()|[\]{}]/g);
const standardSearch = new RegExp(this._inner_search.replace(regexEscapeExp, '\\$&'), regexFlags);
const standardSearch = new RegExp(this._inner_search.replace(regexEscapeExp, "\\$&"), regexFlags);
let regexSearch;
try {
regexSearch = new RegExp(this._inner_search, regexFlags);
@ -193,23 +193,25 @@ window.qBittorrent.MultiRename = (function() {
let replacement = this._inner_replacement;
// Replace numerical groups
for (let g = 0; g < match.length; ++g) {
let group = match[g];
const group = match[g];
if (!group) { continue; }
replacement = replaceGroup(replacement, `$${g}`, group, '\\', false);
replacement = replaceGroup(replacement, `$${g}`, group, "\\", false);
}
// Replace named groups
for (let namedGroup in match.groups) {
replacement = replaceGroup(replacement, `$${namedGroup}`, match.groups[namedGroup], '\\', false);
for (const namedGroup in match.groups) {
if (!Object.hasOwn(match.groups, namedGroup))
continue;
replacement = replaceGroup(replacement, `$${namedGroup}`, match.groups[namedGroup], "\\", false);
}
// Replace auxiliary variables
for (let v = 'dddddddd'; v !== ''; v = v.substring(1)) {
let fileCount = fileEnumeration.toString().padStart(v.length, '0');
replacement = replaceGroup(replacement, `$${v}`, fileCount, '\\', false);
for (let v = "dddddddd"; v !== ""; v = v.substring(1)) {
const fileCount = fileEnumeration.toString().padStart(v.length, "0");
replacement = replaceGroup(replacement, `$${v}`, fileCount, "\\", false);
}
// Remove empty $ variable
replacement = replaceGroup(replacement, '$', '', '\\');
replacement = replaceGroup(replacement, "$", "", "\\");
const wholeMatch = match[0];
const index = match['index'];
const index = match["index"];
renamed = replaceBetween(renamed, index + offset, index + offset + wholeMatch.length, replacement);
}
@ -225,7 +227,7 @@ window.qBittorrent.MultiRename = (function() {
return;
}
let replaced = [];
const replaced = [];
const _inner_rename = async function(i) {
const match = this.matchedFiles[i];
const newName = match.renamed;
@ -242,9 +244,9 @@ window.qBittorrent.MultiRename = (function() {
const newPath = parentPath
? parentPath + window.qBittorrent.Filesystem.PathSeparator + newName
: newName;
let renameRequest = new Request({
url: isFolder ? 'api/v2/torrents/renameFolder' : 'api/v2/torrents/renameFile',
method: 'post',
const renameRequest = new Request({
url: isFolder ? "api/v2/torrents/renameFolder" : "api/v2/torrents/renameFile",
method: "post",
data: {
hash: this.hash,
oldPath: oldPath,

View file

@ -21,7 +21,7 @@
* THE SOFTWARE.
*/
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -91,10 +91,10 @@ window.qBittorrent.Search = (function() {
const init = function() {
// load "Search in" preference from local storage
$('searchInTorrentName').set('value', (LocalPreferences.get('search_in_filter') === "names") ? "names" : "everywhere");
$("searchInTorrentName").set("value", (LocalPreferences.get("search_in_filter") === "names") ? "names" : "everywhere");
const searchResultsTableContextMenu = new window.qBittorrent.ContextMenu.ContextMenu({
targets: '.searchTableRow',
menu: 'searchResultsTableMenu',
targets: ".searchTableRow",
menu: "searchResultsTableMenu",
actions: {
Download: downloadSearchTorrent,
OpenDescriptionUrl: openSearchTorrentDescriptionUrl
@ -105,32 +105,32 @@ window.qBittorrent.Search = (function() {
}
});
searchResultsTable = new window.qBittorrent.DynamicTable.SearchResultsTable();
searchResultsTable.setup('searchResultsTableDiv', 'searchResultsTableFixedHeaderDiv', searchResultsTableContextMenu);
searchResultsTable.setup("searchResultsTableDiv", "searchResultsTableFixedHeaderDiv", searchResultsTableContextMenu);
getPlugins();
// listen for changes to searchInNameFilter
let searchInNameFilterTimer = -1;
$('searchInNameFilter').addEvent('input', () => {
$("searchInNameFilter").addEvent("input", () => {
clearTimeout(searchInNameFilterTimer);
searchInNameFilterTimer = setTimeout(() => {
searchInNameFilterTimer = -1;
const value = $('searchInNameFilter').get("value");
const value = $("searchInNameFilter").get("value");
searchText.filterPattern = value;
searchFilterChanged();
}, window.qBittorrent.Misc.FILTER_INPUT_DELAY);
});
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(e) {
"Enter": function(e) {
// accept enter key as a click
new Event(e).stop();
const elem = e.event.srcElement;
if (elem.className.contains("searchInputField")) {
$('startSearchButton').click();
$("startSearchButton").click();
return;
}
@ -144,14 +144,14 @@ window.qBittorrent.Search = (function() {
}).activate();
// restore search tabs
const searchJobs = JSON.parse(LocalPreferences.get('search_jobs', '[]'));
const searchJobs = JSON.parse(LocalPreferences.get("search_jobs", "[]"));
for (const { id, pattern } of searchJobs) {
createSearchTab(id, pattern);
}
};
const numSearchTabs = function() {
return $('searchTabs').getElements('li').length;
return $("searchTabs").getElements("li").length;
};
const getSearchIdFromTab = function(tab) {
@ -160,38 +160,38 @@ window.qBittorrent.Search = (function() {
const createSearchTab = function(searchId, pattern) {
const newTabId = `${searchTabIdPrefix}${searchId}`;
const tabElem = new Element('a', {
const tabElem = new Element("a", {
text: pattern,
});
const closeTabElem = new Element('img', {
alt: 'QBT_TR(Close tab)QBT_TR[CONTEXT=SearchWidget]',
title: 'QBT_TR(Close tab)QBT_TR[CONTEXT=SearchWidget]',
src: 'images/application-exit.svg',
width: '8',
height: '8',
style: 'padding-right: 7px; margin-bottom: -1px; margin-left: -5px',
onclick: 'qBittorrent.Search.closeSearchTab(this)',
const closeTabElem = new Element("img", {
alt: "QBT_TR(Close tab)QBT_TR[CONTEXT=SearchWidget]",
title: "QBT_TR(Close tab)QBT_TR[CONTEXT=SearchWidget]",
src: "images/application-exit.svg",
width: "8",
height: "8",
style: "padding-right: 7px; margin-bottom: -1px; margin-left: -5px",
onclick: "qBittorrent.Search.closeSearchTab(this)",
});
closeTabElem.inject(tabElem, 'top');
tabElem.appendChild(getStatusIconElement('QBT_TR(Searching...)QBT_TR[CONTEXT=SearchJobWidget]', 'images/queued.svg'));
$('searchTabs').appendChild(new Element('li', {
closeTabElem.inject(tabElem, "top");
tabElem.appendChild(getStatusIconElement("QBT_TR(Searching...)QBT_TR[CONTEXT=SearchJobWidget]", "images/queued.svg"));
$("searchTabs").appendChild(new Element("li", {
id: newTabId,
class: 'selected',
class: "selected",
html: tabElem.outerHTML,
}));
// unhide the results elements
if (numSearchTabs() >= 1) {
$('searchResultsNoSearches').style.display = "none";
$('searchResultsFilters').style.display = "block";
$('searchResultsTableContainer').style.display = "block";
$('searchTabsToolbar').style.display = "block";
$("searchResultsNoSearches").style.display = "none";
$("searchResultsFilters").style.display = "block";
$("searchResultsTableContainer").style.display = "block";
$("searchTabsToolbar").style.display = "block";
}
// reinitialize tabs
$('searchTabs').getElements('li').removeEvents('click');
$('searchTabs').getElements('li').addEvent('click', function(e) {
$('startSearchButton').set('text', 'QBT_TR(Search)QBT_TR[CONTEXT=SearchEngineWidget]');
$("searchTabs").getElements("li").removeEvents("click");
$("searchTabs").getElements("li").addEvent("click", function(e) {
$("startSearchButton").set("text", "QBT_TR(Search)QBT_TR[CONTEXT=SearchEngineWidget]");
setActiveTab(this);
});
@ -220,7 +220,7 @@ window.qBittorrent.Search = (function() {
const closeSearchTab = function(el) {
const tab = el.parentElement.parentElement;
const searchId = getSearchIdFromTab(tab);
const isTabSelected = tab.hasClass('selected');
const isTabSelected = tab.hasClass("selected");
const newTabToSelect = isTabSelected ? tab.nextSibling || tab.previousSibling : null;
const currentSearchId = getSelectedSearchId();
@ -233,34 +233,34 @@ window.qBittorrent.Search = (function() {
tab.destroy();
new Request({
url: new URI('api/v2/search/delete'),
method: 'post',
url: new URI("api/v2/search/delete"),
method: "post",
data: {
id: searchId
},
}).send();
const searchJobs = JSON.parse(LocalPreferences.get('search_jobs', '[]'));
const searchJobs = JSON.parse(LocalPreferences.get("search_jobs", "[]"));
const jobIndex = searchJobs.findIndex((job) => job.id === searchId);
if (jobIndex >= 0) {
searchJobs.splice(jobIndex, 1);
LocalPreferences.set('search_jobs', JSON.stringify(searchJobs));
LocalPreferences.set("search_jobs", JSON.stringify(searchJobs));
}
if (numSearchTabs() === 0) {
resetSearchState();
resetFilters();
$('numSearchResultsVisible').set('html', 0);
$('numSearchResultsTotal').set('html', 0);
$('searchResultsNoSearches').style.display = "block";
$('searchResultsFilters').style.display = "none";
$('searchResultsTableContainer').style.display = "none";
$('searchTabsToolbar').style.display = "none";
$("numSearchResultsVisible").set("html", 0);
$("numSearchResultsTotal").set("html", 0);
$("searchResultsNoSearches").style.display = "block";
$("searchResultsFilters").style.display = "none";
$("searchResultsTableContainer").style.display = "none";
$("searchTabsToolbar").style.display = "none";
}
else if (isTabSelected && newTabToSelect) {
setActiveTab(newTabToSelect);
$('startSearchButton').set('text', 'QBT_TR(Search)QBT_TR[CONTEXT=SearchEngineWidget]');
$("startSearchButton").set("text", "QBT_TR(Search)QBT_TR[CONTEXT=SearchEngineWidget]");
}
};
@ -302,7 +302,7 @@ window.qBittorrent.Search = (function() {
saveCurrentTabState();
MochaUI.selected(tab, 'searchTabs');
MochaUI.selected(tab, "searchTabs");
const state = searchState.get(searchId);
let rowsToSelect = [];
@ -319,32 +319,32 @@ window.qBittorrent.Search = (function() {
// restore filters
searchText.pattern = state.searchPattern;
searchText.filterPattern = state.filterPattern;
$('searchInNameFilter').set("value", state.filterPattern);
$("searchInNameFilter").set("value", state.filterPattern);
searchSeedsFilter.min = state.seedsFilter.min;
searchSeedsFilter.max = state.seedsFilter.max;
$('searchMinSeedsFilter').set('value', state.seedsFilter.min);
$('searchMaxSeedsFilter').set('value', state.seedsFilter.max);
$("searchMinSeedsFilter").set("value", state.seedsFilter.min);
$("searchMaxSeedsFilter").set("value", state.seedsFilter.max);
searchSizeFilter.min = state.sizeFilter.min;
searchSizeFilter.minUnit = state.sizeFilter.minUnit;
searchSizeFilter.max = state.sizeFilter.max;
searchSizeFilter.maxUnit = state.sizeFilter.maxUnit;
$('searchMinSizeFilter').set('value', state.sizeFilter.min);
$('searchMinSizePrefix').set('value', state.sizeFilter.minUnit);
$('searchMaxSizeFilter').set('value', state.sizeFilter.max);
$('searchMaxSizePrefix').set('value', state.sizeFilter.maxUnit);
$("searchMinSizeFilter").set("value", state.sizeFilter.min);
$("searchMinSizePrefix").set("value", state.sizeFilter.minUnit);
$("searchMaxSizeFilter").set("value", state.sizeFilter.max);
$("searchMaxSizePrefix").set("value", state.sizeFilter.maxUnit);
const currentSearchPattern = $('searchPattern').getProperty('value').trim();
const currentSearchPattern = $("searchPattern").getProperty("value").trim();
if (state.running && (state.searchPattern === currentSearchPattern)) {
// allow search to be stopped
$('startSearchButton').set('text', 'QBT_TR(Stop)QBT_TR[CONTEXT=SearchEngineWidget]');
$("startSearchButton").set("text", "QBT_TR(Stop)QBT_TR[CONTEXT=SearchEngineWidget]");
searchPatternChanged = false;
}
searchResultsTable.setSortedColumn(state.sort.column, state.sort.reverse);
$('searchInTorrentName').set('value', state.searchIn);
$("searchInTorrentName").set("value", state.searchIn);
}
// must restore all filters before calling updateTable
@ -356,76 +356,76 @@ window.qBittorrent.Search = (function() {
searchResultsTable.reselectRows(rowsToSelect);
}
$('numSearchResultsVisible').set('html', searchResultsTable.getFilteredAndSortedRows().length);
$('numSearchResultsTotal').set('html', searchResultsTable.getRowIds().length);
$("numSearchResultsVisible").set("html", searchResultsTable.getFilteredAndSortedRows().length);
$("numSearchResultsTotal").set("html", searchResultsTable.getRowIds().length);
setupSearchTableEvents(true);
};
const getStatusIconElement = function(text, image) {
return new Element('img', {
return new Element("img", {
alt: text,
title: text,
src: image,
class: 'statusIcon',
width: '10',
height: '10',
style: 'margin-bottom: -2px; margin-left: 7px',
class: "statusIcon",
width: "10",
height: "10",
style: "margin-bottom: -2px; margin-left: 7px",
});
};
const updateStatusIconElement = function(searchId, text, image) {
const searchTab = $(`${searchTabIdPrefix}${searchId}`);
if (searchTab) {
const statusIcon = searchTab.getElement('.statusIcon');
statusIcon.set('alt', text);
statusIcon.set('title', text);
statusIcon.set('src', image);
const statusIcon = searchTab.getElement(".statusIcon");
statusIcon.set("alt", text);
statusIcon.set("title", text);
statusIcon.set("src", image);
}
};
const startSearch = function(pattern, category, plugins) {
searchPatternChanged = false;
const url = new URI('api/v2/search/start');
const url = new URI("api/v2/search/start");
new Request.JSON({
url: url,
method: 'post',
method: "post",
data: {
pattern: pattern,
category: category,
plugins: plugins
},
onSuccess: function(response) {
$('startSearchButton').set('text', 'QBT_TR(Stop)QBT_TR[CONTEXT=SearchEngineWidget]');
$("startSearchButton").set("text", "QBT_TR(Stop)QBT_TR[CONTEXT=SearchEngineWidget]");
const searchId = response.id;
createSearchTab(searchId, pattern);
const searchJobs = JSON.parse(LocalPreferences.get('search_jobs', '[]'));
const searchJobs = JSON.parse(LocalPreferences.get("search_jobs", "[]"));
searchJobs.push({ id: searchId, pattern: pattern });
LocalPreferences.set('search_jobs', JSON.stringify(searchJobs));
LocalPreferences.set("search_jobs", JSON.stringify(searchJobs));
}
}).send();
};
const stopSearch = function(searchId) {
const url = new URI('api/v2/search/stop');
const url = new URI("api/v2/search/stop");
new Request({
url: url,
method: 'post',
method: "post",
data: {
id: searchId
},
onSuccess: function(response) {
resetSearchState(searchId);
// not strictly necessary to do this when the tab is being closed, but there's no harm in it
updateStatusIconElement(searchId, 'QBT_TR(Search aborted)QBT_TR[CONTEXT=SearchJobWidget]', 'images/task-reject.svg');
updateStatusIconElement(searchId, "QBT_TR(Search aborted)QBT_TR[CONTEXT=SearchJobWidget]", "images/task-reject.svg");
}
}).send();
};
const getSelectedSearchId = function() {
const selectedTab = $('searchTabs').getElement('li.selected');
const selectedTab = $("searchTabs").getElement("li.selected");
return selectedTab ? getSearchIdFromTab(selectedTab) : null;
};
@ -434,9 +434,9 @@ window.qBittorrent.Search = (function() {
const state = searchState.get(currentSearchId);
const isSearchRunning = state && state.running;
if (!isSearchRunning || searchPatternChanged) {
const pattern = $('searchPattern').getProperty('value').trim();
let category = $('categorySelect').getProperty('value');
const plugins = $('pluginsSelect').getProperty('value');
const pattern = $("searchPattern").getProperty("value").trim();
const category = $("categorySelect").getProperty("value");
const plugins = $("pluginsSelect").getProperty("value");
if (!pattern || !category || !plugins)
return;
@ -450,14 +450,14 @@ window.qBittorrent.Search = (function() {
};
const openSearchTorrentDescriptionUrl = function() {
searchResultsTable.selectedRowsIds().each(function(rowId) {
searchResultsTable.selectedRowsIds().each((rowId) => {
window.open(searchResultsTable.rows.get(rowId).full_data.descrLink, "_blank");
});
};
const copySearchTorrentName = function() {
const names = [];
searchResultsTable.selectedRowsIds().each(function(rowId) {
searchResultsTable.selectedRowsIds().each((rowId) => {
names.push(searchResultsTable.rows.get(rowId).full_data.fileName);
});
return names.join("\n");
@ -465,7 +465,7 @@ window.qBittorrent.Search = (function() {
const copySearchTorrentDownloadLink = function() {
const urls = [];
searchResultsTable.selectedRowsIds().each(function(rowId) {
searchResultsTable.selectedRowsIds().each((rowId) => {
urls.push(searchResultsTable.rows.get(rowId).full_data.fileUrl);
});
return urls.join("\n");
@ -473,7 +473,7 @@ window.qBittorrent.Search = (function() {
const copySearchTorrentDescriptionUrl = function() {
const urls = [];
searchResultsTable.selectedRowsIds().each(function(rowId) {
searchResultsTable.selectedRowsIds().each((rowId) => {
urls.push(searchResultsTable.rows.get(rowId).full_data.descrLink);
});
return urls.join("\n");
@ -481,7 +481,7 @@ window.qBittorrent.Search = (function() {
const downloadSearchTorrent = function() {
const urls = [];
searchResultsTable.selectedRowsIds().each(function(rowId) {
searchResultsTable.selectedRowsIds().each((rowId) => {
urls.push(searchResultsTable.rows.get(rowId).full_data.fileUrl);
});
@ -493,13 +493,13 @@ window.qBittorrent.Search = (function() {
};
const manageSearchPlugins = function() {
const id = 'searchPlugins';
const id = "searchPlugins";
if (!$(id))
new MochaUI.Window({
id: id,
title: "QBT_TR(Search plugins)QBT_TR[CONTEXT=PluginSelectDlg]",
loadMethod: 'xhr',
contentURL: 'views/searchplugins.html',
loadMethod: "xhr",
contentURL: "views/searchplugins.html",
scrollbars: false,
maximizable: false,
paddingVertical: 0,
@ -526,15 +526,15 @@ window.qBittorrent.Search = (function() {
const onSearchPatternChanged = function() {
const currentSearchId = getSelectedSearchId();
const state = searchState.get(currentSearchId);
const currentSearchPattern = $('searchPattern').getProperty('value').trim();
const currentSearchPattern = $("searchPattern").getProperty("value").trim();
// start a new search if pattern has changed, otherwise allow the search to be stopped
if (state && (state.searchPattern === currentSearchPattern)) {
searchPatternChanged = false;
$('startSearchButton').set('text', 'QBT_TR(Stop)QBT_TR[CONTEXT=SearchEngineWidget]');
$("startSearchButton").set("text", "QBT_TR(Stop)QBT_TR[CONTEXT=SearchEngineWidget]");
}
else {
searchPatternChanged = true;
$('startSearchButton').set('text', 'QBT_TR(Search)QBT_TR[CONTEXT=SearchEngineWidget]');
$("startSearchButton").set("text", "QBT_TR(Search)QBT_TR[CONTEXT=SearchEngineWidget]");
}
};
@ -568,7 +568,7 @@ window.qBittorrent.Search = (function() {
};
const resetSearchState = function(searchId) {
$('startSearchButton').set('text', 'QBT_TR(Search)QBT_TR[CONTEXT=SearchEngineWidget]');
$("startSearchButton").set("text", "QBT_TR(Search)QBT_TR[CONTEXT=SearchEngineWidget]");
const state = searchState.get(searchId);
if (state) {
state.running = false;
@ -579,7 +579,7 @@ window.qBittorrent.Search = (function() {
const getSearchCategories = function() {
const populateCategorySelect = function(categories) {
const categoryHtml = [];
categories.each(function(category) {
categories.each((category) => {
const option = new Element("option");
option.set("value", category.id);
option.set("html", category.name);
@ -595,10 +595,10 @@ window.qBittorrent.Search = (function() {
categoryHtml.splice(1, 0, option.outerHTML);
}
$('categorySelect').set('html', categoryHtml.join(""));
$("categorySelect").set("html", categoryHtml.join(""));
};
const selectedPlugin = $('pluginsSelect').get("value");
const selectedPlugin = $("pluginsSelect").get("value");
if ((selectedPlugin === "all") || (selectedPlugin === "enabled")) {
const uniqueCategories = {};
@ -626,14 +626,14 @@ window.qBittorrent.Search = (function() {
const getPlugins = function() {
new Request.JSON({
url: new URI('api/v2/search/plugins'),
method: 'get',
url: new URI("api/v2/search/plugins"),
method: "get",
noCache: true,
onSuccess: function(response) {
if (response !== prevSearchPluginsResponse) {
prevSearchPluginsResponse = response;
searchPlugins.length = 0;
response.forEach(function(plugin) {
response.forEach((plugin) => {
searchPlugins.push(plugin);
});
@ -643,9 +643,9 @@ window.qBittorrent.Search = (function() {
const searchPluginsEmpty = (searchPlugins.length === 0);
if (!searchPluginsEmpty) {
$('searchResultsNoPlugins').style.display = "none";
$("searchResultsNoPlugins").style.display = "none";
if (numSearchTabs() === 0) {
$('searchResultsNoSearches').style.display = "block";
$("searchResultsNoSearches").style.display = "block";
}
// sort plugins alphabetically
@ -655,7 +655,7 @@ window.qBittorrent.Search = (function() {
return window.qBittorrent.Misc.naturalSortCollator.compare(leftName, rightName);
});
allPlugins.each(function(plugin) {
allPlugins.each((plugin) => {
if (plugin.enabled === true)
pluginsHtml.push("<option value='" + window.qBittorrent.Misc.escapeHtml(plugin.name) + "'>" + window.qBittorrent.Misc.escapeHtml(plugin.fullName) + "</option>");
});
@ -664,12 +664,12 @@ window.qBittorrent.Search = (function() {
pluginsHtml.splice(2, 0, "<option disabled>──────────</option>");
}
$('pluginsSelect').set('html', pluginsHtml.join(""));
$("pluginsSelect").set("html", pluginsHtml.join(""));
$('searchPattern').setProperty('disabled', searchPluginsEmpty);
$('categorySelect').setProperty('disabled', searchPluginsEmpty);
$('pluginsSelect').setProperty('disabled', searchPluginsEmpty);
$('startSearchButton').setProperty('disabled', searchPluginsEmpty);
$("searchPattern").setProperty("disabled", searchPluginsEmpty);
$("categorySelect").setProperty("disabled", searchPluginsEmpty);
$("pluginsSelect").setProperty("disabled", searchPluginsEmpty);
$("startSearchButton").setProperty("disabled", searchPluginsEmpty);
if (window.qBittorrent.SearchPlugins !== undefined)
window.qBittorrent.SearchPlugins.updateTable();
@ -689,67 +689,67 @@ window.qBittorrent.Search = (function() {
};
const resetFilters = function() {
searchText.filterPattern = '';
$('searchInNameFilter').set('value', '');
searchText.filterPattern = "";
$("searchInNameFilter").set("value", "");
searchSeedsFilter.min = 0;
searchSeedsFilter.max = 0;
$('searchMinSeedsFilter').set('value', searchSeedsFilter.min);
$('searchMaxSeedsFilter').set('value', searchSeedsFilter.max);
$("searchMinSeedsFilter").set("value", searchSeedsFilter.min);
$("searchMaxSeedsFilter").set("value", searchSeedsFilter.max);
searchSizeFilter.min = 0.00;
searchSizeFilter.minUnit = 2; // B = 0, KiB = 1, MiB = 2, GiB = 3, TiB = 4, PiB = 5, EiB = 6
searchSizeFilter.max = 0.00;
searchSizeFilter.maxUnit = 3;
$('searchMinSizeFilter').set('value', searchSizeFilter.min);
$('searchMinSizePrefix').set('value', searchSizeFilter.minUnit);
$('searchMaxSizeFilter').set('value', searchSizeFilter.max);
$('searchMaxSizePrefix').set('value', searchSizeFilter.maxUnit);
$("searchMinSizeFilter").set("value", searchSizeFilter.min);
$("searchMinSizePrefix").set("value", searchSizeFilter.minUnit);
$("searchMaxSizeFilter").set("value", searchSizeFilter.max);
$("searchMaxSizePrefix").set("value", searchSizeFilter.maxUnit);
};
const getSearchInTorrentName = function() {
return $('searchInTorrentName').get('value') === "names" ? "names" : "everywhere";
return $("searchInTorrentName").get("value") === "names" ? "names" : "everywhere";
};
const searchInTorrentName = function() {
LocalPreferences.set('search_in_filter', getSearchInTorrentName());
LocalPreferences.set("search_in_filter", getSearchInTorrentName());
searchFilterChanged();
};
const searchSeedsFilterChanged = function() {
searchSeedsFilter.min = $('searchMinSeedsFilter').get('value');
searchSeedsFilter.max = $('searchMaxSeedsFilter').get('value');
searchSeedsFilter.min = $("searchMinSeedsFilter").get("value");
searchSeedsFilter.max = $("searchMaxSeedsFilter").get("value");
searchFilterChanged();
};
const searchSizeFilterChanged = function() {
searchSizeFilter.min = $('searchMinSizeFilter').get('value');
searchSizeFilter.minUnit = $('searchMinSizePrefix').get('value');
searchSizeFilter.max = $('searchMaxSizeFilter').get('value');
searchSizeFilter.maxUnit = $('searchMaxSizePrefix').get('value');
searchSizeFilter.min = $("searchMinSizeFilter").get("value");
searchSizeFilter.minUnit = $("searchMinSizePrefix").get("value");
searchSizeFilter.max = $("searchMaxSizeFilter").get("value");
searchSizeFilter.maxUnit = $("searchMaxSizePrefix").get("value");
searchFilterChanged();
};
const searchSizeFilterPrefixChanged = function() {
if ((Number($('searchMinSizeFilter').get('value')) !== 0) || (Number($('searchMaxSizeFilter').get('value')) !== 0))
if ((Number($("searchMinSizeFilter").get("value")) !== 0) || (Number($("searchMaxSizeFilter").get("value")) !== 0))
searchSizeFilterChanged();
};
const searchFilterChanged = function() {
searchResultsTable.updateTable();
$('numSearchResultsVisible').set('html', searchResultsTable.getFilteredAndSortedRows().length);
$("numSearchResultsVisible").set("html", searchResultsTable.getFilteredAndSortedRows().length);
};
const setupSearchTableEvents = function(enable) {
if (enable)
$$(".searchTableRow").each(function(target) {
target.addEventListener('dblclick', downloadSearchTorrent, false);
$$(".searchTableRow").each((target) => {
target.addEventListener("dblclick", downloadSearchTorrent, false);
});
else
$$(".searchTableRow").each(function(target) {
target.removeEventListener('dblclick', downloadSearchTorrent, false);
$$(".searchTableRow").each((target) => {
target.removeEventListener("dblclick", downloadSearchTorrent, false);
});
};
@ -757,10 +757,10 @@ window.qBittorrent.Search = (function() {
const state = searchState.get(searchId);
const maxResults = 500;
const url = new URI('api/v2/search/results');
const url = new URI("api/v2/search/results");
new Request.JSON({
url: url,
method: 'get',
method: "get",
noCache: true,
data: {
id: searchId,
@ -771,7 +771,7 @@ window.qBittorrent.Search = (function() {
if ((response.status === 400) || (response.status === 404)) {
// bad params. search id is invalid
resetSearchState(searchId);
updateStatusIconElement(searchId, 'QBT_TR(An error occurred during search...)QBT_TR[CONTEXT=SearchJobWidget]', 'images/error.svg');
updateStatusIconElement(searchId, "QBT_TR(An error occurred during search...)QBT_TR[CONTEXT=SearchJobWidget]", "images/error.svg");
}
else {
clearTimeout(state.loadResultsTimer);
@ -779,13 +779,13 @@ window.qBittorrent.Search = (function() {
}
},
onSuccess: function(response) {
$('error_div').set('html', '');
$("error_div").set("html", "");
const state = searchState.get(searchId);
// check if user stopped the search prior to receiving the response
if (!state.running) {
clearTimeout(state.loadResultsTimer);
updateStatusIconElement(searchId, 'QBT_TR(Search aborted)QBT_TR[CONTEXT=SearchJobWidget]', 'images/task-reject.svg');
updateStatusIconElement(searchId, "QBT_TR(Search aborted)QBT_TR[CONTEXT=SearchJobWidget]", "images/task-reject.svg");
return;
}
@ -823,8 +823,8 @@ window.qBittorrent.Search = (function() {
searchResultsTable.updateRowData(row);
}
$('numSearchResultsVisible').set('html', searchResultsTable.getFilteredAndSortedRows().length);
$('numSearchResultsTotal').set('html', searchResultsTable.getRowIds().length);
$("numSearchResultsVisible").set("html", searchResultsTable.getFilteredAndSortedRows().length);
$("numSearchResultsTotal").set("html", searchResultsTable.getRowIds().length);
searchResultsTable.updateTable();
searchResultsTable.altRow();
@ -834,7 +834,7 @@ window.qBittorrent.Search = (function() {
if ((response.status === "Stopped") && (state.rowId >= response.total)) {
resetSearchState(searchId);
updateStatusIconElement(searchId, 'QBT_TR(Search has finished)QBT_TR[CONTEXT=SearchJobWidget]', 'images/task-complete.svg');
updateStatusIconElement(searchId, "QBT_TR(Search has finished)QBT_TR[CONTEXT=SearchJobWidget]", "images/task-complete.svg");
return;
}
}
@ -851,7 +851,7 @@ window.qBittorrent.Search = (function() {
state.loadResultsTimer = loadSearchResultsData.delay(500, this, searchId);
};
new ClipboardJS('.copySearchDataToClipboard', {
new ClipboardJS(".copySearchDataToClipboard", {
text: function(trigger) {
switch (trigger.id) {
case "copySearchTorrentName":

View file

@ -26,16 +26,16 @@
* exception statement from your version.
*/
'use strict';
"use strict";
MochaUI.extend({
addUpLimitSlider: function(hashes) {
if ($('uplimitSliderarea')) {
if ($("uplimitSliderarea")) {
// Get global upload limit
let maximum = 500;
new Request({
url: 'api/v2/transfer/uploadLimit',
method: 'get',
url: "api/v2/transfer/uploadLimit",
method: "get",
data: {},
onSuccess: function(data) {
if (data) {
@ -52,42 +52,42 @@ MochaUI.extend({
}
// Get torrents upload limit
// And create slider
if (hashes[0] === 'global') {
if (hashes[0] === "global") {
let up_limit = maximum;
if (up_limit < 0)
up_limit = 0;
maximum = 10000;
new Slider($('uplimitSliderarea'), $('uplimitSliderknob'), {
new Slider($("uplimitSliderarea"), $("uplimitSliderknob"), {
steps: maximum,
offset: 0,
initialStep: up_limit.round(),
onChange: function(pos) {
if (pos > 0) {
$('uplimitUpdatevalue').value = pos;
$('upLimitUnit').style.visibility = "visible";
$("uplimitUpdatevalue").value = pos;
$("upLimitUnit").style.visibility = "visible";
}
else {
$('uplimitUpdatevalue').value = '∞';
$('upLimitUnit').style.visibility = "hidden";
$("uplimitUpdatevalue").value = "∞";
$("upLimitUnit").style.visibility = "hidden";
}
}.bind(this)
});
// Set default value
if (up_limit === 0) {
$('uplimitUpdatevalue').value = '∞';
$('upLimitUnit').style.visibility = "hidden";
$("uplimitUpdatevalue").value = "∞";
$("upLimitUnit").style.visibility = "hidden";
}
else {
$('uplimitUpdatevalue').value = up_limit.round();
$('upLimitUnit').style.visibility = "visible";
$("uplimitUpdatevalue").value = up_limit.round();
$("upLimitUnit").style.visibility = "visible";
}
}
else {
new Request.JSON({
url: 'api/v2/torrents/uploadLimit',
method: 'post',
url: "api/v2/torrents/uploadLimit",
method: "post",
data: {
hashes: hashes.join('|')
hashes: hashes.join("|")
},
onSuccess: function(data) {
if (data) {
@ -99,29 +99,29 @@ MochaUI.extend({
}
if (up_limit < 0)
up_limit = 0;
new Slider($('uplimitSliderarea'), $('uplimitSliderknob'), {
new Slider($("uplimitSliderarea"), $("uplimitSliderknob"), {
steps: maximum,
offset: 0,
initialStep: (up_limit / 1024.0).round(),
onChange: function(pos) {
if (pos > 0) {
$('uplimitUpdatevalue').value = pos;
$('upLimitUnit').style.visibility = "visible";
$("uplimitUpdatevalue").value = pos;
$("upLimitUnit").style.visibility = "visible";
}
else {
$('uplimitUpdatevalue').value = '∞';
$('upLimitUnit').style.visibility = "hidden";
$("uplimitUpdatevalue").value = "∞";
$("upLimitUnit").style.visibility = "hidden";
}
}.bind(this)
});
// Set default value
if (up_limit === 0) {
$('uplimitUpdatevalue').value = '∞';
$('upLimitUnit').style.visibility = "hidden";
$("uplimitUpdatevalue").value = "∞";
$("upLimitUnit").style.visibility = "hidden";
}
else {
$('uplimitUpdatevalue').value = (up_limit / 1024.0).round();
$('upLimitUnit').style.visibility = "visible";
$("uplimitUpdatevalue").value = (up_limit / 1024.0).round();
$("upLimitUnit").style.visibility = "visible";
}
}
}
@ -133,12 +133,12 @@ MochaUI.extend({
},
addDlLimitSlider: function(hashes) {
if ($('dllimitSliderarea')) {
if ($("dllimitSliderarea")) {
// Get global upload limit
let maximum = 500;
new Request({
url: 'api/v2/transfer/downloadLimit',
method: 'get',
url: "api/v2/transfer/downloadLimit",
method: "get",
data: {},
onSuccess: function(data) {
if (data) {
@ -155,42 +155,42 @@ MochaUI.extend({
}
// Get torrents download limit
// And create slider
if (hashes[0] === 'global') {
if (hashes[0] === "global") {
let dl_limit = maximum;
if (dl_limit < 0)
dl_limit = 0;
maximum = 10000;
new Slider($('dllimitSliderarea'), $('dllimitSliderknob'), {
new Slider($("dllimitSliderarea"), $("dllimitSliderknob"), {
steps: maximum,
offset: 0,
initialStep: dl_limit.round(),
onChange: function(pos) {
if (pos > 0) {
$('dllimitUpdatevalue').value = pos;
$('dlLimitUnit').style.visibility = "visible";
$("dllimitUpdatevalue").value = pos;
$("dlLimitUnit").style.visibility = "visible";
}
else {
$('dllimitUpdatevalue').value = '∞';
$('dlLimitUnit').style.visibility = "hidden";
$("dllimitUpdatevalue").value = "∞";
$("dlLimitUnit").style.visibility = "hidden";
}
}.bind(this)
});
// Set default value
if (dl_limit === 0) {
$('dllimitUpdatevalue').value = '∞';
$('dlLimitUnit').style.visibility = "hidden";
$("dllimitUpdatevalue").value = "∞";
$("dlLimitUnit").style.visibility = "hidden";
}
else {
$('dllimitUpdatevalue').value = dl_limit.round();
$('dlLimitUnit').style.visibility = "visible";
$("dllimitUpdatevalue").value = dl_limit.round();
$("dlLimitUnit").style.visibility = "visible";
}
}
else {
new Request.JSON({
url: 'api/v2/torrents/downloadLimit',
method: 'post',
url: "api/v2/torrents/downloadLimit",
method: "post",
data: {
hashes: hashes.join('|')
hashes: hashes.join("|")
},
onSuccess: function(data) {
if (data) {
@ -202,29 +202,29 @@ MochaUI.extend({
}
if (dl_limit < 0)
dl_limit = 0;
new Slider($('dllimitSliderarea'), $('dllimitSliderknob'), {
new Slider($("dllimitSliderarea"), $("dllimitSliderknob"), {
steps: maximum,
offset: 0,
initialStep: (dl_limit / 1024.0).round(),
onChange: function(pos) {
if (pos > 0) {
$('dllimitUpdatevalue').value = pos;
$('dlLimitUnit').style.visibility = "visible";
$("dllimitUpdatevalue").value = pos;
$("dlLimitUnit").style.visibility = "visible";
}
else {
$('dllimitUpdatevalue').value = '∞';
$('dlLimitUnit').style.visibility = "hidden";
$("dllimitUpdatevalue").value = "∞";
$("dlLimitUnit").style.visibility = "hidden";
}
}.bind(this)
});
// Set default value
if (dl_limit === 0) {
$('dllimitUpdatevalue').value = '∞';
$('dlLimitUnit').style.visibility = "hidden";
$("dllimitUpdatevalue").value = "∞";
$("dlLimitUnit").style.visibility = "hidden";
}
else {
$('dllimitUpdatevalue').value = (dl_limit / 1024.0).round();
$('dlLimitUnit').style.visibility = "visible";
$("dllimitUpdatevalue").value = (dl_limit / 1024.0).round();
$("dlLimitUnit").style.visibility = "visible";
}
}
}

View file

@ -9,47 +9,47 @@
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(event) {
$('setLocationButton').click();
"Enter": function(event) {
$("setLocationButton").click();
event.preventDefault();
},
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', function() {
const path = new URI().getData('path');
window.addEvent("domready", () => {
const path = new URI().getData("path");
// set text field to current value
if (path)
$('setLocation').value = decodeURIComponent(path);
$("setLocation").value = decodeURIComponent(path);
$('setLocation').focus();
$('setLocationButton').addEvent('click', function(e) {
$("setLocation").focus();
$("setLocationButton").addEvent("click", (e) => {
new Event(e).stop();
// check field
const location = $('setLocation').value.trim();
const location = $("setLocation").value.trim();
if ((location === null) || (location === "")) {
$('error_div').set('text', 'QBT_TR(Save path is empty)QBT_TR[CONTEXT=TorrentsController]');
$("error_div").set("text", "QBT_TR(Save path is empty)QBT_TR[CONTEXT=TorrentsController]");
return false;
}
const hashesList = new URI().getData('hashes');
const hashesList = new URI().getData("hashes");
new Request({
url: 'api/v2/torrents/setLocation',
method: 'post',
url: "api/v2/torrents/setLocation",
method: "post",
data: {
hashes: hashesList,
location: location
@ -58,7 +58,7 @@
window.parent.qBittorrent.Client.closeWindows();
},
onFailure: function(xhr) {
$('error_div').set('text', xhr.response);
$("error_div").set("text", xhr.response);
}
}).send();
});

View file

@ -9,40 +9,40 @@
<script src="scripts/lib/MooTools-More-1.6.0-compat-compressed.js"></script>
<script src="scripts/misc.js?locale=${LANG}&v=${CACHEID}"></script>
<script>
'use strict';
"use strict";
const UseGlobalLimit = -2;
const NoLimit = -1;
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(event) {
$('save').click();
"Enter": function(event) {
$("save").click();
event.preventDefault();
},
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
window.addEvent('domready', function() {
const hashesList = new URI().getData('hashes').split('|');
const origValues = new URI().getData('orig').split('|');
window.addEvent("domready", () => {
const hashesList = new URI().getData("hashes").split("|");
const origValues = new URI().getData("orig").split("|");
const values = {
ratioLimit: window.qBittorrent.Misc.friendlyFloat(origValues[0], 2),
seedingTimeLimit: parseInt(origValues[1]),
inactiveSeedingTimeLimit: parseInt(origValues[2]),
seedingTimeLimit: parseInt(origValues[1], 10),
inactiveSeedingTimeLimit: parseInt(origValues[2], 10),
maxRatio: window.qBittorrent.Misc.friendlyFloat(origValues[3], 2),
maxSeedingTime: parseInt(origValues[4]),
maxInactiveSeedingTime: parseInt(origValues[5])
maxSeedingTime: parseInt(origValues[4], 10),
maxInactiveSeedingTime: parseInt(origValues[5], 10)
};
// select default when orig values not passed. using double equals to compare string and int
@ -51,63 +51,63 @@
&& (values.seedingTimeLimit === UseGlobalLimit)
&& (values.inactiveSeedingTimeLimit === UseGlobalLimit))) {
// use default option
setSelectedRadioValue('shareLimit', 'default');
setSelectedRadioValue("shareLimit", "default");
}
else if ((values.maxRatio === NoLimit) && (values.maxSeedingTime === NoLimit) && (values.maxInactiveSeedingTime === NoLimit)) {
setSelectedRadioValue('shareLimit', 'none');
setSelectedRadioValue("shareLimit", "none");
// TODO set input boxes to *global* max ratio and seeding time
}
else {
setSelectedRadioValue('shareLimit', 'custom');
setSelectedRadioValue("shareLimit", "custom");
if (values.ratioLimit >= 0) {
$('setRatio').set('checked', true);
$('ratio').set('value', values.ratioLimit);
$("setRatio").set("checked", true);
$("ratio").set("value", values.ratioLimit);
}
if (values.seedingTimeLimit >= 0) {
$('setTotalMinutes').set('checked', true);
$('totalMinutes').set('value', values.seedingTimeLimit);
$("setTotalMinutes").set("checked", true);
$("totalMinutes").set("value", values.seedingTimeLimit);
}
if (values.inactiveSeedingTimeLimit >= 0) {
$('setInactiveMinutes').set('checked', true);
$('inactiveMinutes').set('value', values.inactiveSeedingTimeLimit);
$("setInactiveMinutes").set("checked", true);
$("inactiveMinutes").set("value", values.inactiveSeedingTimeLimit);
}
}
shareLimitChanged();
$('default').focus();
$('save').addEvent('click', function(e) {
$("default").focus();
$("save").addEvent("click", (e) => {
new Event(e).stop();
if (!isFormValid()) {
return false;
}
const shareLimit = getSelectedRadioValue('shareLimit');
const shareLimit = getSelectedRadioValue("shareLimit");
let ratioLimitValue = 0.00;
let seedingTimeLimitValue = 0;
let inactiveSeedingTimeLimitValue = 0;
if (shareLimit === 'default') {
if (shareLimit === "default") {
ratioLimitValue = seedingTimeLimitValue = inactiveSeedingTimeLimitValue = UseGlobalLimit;
}
else if (shareLimit === 'none') {
else if (shareLimit === "none") {
ratioLimitValue = seedingTimeLimitValue = inactiveSeedingTimeLimitValue = NoLimit;
}
else if (shareLimit === 'custom') {
ratioLimitValue = $('setRatio').get('checked') ? $('ratio').get('value') : -1;
seedingTimeLimitValue = $('setTotalMinutes').get('checked') ? $('totalMinutes').get('value') : -1;
inactiveSeedingTimeLimitValue = $('setInactiveMinutes').get('checked') ? $('inactiveMinutes').get('value') : -1;
else if (shareLimit === "custom") {
ratioLimitValue = $("setRatio").get("checked") ? $("ratio").get("value") : -1;
seedingTimeLimitValue = $("setTotalMinutes").get("checked") ? $("totalMinutes").get("value") : -1;
inactiveSeedingTimeLimitValue = $("setInactiveMinutes").get("checked") ? $("inactiveMinutes").get("value") : -1;
}
else {
return false;
}
new Request({
url: 'api/v2/torrents/setShareLimits',
method: 'post',
url: "api/v2/torrents/setShareLimits",
method: "post",
data: {
hashes: hashesList.join('|'),
hashes: hashesList.join("|"),
ratioLimit: ratioLimitValue,
seedingTimeLimit: seedingTimeLimitValue,
inactiveSeedingTimeLimit: inactiveSeedingTimeLimitValue
@ -125,7 +125,7 @@
for (let i = 0; i < radios.length; ++i) {
const radio = radios[i];
if (radio.checked) {
return (radio).get('value');
return (radio).get("value");
}
}
}
@ -141,27 +141,27 @@
}
function shareLimitChanged() {
const customShareLimit = getSelectedRadioValue('shareLimit') === 'custom';
$('setRatio').set('disabled', !customShareLimit);
$('setTotalMinutes').set('disabled', !customShareLimit);
$('setInactiveMinutes').set('disabled', !customShareLimit);
const customShareLimit = getSelectedRadioValue("shareLimit") === "custom";
$("setRatio").set("disabled", !customShareLimit);
$("setTotalMinutes").set("disabled", !customShareLimit);
$("setInactiveMinutes").set("disabled", !customShareLimit);
enableInputBoxes();
$('save').set('disabled', !isFormValid());
$("save").set("disabled", !isFormValid());
}
function enableInputBoxes() {
$('ratio').set('disabled', ($('setRatio').get('disabled') || !$('setRatio').get('checked')));
$('totalMinutes').set('disabled', ($('setTotalMinutes').get('disabled') || !$('setTotalMinutes').get('checked')));
$('inactiveMinutes').set('disabled', ($('setInactiveMinutes').get('disabled') || !$('setInactiveMinutes').get('checked')));
$("ratio").set("disabled", ($("setRatio").get("disabled") || !$("setRatio").get("checked")));
$("totalMinutes").set("disabled", ($("setTotalMinutes").get("disabled") || !$("setTotalMinutes").get("checked")));
$("inactiveMinutes").set("disabled", ($("setInactiveMinutes").get("disabled") || !$("setInactiveMinutes").get("checked")));
$('save').set('disabled', !isFormValid());
$("save").set("disabled", !isFormValid());
}
function isFormValid() {
return !((getSelectedRadioValue('shareLimit') === 'custom') && !$('setRatio').get('checked')
&& !$('setTotalMinutes').get('checked') && !$('setInactiveMinutes').get('checked'));
return !((getSelectedRadioValue("shareLimit") === "custom") && !$("setRatio").get("checked")
&& !$("setTotalMinutes").get("checked") && !$("setInactiveMinutes").get("checked"));
}
</script>
</head>

View file

@ -150,27 +150,27 @@
<div id="upload_spinner" class="mochaSpinner"></div>
<script>
'use strict';
"use strict";
let submitted = false;
$('uploadForm').addEventListener("submit", function() {
$('startTorrentHidden').value = $('startTorrent').checked ? 'false' : 'true';
$("uploadForm").addEventListener("submit", () => {
$("startTorrentHidden").value = $("startTorrent").checked ? "false" : "true";
$('dlLimitHidden').value = $('dlLimitText').value.toInt() * 1024;
$('upLimitHidden').value = $('upLimitText').value.toInt() * 1024;
$("dlLimitHidden").value = $("dlLimitText").value.toInt() * 1024;
$("upLimitHidden").value = $("upLimitText").value.toInt() * 1024;
$('upload_spinner').style.display = "block";
$("upload_spinner").style.display = "block";
submitted = true;
});
$('upload_frame').addEventListener("load", function() {
$("upload_frame").addEventListener("load", () => {
if (submitted)
window.parent.qBittorrent.Client.closeWindows();
});
if ((Browser.platform === 'ios') || ((Browser.platform === 'mac') && (navigator.maxTouchPoints > 1))) {
$('fileselect').accept = ".torrent";
if ((Browser.platform === "ios") || ((Browser.platform === "mac") && (navigator.maxTouchPoints > 1))) {
$("fileselect").accept = ".torrent";
}
</script>
</body>

View file

@ -25,17 +25,17 @@
</div>
<script>
'use strict';
"use strict";
const hashes = new URI().getData('hashes').split('|');
const hashes = new URI().getData("hashes").split("|");
const setUpLimit = function() {
const limit = $("uplimitUpdatevalue").value.toInt() * 1024;
if (hashes[0] === "global") {
new Request({
url: 'api/v2/transfer/setUploadLimit',
method: 'post',
url: "api/v2/transfer/setUploadLimit",
method: "post",
data: {
'limit': limit
"limit": limit
},
onComplete: function() {
window.parent.updateMainData();
@ -45,11 +45,11 @@
}
else {
new Request({
url: 'api/v2/torrents/setUploadLimit',
method: 'post',
url: "api/v2/torrents/setUploadLimit",
method: "post",
data: {
'hashes': hashes.join('|'),
'limit': limit
"hashes": hashes.join("|"),
"limit": limit
},
onComplete: function() {
window.parent.qBittorrent.Client.closeWindows();
@ -59,24 +59,24 @@
};
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(event) {
$('applyButton').click();
"Enter": function(event) {
$("applyButton").click();
event.preventDefault();
},
'Escape': function(event) {
"Escape": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
},
'Esc': function(event) {
"Esc": function(event) {
window.parent.qBittorrent.Client.closeWindows();
event.preventDefault();
}
}
}).activate();
$('uplimitUpdatevalue').focus();
$("uplimitUpdatevalue").focus();
MochaUI.addUpLimitSlider(hashes);
</script>

View file

@ -841,18 +841,18 @@
</div>
<script>
'use strict';
"use strict";
(() => {
const qbtVersion = window.parent.qBittorrent.Cache.qbtVersion.get();
const buildInfo = window.parent.qBittorrent.Cache.buildInfo.get();
$('qbittorrentVersion').innerText = `qBittorrent ${qbtVersion} QBT_TR(WebUI)QBT_TR[CONTEXT=OptionsDialog]`;
$('qtVersion').textContent = buildInfo.qt;
$('libtorrentVersion').textContent = buildInfo.libtorrent;
$('boostVersion').textContent = buildInfo.boost;
$('opensslVersion').textContent = buildInfo.openssl;
$('zlibVersion').textContent = buildInfo.zlib;
$('qbittorrentVersion').textContent += ` (${buildInfo.bitness}-bit)`;
$("qbittorrentVersion").innerText = `qBittorrent ${qbtVersion} QBT_TR(WebUI)QBT_TR[CONTEXT=OptionsDialog]`;
$("qtVersion").textContent = buildInfo.qt;
$("libtorrentVersion").textContent = buildInfo.libtorrent;
$("boostVersion").textContent = buildInfo.boost;
$("opensslVersion").textContent = buildInfo.openssl;
$("zlibVersion").textContent = buildInfo.zlib;
$("qbittorrentVersion").textContent += ` (${buildInfo.bitness}-bit)`;
})();
</script>

View file

@ -11,39 +11,39 @@
</div>
<script>
'use strict';
"use strict";
(function() {
MochaUI.initializeTabs('aboutTabs');
MochaUI.initializeTabs("aboutTabs");
$('aboutAboutLink').addEvent('click', function() {
$$('.aboutTabContent').addClass('invisible');
$('aboutAboutContent').removeClass('invisible');
$("aboutAboutLink").addEvent("click", () => {
$$(".aboutTabContent").addClass("invisible");
$("aboutAboutContent").removeClass("invisible");
});
$('aboutAuthorLink').addEvent('click', function() {
$$('.aboutTabContent').addClass('invisible');
$('aboutAuthorContent').removeClass('invisible');
$("aboutAuthorLink").addEvent("click", () => {
$$(".aboutTabContent").addClass("invisible");
$("aboutAuthorContent").removeClass("invisible");
});
$('aboutSpecialThanksLink').addEvent('click', function() {
$$('.aboutTabContent').addClass('invisible');
$('aboutSpecialThanksContent').removeClass('invisible');
$("aboutSpecialThanksLink").addEvent("click", () => {
$$(".aboutTabContent").addClass("invisible");
$("aboutSpecialThanksContent").removeClass("invisible");
});
$('aboutTranslatorsLink').addEvent('click', function() {
$$('.aboutTabContent').addClass('invisible');
$('aboutTranslatorsContent').removeClass('invisible');
$("aboutTranslatorsLink").addEvent("click", () => {
$$(".aboutTabContent").addClass("invisible");
$("aboutTranslatorsContent").removeClass("invisible");
});
$('aboutLicenseLink').addEvent('click', function() {
$$('.aboutTabContent').addClass('invisible');
$('aboutLicenseContent').removeClass('invisible');
$("aboutLicenseLink").addEvent("click", () => {
$$(".aboutTabContent").addClass("invisible");
$("aboutLicenseContent").removeClass("invisible");
});
$('aboutSoftwareUsedLink').addEvent('click', function() {
$$('.aboutTabContent').addClass('invisible');
$('aboutSoftwareUsedContent').removeClass('invisible');
$("aboutSoftwareUsedLink").addEvent("click", () => {
$$(".aboutTabContent").addClass("invisible");
$("aboutSoftwareUsedContent").removeClass("invisible");
});
})();
</script>

View file

@ -42,7 +42,7 @@
</div>
<script>
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -58,8 +58,8 @@
};
const categoriesFilterContextMenu = new window.qBittorrent.ContextMenu.CategoriesFilterContextMenu({
targets: '.categoriesFilterContextMenuTarget',
menu: 'categoriesFilterMenu',
targets: ".categoriesFilterContextMenuTarget",
menu: "categoriesFilterMenu",
actions: {
createCategory: function(element, ref) {
createCategoryFN();
@ -96,8 +96,8 @@
});
const tagsFilterContextMenu = new window.qBittorrent.ContextMenu.TagsFilterContextMenu({
targets: '.tagsFilterContextMenuTarget',
menu: 'tagsFilterMenu',
targets: ".tagsFilterContextMenuTarget",
menu: "tagsFilterMenu",
actions: {
createTag: function(element, ref) {
createTagFN();
@ -128,8 +128,8 @@
});
const trackersFilterContextMenu = new window.qBittorrent.ContextMenu.ContextMenu({
targets: '.trackersFilterContextMenuTarget',
menu: 'trackersFilterMenu',
targets: ".trackersFilterContextMenuTarget",
menu: "trackersFilterMenu",
actions: {
startTorrentsByTracker: function(element, ref) {
startTorrentsByTrackerFN(element.id);
@ -150,17 +150,17 @@
}
});
if (LocalPreferences.get('filter_status_collapsed') === "true")
toggleFilterDisplay('status');
if (LocalPreferences.get("filter_status_collapsed") === "true")
toggleFilterDisplay("status");
if (LocalPreferences.get('filter_category_collapsed') === "true")
toggleFilterDisplay('category');
if (LocalPreferences.get("filter_category_collapsed") === "true")
toggleFilterDisplay("category");
if (LocalPreferences.get('filter_tag_collapsed') === "true")
toggleFilterDisplay('tag');
if (LocalPreferences.get("filter_tag_collapsed") === "true")
toggleFilterDisplay("tag");
if (LocalPreferences.get('filter_tracker_collapsed') === "true")
toggleFilterDisplay('tracker');
if (LocalPreferences.get("filter_tracker_collapsed") === "true")
toggleFilterDisplay("tracker");
return exports();
})();

View file

@ -27,7 +27,7 @@
</div>
<script>
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -42,9 +42,9 @@
const init = function() {
new Keyboard({
defaultEventType: 'keydown',
defaultEventType: "keydown",
events: {
'Enter': function(e) {
"Enter": function(e) {
// accept enter key as a click
new Event(e).stop();
@ -52,25 +52,25 @@
if ((elem.id === "newPluginPath") || (elem.id === "newPluginOk"))
newPluginOk();
else if (elem.id === "newPluginCancel")
window.qBittorrent.SearchPlugins.closeSearchWindow('installSearchPlugin');
window.qBittorrent.SearchPlugins.closeSearchWindow("installSearchPlugin");
}
}
}).activate();
$('newPluginPath').select();
$("newPluginPath").select();
};
const newPluginOk = function() {
const path = $("newPluginPath").get("value").trim();
if (path)
new Request({
url: 'api/v2/search/installPlugin',
method: 'post',
url: "api/v2/search/installPlugin",
method: "post",
data: {
sources: path,
},
onRequest: function() {
window.qBittorrent.SearchPlugins.closeSearchWindow('installSearchPlugin');
window.qBittorrent.SearchPlugins.closeSearchWindow("installSearchPlugin");
}
}).send();
};

View file

@ -146,7 +146,7 @@
</ul>
<script>
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -166,8 +166,8 @@
};
};
let currentSelectedTab = 'main';
let tableInfo = {
let currentSelectedTab = "main";
const tableInfo = {
main: {
instance: new window.qBittorrent.DynamicTable.LogMessageTable(),
progress: false,
@ -186,10 +186,10 @@
let logFilterTimer = -1;
let inputtedFilterText = "";
let selectBox;
let selectedLogLevels = JSON.parse(LocalPreferences.get('qbt_selected_log_levels')) || ['1', '2', '4', '8'];
let selectedLogLevels = JSON.parse(LocalPreferences.get("qbt_selected_log_levels")) || ["1", "2", "4", "8"];
const init = () => {
$('logLevelSelect').getElements('option').each((x) => {
$("logLevelSelect").getElements("option").each((x) => {
if (selectedLogLevels.indexOf(x.value.toString()) !== -1) {
x.selected = true;
}
@ -198,26 +198,26 @@
}
});
selectBox = new vanillaSelectBox('#logLevelSelect', {
selectBox = new vanillaSelectBox("#logLevelSelect", {
maxHeight: 200,
search: false,
translations: {
all: 'QBT_TR(All)QBT_TR[CONTEXT=ExecutionLogWidget]',
item: 'QBT_TR(item)QBT_TR[CONTEXT=ExecutionLogWidget]',
items: 'QBT_TR(items)QBT_TR[CONTEXT=ExecutionLogWidget]',
selectAll: 'QBT_TR(Select All)QBT_TR[CONTEXT=ExecutionLogWidget]',
clearAll: 'QBT_TR(Clear All)QBT_TR[CONTEXT=ExecutionLogWidget]',
all: "QBT_TR(All)QBT_TR[CONTEXT=ExecutionLogWidget]",
item: "QBT_TR(item)QBT_TR[CONTEXT=ExecutionLogWidget]",
items: "QBT_TR(items)QBT_TR[CONTEXT=ExecutionLogWidget]",
selectAll: "QBT_TR(Select All)QBT_TR[CONTEXT=ExecutionLogWidget]",
clearAll: "QBT_TR(Clear All)QBT_TR[CONTEXT=ExecutionLogWidget]",
},
placeHolder: "QBT_TR(Choose a log level...)QBT_TR[CONTEXT=ExecutionLogWidget]",
keepInlineStyles: false
});
const logTableContextMenu = new window.qBittorrent.ContextMenu.ContextMenu({
targets: '.logTableRow',
menu: 'logTableMenu',
targets: ".logTableRow",
menu: "logTableMenu",
actions: {
Clear: () => {
tableInfo[currentSelectedTab].instance.selectedRowsIds().forEach(function(rowId) {
tableInfo[currentSelectedTab].instance.selectedRowsIds().forEach((rowId) => {
tableInfo[currentSelectedTab].instance.removeRow(rowId);
});
@ -230,18 +230,21 @@
}
});
tableInfo['main'].instance.setup('logMessageTableDiv', 'logMessageTableFixedHeaderDiv', logTableContextMenu);
tableInfo['peer'].instance.setup('logPeerTableDiv', 'logPeerTableFixedHeaderDiv', logTableContextMenu);
tableInfo["main"].instance.setup("logMessageTableDiv", "logMessageTableFixedHeaderDiv", logTableContextMenu);
tableInfo["peer"].instance.setup("logPeerTableDiv", "logPeerTableFixedHeaderDiv", logTableContextMenu);
MUI.Panels.instances.LogPanel.contentEl.setStyle('height', '100%');
$('logView').setStyle('height', 'inherit');
MUI.Panels.instances.LogPanel.contentEl.setStyle("height", "100%");
$("logView").setStyle("height", "inherit");
load();
};
const unload = () => {
for (let table in tableInfo)
for (const table in tableInfo) {
if (!Object.hasOwn(tableInfo, table))
continue;
resetTableTimer(table);
}
};
const load = () => {
@ -282,13 +285,13 @@
if (selectedLogLevels !== value) {
tableInfo[currentSelectedTab].last_id = -1;
selectedLogLevels = value;
LocalPreferences.set('qbt_selected_log_levels', JSON.stringify(selectedLogLevels));
LocalPreferences.set("qbt_selected_log_levels", JSON.stringify(selectedLogLevels));
logFilterChanged();
}
};
const filterTextChanged = () => {
const value = $('filterTextInput').get('value').trim();
const value = $("filterTextInput").get("value").trim();
if (inputtedFilterText !== value) {
inputtedFilterText = value;
logFilterChanged();
@ -310,17 +313,17 @@
return;
currentSelectedTab = tab;
if (currentSelectedTab === 'main') {
if (currentSelectedTab === "main") {
selectBox.enable();
$('logMessageView').removeClass('invisible');
$('logPeerView').addClass('invisible');
resetTableTimer('peer');
$("logMessageView").removeClass("invisible");
$("logPeerView").addClass("invisible");
resetTableTimer("peer");
}
else {
selectBox.disable();
$('logMessageView').addClass('invisible');
$('logPeerView').removeClass('invisible');
resetTableTimer('main');
$("logMessageView").addClass("invisible");
$("logPeerView").removeClass("invisible");
resetTableTimer("main");
}
clearTimeout(logFilterTimer);
@ -337,8 +340,8 @@
if (curTab === undefined)
curTab = currentSelectedTab;
$('numFilteredLogs').set('text', tableInfo[curTab].instance.filteredLength());
$('numTotalLogs').set('text', tableInfo[curTab].instance.getRowIds().length);
$("numFilteredLogs").set("text", tableInfo[curTab].instance.filteredLength());
$("numTotalLogs").set("text", tableInfo[curTab].instance.getRowIds().length);
};
const syncLogData = (curTab) => {
@ -346,37 +349,37 @@
curTab = currentSelectedTab;
let url;
if (curTab === 'main') {
url = new URI('api/v2/log/main');
if (curTab === "main") {
url = new URI("api/v2/log/main");
url.setData({
normal: selectedLogLevels.indexOf('1') !== -1,
info: selectedLogLevels.indexOf('2') !== -1,
warning: selectedLogLevels.indexOf('4') !== -1,
critical: selectedLogLevels.indexOf('8') !== -1
normal: selectedLogLevels.indexOf("1") !== -1,
info: selectedLogLevels.indexOf("2") !== -1,
warning: selectedLogLevels.indexOf("4") !== -1,
critical: selectedLogLevels.indexOf("8") !== -1
});
}
else {
url = new URI('api/v2/log/peers');
url = new URI("api/v2/log/peers");
}
url.setData('last_known_id', tableInfo[curTab].last_id);
url.setData("last_known_id", tableInfo[curTab].last_id);
tableInfo[curTab].progress = true;
new Request.JSON({
url: url,
method: 'get',
method: "get",
noCache: true,
onFailure: function(response) {
const errorDiv = $('error_div');
const errorDiv = $("error_div");
if (errorDiv)
errorDiv.set('text', 'QBT_TR(qBittorrent client is not reachable)QBT_TR[CONTEXT=HttpServer]');
errorDiv.set("text", "QBT_TR(qBittorrent client is not reachable)QBT_TR[CONTEXT=HttpServer]");
tableInfo[curTab].progress = false;
syncLogWithInterval(10000);
},
onSuccess: function(response) {
$('error_div').set('text', '');
$("error_div").set("text", "");
if ($('logTabColumn').hasClass('invisible'))
if ($("logTabColumn").hasClass("invisible"))
return;
if (response.length > 0) {
@ -385,7 +388,7 @@
for (let i = 0; i < response.length; ++i) {
let row;
if (curTab === 'main') {
if (curTab === "main") {
row = {
rowId: response[i].id,
message: response[i].message,
@ -417,14 +420,14 @@
}).send();
};
new ClipboardJS('.copyLogDataToClipboard', {
new ClipboardJS(".copyLogDataToClipboard", {
text: function() {
let msg = [];
tableInfo[currentSelectedTab].instance.selectedRowsIds().each(function(rowId) {
msg.push(tableInfo[currentSelectedTab].instance.rows.get(rowId).full_data[(currentSelectedTab === 'main') ? 'message' : 'ip']);
const msg = [];
tableInfo[currentSelectedTab].instance.selectedRowsIds().each((rowId) => {
msg.push(tableInfo[currentSelectedTab].instance.rows.get(rowId).full_data[(currentSelectedTab === "main") ? "message" : "ip"]);
});
return msg.join('\n');
return msg.join("\n");
}
});

File diff suppressed because it is too large Load diff

View file

@ -14,43 +14,43 @@
</div>
<script>
'use strict';
"use strict";
(function() {
// Tabs
MochaUI.initializeTabs('preferencesTabs');
MochaUI.initializeTabs("preferencesTabs");
$('PrefBehaviorLink').addEvent('click', function(e) {
$$('.PrefTab').addClass('invisible');
$('BehaviorTab').removeClass('invisible');
$("PrefBehaviorLink").addEvent("click", (e) => {
$$(".PrefTab").addClass("invisible");
$("BehaviorTab").removeClass("invisible");
});
$('PrefDownloadsLink').addEvent('click', function(e) {
$$('.PrefTab').addClass('invisible');
$('DownloadsTab').removeClass('invisible');
$("PrefDownloadsLink").addEvent("click", (e) => {
$$(".PrefTab").addClass("invisible");
$("DownloadsTab").removeClass("invisible");
});
$('PrefConnectionLink').addEvent('click', function(e) {
$$('.PrefTab').addClass('invisible');
$('ConnectionTab').removeClass('invisible');
$("PrefConnectionLink").addEvent("click", (e) => {
$$(".PrefTab").addClass("invisible");
$("ConnectionTab").removeClass("invisible");
});
$('PrefSpeedLink').addEvent('click', function(e) {
$$('.PrefTab').addClass('invisible');
$('SpeedTab').removeClass('invisible');
$("PrefSpeedLink").addEvent("click", (e) => {
$$(".PrefTab").addClass("invisible");
$("SpeedTab").removeClass("invisible");
});
$('PrefBittorrentLink').addEvent('click', function(e) {
$$('.PrefTab').addClass('invisible');
$('BittorrentTab').removeClass('invisible');
$("PrefBittorrentLink").addEvent("click", (e) => {
$$(".PrefTab").addClass("invisible");
$("BittorrentTab").removeClass("invisible");
});
$('PrefRSSLink').addEvent('click', function(e) {
$$('.PrefTab').addClass('invisible');
$('RSSTab').removeClass('invisible');
$("PrefRSSLink").addEvent("click", (e) => {
$$(".PrefTab").addClass("invisible");
$("RSSTab").removeClass("invisible");
});
$('PrefWebUILink').addEvent('click', function(e) {
$$('.PrefTab').addClass('invisible');
$('WebUITab').removeClass('invisible');
$("PrefWebUILink").addEvent("click", (e) => {
$$(".PrefTab").addClass("invisible");
$("WebUITab").removeClass("invisible");
});
$('PrefAdvancedLink').addEvent('click', function(e) {
$$('.PrefTab').addClass('invisible');
$('AdvancedTab').removeClass('invisible');
$("PrefAdvancedLink").addEvent("click", (e) => {
$$(".PrefTab").addClass("invisible");
$("AdvancedTab").removeClass("invisible");
});
})();
</script>

View file

@ -168,10 +168,10 @@
</div>
<script>
'use strict';
"use strict";
(function() {
const selectedTab = $(LocalPreferences.get('selected_tab', 'PropGeneralLink'));
const selectedTab = $(LocalPreferences.get("selected_tab", "PropGeneralLink"));
if (selectedTab)
selectedTab.click();
})();

View file

@ -156,13 +156,13 @@
</ul>
<script>
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
}
let serverSyncRssDataInterval = 1500;
const serverSyncRssDataInterval = 1500;
window.qBittorrent.Rss = (() => {
const exports = () => {
@ -185,37 +185,37 @@
let feedData = {};
let pathByFeedId = new Map();
let feedRefreshTimer;
let rssFeedTable = new window.qBittorrent.DynamicTable.RssFeedTable();
let rssArticleTable = new window.qBittorrent.DynamicTable.RssArticleTable();
const rssFeedTable = new window.qBittorrent.DynamicTable.RssFeedTable();
const rssArticleTable = new window.qBittorrent.DynamicTable.RssArticleTable();
const init = () => {
const pref = window.parent.qBittorrent.Cache.preferences.get();
if (!pref.rss_processing_enabled)
$('rssFetchingDisabled').removeClass('invisible');
$("rssFetchingDisabled").removeClass("invisible");
// recalculate heights
const nonPageHeight = $('rssTopBar').getBoundingClientRect().height
+ $('desktopHeader').getBoundingClientRect().height
+ $('desktopFooterWrapper').getBoundingClientRect().height + 20;
$('rssDetailsView').style.height = 'calc(100vh - ' + nonPageHeight + 'px)';
const nonPageHeight = $("rssTopBar").getBoundingClientRect().height
+ $("desktopHeader").getBoundingClientRect().height
+ $("desktopFooterWrapper").getBoundingClientRect().height + 20;
$("rssDetailsView").style.height = "calc(100vh - " + nonPageHeight + "px)";
const nonTableHeight = nonPageHeight + $('rssFeedFixedHeaderDiv').getBoundingClientRect().height;
$('rssFeedTableDiv').style.height = 'calc(100vh - ' + nonTableHeight + 'px)';
$('rssArticleTableDiv').style.height = 'calc(100vh - ' + nonTableHeight + 'px)';
const nonTableHeight = nonPageHeight + $("rssFeedFixedHeaderDiv").getBoundingClientRect().height;
$("rssFeedTableDiv").style.height = "calc(100vh - " + nonTableHeight + "px)";
$("rssArticleTableDiv").style.height = "calc(100vh - " + nonTableHeight + "px)";
$('rssContentView').style.height = 'calc(100% - ' + $('rssTopBar').getBoundingClientRect().height + 'px)';
$("rssContentView").style.height = "calc(100% - " + $("rssTopBar").getBoundingClientRect().height + "px)";
const rssFeedContextMenu = new window.qBittorrent.ContextMenu.RssFeedContextMenu({
targets: '.rssFeedContextMenuTarget',
menu: 'rssFeedMenu',
targets: ".rssFeedContextMenuTarget",
menu: "rssFeedMenu",
actions: {
update: (el) => {
let feedsToUpdate = new Set();
const feedsToUpdate = new Set();
rssFeedTable.selectedRows.each((rowId) => {
let selectedPath = rssFeedTable.rows[rowId].full_data.dataPath;
const selectedPath = rssFeedTable.rows[rowId].full_data.dataPath;
rssFeedTable.rows.filter((row) => row.full_data.dataPath.slice(0, selectedPath.length) === selectedPath)
.filter((row) => row.full_data.dataUid !== '')
.filter((row) => row.full_data.dataUid !== "")
.each((row) => feedsToUpdate.add(row));
});
feedsToUpdate.forEach((feed) => refreshFeed(feed.full_data.dataUid));
@ -225,11 +225,11 @@
moveItem(rssFeedTable.rows[rssFeedTable.selectedRows[0]].full_data.dataPath);
},
delete: (el) => {
let selectedDatapaths = rssFeedTable.selectedRows
const selectedDatapaths = rssFeedTable.selectedRows
.filter((e) => e !== 0)
.map((sRow) => rssFeedTable.rows[sRow].full_data.dataPath);
// filter children
let reducedDatapaths = selectedDatapaths.filter((path) =>
const reducedDatapaths = selectedDatapaths.filter((path) =>
selectedDatapaths.filter((innerPath) => path.slice(0, innerPath.length) === innerPath).length === 1
);
removeItem(reducedDatapaths);
@ -244,39 +244,39 @@
}
});
rssFeedContextMenu.addTarget($('rssFeedTableDiv'));
rssFeedContextMenu.addTarget($("rssFeedTableDiv"));
// deselect feed when clicking on empty part of table
$('rssFeedTableDiv').addEventListener('click', (e) => {
$("rssFeedTableDiv").addEventListener("click", (e) => {
rssFeedTable.deselectAll();
rssFeedTable.deselectRow();
});
$('rssFeedTableDiv').addEventListener('contextmenu', (e) => {
if (e.toElement.nodeName === 'DIV') {
$("rssFeedTableDiv").addEventListener("contextmenu", (e) => {
if (e.toElement.nodeName === "DIV") {
rssFeedTable.deselectAll();
rssFeedTable.deselectRow();
rssFeedContextMenu.updateMenuItems();
}
});
new ClipboardJS('#CopyFeedURL', {
new ClipboardJS("#CopyFeedURL", {
text: () => {
let joined = '';
let joined = "";
rssFeedTable.selectedRows
.filter((row) => rssFeedTable.rows[row].full_data.dataUid !== '')
.each((row) => joined += rssFeedTable.rows[row].full_data.dataUrl + '\n');
.filter((row) => rssFeedTable.rows[row].full_data.dataUid !== "")
.each((row) => joined += rssFeedTable.rows[row].full_data.dataUrl + "\n");
return joined.slice(0, -1);
}
});
rssFeedTable.setup('rssFeedTableDiv', 'rssFeedFixedHeaderDiv', rssFeedContextMenu);
rssFeedTable.setup("rssFeedTableDiv", "rssFeedFixedHeaderDiv", rssFeedContextMenu);
const rssArticleContextMenu = new window.qBittorrent.ContextMenu.RssArticleContextMenu({
targets: '.rssArticleElement',
menu: 'rssArticleMenu',
targets: ".rssArticleElement",
menu: "rssArticleMenu",
actions: {
Download: (el) => {
let dlString = '';
let dlString = "";
rssArticleTable.selectedRows.each((row) => {
dlString += rssArticleTable.rows[row].full_data.torrentURL + '\n';
dlString += rssArticleTable.rows[row].full_data.torrentURL + "\n";
});
showDownloadPage([dlString]);
},
@ -291,7 +291,7 @@
y: -57
}
});
rssArticleTable.setup('rssArticleTableDiv', 'rssArticleFixedHeaderDiv', rssArticleContextMenu);
rssArticleTable.setup("rssArticleTableDiv", "rssArticleFixedHeaderDiv", rssArticleContextMenu);
updateRssFeedList();
load();
};
@ -305,24 +305,24 @@
};
const addRSSFeed = () => {
let path = '';
let path = "";
if (rssFeedTable.selectedRows.length !== 0) {
let row = rssFeedTable.rows[rssFeedTable.selectedRows[0]];
if (row.full_data.dataUid === '') {
const row = rssFeedTable.rows[rssFeedTable.selectedRows[0]];
if (row.full_data.dataUid === "") {
path = row.full_data.dataPath;
}
else {
let lastIndex = row.full_data.dataPath.lastIndexOf('\\');
const lastIndex = row.full_data.dataPath.lastIndexOf("\\");
if (lastIndex !== -1)
path = row.full_data.dataPath.slice(0, lastIndex);
}
}
new MochaUI.Window({
id: 'newFeed',
title: 'QBT_TR(Please type a RSS feed URL)QBT_TR[CONTEXT=RSSWidget]',
loadMethod: 'iframe',
contentURL: 'newfeed.html?path=' + encodeURIComponent(path),
id: "newFeed",
title: "QBT_TR(Please type a RSS feed URL)QBT_TR[CONTEXT=RSSWidget]",
loadMethod: "iframe",
contentURL: "newfeed.html?path=" + encodeURIComponent(path),
scrollbars: false,
resizable: false,
maximizable: false,
@ -332,24 +332,24 @@
};
const addFolder = () => {
let path = '';
let path = "";
if (rssFeedTable.selectedRows.length !== 0) {
let row = rssFeedTable.rows[rssFeedTable.selectedRows[0]];
if (row.full_data.dataUid === '') {
const row = rssFeedTable.rows[rssFeedTable.selectedRows[0]];
if (row.full_data.dataUid === "") {
path = row.full_data.dataPath;
}
else {
let lastIndex = row.full_data.dataPath.lastIndexOf('\\');
const lastIndex = row.full_data.dataPath.lastIndexOf("\\");
if (lastIndex !== -1)
path = row.full_data.dataPath.slice(0, lastIndex);
}
}
new MochaUI.Window({
id: 'newFolder',
title: 'QBT_TR(Please choose a folder name)QBT_TR[CONTEXT=RSSWidget]',
loadMethod: 'iframe',
contentURL: 'newfolder.html?path=' + encodeURIComponent(path),
id: "newFolder",
title: "QBT_TR(Please choose a folder name)QBT_TR[CONTEXT=RSSWidget]",
loadMethod: "iframe",
contentURL: "newfolder.html?path=" + encodeURIComponent(path),
scrollbars: false,
resizable: false,
maximizable: false,
@ -362,13 +362,13 @@
rssArticleTable.clear();
let rowCount = 0;
let childFeeds = new Set();
const childFeeds = new Set();
rssFeedTable.rows.filter((row) => row.full_data.dataPath.slice(0, path.length) === path)
.filter((row) => row.full_data.dataUid !== '')
.filter((row) => row.full_data.dataUid !== "")
.each((row) => childFeeds.add(row.full_data.dataUid));
let visibleArticles = [];
for (let feedEntry in feedData) {
for (const feedEntry in feedData) {
if (childFeeds.has(feedEntry))
visibleArticles.append(feedData[feedEntry]
.map((a) => {
@ -377,7 +377,7 @@
}));
}
//filter read articles if "Unread" feed is selected
if (path === '')
if (path === "")
visibleArticles = visibleArticles.filter((a) => !a.isRead);
visibleArticles.sort((e1, e2) => new Date(e2.date) - new Date(e1.date))
@ -393,61 +393,64 @@
});
});
$('rssDetailsView').getChildren().each(c => c.destroy());
$("rssDetailsView").getChildren().each(c => c.destroy());
rssArticleTable.updateTable(false);
};
const showDetails = (feedUid, articleID) => {
markArticleAsRead(pathByFeedId.get(feedUid), articleID);
$('rssDetailsView').getChildren().each(c => c.destroy());
let article = feedData[feedUid].filter((article) => article.id === articleID)[0];
$("rssDetailsView").getChildren().each(c => c.destroy());
const article = feedData[feedUid].filter((article) => article.id === articleID)[0];
if (article) {
$('rssDetailsView').append((() => {
let torrentName = document.createElement('p');
$("rssDetailsView").append((() => {
const torrentName = document.createElement("p");
torrentName.innerText = article.title;
torrentName.setAttribute('id', 'rssTorrentDetailsName');
torrentName.setAttribute("id", "rssTorrentDetailsName");
return torrentName;
})());
$('rssDetailsView').append((() => {
let torrentDate = document.createElement('div');
torrentDate.setAttribute('id', 'rssTorrentDetailsDate');
$("rssDetailsView").append((() => {
const torrentDate = document.createElement("div");
torrentDate.setAttribute("id", "rssTorrentDetailsDate");
let torrentDateDesc = document.createElement('b');
torrentDateDesc.innerText = 'QBT_TR(Date: )QBT_TR[CONTEXT=RSSWidget]';
const torrentDateDesc = document.createElement("b");
torrentDateDesc.innerText = "QBT_TR(Date: )QBT_TR[CONTEXT=RSSWidget]";
torrentDate.append(torrentDateDesc);
let torrentDateData = document.createElement('span');
const torrentDateData = document.createElement("span");
torrentDateData.innerText = new Date(article.date).toLocaleString();
torrentDate.append(torrentDateData);
return torrentDate;
})());
// Place in iframe with sandbox attribute to prevent js execution
let torrentDescription = document.createRange().createContextualFragment('<iframe sandbox id="rssDescription"></iframe>');
$('rssDetailsView').append(torrentDescription);
document.getElementById('rssDescription').srcdoc = '<html><head><link rel="stylesheet" type="text/css" href="css/style.css" /></head><body>' + article.description + "</body></html>";
const torrentDescription = document.createRange().createContextualFragment('<iframe sandbox id="rssDescription"></iframe>');
$("rssDetailsView").append(torrentDescription);
document.getElementById("rssDescription").srcdoc = '<html><head><link rel="stylesheet" type="text/css" href="css/style.css" /></head><body>' + article.description + "</body></html>";
//calculate height to fill screen
document.getElementById('rssDescription').style.height =
"calc(100% - " + document.getElementById('rssTorrentDetailsName').offsetHeight + "px - "
+ document.getElementById('rssTorrentDetailsDate').offsetHeight + "px - 5px)";
document.getElementById("rssDescription").style.height =
"calc(100% - " + document.getElementById("rssTorrentDetailsName").offsetHeight + "px - "
+ document.getElementById("rssTorrentDetailsDate").offsetHeight + "px - 5px)";
}
};
const updateRssFeedList = () => {
new Request.JSON({
url: 'api/v2/rss/items',
method: 'get',
url: "api/v2/rss/items",
method: "get",
noCache: true,
data: {
withData: true
},
onSuccess: (response) => {
// flatten folder structure
let flattenedResp = [];
let recFlatten = (current, name = '', depth = 0, fullName = '') => {
for (let child in current) {
let currentFullName = fullName ? (fullName + '\\' + child) : child;
const flattenedResp = [];
const recFlatten = (current, name = "", depth = 0, fullName = "") => {
for (const child in current) {
if (!Object.hasOwn(current, child))
continue;
const currentFullName = fullName ? (fullName + "\\" + child) : child;
if (current[child].uid !== undefined) {
current[child].name = child;
current[child].isFolder = false;
@ -473,7 +476,7 @@
if ((rssFeedTable.rows.getLength() - 1) === flattenedResp.length) {
match = true;
for (let i = 0; i < flattenedResp.length; ++i) {
if (((flattenedResp[i].uid ? flattenedResp[i].uid : '') !== rssFeedTable.rows[i + 1].full_data.dataUid)
if (((flattenedResp[i].uid ? flattenedResp[i].uid : "") !== rssFeedTable.rows[i + 1].full_data.dataUid)
|| (flattenedResp[i].fullName !== rssFeedTable.rows[i + 1].full_data.dataPath)) {
match = false;
break;
@ -486,14 +489,14 @@
// update status
let statusDiffers = false;
for (let i = 0; i < flattenedResp.length; ++i) {
let oldStatus = rssFeedTable.rows[i + 1].full_data.status;
let status = 'default';
const oldStatus = rssFeedTable.rows[i + 1].full_data.status;
let status = "default";
if (flattenedResp[i].hasError)
status = 'hasError';
status = "hasError";
if (flattenedResp[i].isLoading)
status = 'isLoading';
status = "isLoading";
if (flattenedResp[i].isFolder)
status = 'isFolder';
status = "isFolder";
if (oldStatus !== status) {
statusDiffers = true;
@ -509,7 +512,7 @@
// get currently opened feed
let openedFeedPath = undefined;
if (rssFeedTable.selectedRows.length !== 0) {
let lastSelectedRow = rssFeedTable.selectedRows[rssFeedTable.selectedRows.length - 1];
const lastSelectedRow = rssFeedTable.selectedRows[rssFeedTable.selectedRows.length - 1];
openedFeedPath = rssFeedTable.rows[lastSelectedRow].full_data.dataPath;
}
@ -528,9 +531,9 @@
if (articlesDiffer) {
// update unread count
let oldUnread = feedData[r.uid].map((art) => !art.isRead).filter((v) => v).length;
let newUnread = r.articles.map((art) => !art.isRead).filter((v) => v).length;
let unreadDifference = newUnread - oldUnread;
const oldUnread = feedData[r.uid].map((art) => !art.isRead).filter((v) => v).length;
const newUnread = r.articles.map((art) => !art.isRead).filter((v) => v).length;
const unreadDifference = newUnread - oldUnread;
// find all parents (and self) and add unread difference
rssFeedTable.rows.filter((row) => r.fullName.slice(0, row.full_data.dataPath.length) === row.full_data.dataPath)
@ -549,8 +552,8 @@
let readDifference = 0;
let readChanged = false;
for (let i = 0; i < r.articles.length; ++i) {
let oldRead = feedData[r.uid][i].isRead ? 1 : 0;
let newRead = r.articles[i].isRead ? 1 : 0;
const oldRead = feedData[r.uid][i].isRead ? 1 : 0;
const newRead = r.articles[i].isRead ? 1 : 0;
feedData[r.uid][i].isRead = r.articles[i].isRead;
readDifference += oldRead - newRead;
if (readDifference !== 0)
@ -567,7 +570,7 @@
// if feed that is opened changed update dynamically
if ((openedFeedPath !== undefined) && (r.fullName.slice(0, openedFeedPath.length) === openedFeedPath)) {
for (let i = 0; i < r.articles.length; ++i) {
let matchingRow = rssArticleTable.rows.filter((row) => row.full_data.feedUid === r.uid)
const matchingRow = rssArticleTable.rows.filter((row) => row.full_data.feedUid === r.uid)
.filter((row) => row.full_data.dataId === r.articles[i].id);
matchingRow[Object.keys(matchingRow)[0]].full_data.isRead = r.articles[i].isRead;
}
@ -590,35 +593,35 @@
// Unread entry at top
rssFeedTable.updateRowData({
rowId: 0,
name: 'QBT_TR(Unread)QBT_TR[CONTEXT=FeedListWidget]',
name: "QBT_TR(Unread)QBT_TR[CONTEXT=FeedListWidget]",
unread: 0,
status: 'unread',
status: "unread",
indentation: 0,
dataUid: '',
dataUrl: '',
dataPath: ''
dataUid: "",
dataUrl: "",
dataPath: ""
});
let rowCount = 1;
for (let dataEntry of flattenedResp) {
for (const dataEntry of flattenedResp) {
if (dataEntry.isFolder) {
rssFeedTable.updateRowData({
rowId: rowCount,
name: dataEntry.name,
unread: 0,
status: 'isFolder',
status: "isFolder",
indentation: dataEntry.depth,
dataUid: '',
dataUrl: '',
dataUid: "",
dataUrl: "",
dataPath: dataEntry.fullName
});
}
else {
let status = 'default';
let status = "default";
if (dataEntry.hasError)
status = 'hasError';
status = "hasError";
if (dataEntry.isLoading)
status = 'isLoading';
status = "isLoading";
rssFeedTable.updateRowData({
rowId: rowCount,
@ -632,7 +635,7 @@
});
// calculate number of unread
let numberOfUnread = dataEntry.articles.map((art) => !art.isRead).filter((v) => v).length;
const numberOfUnread = dataEntry.articles.map((art) => !art.isRead).filter((v) => v).length;
// find all items that contain this rss feed and add unread count
rssFeedTable.rows.filter((row) => dataEntry.fullName.slice(0, row.full_data.dataPath.length) === row.full_data.dataPath)
.each((row) => row.full_data.unread += numberOfUnread);
@ -653,13 +656,13 @@
// set icon to loading
rssFeedTable.rows.forEach((row) => {
if (row.full_data.dataUid === feedUid)
row.full_data.status = 'isLoading';
row.full_data.status = "isLoading";
});
rssFeedTable.updateIcons();
new Request({
url: 'api/v2/rss/refreshItem',
method: 'post',
url: "api/v2/rss/refreshItem",
method: "post",
data: {
itemPath: pathByFeedId.get(feedUid)
},
@ -671,16 +674,19 @@
};
const refreshAllFeeds = () => {
for (let feedEntry in feedData)
for (const feedEntry in feedData) {
if (!Object.hasOwn(feedData, feedEntry))
continue;
refreshFeed(feedEntry);
}
};
const moveItem = (oldPath) => {
new MochaUI.Window({
id: 'renamePage',
title: 'QBT_TR(Please choose a new name for this RSS feed)QBT_TR[CONTEXT=RSSWidget]',
loadMethod: 'iframe',
contentURL: 'rename_feed.html?oldPath=' + encodeURIComponent(oldPath),
id: "renamePage",
title: "QBT_TR(Please choose a new name for this RSS feed)QBT_TR[CONTEXT=RSSWidget]",
loadMethod: "iframe",
contentURL: "rename_feed.html?oldPath=" + encodeURIComponent(oldPath),
scrollbars: false,
resizable: false,
maximizable: false,
@ -692,10 +698,10 @@
const removeItem = (paths) => {
const encodedPaths = paths.map((path) => encodeURIComponent(path));
new MochaUI.Window({
id: 'confirmFeedDeletionPage',
title: 'QBT_TR(Deletion confirmation)QBT_TR[CONTEXT=RSSWidget]',
loadMethod: 'iframe',
contentURL: 'confirmfeeddeletion.html?paths=' + encodeURIComponent(encodedPaths.join('|')),
id: "confirmFeedDeletionPage",
title: "QBT_TR(Deletion confirmation)QBT_TR[CONTEXT=RSSWidget]",
loadMethod: "iframe",
contentURL: "confirmfeeddeletion.html?paths=" + encodeURIComponent(encodedPaths.join("|")),
scrollbars: false,
resizable: false,
maximizable: false,
@ -706,7 +712,7 @@
const markItemAsRead = (path) => {
// feed data mark as read
for (let feedID in feedData)
for (const feedID in feedData)
if (pathByFeedId.get(feedID).slice(0, path.length) === path)
feedData[feedID].each((el) => el.isRead = true);
@ -735,8 +741,8 @@
// send request
new Request({
url: 'api/v2/rss/markAsRead',
method: 'post',
url: "api/v2/rss/markAsRead",
method: "post",
data: {
itemPath: path
},
@ -775,8 +781,8 @@
rssFeedTable.updateTable(true);
new Request({
url: 'api/v2/rss/markAsRead',
method: 'post',
url: "api/v2/rss/markAsRead",
method: "post",
data: {
itemPath: path,
articleId: id
@ -790,22 +796,22 @@
};
const markSelectedAsRead = () => {
let selectedDatapaths = rssFeedTable.selectedRows
const selectedDatapaths = rssFeedTable.selectedRows
.map((sRow) => rssFeedTable.rows[sRow].full_data.dataPath);
// filter children
let reducedDatapaths = selectedDatapaths.filter((path) =>
const reducedDatapaths = selectedDatapaths.filter((path) =>
selectedDatapaths.filter((innerPath) => path.slice(0, innerPath.length) === innerPath).length === 1
);
reducedDatapaths.each((path) => markItemAsRead(path));
};
const openRssDownloader = () => {
const id = 'rssdownloaderpage';
const id = "rssdownloaderpage";
new MochaUI.Window({
id: id,
title: 'QBT_TR(Rss Downloader)QBT_TR[CONTEXT=AutomatedRssDownloader]',
loadMethod: 'xhr',
contentURL: 'views/rssDownloader.html',
title: "QBT_TR(Rss Downloader)QBT_TR[CONTEXT=AutomatedRssDownloader]",
loadMethod: "xhr",
contentURL: "views/rssDownloader.html",
maximizable: false,
width: loadWindowWidth(id, 800),
height: loadWindowHeight(id, 650),
@ -813,8 +819,8 @@
saveWindowSize(id);
},
resizeLimit: {
'x': [800, 2500],
'y': [500, 2000]
"x": [800, 2500],
"y": [500, 2000]
}
});
};

View file

@ -328,7 +328,7 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
</ul>
<script>
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -350,9 +350,9 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
};
};
let rssDownloaderRulesTable = new window.qBittorrent.DynamicTable.RssDownloaderRulesTable();
let rssDownloaderFeedSelectionTable = new window.qBittorrent.DynamicTable.RssDownloaderFeedSelectionTable();
let rssDownloaderArticlesTable = new window.qBittorrent.DynamicTable.RssDownloaderArticlesTable();
const rssDownloaderRulesTable = new window.qBittorrent.DynamicTable.RssDownloaderRulesTable();
const rssDownloaderFeedSelectionTable = new window.qBittorrent.DynamicTable.RssDownloaderFeedSelectionTable();
const rssDownloaderArticlesTable = new window.qBittorrent.DynamicTable.RssDownloaderArticlesTable();
let rulesList = {};
let feedList = [];
@ -361,35 +361,35 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
const pref = window.parent.qBittorrent.Cache.preferences.get();
if (!pref.rss_auto_downloading_enabled)
$('rssDownloaderDisabled').removeClass('invisible');
$("rssDownloaderDisabled").removeClass("invisible");
// recalculate height
const warningHeight = $('rssDownloaderDisabled').getBoundingClientRect().height;
const warningHeight = $("rssDownloaderDisabled").getBoundingClientRect().height;
$('leftRssDownloaderColumn').style.height = 'calc(100% - ' + warningHeight + 'px)';
$('centerRssDownloaderColumn').style.height = 'calc(100% - ' + warningHeight + 'px)';
$('rightRssDownloaderColumn').style.height = 'calc(100% - ' + warningHeight + 'px)';
$("leftRssDownloaderColumn").style.height = "calc(100% - " + warningHeight + "px)";
$("centerRssDownloaderColumn").style.height = "calc(100% - " + warningHeight + "px)";
$("rightRssDownloaderColumn").style.height = "calc(100% - " + warningHeight + "px)";
$('rulesTable').style.height = 'calc(100% - ' + $('rulesTableDesc').getBoundingClientRect().height + 'px)';
$('rssDownloaderArticlesTable').style.height = 'calc(100% - ' + $('articleTableDesc').getBoundingClientRect().height + 'px)';
$("rulesTable").style.height = "calc(100% - " + $("rulesTableDesc").getBoundingClientRect().height + "px)";
$("rssDownloaderArticlesTable").style.height = "calc(100% - " + $("articleTableDesc").getBoundingClientRect().height + "px)";
const centerRowNotTableHeight = $('saveButton').getBoundingClientRect().height
+ $('ruleSettings').getBoundingClientRect().height + 15;
const centerRowNotTableHeight = $("saveButton").getBoundingClientRect().height
+ $("ruleSettings").getBoundingClientRect().height + 15;
$('rssDownloaderFeeds').style.height = 'calc(100% - ' + centerRowNotTableHeight + 'px)';
$("rssDownloaderFeeds").style.height = "calc(100% - " + centerRowNotTableHeight + "px)";
// firefox calculates the height of the table inside fieldset differently and thus doesn't need the offset
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
$('rssDownloaderFeedsTable').style.height = '100%';
if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
$("rssDownloaderFeedsTable").style.height = "100%";
}
else {
let outsideTableHeight = ($('rssDownloaderFeedsTable').getBoundingClientRect().top - $('rssDownloaderFeeds').getBoundingClientRect().top) - 10;
$('rssDownloaderFeedsTable').style.height = 'calc(100% - ' + outsideTableHeight + 'px)';
const outsideTableHeight = ($("rssDownloaderFeedsTable").getBoundingClientRect().top - $("rssDownloaderFeeds").getBoundingClientRect().top) - 10;
$("rssDownloaderFeedsTable").style.height = "calc(100% - " + outsideTableHeight + "px)";
}
const rssDownloaderRuleContextMenu = new window.qBittorrent.ContextMenu.RssDownloaderRuleContextMenu({
targets: '',
menu: 'rssDownloaderRuleMenu',
targets: "",
menu: "rssDownloaderRuleMenu",
actions: {
addRule: addRule,
deleteRule: removeSelectedRule,
@ -406,34 +406,37 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
y: -4
}
});
rssDownloaderRulesTable.setup('rssDownloaderRuleTableDiv', 'rssDownloaderRuleFixedHeaderDiv', rssDownloaderRuleContextMenu);
rssDownloaderFeedSelectionTable.setup('rssDownloaderFeedSelectionTableDiv', 'rssDownloaderFeedSelectionFixedHeaderDiv');
rssDownloaderArticlesTable.setup('rssDownloaderArticlesTableDiv', 'rssDownloaderArticlesFixedHeaderDiv');
rssDownloaderRulesTable.setup("rssDownloaderRuleTableDiv", "rssDownloaderRuleFixedHeaderDiv", rssDownloaderRuleContextMenu);
rssDownloaderFeedSelectionTable.setup("rssDownloaderFeedSelectionTableDiv", "rssDownloaderFeedSelectionFixedHeaderDiv");
rssDownloaderArticlesTable.setup("rssDownloaderArticlesTableDiv", "rssDownloaderArticlesFixedHeaderDiv");
rssDownloaderRuleContextMenu.addTarget($('rulesTable'));
rssDownloaderRuleContextMenu.addTarget($("rulesTable"));
// deselect feed when clicking on empty part of table
$('rulesTable').addEventListener('click', (e) => {
$("rulesTable").addEventListener("click", (e) => {
rssDownloaderRulesTable.deselectAll();
rssDownloaderRulesTable.deselectRow();
showRule('');
showRule("");
});
$('rulesTable').addEventListener('contextmenu', (e) => {
if (e.toElement.nodeName === 'DIV') {
$("rulesTable").addEventListener("contextmenu", (e) => {
if (e.toElement.nodeName === "DIV") {
rssDownloaderRulesTable.deselectAll();
rssDownloaderRulesTable.deselectRow();
rssDownloaderRuleContextMenu.updateMenuItems();
showRule('');
showRule("");
}
});
// get all categories and add to combobox
new Request.JSON({
url: 'api/v2/torrents/categories',
method: 'get',
url: "api/v2/torrents/categories",
method: "get",
noCache: true,
onSuccess: (response) => {
let combobox = $('assignCategoryCombobox');
for (let cat in response) {
let option = document.createElement('option');
const combobox = $("assignCategoryCombobox");
for (const cat in response) {
if (!Object.hasOwn(response, cat))
continue;
const option = document.createElement("option");
option.text = option.value = cat;
combobox.add(option);
}
@ -441,16 +444,16 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
}).send();
// get all rss feed
new Request.JSON({
url: 'api/v2/rss/items',
method: 'get',
url: "api/v2/rss/items",
method: "get",
noCache: true,
data: {
withData: false
},
onSuccess: (response) => {
feedList = [];
let flatten = (root) => {
for (let child in root) {
const flatten = (root) => {
for (const child in root) {
if (root[child].uid !== undefined)
feedList.push({ name: child, url: root[child].url });
else
@ -460,8 +463,8 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
flatten(response);
}
}).send();
$('savetoDifferentDir').addEvent('click', () => {
$('saveToText').disabled = !$('savetoDifferentDir').checked;
$("savetoDifferentDir").addEvent("click", () => {
$("saveToText").disabled = !$("savetoDifferentDir").checked;
});
updateRulesList();
};
@ -469,13 +472,15 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
const updateRulesList = () => {
// get all rules
new Request.JSON({
url: 'api/v2/rss/rules',
method: 'get',
url: "api/v2/rss/rules",
method: "get",
noCache: true,
onSuccess: (response) => {
rssDownloaderRulesTable.clear();
let rowCount = 0;
for (let rule in response) {
for (const rule in response) {
if (!Object.hasOwn(response, rule))
continue;
rssDownloaderRulesTable.updateRowData({
rowId: rowCount++,
checked: response[rule].enabled,
@ -491,8 +496,8 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
const modifyRuleState = (rule, setting, newState, callback = () => {}) => {
rulesList[rule][setting] = newState;
new Request({
url: 'api/v2/rss/setRule',
method: 'post',
url: "api/v2/rss/setRule",
method: "post",
data: {
ruleName: rule,
ruleDef: JSON.stringify(rulesList[rule])
@ -505,10 +510,10 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
const addRule = () => {
new MochaUI.Window({
id: 'newRulePage',
title: 'QBT_TR(New rule name)QBT_TR[CONTEXT=AutomatedRssDownloader]',
loadMethod: 'iframe',
contentURL: 'newrule.html',
id: "newRulePage",
title: "QBT_TR(New rule name)QBT_TR[CONTEXT=AutomatedRssDownloader]",
loadMethod: "iframe",
contentURL: "newrule.html",
scrollbars: false,
resizable: false,
maximizable: false,
@ -519,10 +524,10 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
const renameRule = (rule) => {
new MochaUI.Window({
id: 'renameRulePage',
title: 'QBT_TR(Rule renaming)QBT_TR[CONTEXT=AutomatedRssDownloader]',
loadMethod: 'iframe',
contentURL: 'rename_rule.html?rule=' + encodeURIComponent(rule),
id: "renameRulePage",
title: "QBT_TR(Rule renaming)QBT_TR[CONTEXT=AutomatedRssDownloader]",
loadMethod: "iframe",
contentURL: "rename_rule.html?rule=" + encodeURIComponent(rule),
scrollbars: false,
resizable: false,
maximizable: false,
@ -541,10 +546,10 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
const removeRules = (rules) => {
const encodedRules = rules.map((rule) => encodeURIComponent(rule));
new MochaUI.Window({
id: 'removeRulePage',
title: 'QBT_TR(Rule deletion confirmation)QBT_TR[CONTEXT=AutomatedRssDownloader]',
loadMethod: 'iframe',
contentURL: 'confirmruledeletion.html?rules=' + encodeURIComponent(encodedRules.join('|')),
id: "removeRulePage",
title: "QBT_TR(Rule deletion confirmation)QBT_TR[CONTEXT=AutomatedRssDownloader]",
loadMethod: "iframe",
contentURL: "confirmruledeletion.html?rules=" + encodeURIComponent(encodedRules.join("|")),
scrollbars: false,
resizable: false,
maximizable: false,
@ -556,10 +561,10 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
const clearDownloadedEpisodes = (rules) => {
const encodedRules = rules.map((rule) => encodeURIComponent(rule));
new MochaUI.Window({
id: 'clearRulesPage',
title: 'QBT_TR(New rule name)QBT_TR[CONTEXT=AutomatedRssDownloader]',
loadMethod: 'iframe',
contentURL: 'confirmruleclear.html?rules=' + encodeURIComponent(encodedRules.join('|')),
id: "clearRulesPage",
title: "QBT_TR(New rule name)QBT_TR[CONTEXT=AutomatedRssDownloader]",
loadMethod: "iframe",
contentURL: "confirmruleclear.html?rules=" + encodeURIComponent(encodedRules.join("|")),
scrollbars: false,
resizable: false,
maximizable: false,
@ -569,56 +574,56 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
};
const saveSettings = () => {
let lastSelectedRow = rssDownloaderRulesTable.selectedRows[rssDownloaderRulesTable.selectedRows.length - 1];
let rule = rssDownloaderRulesTable.rows[lastSelectedRow].full_data.name;
const lastSelectedRow = rssDownloaderRulesTable.selectedRows[rssDownloaderRulesTable.selectedRows.length - 1];
const rule = rssDownloaderRulesTable.rows[lastSelectedRow].full_data.name;
rulesList[rule].useRegex = $('useRegEx').checked;
rulesList[rule].mustContain = $('mustContainText').value;
rulesList[rule].mustNotContain = $('mustNotContainText').value;
rulesList[rule].episodeFilter = $('episodeFilterText').value;
rulesList[rule].smartFilter = $('useSmartFilter').checked;
rulesList[rule].ignoreDays = parseInt($('ignoreDaysValue').value);
rulesList[rule].useRegex = $("useRegEx").checked;
rulesList[rule].mustContain = $("mustContainText").value;
rulesList[rule].mustNotContain = $("mustNotContainText").value;
rulesList[rule].episodeFilter = $("episodeFilterText").value;
rulesList[rule].smartFilter = $("useSmartFilter").checked;
rulesList[rule].ignoreDays = parseInt($("ignoreDaysValue").value, 10);
rulesList[rule].affectedFeeds = rssDownloaderFeedSelectionTable.rows.filter((row) => row.full_data.checked)
.map((row) => row.full_data.url)
.getValues();
rulesList[rule].torrentParams.category = $('assignCategoryCombobox').value;
rulesList[rule].torrentParams.tags = $('ruleAddTags').value.split(',');
if ($('savetoDifferentDir').checked) {
rulesList[rule].torrentParams.save_path = $('saveToText').value;
rulesList[rule].torrentParams.category = $("assignCategoryCombobox").value;
rulesList[rule].torrentParams.tags = $("ruleAddTags").value.split(",");
if ($("savetoDifferentDir").checked) {
rulesList[rule].torrentParams.save_path = $("saveToText").value;
rulesList[rule].torrentParams.use_auto_tmm = false;
}
switch ($('addStoppedCombobox').value) {
case 'default':
switch ($("addStoppedCombobox").value) {
case "default":
rulesList[rule].torrentParams.stopped = null;
break;
case 'always':
case "always":
rulesList[rule].torrentParams.stopped = true;
break;
case 'never':
case "never":
rulesList[rule].torrentParams.stopped = false;
break;
}
switch ($('contentLayoutCombobox').value) {
case 'Default':
switch ($("contentLayoutCombobox").value) {
case "Default":
rulesList[rule].torrentParams.content_layout = null;
break;
case 'Original':
rulesList[rule].torrentParams.content_layout = 'Original';
case "Original":
rulesList[rule].torrentParams.content_layout = "Original";
break;
case 'Subfolder':
rulesList[rule].torrentParams.content_layout = 'Subfolder';
case "Subfolder":
rulesList[rule].torrentParams.content_layout = "Subfolder";
break;
case 'NoSubfolder':
rulesList[rule].torrentParams.content_layout = 'NoSubfolder';
case "NoSubfolder":
rulesList[rule].torrentParams.content_layout = "NoSubfolder";
break;
}
new Request({
url: 'api/v2/rss/setRule',
method: 'post',
url: "api/v2/rss/setRule",
method: "post",
data: {
ruleName: rule,
ruleDef: JSON.stringify(rulesList[rule])
@ -631,8 +636,8 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
const updateMatchingArticles = (ruleName) => {
new Request.JSON({
url: 'api/v2/rss/matchingArticles',
method: 'get',
url: "api/v2/rss/matchingArticles",
method: "get",
noCache: true,
data: {
ruleName: ruleName
@ -640,7 +645,9 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
onSuccess: (response) => {
rssDownloaderArticlesTable.clear();
let rowCount = 0;
for (let feed in response) {
for (const feed in response) {
if (!Object.hasOwn(response, feed))
continue;
rssDownloaderArticlesTable.updateRowData({
rowId: rowCount++,
name: feed,
@ -660,91 +667,91 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
};
const showRule = (ruleName) => {
if (ruleName === '') {
if (ruleName === "") {
// disable all
$('saveButton').disabled = true;
$('useRegEx').disabled = true;
$('mustContainText').disabled = true;
$('mustNotContainText').disabled = true;
$('episodeFilterText').disabled = true;
$('useSmartFilter').disabled = true;
$('assignCategoryCombobox').disabled = true;
$('ruleAddTags').disabled = true;
$('savetoDifferentDir').disabled = true;
$('saveToText').disabled = true;
$('ignoreDaysValue').disabled = true;
$('addStoppedCombobox').disabled = true;
$('contentLayoutCombobox').disabled = true;
$("saveButton").disabled = true;
$("useRegEx").disabled = true;
$("mustContainText").disabled = true;
$("mustNotContainText").disabled = true;
$("episodeFilterText").disabled = true;
$("useSmartFilter").disabled = true;
$("assignCategoryCombobox").disabled = true;
$("ruleAddTags").disabled = true;
$("savetoDifferentDir").disabled = true;
$("saveToText").disabled = true;
$("ignoreDaysValue").disabled = true;
$("addStoppedCombobox").disabled = true;
$("contentLayoutCombobox").disabled = true;
// reset all boxes
$('useRegEx').checked = false;
$('mustContainText').value = '';
$('mustNotContainText').value = '';
$('episodeFilterText').value = '';
$('useSmartFilter').checked = false;
$('assignCategoryCombobox').value = 'default';
$('ruleAddTags').value = '';
$('savetoDifferentDir').checked = false;
$('saveToText').value = '';
$('ignoreDaysValue').value = 0;
$('lastMatchText').textContent = 'QBT_TR(Last Match: Unknown)QBT_TR[CONTEXT=AutomatedRssDownloader]';
$('addStoppedCombobox').value = 'default';
$('contentLayoutCombobox').value = 'Default';
$("useRegEx").checked = false;
$("mustContainText").value = "";
$("mustNotContainText").value = "";
$("episodeFilterText").value = "";
$("useSmartFilter").checked = false;
$("assignCategoryCombobox").value = "default";
$("ruleAddTags").value = "";
$("savetoDifferentDir").checked = false;
$("saveToText").value = "";
$("ignoreDaysValue").value = 0;
$("lastMatchText").textContent = "QBT_TR(Last Match: Unknown)QBT_TR[CONTEXT=AutomatedRssDownloader]";
$("addStoppedCombobox").value = "default";
$("contentLayoutCombobox").value = "Default";
rssDownloaderFeedSelectionTable.clear();
rssDownloaderArticlesTable.clear();
$('mustContainText').title = '';
$('mustNotContainText').title = '';
$('episodeFilterText').title = '';
$("mustContainText").title = "";
$("mustNotContainText").title = "";
$("episodeFilterText").title = "";
}
else {
// enable all
$('saveButton').disabled = false;
$('useRegEx').disabled = false;
$('mustContainText').disabled = false;
$('mustNotContainText').disabled = false;
$('episodeFilterText').disabled = false;
$('useSmartFilter').disabled = false;
$('assignCategoryCombobox').disabled = false;
$('ruleAddTags').disabled = false;
$('savetoDifferentDir').disabled = false;
$('ignoreDaysValue').disabled = false;
$('addStoppedCombobox').disabled = false;
$('contentLayoutCombobox').disabled = false;
$("saveButton").disabled = false;
$("useRegEx").disabled = false;
$("mustContainText").disabled = false;
$("mustNotContainText").disabled = false;
$("episodeFilterText").disabled = false;
$("useSmartFilter").disabled = false;
$("assignCategoryCombobox").disabled = false;
$("ruleAddTags").disabled = false;
$("savetoDifferentDir").disabled = false;
$("ignoreDaysValue").disabled = false;
$("addStoppedCombobox").disabled = false;
$("contentLayoutCombobox").disabled = false;
// load rule settings
$('useRegEx').checked = rulesList[ruleName].useRegex;
$('mustContainText').value = rulesList[ruleName].mustContain;
$('mustNotContainText').value = rulesList[ruleName].mustNotContain;
$('episodeFilterText').value = rulesList[ruleName].episodeFilter;
$('useSmartFilter').checked = rulesList[ruleName].smartFilter;
$("useRegEx").checked = rulesList[ruleName].useRegex;
$("mustContainText").value = rulesList[ruleName].mustContain;
$("mustNotContainText").value = rulesList[ruleName].mustNotContain;
$("episodeFilterText").value = rulesList[ruleName].episodeFilter;
$("useSmartFilter").checked = rulesList[ruleName].smartFilter;
$('assignCategoryCombobox').value = rulesList[ruleName].torrentParams.category ? rulesList[ruleName].torrentParams.category : 'default';
$('ruleAddTags').value = rulesList[ruleName].torrentParams.tags.join(',');
$('savetoDifferentDir').checked = rulesList[ruleName].torrentParams.save_path !== '';
$('saveToText').disabled = !$('savetoDifferentDir').checked;
$('saveToText').value = rulesList[ruleName].torrentParams.save_path;
$('ignoreDaysValue').value = rulesList[ruleName].ignoreDays;
$("assignCategoryCombobox").value = rulesList[ruleName].torrentParams.category ? rulesList[ruleName].torrentParams.category : "default";
$("ruleAddTags").value = rulesList[ruleName].torrentParams.tags.join(",");
$("savetoDifferentDir").checked = rulesList[ruleName].torrentParams.save_path !== "";
$("saveToText").disabled = !$("savetoDifferentDir").checked;
$("saveToText").value = rulesList[ruleName].torrentParams.save_path;
$("ignoreDaysValue").value = rulesList[ruleName].ignoreDays;
// calculate days since last match
if (rulesList[ruleName].lastMatch !== '') {
let timeDiffInMs = new Date().getTime() - new Date(rulesList[ruleName].lastMatch).getTime();
let daysAgo = Math.floor(timeDiffInMs / (1000 * 60 * 60 * 24)).toString();
$('lastMatchText').textContent = ' QBT_TR(Last Match: %1 days ago)QBT_TR[CONTEXT=AutomatedRssDownloader]'.replace('%1', daysAgo);
if (rulesList[ruleName].lastMatch !== "") {
const timeDiffInMs = new Date().getTime() - new Date(rulesList[ruleName].lastMatch).getTime();
const daysAgo = Math.floor(timeDiffInMs / (1000 * 60 * 60 * 24)).toString();
$("lastMatchText").textContent = " QBT_TR(Last Match: %1 days ago)QBT_TR[CONTEXT=AutomatedRssDownloader]".replace("%1", daysAgo);
}
else {
$('lastMatchText').textContent = 'QBT_TR(Last Match: Unknown)QBT_TR[CONTEXT=AutomatedRssDownloader]';
$("lastMatchText").textContent = "QBT_TR(Last Match: Unknown)QBT_TR[CONTEXT=AutomatedRssDownloader]";
}
if (rulesList[ruleName].torrentParams.stopped === null)
$('addStoppedCombobox').value = 'default';
$("addStoppedCombobox").value = "default";
else
$('addStoppedCombobox').value = rulesList[ruleName].torrentParams.stopped ? 'always' : 'never';
$("addStoppedCombobox").value = rulesList[ruleName].torrentParams.stopped ? "always" : "never";
if (rulesList[ruleName].torrentParams.content_layout === null)
$('contentLayoutCombobox').value = 'Default';
$("contentLayoutCombobox").value = "Default";
else
$('contentLayoutCombobox').value = rulesList[ruleName].torrentParams.content_layout;
$("contentLayoutCombobox").value = rulesList[ruleName].torrentParams.content_layout;
setElementTitles();
@ -765,38 +772,38 @@ Supports the formats: S01E01, 1x1, 2017.12.31 and 31.12.2017 (Date formats also
const setElementTitles = () => {
let mainPart;
if ($('useRegEx').checked) {
mainPart = 'QBT_TR(Regex mode: use Perl-compatible regular expressions)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n';
if ($("useRegEx").checked) {
mainPart = "QBT_TR(Regex mode: use Perl-compatible regular expressions)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n";
}
else {
mainPart = 'QBT_TR(Wildcard mode: you can use)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n'
+ ' ● QBT_TR(? to match any single character)QBT_TR[CONTEXT=AutomatedRssDownloader]\n'
+ ' ● QBT_TR(* to match zero or more of any characters)QBT_TR[CONTEXT=AutomatedRssDownloader]\n'
+ ' ● QBT_TR(Whitespaces count as AND operators (all words, any order))QBT_TR[CONTEXT=AutomatedRssDownloader]\n'
+ ' ● QBT_TR(| is used as OR operator)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n'
+ 'QBT_TR(If word order is important use * instead of whitespace.)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n';
mainPart = "QBT_TR(Wildcard mode: you can use)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n"
+ " ● QBT_TR(? to match any single character)QBT_TR[CONTEXT=AutomatedRssDownloader]\n"
+ " ● QBT_TR(* to match zero or more of any characters)QBT_TR[CONTEXT=AutomatedRssDownloader]\n"
+ " ● QBT_TR(Whitespaces count as AND operators (all words, any order))QBT_TR[CONTEXT=AutomatedRssDownloader]\n"
+ " ● QBT_TR(| is used as OR operator)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n"
+ "QBT_TR(If word order is important use * instead of whitespace.)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n";
}
let secondPart = 'QBT_TR(An expression with an empty %1 clause (e.g. %2))QBT_TR[CONTEXT=AutomatedRssDownloader]'
.replace('%1', '|').replace('%2', 'expr|');
const secondPart = "QBT_TR(An expression with an empty %1 clause (e.g. %2))QBT_TR[CONTEXT=AutomatedRssDownloader]"
.replace("%1", "|").replace("%2", "expr|");
$('mustContainText').title = mainPart + secondPart + 'QBT_TR( will match all articles.)QBT_TR[CONTEXT=AutomatedRssDownloader]';
$('mustNotContainText').title = mainPart + secondPart + 'QBT_TR( will exclude all articles.)QBT_TR[CONTEXT=AutomatedRssDownloader]';
$("mustContainText").title = mainPart + secondPart + "QBT_TR( will match all articles.)QBT_TR[CONTEXT=AutomatedRssDownloader]";
$("mustNotContainText").title = mainPart + secondPart + "QBT_TR( will exclude all articles.)QBT_TR[CONTEXT=AutomatedRssDownloader]";
let episodeFilterTitle = 'QBT_TR(Matches articles based on episode filter.)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n'
+ 'QBT_TR(Example: )QBT_TR[CONTEXT=AutomatedRssDownloader]'
+ '1x2;8-15;5;30-;'
+ 'QBT_TR( will match 2, 5, 8 through 15, 30 and onward episodes of season one)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n'
+ 'QBT_TR(Episode filter rules: )QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n'
+ ' ● QBT_TR(Season number is a mandatory non-zero value)QBT_TR[CONTEXT=AutomatedRssDownloader]\n'
+ ' ● QBT_TR(Episode number is a mandatory positive value)QBT_TR[CONTEXT=AutomatedRssDownloader]\n'
+ ' ● QBT_TR(Filter must end with semicolon)QBT_TR[CONTEXT=AutomatedRssDownloader]\n'
+ ' ● QBT_TR(Three range types for episodes are supported: )QBT_TR[CONTEXT=AutomatedRssDownloader]\n'
+ ' ● QBT_TR(Single number: <b>1x25;</b> matches episode 25 of season one)QBT_TR[CONTEXT=AutomatedRssDownloader]\n'
+ ' ● QBT_TR(Normal range: <b>1x25-40;</b> matches episodes 25 through 40 of season one)QBT_TR[CONTEXT=AutomatedRssDownloader]\n'
+ ' ● QBT_TR(Infinite range: <b>1x25-;</b> matches episodes 25 and upward of season one, and all episodes of later seasons)QBT_TR[CONTEXT=AutomatedRssDownloader]';
let episodeFilterTitle = "QBT_TR(Matches articles based on episode filter.)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n"
+ "QBT_TR(Example: )QBT_TR[CONTEXT=AutomatedRssDownloader]"
+ "1x2;8-15;5;30-;"
+ "QBT_TR( will match 2, 5, 8 through 15, 30 and onward episodes of season one)QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n"
+ "QBT_TR(Episode filter rules: )QBT_TR[CONTEXT=AutomatedRssDownloader]\n\n"
+ " ● QBT_TR(Season number is a mandatory non-zero value)QBT_TR[CONTEXT=AutomatedRssDownloader]\n"
+ " ● QBT_TR(Episode number is a mandatory positive value)QBT_TR[CONTEXT=AutomatedRssDownloader]\n"
+ " ● QBT_TR(Filter must end with semicolon)QBT_TR[CONTEXT=AutomatedRssDownloader]\n"
+ " ● QBT_TR(Three range types for episodes are supported: )QBT_TR[CONTEXT=AutomatedRssDownloader]\n"
+ " ● QBT_TR(Single number: <b>1x25;</b> matches episode 25 of season one)QBT_TR[CONTEXT=AutomatedRssDownloader]\n"
+ " ● QBT_TR(Normal range: <b>1x25-40;</b> matches episodes 25 through 40 of season one)QBT_TR[CONTEXT=AutomatedRssDownloader]\n"
+ " ● QBT_TR(Infinite range: <b>1x25-;</b> matches episodes 25 and upward of season one, and all episodes of later seasons)QBT_TR[CONTEXT=AutomatedRssDownloader]";
episodeFilterTitle = episodeFilterTitle.replace(/<b>/g, '').replace(/<\/b>/g, '');
$('episodeFilterText').title = episodeFilterTitle;
episodeFilterTitle = episodeFilterTitle.replace(/<b>/g, "").replace(/<\/b>/g, "");
$("episodeFilterText").title = episodeFilterTitle;
};
initRssDownloader();

View file

@ -77,7 +77,7 @@
</ul>
<script>
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -101,15 +101,15 @@
const initSearchPlugins = function() {
searchPluginsTable = new window.qBittorrent.DynamicTable.SearchPluginsTable();
searchPluginsTableContextMenu = new window.qBittorrent.ContextMenu.SearchPluginsTableContextMenu({
targets: '.searchPluginsTableRow',
menu: 'searchPluginsTableMenu',
targets: ".searchPluginsTableRow",
menu: "searchPluginsTableMenu",
actions: {
Enabled: enablePlugin,
Uninstall: uninstallPlugin
},
offsets: calculateContextMenuOffsets()
});
searchPluginsTable.setup('searchPluginsTableDiv', 'searchPluginsTableFixedHeaderDiv', searchPluginsTableContextMenu);
searchPluginsTable.setup("searchPluginsTableDiv", "searchPluginsTableFixedHeaderDiv", searchPluginsTableContextMenu);
updateTable();
};
@ -119,10 +119,10 @@
const installPlugin = function(path) {
new MochaUI.Window({
id: 'installSearchPlugin',
id: "installSearchPlugin",
title: "QBT_TR(Install plugin)QBT_TR[CONTEXT=PluginSourceDlg]",
loadMethod: 'xhr',
contentURL: 'views/installsearchplugin.html',
loadMethod: "xhr",
contentURL: "views/installsearchplugin.html",
scrollbars: false,
resizable: false,
maximizable: false,
@ -134,11 +134,11 @@
};
const uninstallPlugin = function() {
const plugins = searchPluginsTable.selectedRowsIds().join('|');
const url = new URI('api/v2/search/uninstallPlugin');
const plugins = searchPluginsTable.selectedRowsIds().join("|");
const url = new URI("api/v2/search/uninstallPlugin");
new Request({
url: url,
method: 'post',
method: "post",
data: {
names: plugins,
}
@ -151,22 +151,22 @@
if (plugins && plugins.length)
enable = !window.qBittorrent.Search.getPlugin(plugins[0]).enabled;
const url = new URI('api/v2/search/enablePlugin');
const url = new URI("api/v2/search/enablePlugin");
new Request({
url: url,
method: 'post',
method: "post",
data: {
names: plugins.join('|'),
names: plugins.join("|"),
enable: enable
}
}).send();
};
const checkForUpdates = function() {
const url = new URI('api/v2/search/updatePlugins');
const url = new URI("api/v2/search/updatePlugins");
new Request({
url: url,
method: 'post'
method: "post"
}).send();
};
@ -188,14 +188,14 @@
const setupSearchPluginTableEvents = function(enable) {
if (enable)
$$(".searchPluginsTableRow").each(function(target) {
target.addEventListener('dblclick', enablePlugin, false);
target.addEventListener('contextmenu', updateSearchPluginsTableContextMenuOffset, true);
$$(".searchPluginsTableRow").each((target) => {
target.addEventListener("dblclick", enablePlugin, false);
target.addEventListener("contextmenu", updateSearchPluginsTableContextMenuOffset, true);
});
else
$$(".searchPluginsTableRow").each(function(target) {
target.removeEventListener('dblclick', enablePlugin, false);
target.removeEventListener('contextmenu', updateSearchPluginsTableContextMenuOffset, true);
$$(".searchPluginsTableRow").each((target) => {
target.removeEventListener("dblclick", enablePlugin, false);
target.removeEventListener("contextmenu", updateSearchPluginsTableContextMenuOffset, true);
});
};

View file

@ -16,7 +16,7 @@
</div>
<script>
'use strict';
"use strict";
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
@ -31,8 +31,8 @@
//create a context menu
const contextMenu = new window.qBittorrent.ContextMenu.TorrentsTableContextMenu({
targets: '.torrentsTableContextMenuTarget',
menu: 'torrentsTableMenu',
targets: ".torrentsTableContextMenuTarget",
menu: "torrentsTableMenu",
actions: {
start: function(element, ref) {
startFN();
@ -59,16 +59,16 @@
renameFilesFN();
},
queueTop: function(element, ref) {
setQueuePositionFN('topPrio');
setQueuePositionFN("topPrio");
},
queueUp: function(element, ref) {
setQueuePositionFN('increasePrio');
setQueuePositionFN("increasePrio");
},
queueDown: function(element, ref) {
setQueuePositionFN('decreasePrio');
setQueuePositionFN("decreasePrio");
},
queueBottom: function(element, ref) {
setQueuePositionFN('bottomPrio');
setQueuePositionFN("bottomPrio");
},
downloadLimit: function(element, ref) {
@ -99,7 +99,7 @@
},
superSeeding: function(element, ref) {
setSuperSeedingFN(!ref.getItemChecked('superSeeding'));
setSuperSeedingFN(!ref.getItemChecked("superSeeding"));
},
exportTorrent: function(element, ref) {
@ -112,7 +112,7 @@
},
});
torrentsTable.setup('torrentsTableDiv', 'torrentsTableFixedHeaderDiv', contextMenu);
torrentsTable.setup("torrentsTableDiv", "torrentsTableFixedHeaderDiv", contextMenu);
return exports();
})();

View file

@ -26,31 +26,31 @@
* exception statement from your version.
*/
'use strict';
"use strict";
async function setupI18n() {
const languages = (() => {
const langs = new Set();
// list of available languages: https://github.com/qbittorrent/qBittorrent/tree/master/src/webui/www/public/lang
const queryLang = new URLSearchParams(window.location.search).get('lang');
const queryLang = new URLSearchParams(window.location.search).get("lang");
if (queryLang !== null) {
// use the fallback lang if `queryLang` is present but empty
// limit the length of the language string to prevent Client-side Request Forgery
if ((queryLang.length > 0) && (queryLang.length <= 8))
langs.add(queryLang.replace('-', '_'));
langs.add(queryLang.replace("-", "_"));
}
else {
for (const lang of navigator.languages) {
langs.add(lang.replace('-', '_'));
langs.add(lang.replace("-", "_"));
const idx = lang.indexOf('-');
const idx = lang.indexOf("-");
if (idx > 0)
langs.add(lang.slice(0, idx));
}
}
langs.add('en'); // fallback
langs.add("en"); // fallback
return Array.from(langs);
})();
@ -61,7 +61,7 @@ async function setupI18n() {
.map((value, idx) => ({ lang: languages[idx], result: value }))
.filter(v => (v.result.value.status === 200));
const translation = {
lang: (translations.length > 0) ? translations[0].lang.replace('_', '-') : undefined,
lang: (translations.length > 0) ? translations[0].lang.replace("_", "-") : undefined,
data: (translations.length > 0) ? (await translations[0].result.value.json()) : {}
};
@ -69,7 +69,7 @@ async function setupI18n() {
const i18nextOptions = {
lng: translation.lang,
fallbackLng: false,
load: 'currentOnly',
load: "currentOnly",
resources: {
[translation.lang]: { translation: translation.data }
},
@ -80,14 +80,14 @@ async function setupI18n() {
function replaceI18nText() {
const tr = i18next.t; // workaround for warnings from i18next-parser
for (const element of document.getElementsByClassName('qbt-translatable')) {
const translationKey = element.getAttribute('data-i18n');
for (const element of document.getElementsByClassName("qbt-translatable")) {
const translationKey = element.getAttribute("data-i18n");
const translatedValue = tr(translationKey);
switch (element.nodeName) {
case 'INPUT':
case "INPUT":
element.value = translatedValue;
break;
case 'LABEL':
case "LABEL":
element.textContent = translatedValue;
break;
default:
@ -96,43 +96,43 @@ function replaceI18nText() {
}
}
document.documentElement.lang = i18next.language.split('-')[0];
document.documentElement.lang = i18next.language.split("-")[0];
}
function submitLoginForm(event) {
event.preventDefault();
const errorMsgElement = document.getElementById('error_msg');
const errorMsgElement = document.getElementById("error_msg");
const xhr = new XMLHttpRequest();
xhr.open('POST', 'api/v2/auth/login', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.addEventListener('readystatechange', () => {
xhr.open("POST", "api/v2/auth/login", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.addEventListener("readystatechange", () => {
if (xhr.readyState === 4) { // DONE state
if ((xhr.status === 200) && (xhr.responseText === "Ok."))
location.replace(location);
else
errorMsgElement.textContent = i18next.t('Invalid Username or Password.');
errorMsgElement.textContent = i18next.t("Invalid Username or Password.");
}
});
xhr.addEventListener('error', () => {
xhr.addEventListener("error", () => {
errorMsgElement.textContent = (xhr.responseText !== "")
? xhr.responseText
: i18next.t('Unable to log in, server is probably unreachable.');
: i18next.t("Unable to log in, server is probably unreachable.");
});
const usernameElement = document.getElementById('username');
const passwordElement = document.getElementById('password');
const usernameElement = document.getElementById("username");
const passwordElement = document.getElementById("password");
const queryString = "username=" + encodeURIComponent(usernameElement.value) + "&password=" + encodeURIComponent(passwordElement.value);
xhr.send(queryString);
// clear the field
passwordElement.value = '';
passwordElement.value = "";
}
document.addEventListener('DOMContentLoaded', () => {
const loginForm = document.getElementById('loginform');
loginForm.setAttribute('method', 'POST');
loginForm.addEventListener('submit', submitLoginForm);
document.addEventListener("DOMContentLoaded", () => {
const loginForm = document.getElementById("loginform");
loginForm.setAttribute("method", "POST");
loginForm.addEventListener("submit", submitLoginForm);
setupI18n();
});