Clean up functions in global scope

This commit is contained in:
Chocobo1 2024-02-08 12:03:10 +08:00
parent 9b64d50660
commit f7e9ff0fb0
24 changed files with 294 additions and 270 deletions

View file

@ -14,11 +14,11 @@
defaultEventType: 'keydown', defaultEventType: 'keydown',
events: { events: {
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -49,7 +49,7 @@
alert("QBT_TR(Unable to add peers. Please ensure you are adhering to the IP:port format.)QBT_TR[CONTEXT=HttpServer]"); alert("QBT_TR(Unable to add peers. Please ensure you are adhering to the IP:port format.)QBT_TR[CONTEXT=HttpServer]");
}, },
onSuccess: function() { onSuccess: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
}); });
@ -62,7 +62,7 @@
<p>QBT_TR(List of peers to add (one IP per line):)QBT_TR[CONTEXT=PeersAdditionDialog]</p> <p>QBT_TR(List of peers to add (one IP per line):)QBT_TR[CONTEXT=PeersAdditionDialog]</p>
<textarea id="peers" rows="10" style="width: 100%;" placeholder="QBT_TR(Format: IPv4:port / [IPv6]:port)QBT_TR[CONTEXT=PeersAdditionDialog]"></textarea> <textarea id="peers" rows="10" style="width: 100%;" placeholder="QBT_TR(Format: IPv4:port / [IPv6]:port)QBT_TR[CONTEXT=PeersAdditionDialog]"></textarea>
<div style="margin-top: 10px; text-align: center;"> <div style="margin-top: 10px; text-align: center;">
<button type="button" onclick="parent.closeWindows();">QBT_TR(Cancel)QBT_TR[CONTEXT=PeersAdditionDialog]</button> <button type="button" onclick="parent.qBittorrent.Client.closeWindows();">QBT_TR(Cancel)QBT_TR[CONTEXT=PeersAdditionDialog]</button>
<button type="button" id="addPeersOk">QBT_TR(Ok)QBT_TR[CONTEXT=PeersAdditionDialog]</button> <button type="button" id="addPeersOk">QBT_TR(Ok)QBT_TR[CONTEXT=PeersAdditionDialog]</button>
</div> </div>
</div> </div>

View file

@ -15,11 +15,11 @@
defaultEventType: 'keydown', defaultEventType: 'keydown',
events: { events: {
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -37,7 +37,7 @@
urls: $('trackersUrls').value urls: $('trackersUrls').value
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
}); });

View file

@ -75,7 +75,7 @@
$('cancelBtn').focus(); $('cancelBtn').focus();
$('cancelBtn').addEvent('click', function(e) { $('cancelBtn').addEvent('click', function(e) {
new Event(e).stop(); new Event(e).stop();
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
}); });
$('confirmBtn').addEvent('click', function(e) { $('confirmBtn').addEvent('click', function(e) {
parent.torrentsTable.deselectAll(); parent.torrentsTable.deselectAll();
@ -90,7 +90,7 @@
'deleteFiles': deleteFiles 'deleteFiles': deleteFiles
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
}); });

View file

@ -15,7 +15,7 @@
$('cancelBtn').focus(); $('cancelBtn').focus();
$('cancelBtn').addEvent('click', (e) => { $('cancelBtn').addEvent('click', (e) => {
new Event(e).stop(); new Event(e).stop();
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
}); });
$('confirmBtn').addEvent('click', (e) => { $('confirmBtn').addEvent('click', (e) => {
new Event(e).stop(); new Event(e).stop();
@ -32,7 +32,7 @@
++completionCount; ++completionCount;
if (completionCount === paths.length) { if (completionCount === paths.length) {
window.parent.qBittorrent.Rss.updateRssFeedList(); window.parent.qBittorrent.Rss.updateRssFeedList();
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
} }
}).send(); }).send();

View file

@ -187,7 +187,7 @@
$('download_frame').addEventListener("load", function() { $('download_frame').addEventListener("load", function() {
if (submitted) if (submitted)
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
}); });
</script> </script>
<div id="download_spinner" class="mochaSpinner"></div> <div id="download_spinner" class="mochaSpinner"></div>

View file

@ -36,7 +36,7 @@
}, },
onComplete: function() { onComplete: function() {
window.parent.updateMainData(); window.parent.updateMainData();
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
} }
@ -49,7 +49,7 @@
'limit': limit 'limit': limit
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
} }
@ -67,11 +67,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }

View file

@ -19,11 +19,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -48,7 +48,7 @@
newUrl: $('trackerUrl').value newUrl: $('trackerUrl').value
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
}); });

View file

@ -19,11 +19,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -89,7 +89,7 @@
category: categoryName category: categoryName
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
}, },
@ -111,7 +111,7 @@
savePath: savePath savePath: savePath
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
break; break;
@ -124,7 +124,7 @@
savePath: savePath savePath: savePath
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
break; break;

View file

@ -19,11 +19,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': (event) => { 'Escape': (event) => {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': (event) => { 'Esc': (event) => {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -52,7 +52,7 @@
}, },
onSuccess: (response) => { onSuccess: (response) => {
window.parent.qBittorrent.Rss.updateRssFeedList(); window.parent.qBittorrent.Rss.updateRssFeedList();
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
}, },
onFailure: (response) => { onFailure: (response) => {
if (response.status === 409) if (response.status === 409)

View file

@ -19,11 +19,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': (event) => { 'Escape': (event) => {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': (event) => { 'Esc': (event) => {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -51,7 +51,7 @@
}, },
onSuccess: (response) => { onSuccess: (response) => {
window.parent.qBittorrent.Rss.updateRssFeedList(); window.parent.qBittorrent.Rss.updateRssFeedList();
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
}, },
onFailure: (response) => { onFailure: (response) => {
if (response.status === 409) if (response.status === 409)

View file

@ -19,11 +19,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -66,7 +66,7 @@
tags: tagName, tags: tagName,
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
break; break;
@ -82,7 +82,7 @@
tags: tagName, tags: tagName,
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
break; break;

View file

@ -19,11 +19,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -53,7 +53,7 @@
name: name name: name
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
} }

View file

@ -19,11 +19,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': (event) => { 'Escape': (event) => {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': (event) => { 'Esc': (event) => {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -61,7 +61,7 @@
}, },
onSuccess: (response) => { onSuccess: (response) => {
window.parent.qBittorrent.Rss.updateRssFeedList(); window.parent.qBittorrent.Rss.updateRssFeedList();
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
}, },
onFailure: (response) => { onFailure: (response) => {
if (response.status === 409) { if (response.status === 409) {

View file

@ -20,11 +20,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -70,7 +70,7 @@
newPath: newPath newPath: newPath
}, },
onSuccess: function() { onSuccess: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
}, },
onFailure: function() { onFailure: function() {
alert('QBT_TR(Failed to update name)QBT_TR[CONTEXT=HttpServer]'); alert('QBT_TR(Failed to update name)QBT_TR[CONTEXT=HttpServer]');

View file

@ -75,11 +75,11 @@
defaultEventType: 'keydown', defaultEventType: 'keydown',
events: { events: {
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -298,7 +298,7 @@
$('renameButton').set('value', replaceOperation); $('renameButton').set('value', replaceOperation);
}); });
$('closeButton').addEvent('click', function() { $('closeButton').addEvent('click', function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}); });
// synchronize header scrolling to table body // synchronize header scrolling to table body

View file

@ -1,5 +1,6 @@
/* /*
* MIT License * MIT License
* Copyright (C) 2024 Mike Tzou (Chocobo1)
* Copyright (c) 2008 Ishan Arora <ishan@qbittorrent.org>, * Copyright (c) 2008 Ishan Arora <ishan@qbittorrent.org>,
* Christophe Dumez <chris@qbittorrent.org> * Christophe Dumez <chris@qbittorrent.org>
* *
@ -24,6 +25,48 @@
'use strict'; 'use strict';
if (window.qBittorrent === undefined) {
window.qBittorrent = {};
}
window.qBittorrent.Client = (() => {
const exports = () => {
return {
closeWindows: closeWindows,
genHash: genHash,
getSyncMainDataInterval: getSyncMainDataInterval,
qbtVersion: qbtVersion
};
};
const closeWindows = function() {
MochaUI.closeAll();
};
const genHash = function(string) {
// origins:
// https://stackoverflow.com/a/8831937
// https://gist.github.com/hyamamoto/fd435505d29ebfa3d9716fd2be8d42f0
let hash = 0;
for (let i = 0; i < string.length; ++i)
hash = ((Math.imul(hash, 31) + string.charCodeAt(i)) | 0);
return hash;
};
const getSyncMainDataInterval = function() {
return customSyncMainDataInterval ? customSyncMainDataInterval : serverSyncMainDataInterval;
};
const qbtVersion = function() {
return LocalPreferences.get('qbtVersion', '');
};
return exports();
})();
Object.freeze(window.qBittorrent.Client);
// TODO: move global functions/variables into some namespace/scope
this.torrentsTable = new window.qBittorrent.DynamicTable.TorrentsTable(); this.torrentsTable = new window.qBittorrent.DynamicTable.TorrentsTable();
let updatePropertiesPanel = function() {}; let updatePropertiesPanel = function() {};
@ -34,13 +77,6 @@ let queueing_enabled = true;
let serverSyncMainDataInterval = 1500; let serverSyncMainDataInterval = 1500;
let customSyncMainDataInterval = null; let customSyncMainDataInterval = null;
let useSubcategories = true; let useSubcategories = true;
let searchTabInitialized = false;
let rssTabInitialized = false;
let logTabInitialized = false;
let syncRequestInProgress = false;
let clipboardEvent;
/* Categories filter */ /* Categories filter */
const CATEGORIES_ALL = 1; const CATEGORIES_ALL = 1;
@ -66,7 +102,7 @@ const TRACKERS_TRACKERLESS = 2;
const trackerList = new Map(); const trackerList = new Map();
let selectedTracker = TRACKERS_ALL; let selectedTracker = LocalPreferences.get('selected_tracker', TRACKERS_ALL);
let setTrackerFilter = function() {}; let setTrackerFilter = function() {};
/* All filters */ /* All filters */
@ -74,61 +110,6 @@ let selected_filter = LocalPreferences.get('selected_filter', 'all');
let setFilter = function() {}; let setFilter = function() {};
let toggleFilterDisplay = function() {}; let toggleFilterDisplay = function() {};
const loadSelectedTracker = function() {
selectedTracker = LocalPreferences.get('selected_tracker', TRACKERS_ALL);
};
loadSelectedTracker();
const getShowFiltersSidebar = function() {
// Show Filters Sidebar is enabled by default
const show = LocalPreferences.get('show_filters_sidebar');
return (show === null) || (show === 'true');
};
// getHost emulate the GUI version `QString getHost(const QString &url)`
function getHost(url) {
// We want the hostname.
// If failed to parse the domain, original input should be returned
if (!/^(?:https?|udp):/i.test(url)) {
return url;
}
try {
// hack: URL can not get hostname from udp protocol
const parsedUrl = new URL(url.replace(/^udp:/i, 'https:'));
// host: "example.com:8443"
// hostname: "example.com"
const host = parsedUrl.hostname;
if (!host) {
return url;
}
return host;
}
catch (error) {
return url;
}
}
function genHash(string) {
// origins:
// https://stackoverflow.com/a/8831937
// https://gist.github.com/hyamamoto/fd435505d29ebfa3d9716fd2be8d42f0
let hash = 0;
for (let i = 0; i < string.length; ++i)
hash = ((Math.imul(hash, 31) + string.charCodeAt(i)) | 0);
return hash;
}
function getSyncMainDataInterval() {
return customSyncMainDataInterval ? customSyncMainDataInterval : serverSyncMainDataInterval;
}
const qbtVersion = function() {
return LocalPreferences.get('qbtVersion', '');
};
window.addEvent('load', function() { window.addEvent('load', function() {
const saveColumnSizes = function() { const saveColumnSizes = function() {
const filters_width = $('Filters').getSize().x; const filters_width = $('Filters').getSize().x;
@ -305,6 +286,11 @@ window.addEvent('load', function() {
$('desktopFooterWrapper').addClass('invisible'); $('desktopFooterWrapper').addClass('invisible');
} }
const getShowFiltersSidebar = function() {
// Show Filters Sidebar is enabled by default
const show = LocalPreferences.get('show_filters_sidebar');
return (show === null) || (show === 'true');
};
const showFiltersSidebar = getShowFiltersSidebar(); const showFiltersSidebar = getShowFiltersSidebar();
if (!showFiltersSidebar) { if (!showFiltersSidebar) {
$('showFiltersSidebarLink').firstChild.style.opacity = '0'; $('showFiltersSidebarLink').firstChild.style.opacity = '0';
@ -351,7 +337,7 @@ window.addEvent('load', function() {
return true; return true;
} }
const categoryHash = genHash(category); const categoryHash = window.qBittorrent.Client.genHash(category);
if (!category_list.has(categoryHash)) { // This should not happen if (!category_list.has(categoryHash)) { // This should not happen
category_list.set(categoryHash, { category_list.set(categoryHash, {
name: category, name: category,
@ -394,7 +380,7 @@ window.addEvent('load', function() {
const tags = torrent['tags'].split(','); const tags = torrent['tags'].split(',');
let added = false; let added = false;
for (let i = 0; i < tags.length; ++i) { for (let i = 0; i < tags.length; ++i) {
const tagHash = genHash(tags[i].trim()); const tagHash = window.qBittorrent.Client.genHash(tags[i].trim());
if (!tagList.has(tagHash)) { // This should not happen if (!tagList.has(tagHash)) { // This should not happen
tagList.set(tagHash, { tagList.set(tagHash, {
name: tags, name: tags,
@ -573,6 +559,32 @@ window.addEvent('load', function() {
children[i].className = (Number(children[i].id) === selectedTag) ? "selectedFilter" : ""; children[i].className = (Number(children[i].id) === selectedTag) ? "selectedFilter" : "";
}; };
// getHost emulate the GUI version `QString getHost(const QString &url)`
const getHost = function(url) {
// We want the hostname.
// If failed to parse the domain, original input should be returned
if (!/^(?:https?|udp):/i.test(url)) {
return url;
}
try {
// hack: URL can not get hostname from udp protocol
const parsedUrl = new URL(url.replace(/^udp:/i, 'https:'));
// host: "example.com:8443"
// hostname: "example.com"
const host = parsedUrl.hostname;
if (!host) {
return url;
}
return host;
}
catch (error) {
return url;
}
};
const updateTrackerList = function() { const updateTrackerList = function() {
const trackerFilterList = $('trackerFilterList'); const trackerFilterList = $('trackerFilterList');
if (trackerFilterList === null) if (trackerFilterList === null)
@ -625,7 +637,38 @@ window.addEvent('load', function() {
child.className = (child.id === selectedTracker) ? "selectedFilter" : ""; child.className = (child.id === selectedTracker) ? "selectedFilter" : "";
}; };
const setupCopyEventHandler = (function() {
let clipboardEvent;
return () => {
if (clipboardEvent)
clipboardEvent.destroy();
clipboardEvent = new ClipboardJS('.copyToClipboard', {
text: function(trigger) {
switch (trigger.id) {
case "copyName":
return copyNameFN();
case "copyInfohash1":
return copyInfohashFN(1);
case "copyInfohash2":
return copyInfohashFN(2);
case "copyMagnetLink":
return copyMagnetLinkFN();
case "copyID":
return copyIdFN();
case "copyComment":
return copyCommentFN();
default:
return "";
}
}
});
};
})();
let syncMainDataTimer; let syncMainDataTimer;
let syncRequestInProgress = false;
const syncMainData = function() { const syncMainData = function() {
const url = new URI('api/v2/sync/maindata'); const url = new URI('api/v2/sync/maindata');
url.setData('rid', syncMainDataLastResponseId); url.setData('rid', syncMainDataLastResponseId);
@ -664,7 +707,7 @@ window.addEvent('load', function() {
continue; continue;
const responseCategory = response['categories'][key]; const responseCategory = response['categories'][key];
const categoryHash = genHash(key); const categoryHash = window.qBittorrent.Client.genHash(key);
const category = category_list.get(categoryHash); const category = category_list.get(categoryHash);
if (category !== undefined) { if (category !== undefined) {
// only the save path can change for existing categories // only the save path can change for existing categories
@ -682,14 +725,14 @@ window.addEvent('load', function() {
} }
if (response['categories_removed']) { if (response['categories_removed']) {
response['categories_removed'].each(function(category) { response['categories_removed'].each(function(category) {
const categoryHash = genHash(category); const categoryHash = window.qBittorrent.Client.genHash(category);
category_list.delete(categoryHash); category_list.delete(categoryHash);
}); });
update_categories = true; update_categories = true;
} }
if (response['tags']) { if (response['tags']) {
for (const tag of response['tags']) { for (const tag of response['tags']) {
const tagHash = genHash(tag); const tagHash = window.qBittorrent.Client.genHash(tag);
if (!tagList.has(tagHash)) { if (!tagList.has(tagHash)) {
tagList.set(tagHash, { tagList.set(tagHash, {
name: tag, name: tag,
@ -701,7 +744,7 @@ window.addEvent('load', function() {
} }
if (response['tags_removed']) { if (response['tags_removed']) {
for (let i = 0; i < response['tags_removed'].length; ++i) { for (let i = 0; i < response['tags_removed'].length; ++i) {
const tagHash = genHash(response['tags_removed'][i]); const tagHash = window.qBittorrent.Client.genHash(response['tags_removed'][i]);
tagList.delete(tagHash); tagList.delete(tagHash);
} }
updateTags = true; updateTags = true;
@ -709,7 +752,7 @@ window.addEvent('load', function() {
if (response['trackers']) { if (response['trackers']) {
for (const tracker in response['trackers']) { for (const tracker in response['trackers']) {
const torrents = response['trackers'][tracker]; const torrents = response['trackers'][tracker];
const hash = genHash(getHost(tracker)); const hash = window.qBittorrent.Client.genHash(getHost(tracker));
// the reason why we need the merge here is because the web ui api returned trackers may have different url for the same tracker host. // the reason why we need the merge here is because the web ui api returned trackers may have different url for the same tracker host.
// for example, some private trackers use diff urls for each torrent from the same tracker host. // for example, some private trackers use diff urls for each torrent from the same tracker host.
@ -739,7 +782,7 @@ window.addEvent('load', function() {
if (response['trackers_removed']) { if (response['trackers_removed']) {
for (let i = 0; i < response['trackers_removed'].length; ++i) { for (let i = 0; i < response['trackers_removed'].length; ++i) {
const tracker = response['trackers_removed'][i]; const tracker = response['trackers_removed'][i];
const hash = genHash(getHost(tracker)); const hash = window.qBittorrent.Client.genHash(getHost(tracker));
trackerList.delete(hash); trackerList.delete(hash);
} }
updateTrackers = true; updateTrackers = true;
@ -796,7 +839,7 @@ window.addEvent('load', function() {
torrentsTable.reselectRows(torrentsTableSelectedRows); torrentsTable.reselectRows(torrentsTableSelectedRows);
} }
syncRequestInProgress = false; syncRequestInProgress = false;
syncData(getSyncMainDataInterval()); syncData(window.qBittorrent.Client.getSyncMainDataInterval());
} }
}); });
syncRequestInProgress = true; syncRequestInProgress = true;
@ -827,11 +870,11 @@ window.addEvent('load', function() {
transfer_info += " (" + window.qBittorrent.Misc.friendlyUnit(serverState.up_info_data, false) + ")"; transfer_info += " (" + window.qBittorrent.Misc.friendlyUnit(serverState.up_info_data, false) + ")";
$("UpInfos").set('html', transfer_info); $("UpInfos").set('html', transfer_info);
if (speedInTitle) { if (speedInTitle) {
document.title = "QBT_TR([D: %1, U: %2] qBittorrent %3)QBT_TR[CONTEXT=MainWindow]".replace("%1", window.qBittorrent.Misc.friendlyUnit(serverState.dl_info_speed, true)).replace("%2", window.qBittorrent.Misc.friendlyUnit(serverState.up_info_speed, true)).replace("%3", qbtVersion()); document.title = "QBT_TR([D: %1, U: %2] qBittorrent %3)QBT_TR[CONTEXT=MainWindow]".replace("%1", window.qBittorrent.Misc.friendlyUnit(serverState.dl_info_speed, true)).replace("%2", window.qBittorrent.Misc.friendlyUnit(serverState.up_info_speed, true)).replace("%3", window.qBittorrent.Client.qbtVersion());
document.title += " QBT_TR(Web UI)QBT_TR[CONTEXT=OptionsDialog]"; document.title += " QBT_TR(Web UI)QBT_TR[CONTEXT=OptionsDialog]";
} }
else else
document.title = ("qBittorrent " + qbtVersion() + " QBT_TR(Web UI)QBT_TR[CONTEXT=OptionsDialog]"); document.title = ("qBittorrent " + window.qBittorrent.Client.qbtVersion() + " QBT_TR(Web UI)QBT_TR[CONTEXT=OptionsDialog]");
$('freeSpaceOnDisk').set('html', 'QBT_TR(Free space: %1)QBT_TR[CONTEXT=HttpServer]'.replace("%1", window.qBittorrent.Misc.friendlyUnit(serverState.free_space_on_disk))); $('freeSpaceOnDisk').set('html', 'QBT_TR(Free space: %1)QBT_TR[CONTEXT=HttpServer]'.replace("%1", window.qBittorrent.Misc.friendlyUnit(serverState.free_space_on_disk)));
$('DHTNodes').set('html', 'QBT_TR(DHT: %1 nodes)QBT_TR[CONTEXT=StatusBar]'.replace("%1", serverState.dht_nodes)); $('DHTNodes').set('html', 'QBT_TR(DHT: %1 nodes)QBT_TR[CONTEXT=StatusBar]'.replace("%1", serverState.dht_nodes));
@ -966,6 +1009,26 @@ window.addEvent('load', function() {
MochaUI.Desktop.setDesktopSize(); MochaUI.Desktop.setDesktopSize();
}); });
const registerMagnetHandler = function() {
if (typeof navigator.registerProtocolHandler !== 'function') {
if (window.location.protocol !== 'https:')
alert("QBT_TR(To use this feature, the WebUI needs to be accessed over HTTPS)QBT_TR[CONTEXT=MainWindow]");
else
alert("QBT_TR(Your browser does not support this feature)QBT_TR[CONTEXT=MainWindow]");
return;
}
const hashString = location.hash ? location.hash.replace(/^#/, '') : '';
const hashParams = new URLSearchParams(hashString);
hashParams.set('download', '');
const templateHashString = hashParams.toString().replace('download=', 'download=%s');
const templateUrl = location.origin + location.pathname
+ location.search + '#' + templateHashString;
navigator.registerProtocolHandler('magnet', templateUrl,
'qBittorrent WebUI magnet handler');
};
$('registerMagnetHandlerLink').addEvent('click', function(e) { $('registerMagnetHandlerLink').addEvent('click', function(e) {
registerMagnetHandler(); registerMagnetHandler();
}); });
@ -1088,7 +1151,10 @@ window.addEvent('load', function() {
MochaUI.Desktop.resizePanels(); MochaUI.Desktop.resizePanels();
}; };
const showSearchTab = function() { const showSearchTab = (function() {
let searchTabInitialized = false;
return () => {
if (!searchTabInitialized) { if (!searchTabInitialized) {
window.qBittorrent.Search.init(); window.qBittorrent.Search.init();
searchTabInitialized = true; searchTabInitialized = true;
@ -1100,13 +1166,17 @@ window.addEvent('load', function() {
hideRssTab(); hideRssTab();
hideLogTab(); hideLogTab();
}; };
})();
const hideSearchTab = function() { const hideSearchTab = function() {
$("searchTabColumn").addClass("invisible"); $("searchTabColumn").addClass("invisible");
MochaUI.Desktop.resizePanels(); MochaUI.Desktop.resizePanels();
}; };
const showRssTab = function() { const showRssTab = (function() {
let rssTabInitialized = false;
return () => {
if (!rssTabInitialized) { if (!rssTabInitialized) {
window.qBittorrent.Rss.init(); window.qBittorrent.Rss.init();
rssTabInitialized = true; rssTabInitialized = true;
@ -1121,6 +1191,7 @@ window.addEvent('load', function() {
hideSearchTab(); hideSearchTab();
hideLogTab(); hideLogTab();
}; };
})();
const hideRssTab = function() { const hideRssTab = function() {
$("rssTabColumn").addClass("invisible"); $("rssTabColumn").addClass("invisible");
@ -1128,7 +1199,10 @@ window.addEvent('load', function() {
MochaUI.Desktop.resizePanels(); MochaUI.Desktop.resizePanels();
}; };
const showLogTab = function() { const showLogTab = (function() {
let logTabInitialized = false;
return () => {
if (!logTabInitialized) { if (!logTabInitialized) {
window.qBittorrent.Log.init(); window.qBittorrent.Log.init();
logTabInitialized = true; logTabInitialized = true;
@ -1143,6 +1217,7 @@ window.addEvent('load', function() {
hideSearchTab(); hideSearchTab();
hideRssTab(); hideRssTab();
}; };
})();
const hideLogTab = function() { const hideLogTab = function() {
$('logTabColumn').addClass('invisible'); $('logTabColumn').addClass('invisible');
@ -1224,6 +1299,18 @@ window.addEvent('load', function() {
}); });
}; };
const handleDownloadParam = function() {
// Extract torrent URL from download param in WebUI URL hash
const downloadHash = "#download=";
if (location.hash.indexOf(downloadHash) !== 0)
return;
const url = decodeURIComponent(location.hash.substring(downloadHash.length));
// Remove the processed hash from the URL
history.replaceState('', document.title, (location.pathname + location.search));
showDownloadPage([url]);
};
new MochaUI.Panel({ new MochaUI.Panel({
id: 'transferList', id: 'transferList',
title: 'Panel', title: 'Panel',
@ -1459,6 +1546,36 @@ window.addEvent('load', function() {
}; };
registerDragAndDrop(); registerDragAndDrop();
new Keyboard({
defaultEventType: 'keydown',
events: {
'ctrl+a': function(event) {
if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA")
return;
if (event.target.isContentEditable)
return;
torrentsTable.selectAll();
event.preventDefault();
},
'delete': function(event) {
if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA")
return;
if (event.target.isContentEditable)
return;
deleteFN();
event.preventDefault();
},
'shift+delete': (event) => {
if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA")
return;
if (event.target.isContentEditable)
return;
deleteFN(true);
event.preventDefault();
}
}
}).activate();
// fetch qbt version and store it locally // fetch qbt version and store it locally
new Request({ new Request({
url: 'api/v2/app/version', url: 'api/v2/app/version',
@ -1491,96 +1608,3 @@ window.addEvent('load', function() {
} }
}).send(); }).send();
}); });
function registerMagnetHandler() {
if (typeof navigator.registerProtocolHandler !== 'function') {
if (window.location.protocol !== 'https:')
alert("QBT_TR(To use this feature, the WebUI needs to be accessed over HTTPS)QBT_TR[CONTEXT=MainWindow]");
else
alert("QBT_TR(Your browser does not support this feature)QBT_TR[CONTEXT=MainWindow]");
return;
}
const hashString = location.hash ? location.hash.replace(/^#/, '') : '';
const hashParams = new URLSearchParams(hashString);
hashParams.set('download', '');
const templateHashString = hashParams.toString().replace('download=', 'download=%s');
const templateUrl = location.origin + location.pathname
+ location.search + '#' + templateHashString;
navigator.registerProtocolHandler('magnet', templateUrl,
'qBittorrent WebUI magnet handler');
}
function handleDownloadParam() {
// Extract torrent URL from download param in WebUI URL hash
const downloadHash = "#download=";
if (location.hash.indexOf(downloadHash) !== 0)
return;
const url = decodeURIComponent(location.hash.substring(downloadHash.length));
// Remove the processed hash from the URL
history.replaceState('', document.title, (location.pathname + location.search));
showDownloadPage([url]);
}
function closeWindows() {
MochaUI.closeAll();
}
function setupCopyEventHandler() {
if (clipboardEvent)
clipboardEvent.destroy();
clipboardEvent = new ClipboardJS('.copyToClipboard', {
text: function(trigger) {
switch (trigger.id) {
case "copyName":
return copyNameFN();
case "copyInfohash1":
return copyInfohashFN(1);
case "copyInfohash2":
return copyInfohashFN(2);
case "copyMagnetLink":
return copyMagnetLinkFN();
case "copyID":
return copyIdFN();
case "copyComment":
return copyCommentFN();
default:
return "";
}
}
});
}
new Keyboard({
defaultEventType: 'keydown',
events: {
'ctrl+a': function(event) {
if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA")
return;
if (event.target.isContentEditable)
return;
torrentsTable.selectAll();
event.preventDefault();
},
'delete': function(event) {
if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA")
return;
if (event.target.isContentEditable)
return;
deleteFN();
event.preventDefault();
},
'shift+delete': (event) => {
if (event.target.nodeName == "INPUT" || event.target.nodeName == "TEXTAREA")
return;
if (event.target.isContentEditable)
return;
deleteFN(true);
event.preventDefault();
}
}
}).activate();

View file

@ -1395,7 +1395,7 @@ window.qBittorrent.DynamicTable = (function() {
break; // do nothing break; // do nothing
default: default:
if (!useSubcategories) { if (!useSubcategories) {
if (categoryHash !== genHash(row['full_data'].category)) if (categoryHash !== window.qBittorrent.Client.genHash(row['full_data'].category))
return false; return false;
} }
else { else {
@ -1417,7 +1417,7 @@ window.qBittorrent.DynamicTable = (function() {
break; // do nothing break; // do nothing
default: { default: {
const tagHashes = row['full_data'].tags.split(', ').map(tag => genHash(tag)); const tagHashes = row['full_data'].tags.split(', ').map(tag => window.qBittorrent.Client.genHash(tag));
if (!tagHashes.contains(tagHash)) if (!tagHashes.contains(tagHash))
return false; return false;
break; break;

View file

@ -56,7 +56,7 @@ window.qBittorrent.PropPeers = (function() {
syncTorrentPeersLastResponseId = 0; syncTorrentPeersLastResponseId = 0;
torrentPeersTable.clear(); torrentPeersTable.clear();
clearTimeout(loadTorrentPeersTimer); clearTimeout(loadTorrentPeersTimer);
loadTorrentPeersTimer = loadTorrentPeersData.delay(getSyncMainDataInterval()); loadTorrentPeersTimer = loadTorrentPeersData.delay(window.qBittorrent.Client.getSyncMainDataInterval());
return; return;
} }
const url = new URI('api/v2/sync/torrentPeers'); const url = new URI('api/v2/sync/torrentPeers');
@ -68,7 +68,7 @@ window.qBittorrent.PropPeers = (function() {
method: 'get', method: 'get',
onComplete: function() { onComplete: function() {
clearTimeout(loadTorrentPeersTimer); clearTimeout(loadTorrentPeersTimer);
loadTorrentPeersTimer = loadTorrentPeersData.delay(getSyncMainDataInterval()); loadTorrentPeersTimer = loadTorrentPeersData.delay(window.qBittorrent.Client.getSyncMainDataInterval());
}, },
onSuccess: function(response) { onSuccess: function(response) {
$('error_div').set('html', ''); $('error_div').set('html', '');

View file

@ -19,11 +19,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -55,7 +55,7 @@
location: location location: location
}, },
onSuccess: function() { onSuccess: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
}, },
onFailure: function(xhr) { onFailure: function(xhr) {
$('error_div').set('text', xhr.response); $('error_div').set('text', xhr.response);

View file

@ -22,11 +22,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }
@ -111,7 +111,7 @@
inactiveSeedingTimeLimit: inactiveSeedingTimeLimitValue inactiveSeedingTimeLimit: inactiveSeedingTimeLimitValue
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
}); });

View file

@ -164,7 +164,7 @@
$('upload_frame').addEventListener("load", function() { $('upload_frame').addEventListener("load", function() {
if (submitted) if (submitted)
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
}); });
if ((Browser.platform === 'ios') || ((Browser.platform === 'mac') && (navigator.maxTouchPoints > 1))) { if ((Browser.platform === 'ios') || ((Browser.platform === 'mac') && (navigator.maxTouchPoints > 1))) {

View file

@ -36,7 +36,7 @@
}, },
onComplete: function() { onComplete: function() {
window.parent.updateMainData(); window.parent.updateMainData();
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
} }
@ -49,7 +49,7 @@
'limit': limit 'limit': limit
}, },
onComplete: function() { onComplete: function() {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
} }
@ -67,11 +67,11 @@
event.preventDefault(); event.preventDefault();
}, },
'Escape': function(event) { 'Escape': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
}, },
'Esc': function(event) { 'Esc': function(event) {
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
event.preventDefault(); event.preventDefault();
} }
} }

View file

@ -843,7 +843,7 @@
<script> <script>
'use strict'; 'use strict';
$('qbittorrentVersion').innerText = `qBittorrent ${qbtVersion()} QBT_TR(Web UI)QBT_TR[CONTEXT=OptionsDialog]`; $('qbittorrentVersion').innerText = `qBittorrent ${window.qBittorrent.Client.qbtVersion()} QBT_TR(Web UI)QBT_TR[CONTEXT=OptionsDialog]`;
$('qtVersion').textContent = LocalPreferences.get('buildInfo.qtVersion'); $('qtVersion').textContent = LocalPreferences.get('buildInfo.qtVersion');
$('libtorrentVersion').textContent = LocalPreferences.get('buildInfo.libtorrentVersion'); $('libtorrentVersion').textContent = LocalPreferences.get('buildInfo.libtorrentVersion');
$('boostVersion').textContent = LocalPreferences.get('buildInfo.boostVersion'); $('boostVersion').textContent = LocalPreferences.get('buildInfo.boostVersion');

View file

@ -2850,12 +2850,12 @@ Use ';' to split multiple entries. Can use wildcard '*'.)QBT_TR[CONTEXT=OptionsD
}, },
onFailure: function() { onFailure: function() {
alert("QBT_TR(Unable to save program preferences, qBittorrent is probably unreachable.)QBT_TR[CONTEXT=HttpServer]"); alert("QBT_TR(Unable to save program preferences, qBittorrent is probably unreachable.)QBT_TR[CONTEXT=HttpServer]");
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
}, },
onSuccess: function() { onSuccess: function() {
// Close window // Close window
window.parent.location.reload(); window.parent.location.reload();
window.parent.closeWindows(); window.parent.qBittorrent.Client.closeWindows();
} }
}).send(); }).send();
}; };