From d49379789aa016b85fc52adbf8cfad85ac2aca5b Mon Sep 17 00:00:00 2001 From: Cory Date: Mon, 29 Apr 2019 22:52:24 -0700 Subject: [PATCH] Register protocol handler in WebUI for magnet links --- src/webui/www/private/scripts/client.js | 41 +++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/webui/www/private/scripts/client.js b/src/webui/www/private/scripts/client.js index e3c875219..1498162d3 100644 --- a/src/webui/www/private/scripts/client.js +++ b/src/webui/www/private/scripts/client.js @@ -677,6 +677,7 @@ window.addEvent('load', function() { loadMethod: 'xhr', contentURL: 'transferlist.html', onContentLoaded: function() { + handleDownloadParam(); updateMainData(); }, column: 'mainColumn', @@ -781,8 +782,48 @@ window.addEvent('load', function() { addMainWindowTabsEventListener(); addSearchPanel(); } + + registerMagnetHandler(); }); +function registerMagnetHandler() { + if (typeof navigator.registerProtocolHandler !== 'function') + return; + + const hashParams = getHashParamsFromUrl(); + hashParams.download = ''; + + const templateHashString = Object.toQueryString(hashParams).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 hashParams = getHashParamsFromUrl(); + const url = hashParams.download; + if (!url) + return; + + // Remove the download param from WebUI URL hash + delete hashParams.download; + let newHash = Object.toQueryString(hashParams); + newHash = newHash ? ('#' + newHash) : ''; + history.replaceState('', document.title, + (location.pathname + location.search + newHash)); + + showDownloadPage([url]); +} + +function getHashParamsFromUrl() { + const hashString = location.hash ? location.hash.replace(/^#/, '') : ''; + return (hashString.length > 0) ? String.parseQueryString(hashString) : {}; +} + function closeWindows() { MochaUI.closeAll(); }