[RED] Import release details from Bandcamp

Lets find music release on Bandcamp and import release about, personnel credits, cover image and tags.

当前为 2022-11-07 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name [RED] Import release details from Bandcamp
  3. // @namespace https://greasyfork.org/users/321857-anakunda
  4. // @version 0.25.1
  5. // @match https://redacted.ch/upload.php
  6. // @match https://redacted.ch/upload.php&url=*
  7. // @match https://redacted.ch/requests.php?action=new
  8. // @match https://redacted.ch/requests.php?action=new&groupid=*
  9. // @match https://redacted.ch/requests.php?action=new&url=*
  10. // @match https://redacted.ch/torrents.php?id=*
  11. // @match https://redacted.ch/torrents.php?page=*&id=*
  12. // @match https://orpheus.network/upload.php
  13. // @match https://orpheus.network/upload.php?url=*
  14. // @match https://orpheus.network/requests.php?action=new
  15. // @match https://orpheus.network/requests.php?action=new&groupid=*
  16. // @match https://orpheus.network/requests.php?action=new&url=*
  17. // @match https://orpheus.network/torrents.php?id=*
  18. // @match https://orpheus.network/torrents.php?page=*&id=*
  19. // @run-at document-end
  20. // @iconURL https://s4.bcbits.com/img/favicon/favicon-32x32.png
  21. // @author Anakunda
  22. // @description Lets find music release on Bandcamp and import release about, personnel credits, cover image and tags.
  23. // @copyright 2022, Anakunda (https://greasyfork.org/users/321857-anakunda)
  24. // @license GPL-3.0-or-later
  25. // @connect *
  26. // @grant GM_xmlhttpRequest
  27. // @grant GM_getValue
  28. // @grant GM_setValue
  29. // @require https://openuserjs.org/src/libs/Anakunda/xhrLib.min.js
  30. // @require https://openuserjs.org/src/libs/Anakunda/libLocks.min.js
  31. // @require https://openuserjs.org/src/libs/Anakunda/gazelleApiLib.min.js
  32. // @require https://openuserjs.org/src/libs/Anakunda/QobuzLib.min.js
  33. // @require https://openuserjs.org/src/libs/Anakunda/GazelleTagManager.min.js
  34. // ==/UserScript==
  35.  
  36. 'use strict';
  37.  
  38. const imageHostHelper = (function() {
  39. const input = document.head.querySelector('meta[name="ImageHostHelper"]');
  40. return (input != null ? Promise.resolve(input) : new Promise(function(resolve, reject) {
  41. const mo = new MutationObserver(function(mutationsList, mo) {
  42. for (let mutation of mutationsList) for (let node of mutation.addedNodes) {
  43. if (node.nodeName != 'META' || node.name != 'ImageHostHelper') continue;
  44. clearTimeout(timer); mo.disconnect();
  45. return resolve(node);
  46. }
  47. }), timer = setTimeout(function(mo) {
  48. mo.disconnect();
  49. reject('Timeout reached');
  50. }, 15000, mo);
  51. mo.observe(document.head, { childList: true });
  52. })).then(function(node) {
  53. console.assert(node instanceof HTMLElement);
  54. const propName = node.getAttribute('propertyname');
  55. console.assert(propName);
  56. return unsafeWindow[propName] || Promise.reject(`Assertion failed: '${propName}' not in unsafeWindow`);
  57. });
  58. })();
  59.  
  60. const nothingFound = 'Nothing found';
  61. const stripText = text => text ? [
  62. [/\r\n/gm, '\n'], [/[^\S\n]+$/gm, ''], [/\n{3,}/gm, '\n\n'],
  63. ].reduce((text, subst) => text.replace(...subst), text.trim()) : '';
  64.  
  65. function getSearchResults(torrentGroup, fullSearchResults = true, thoroughSearch = false) {
  66. function tryQuery(terms) {
  67. if (!Array.isArray(terms)) throw 'Invalid qrgument';
  68. if (terms.length <= 0) return Promise.reject(nothingFound);
  69. const url = new URL('https://bandcamp.com/search');
  70. url.searchParams.set('q', terms.map(term => '"' + term + '"').join(' '));
  71. const searchType = itemType => (function getPage(page = 1) {
  72. if (itemType) url.searchParams.set('item_type', itemType); else url.searchParams.delete('item_type');
  73. url.searchParams.set('page', page);
  74. return globalXHR(url).then(function({document}) {
  75. const results = Array.prototype.filter.call(document.body.querySelectorAll('div.search ul.result-items > li.searchresult'), function(li) {
  76. let searchType = li.dataset.search;
  77. if (searchType) try { searchType = JSON.parse(searchType).type.toLowerCase() } catch(e) { console.warn(e) }
  78. return !searchType || ['a', 't'].includes(searchType);
  79. });
  80. const nextLink = document.body.querySelector('div.pager > a.next');
  81. return nextLink != null ? getPage(page + 1, itemType).then(_results => results.concat(_results)) : results;
  82. });
  83. })().then(results => results.length > 0 ? results : Promise.reject(nothingFound));
  84. return searchType(); //('a').catch(reason => torrentGroup.group.releaseType == 9 && reason == nothingFound ? searchType('t') : Promise.reject(reason));
  85. }
  86.  
  87. if (!torrentGroup) return Promise.reject('Assertion failed: invalid argument (torrentGroup)');
  88. const artists = torrentGroup.group.releaseType != 7 && torrentGroup.group.musicInfo
  89. && Array.isArray(torrentGroup.group.musicInfo.artists) && torrentGroup.group.musicInfo.artists.length > 0 ?
  90. torrentGroup.group.musicInfo.artists.map(artist => artist.name.trim()).slice(0, 2) : null;
  91. const album = [
  92. /\s+(?:EP|E\.\s?P\.|-\s+(?:EP|E\.\s?P\.))$/i,
  93. /\s+\((?:EP|E\.\s?P\.|Live)\)$/i, /\s+\[(?:EP|E\.\s?P\.|Live)\]$/i,
  94. /\s+\((?:feat\.|ft\.|featuring\s).+\)$/i, /\s+\[(?:feat\.|ft\.|featuring\s).+\]$/i,
  95. ].reduce((title, rx) => title.replace(rx, ''), torrentGroup.group.name.trim());
  96. if (!album) return Promise.reject('Album title missing');
  97. const bracketStripper = /(?:\s+(?:\([^\(\)]+\)|\[[^\[\]]+\]|\{[^\{\}]+\}))+$/g;
  98. const searchAlbumOnly = () => tryQuery([album]).catch(reason => reason == nothingFound ? bracketStripper.test(album) ?
  99. tryQuery([album.replace(bracketStripper, '')]) : Promise.reject(nothingFound) : Promise.reject(reason));
  100. if (artists == null) return searchAlbumOnly();
  101. let lookupWorker = tryQuery(artists.concat(album)).catch(reason => reason == nothingFound ?
  102. artists.some(artist => bracketStripper.test(artist)) || bracketStripper.test(album) ?
  103. tryQuery(artists.map(artist => artist.replace(bracketStripper, '')).concat(album.replace(bracketStripper, '')))
  104. : Promise.reject(nothingFound) : Promise.reject(reason));
  105. if (thoroughSearch) lookupWorker = lookupWorker.catch(reason =>
  106. reason == nothingFound ? searchAlbumOnly() : Promise.reject(reason));
  107. return lookupWorker;
  108. }
  109.  
  110. const matchingResultsCount = groupId => groupId > 0 ? new Promise(function findSharedTorrentGroup(resolve, reject) {
  111. const meta = document.head.querySelector(':scope > meta[name="torrentgroup"]');
  112. if (meta != null && 'torrentGroup' in unsafeWindow) return resolve(unsafeWindow.torrentGroup);
  113. const mo = new MutationObserver(function(ml, mo) {
  114. for (let mutation of ml) for (let node of mutation.addedNodes) if (node.tagName == 'META' && node.name == 'torrentgroup') {
  115. clearTimeout(timeout); mo.disconnect();
  116. if (unsafeWindow.torrentGroup) resolve(unsafeWindow.torrentGroup);
  117. else reject('Assertion failed: ' + node.name + ' not in unsafeWindow');
  118. }
  119. });
  120. mo.observe(document.head, { childList: true });
  121. const timeout = setTimeout(function(mo) {
  122. mo.disconnect();
  123. reject('torrentGroup monitor timed out');
  124. }, GM_getValue('tab_data_timeout', 2500), mo);
  125. }).catch(function(reason) {
  126. console.log(reason);
  127. return queryAjaxAPICached('torrentgroup', { id: groupId }, true);
  128. }).then(torrentGroup => getSearchResults(torrentGroup).then(searchResults => searchResults.map(function(li) {
  129. const searchResult = {
  130. itemType: li.querySelector('div.itemtype'),
  131. numTracks: li.querySelector('div.length'),
  132. releaseYear: li.querySelector('div.released'),
  133. };
  134. if (searchResult.itemType != null) searchResult.itemType = searchResult.itemType.textContent.trim().toLowerCase();
  135. if (searchResult.releaseYear != null
  136. && (searchResult.releaseYear = /\b(\d{4})\b/.exec(searchResult.releaseYear.textContent)) != null)
  137. searchResult.releaseYear = parseInt(searchResult.releaseYear[1]);
  138. if (searchResult.itemType == 'track') searchResult.numTracks = 1;
  139. else if (searchResult.numTracks != null
  140. && (searchResult.numTracks = /\b(\d+)\s+(?:tracks?)\b/i.exec(searchResult.numTracks.textContent)) != null)
  141. searchResult.numTracks = parseInt(searchResult.numTracks[1]);
  142. else searchResult.numTracks = 0;
  143. return searchResult;
  144. })).then(searchResults => searchResults.filter(function(searchResult) {
  145. if (searchResult.releaseYear > 0 && torrentGroup.group.year > searchResult.releaseYear) return false;
  146. return torrentGroup.torrents.some(function(torrent) {
  147. if (torrent.remasterYear > 0 && searchResult.releaseYear > 0 && torrent.remasterYear != searchResult.releaseYear) return false;
  148. const audioFileCount = torrent.fileList ? torrent.fileList.split('|||').filter(file =>
  149. /^(.+\.(?:flac|mp3|m4[ab]|aac|dts(?:hd)?|truehd|ac3|ogg|opus|wv|ape))\{{3}(\d+)\}{3}$/i.test(file)).length : 0;
  150. console.assert(audioFileCount > 0);
  151. if (audioFileCount > 0 && searchResult.numTracks > 0 && audioFileCount != searchResult.numTracks) return false;
  152. return torrent.remasterYear > 0 && searchResult.releaseYear > 0 || audioFileCount > 0 && searchResult.numTracks > 0;
  153. });
  154. }))).then(matchingResults => matchingResults.length > 0 ? matchingResults.length : Promise.reject(nothingFound)) : Promise.reject('Invalid argument');
  155.  
  156. const fetchBandcampDetails = torrentGroup => getSearchResults(torrentGroup, GM_getValue('full_search_results', true), true)
  157. .then(searchResults => new Promise(function(resolve, reject) {
  158. console.assert(searchResults.length > 0);
  159. let selectedRow = null, dialog = document.createElement('DIALOG');
  160. dialog.innerHTML = `
  161. <form method="dialog">
  162. <div style="margin-bottom: 10pt; padding: 4px; background-color: #111; box-shadow: 1pt 1pt 5px #bbb inset;">
  163. <ul id="bandcamp-search-results" style="list-style-type: none; width: 645px; max-height: 70vw; overflow-y: auto; overscroll-behavior-y: none; scrollbar-gutter: stable; scroll-behavior: auto; scrollbar-color: #444 #222;" />
  164. </div>
  165. <input value="Import" type="button" disabled /><input value="Cancel" type="button" style="margin-left: 5pt;" /><div style="display: inline-block; margin-left: 15pt;">
  166. <label style="border: 2px groove black; padding: 3pt 3pt 3pt 4pt;"><input name="update-tags" style="margin-right: 4pt;" type="checkbox" />Tags
  167. <label style="margin-left: 5pt;"><input style="margin-right: 4pt;" name="preserve-tags" type="checkbox" />Preserve</label>
  168. </label><label style="margin-left: 5pt;border: 2px groove black; padding: 3pt 3pt 3pt 4pt;"><input style="margin-right: 4pt;" name="update-image" type="checkbox" />Cover</label><label style="margin-left: 4pt;border: 2px groove black; padding: 3pt 3pt 3pt 4pt;"><input style="margin-right: 4pt;" name="update-description" type="checkbox" />Description
  169. <label style="margin-left: 5pt;"><input style="margin-right: 4pt;" name="insert-about" type="checkbox" />About</label><label style="margin-left: 5pt;"><input style="margin-right: 4pt;" name="insert-credits" type="checkbox" />Credits</label><label style="margin-left: 5pt;"><input style="margin-right: 4pt;" name="insert-url" type="checkbox" />URL</label>
  170. </label>
  171. </div>
  172. </form>`;
  173. const form = dialog.querySelector(':scope > form');
  174. console.assert(form != null);
  175. dialog.style = 'position: fixed; top: 5%; left: 0; right: 0; padding: 10pt; margin-left: auto; margin-right: auto; background-color: gray; box-shadow: 5px 5px 10px; z-index: 9999;';
  176. dialog.onkeyup = function(evt) {
  177. if (evt.key != 'Escape') return true;
  178. evt.currentTarget.close();
  179. return false;
  180. };
  181. dialog.oncancel = evt => { reject('Cancelled') };
  182. dialog.onclose = function(evt) {
  183. if (!evt.currentTarget.returnValue) reject('Cancelled');
  184. document.body.removeChild(evt.currentTarget);
  185. };
  186. const ul = dialog.querySelector('ul#bandcamp-search-results'), buttons = dialog.querySelectorAll('input[type="button"]');
  187. for (let li of searchResults) {
  188. for (let a of li.getElementsByTagName('A')) {
  189. a.onclick = evt => { if (!evt.ctrlKey && !evt.shiftKey) return false };
  190. a.search = '';
  191. }
  192. for (let styleSheet of [
  193. ['.searchresult .art img', 'max-height: 145px; max-width: 145px;'],
  194. ['.result-info', 'display: inline-block; color: white; padding: 1pt 10pt; box-sizing: border-box; vertical-align: top; width: 475px; line-height: 1.4em;'],
  195. ['.itemtype', 'font-size: 10px; color: #999; margin-bottom: 0.5em; padding: 0;'],
  196. ['.heading', 'font-size: 16px; margin-bottom: 0.1em; padding: 0;'],
  197. ['.subhead', 'font-size: 13px; margin-bottom: 0.3em; padding: 0;'],
  198. ['.released', 'font-size: 11px; padding: 0;'],
  199. ['.itemurl', 'font-size: 11px; padding: 0;'],
  200. ['.itemurl a', 'color: #84c67d;'],
  201. ['.tags', 'color: #aaa; font-size: 11px; padding: 0;'],
  202. ]) for (let elem of li.querySelectorAll(styleSheet[0])) elem.style = styleSheet[1];
  203. li.style = 'cursor: pointer; margin: 0; padding: 4px;';
  204. for (let child of li.children) child.style.display = 'inline-block';
  205. let confidence = 1;
  206. let [itemType, numTracks, releaseYear] = ['div.itemtype', 'div.length', 'div.released'].map(sel => li.querySelector(sel));
  207. if (itemType != null) itemType = itemType.textContent.trim().toLowerCase();
  208. if (releaseYear != null && (releaseYear = /\b(\d{4})\b/.exec(releaseYear.textContent)) != null) releaseYear = parseInt(releaseYear[1]);
  209. if (itemType == 'track') numTracks = 1;
  210. else if (numTracks != null && (numTracks = /\b(\d+)\s+(?:tracks?)\b/i.exec(numTracks.textContent)) != null)
  211. numTracks = parseInt(numTracks[1]);
  212. if (releaseYear > 0 && torrentGroup.group.year > releaseYear) confidence *= 1/2;
  213. else if ('torrents' in torrentGroup && torrentGroup.torrents.length > 0) {
  214. if (releaseYear > 0 && !torrentGroup.torrents.some(torrent =>
  215. !(torrent.remasterYear > 0) || torrent.remasterYear == releaseYear)) confidence *= 3/4;
  216. if (numTracks > 0 && !torrentGroup.torrents.some(function(torrent) {
  217. const audioFileCount = torrent.fileList ? torrent.fileList.split('|||').filter(file =>
  218. /^(.+\.(?:flac|mp3|m4[ab]|aac|dts(?:hd)?|truehd|ac3|ogg|opus|wv|ape))\{{3}(\d+)\}{3}$/i.test(file)).length : 0;
  219. console.assert(audioFileCount > 0);
  220. return audioFileCount == numTracks || audioFileCount == 0;
  221. })) confidence *= 3/4;
  222. }
  223. if (confidence < 1) li.style.opacity = confidence;
  224. li.onclick = function(evt) {
  225. if (selectedRow != null) selectedRow.style.backgroundColor = null;
  226. (selectedRow = evt.currentTarget).style.backgroundColor = '#066';
  227. buttons[0].disabled = false;
  228. };
  229. }
  230. for (let li of searchResults.sort((a, b) => (parseFloat(b.style.opacity) || 1) - (parseFloat(a.style.opacity) || 1))) ul.append(li);
  231. buttons[0].onclick = function(evt) {
  232. evt.currentTarget.disabled = true;
  233. console.assert(selectedRow instanceof HTMLLIElement);
  234. const a = selectedRow.querySelector('div.result-info > div.heading > a');
  235. if (a != null) globalXHR(a.href).then(function({document}) {
  236. function safeParse(serialized) {
  237. if (serialized) try { return JSON.parse(serialized) } catch (e) { console.warn('BC meta invalid: %s', e, serialized) }
  238. return null;
  239. }
  240.  
  241. const savePreset = (prefName, inputName) => { GM_setValue(prefName, form.elements[inputName].checked) };
  242. savePreset('update_tags', 'update-tags');
  243. GM_setValue('preserve_tags', form.elements['preserve-tags'].checked ? 1 : 0);
  244. savePreset('update_image', 'update-image');
  245. savePreset('update_description', 'update-description');
  246. savePreset('description_insert_about', 'insert-about');
  247. savePreset('description_insert_credits', 'insert-credits');
  248. savePreset('description_insert_url', 'insert-url');
  249.  
  250. const details = { };
  251. let elem = document.head.querySelector(':scope > script[type="application/ld+json"]');
  252. const releaseMeta = elem && safeParse(elem.text);
  253. const tralbum = (elem = document.head.querySelector('script[data-tralbum]')) && safeParse(elem.dataset.tralbum);
  254. if (tralbum != null && Array.isArray(tralbum.packages) && tralbum.packages.length > 0) for (let key in tralbum.packages[0])
  255. if (!tralbum.current[key] && tralbum.packages.every(pkg => pkg[key] == tralbum.packages[0][key]))
  256. tralbum.current[key] = tralbum.packages[0][key];
  257. if (releaseMeta != null && releaseMeta.byArtist) details.artist = releaseMeta.byArtist.name;
  258. if (releaseMeta != null && releaseMeta.name) details.title = releaseMeta.name;
  259. if (releaseMeta != null && releaseMeta.numTracks) details.numTracks = releaseMeta.numTracks;
  260. if (releaseMeta != null && releaseMeta.datePublished) details.releaseDate = new Date(releaseMeta.datePublished);
  261. else if (tralbum != null && tralbum.current.album_publish_date) details.releaseDate = new Date(tralbum.current.album_publish_date);
  262. if (releaseMeta != null && releaseMeta.publisher) details.publisher = releaseMeta.publisher.name;
  263. if (tralbum != null && tralbum.current.upc) details.upc = tralbum.current.upc;
  264. if (releaseMeta != null && releaseMeta.image) details.image = releaseMeta.image;
  265. else if ((elem = document.head.querySelector('meta[property="og:image"][content]')) != null) details.image = elem.content;
  266. else if ((elem = document.querySelector('div#tralbumArt > a.popupImage')) != null) details.image = elem.href;
  267. if (details.image) details.image = details.image.replace(/_\d+(?=\.\w+$)/, '_10');
  268. details.tags = releaseMeta != null && Array.isArray(releaseMeta.keywords) ? new TagManager(...releaseMeta.keywords)
  269. : new TagManager(...Array.from(document.querySelectorAll('div.tralbum-tags > a.tag'), a => a.textContent.trim()));
  270. if (details.tags.length < 0) delete details.tags;
  271. if (tralbum != null && tralbum.current.minimum_price <= 0) details.tags.add('freely.available');
  272. if (releaseMeta != null && releaseMeta.description) details.description = releaseMeta.description;
  273. else if (tralbum != null && tralbum.current.about) details.description = tralbum.current.about;
  274. if (details.description) details.description = stripText(details.description)
  275. .replace(/^24[^\S\n]*bits?[^\S\n]*\/[^\S\n]*\d+(?:\.\d+)?[^\S\n]*k(?:Hz)?$\n+/m, '');
  276. if (releaseMeta != null && releaseMeta.creditText) details.credits = tralbum.current.credits;
  277. else if (tralbum != null && tralbum.current.credits) details.credits = tralbum.current.credits;
  278. if (details.credits) details.credits = stripText(details.credits);
  279. if (releaseMeta != null && releaseMeta.mainEntityOfPage) details.url = releaseMeta.mainEntityOfPage;
  280. else if (tralbum != null && tralbum.url) details.url = tralbum.url;
  281. if (tralbum != null && tralbum.art_id) details.artId = tralbum.art_id;
  282. if (tralbum != null && tralbum.current.album_id) details.id = tralbum.current.album_id;
  283. resolve(details);
  284. }, reject); else reject('Assertion failed: BC release link not found');
  285. dialog.close(a != null ? a.href : '');
  286. };
  287. buttons[1].onclick = evt => { dialog.close() };
  288.  
  289. const loadPreset = (inputName, presetName, presetDefault) =>
  290. { form.elements[inputName].checked = GM_getValue(presetName, presetDefault) };
  291. loadPreset('update-tags', 'update_tags', true);
  292. form.elements['update-tags'].onchange = function(evt) {
  293. form.elements['preserve-tags'].disabled = !evt.currentTarget.checked;
  294. };
  295. form.elements['update-tags'].dispatchEvent(new Event('change'));
  296. form.elements['preserve-tags'].checked = GM_getValue('preserve_tags', 0) > 0;
  297. loadPreset('update-image', 'update_image', true);
  298. loadPreset('update-description', 'update_description', true);
  299. form.elements['update-description'].onchange = function(evt) {
  300. form.elements['insert-about'].disabled = form.elements['insert-credits'].disabled =
  301. form.elements['insert-url'].disabled = !evt.currentTarget.checked;
  302. };
  303. form.elements['update-description'].dispatchEvent(new Event('change'));
  304. loadPreset('insert-about', 'description_insert_about', true);
  305. loadPreset('insert-credits', 'description_insert_credits', true);
  306. loadPreset('insert-url', 'description_insert_url', true);
  307.  
  308. document.body.append(dialog);
  309. dialog.showModal();
  310. ul.focus();
  311. }));
  312.  
  313. const siteTagsCache = 'siteTagsCache' in localStorage ? (function(serialized) {
  314. try { return JSON.parse(serialized) } catch(e) { return { } }
  315. })(localStorage.getItem('siteTagsCache')) : { };
  316. function getVerifiedTags(tags, confidencyThreshold = GM_getValue('tags_confidency_threshold', 1)) {
  317. if (!Array.isArray(tags)) throw 'Invalid argument';
  318. return Promise.all(tags.map(function(tag) {
  319. if (!(confidencyThreshold > 0) || tmWhitelist.includes(tag) || siteTagsCache[tag] >= confidencyThreshold)
  320. return Promise.resolve(tag);
  321. return queryAjaxAPICached('browse', { taglist: tag }).then(function(response) {
  322. const usage = response.pages > 1 ? (response.pages - 1) * 50 + 1 : response.results.length;
  323. if (usage < confidencyThreshold) return false;
  324. siteTagsCache[tag] = usage;
  325. Promise.resolve(siteTagsCache).then(cache => { localStorage.setItem('siteTagsCache', JSON.stringify(cache)) });
  326. return tag;
  327. }, reason => false);
  328. })).then(results => results.filter(Boolean));
  329. }
  330.  
  331. function importToBody(bcReleaseDetails, body) {
  332. function insertSection(section, afterBegin = true, beforeLinks = true, beforeEnd = true) {
  333. if (section) if (!body) body = section;
  334. else if (afterBegin && rx.afterBegin.some(rx => rx.test(body)))
  335. body = RegExp.lastMatch + section + '\n\n' + RegExp.rightContext.trimLeft();
  336. else if (beforeLinks && rx.beforeLinks.test('\n' + body))
  337. body = (RegExp.leftContext + '\n\n').trimLeft() + section + '\n\n' + RegExp.lastMatch.trimLeft();
  338. else if (beforeEnd && rx.beforeEnd.some(rx => rx.test(body)))
  339. body = RegExp.leftContext.trimRight() + '\n\n' + section + RegExp.lastMatch.trimLeft();
  340. else body += '\n\n' + section;
  341. }
  342.  
  343. body = stripText(body);
  344. const rx = {
  345. afterBegin: [/^\[pad=\d+\|\d+\]/i, /^Releas(?:ing|ed) .+\d{4}$(?:\r?\n){2,}/im],
  346. beforeLinks: /(?:(?:\r?\n)+(?:(?:More info(?:rmation)?:|\[b\]More info(?:rmation)?:\[\/b\])[^\S\r\n]+)?(?:\[url(?:=[^\[\]]+)?\].+\[\/url\]|https?:\/\/\S+))+(?:\[\/size\]\[\/pad\])?$/i,
  347. beforeEnd: [/\[\/size\]\[\/pad\]$/i],
  348. };
  349. if (bcReleaseDetails.description && bcReleaseDetails.description.length > 10
  350. && ![ ].some(rx => rx.test(bcReleaseDetails.description))
  351. && GM_getValue('description_insert_about', true) && !body.includes(bcReleaseDetails.description))
  352. insertSection('[quote][plain]' + bcReleaseDetails.description + '[/plain][/quote]', true, true, true);
  353. if (document.location.pathname != '/requests.php' && bcReleaseDetails.credits && bcReleaseDetails.credits.length > 10
  354. && ![ ].some(rx => rx.test(bcReleaseDetails.credits))
  355. && GM_getValue('description_insert_credits', true) && !body.includes(bcReleaseDetails.credits))
  356. insertSection('[hide=Credits][plain]' + bcReleaseDetails.credits + '[/plain][/hide]', false, true, true);
  357. if (bcReleaseDetails.url && GM_getValue('description_insert_url', true) && !body.includes(bcReleaseDetails.url))
  358. insertSection('[url=' + bcReleaseDetails.url + ']Bandcamp[/url]', false, false, true);
  359. return body.replace(/(\[\/quote\])(?:\r?\n){2,}/ig, '$1\n');
  360. }
  361.  
  362. const urlParams = new URLSearchParams(document.location.search);
  363. switch (document.location.pathname) {
  364. case '/torrents.php': {
  365. if (document.querySelector('div.sidebar > div.box_artists') == null) break; // Nothing to do here - not music torrent
  366. const groupId = parseInt(urlParams.get('id'));
  367. if (!(groupId > 0)) throw 'Invalid group id';
  368. const linkBox = document.body.querySelector('div.header > div.linkbox');
  369. if (linkBox == null) throw 'LinkBox not found';
  370. const a = document.createElement('A');
  371. a.textContent = 'Bandcamp import';
  372. a.href = '#';
  373. a.title = 'Import album textual description, tags and cover image from Bandcamp release page';
  374. a.className = 'brackets';
  375. a.onclick = function(evt) {
  376. if (!this.disabled) this.disabled = true; else return false;
  377. this.style.color = 'orange';
  378. queryAjaxAPI('torrentgroup', { id: groupId }).then(torrentGroup => fetchBandcampDetails(torrentGroup).then(function(bcRelease) {
  379. const updateWorkers = [ ];
  380. if (bcRelease.tags instanceof TagManager && GM_getValue('update_tags', true) && bcRelease.tags.length > 0) {
  381. const releaseTags = Array.from(document.body.querySelectorAll('div.box_tags ul > li'), function(li) {
  382. const tag = { name: li.querySelector(':scope > a'), id: li.querySelector('span.remove_tag > a') };
  383. if (tag.name != null) tag.name = tag.name.textContent.trim();
  384. if (tag.id != null) tag.id = parseInt(new URLSearchParams(tag.id.search).get('tagid'));
  385. return tag.name && tag.id ? tag : null;
  386. }).filter(Boolean);
  387. let bcTags = [ ];
  388. if (torrentGroup.group.musicInfo) for (let importance of Object.keys(torrentGroup.group.musicInfo))
  389. if (Array.isArray(torrentGroup.group.musicInfo[importance]))
  390. Array.prototype.push.apply(bcTags, torrentGroup.group.musicInfo[importance].map(artist => artist.name));
  391. if (Array.isArray(torrentGroup.torrents)) for (let torrent of torrentGroup.torrents) {
  392. if (!torrent.remasterRecordLabel) continue;
  393. const labels = torrent.remasterRecordLabel.split('/').map(label => label.trim());
  394. if (labels.length > 0) {
  395. Array.prototype.push.apply(bcTags, labels);
  396. Array.prototype.push.apply(bcTags, labels.map(function(label) {
  397. const bareLabel = label.replace(/(?:\s+(?:under license.+|Records|Recordings|(?:Ltd|Inc)\.?))+$/, '');
  398. if (bareLabel != label) return bareLabel;
  399. }).filter(Boolean));
  400. }
  401. }
  402. bcTags = new TagManager(...bcTags);
  403. bcTags = Array.from(bcRelease.tags).filter(tag => !bcTags.includes(tag));
  404. if (bcTags.length > 0 && (releaseTags.length <= 0 || !(Number(GM_getValue('preserve_tags', 0)) > 1)))
  405. updateWorkers.push(getVerifiedTags(bcTags, 3).then(function(verifiedBcTags) {
  406. if (verifiedBcTags.length <= 0) return false;
  407. let userAuth = document.body.querySelector('input[name="auth"][value]');
  408. if (userAuth != null) userAuth = userAuth.value; else throw 'Failed to capture user auth';
  409. const updateWorkers = [ ];
  410. const addTags = verifiedBcTags.filter(tag => !releaseTags.map(tag => tag.name).includes(tag));
  411. if (addTags.length > 0) Array.prototype.push.apply(updateWorkers, addTags.map(tag => localXHR('/torrents.php', { responseType: null }, new URLSearchParams({
  412. action: 'add_tag',
  413. groupid: torrentGroup.group.id,
  414. tagname: tag,
  415. auth: userAuth,
  416. }))));
  417. const deleteTags = releaseTags.filter(tag => !verifiedBcTags.includes(tag.name)).map(tag => tag.id);
  418. if (deleteTags.length > 0 && !(Number(GM_getValue('preserve_tags', 0)) > 0))
  419. Array.prototype.push.apply(updateWorkers, deleteTags.map(tagId => localXHR('/torrents.php?' + new URLSearchParams({
  420. action: 'delete_tag',
  421. groupid: torrentGroup.group.id,
  422. tagid: tagId,
  423. auth: userAuth,
  424. }), { responseType: null })));
  425. return updateWorkers.length > 0 ? Promise.all(updateWorkers.map(updateWorker =>
  426. updateWorker.then(responseCode => true, reason => reason))).then(function(results) {
  427. if (results.some(result => result === true)) return results;
  428. return Promise.reject(`All of ${results.length} tag update workers failed (see browser console for more details)`);
  429. }) : false;
  430. }));
  431. }
  432. const rehostWorker = bcRelease.image && GM_getValue('update_image', true) ?
  433. imageHostHelper.then(ihh => ihh.rehostImageLinks([bcRelease.image])
  434. .then(ihh.singleImageGetter)).catch(reason => bcRelease.image) : Promise.resolve(null);
  435. if (ajaxApiKey) {
  436. let origBody = document.createElement('TEXTAREA');
  437. origBody.innerHTML = torrentGroup.group.bbBody;
  438. const body = importToBody(bcRelease, (origBody = origBody.textContent)), formData = new FormData;
  439. updateWorkers.push(rehostWorker.then(function(rehostedImageUrl) {
  440. const updateImage = rehostedImageUrl != null && (!torrentGroup.group.wikiImage || !GM_getValue('preserve_image', false))
  441. && rehostedImageUrl != torrentGroup.group.wikiImage;
  442. if (updateImage || GM_getValue('update_description', true) && body != origBody.trim()) {
  443. if (updateImage) formData.set('image', rehostedImageUrl);
  444. if (GM_getValue('update_description', true) && body != origBody) formData.set('body', body);
  445. formData.set('summary', 'Additional description/cover image import from Bandcamp');
  446. return queryAjaxAPI('groupedit', { id: torrentGroup.group.id }, formData).then(function(response) {
  447. console.log(response);
  448. return true;
  449. });
  450. } else return false;
  451. }));
  452. } else {
  453. updateWorkers.push(localXHR('/torrents.php?' + new URLSearchParams({
  454. action: 'editgroup',
  455. groupid: torrentGroup.group.id,
  456. })).then(function(document) {
  457. const editForm = document.querySelector('form.edit_form');
  458. if (editForm == null) throw 'Edit form not exists';
  459. const formData = new FormData(editForm);
  460. const image = editForm.elements.namedItem('image').value, origBody = editForm.elements.namedItem('body').value;
  461. const body = importToBody(bcRelease, origBody);
  462. return rehostWorker.then(function(resolvedImageUrl) {
  463. const updateImage = resolvedImageUrl != null && (!image || !GM_getValue('preserve_image', false))
  464. && resolvedImageUrl != image;
  465. if (updateImage || GM_getValue('update_description', true) && body != origBody.trim()) {
  466. if (updateImage) formData.set('image', resolved[1]);
  467. if (GM_getValue('update_description', true) && body != origBody) formData.set('body', body);
  468. formData.set('summary', 'Additional description/cover image import from Bandcamp');
  469. return localXHR('/torrents.php', { responseType: null }, formData).then(responseCode => true);
  470. } else return false;
  471. });
  472. }));
  473. if (document.domain == 'redacted.ch' && !(GM_getValue('red_nag_shown', 0) >= 3)) {
  474. const cpLink = new URL('/user.php?action=edit#api_key_settings', document.location.origin);
  475. let userId = document.body.querySelector('#userinfo_username a.username');
  476. if (userId != null) userId = parseInt(new URLSearchParams(userId.search).get('id'));
  477. if (userId > 0) cpLink.searchParams.set('userid', userId);
  478. alert('Please consider generating your personal API token (' + cpLink.href + ')\nSet up as "redacted_api_key" script storage entry');
  479. GM_setValue('red_nag_shown', GM_getValue('red_nag_shown', 0) + 1 || 1);
  480. // updateWorkers.push(localXHR('/user.php?' + URLSearchParams({ action: 'edit', userid: userId })).then(function(document) {
  481. // const form = document.body.querySelector('form#userform');
  482. // if (form == null) throw 'User form not found';
  483. // const formData = new FormData(form), newApiKey = formData.get('new_api_key');
  484. // if (newApiKey) formData.set('confirmapikey', 'on'); else throw 'API key not exist';
  485. // formData.set('api_torrents_scope', 'on');
  486. // for (let name of ['api_user_scope', 'api_requests_scope', 'api_forums_scope', 'api_wiki_scope']) formData.delete(name);
  487. // return localXHR('/user.php', { responseType: null }, formData).then(statusCode => newApiKey);
  488. // }).then(function(newApiKey) {
  489. // GM_setValue('redacted_api_key', newApiKey);
  490. // alert('Your personal API key [' + newApiKey + '] was successfulloy created and saved');
  491. // return false;
  492. // }));
  493. }
  494. }
  495. if (updateWorkers.length > 0) return Promise.all(updateWorkers.map(updateWorker =>
  496. updateWorker.then(response => Boolean(response), function(reason) {
  497. console.warn('Update worker failed with reason ' + reason);
  498. return reason;
  499. }))).then(function(results) {
  500. if (results.filter(Boolean).length > 0 && !results.some(result => result === true))
  501. return Promise.reject(`All of ${results.length} update workers failed (see browser console for more details)`);
  502. if (results.some(result => result === true)) return (document.location.reload(), true);
  503. });
  504. })).catch(reason => { if (!['Cancelled'].includes(reason)) alert(reason) }).then(status => {
  505. this.style.color = status ? 'springgreen' : null;
  506. this.disabled = false;
  507. });
  508. return false;
  509. };
  510. linkBox.append(' ', a);
  511.  
  512. if (urlParams.has('presearch-bandcamp')) matchingResultsCount(groupId).then(function(matchedCount) {
  513. a.style.fontWeight = 'bold';
  514. a.title += `\n\n${matchedCount} possibly matching release(s)`;
  515. }, reason => { a.style.color = 'gray' });
  516. break;
  517. }
  518. case '/upload.php':
  519. if (urlParams.has('groupid')) break;
  520. case '/requests.php': {
  521. function hasStyleSheet(name) {
  522. if (name) name = name.toLowerCase(); else throw 'Invalid argument';
  523. const hrefRx = new RegExp('\\/' + name + '\\b', 'i');
  524. if (document.styleSheets) for (let styleSheet of document.styleSheets)
  525. if (styleSheet.title && styleSheet.title.toLowerCase() == name) return true;
  526. else if (styleSheet.href && hrefRx.test(styleSheet.href)) return true;
  527. return false;
  528. }
  529. function checkFields() {
  530. const visible = ['0', 'Music'].includes(categories.value) && title.textLength > 0;
  531. if (container.hidden != !visible) container.hidden = !visible;
  532. }
  533.  
  534. const categories = document.getElementById('categories');
  535. if (categories == null) throw 'Categories select not found';
  536. const form = document.getElementById('upload_table') || document.getElementById('request_form');
  537. if (form == null) throw 'Main form not found';
  538. let title = form.elements.namedItem('title');
  539. if (title != null) title.addEventListener('input', checkFields); else throw 'Title select not found';
  540. const dynaForm = document.getElementById('dynamic_form');
  541. if (dynaForm != null) new MutationObserver(function(ml, mo) {
  542. for (let mutation of ml) if (mutation.addedNodes.length > 0) {
  543. if (title != null) title.removeEventListener('input', checkFields);
  544. if ((title = document.getElementById('title')) != null) title.addEventListener('input', checkFields);
  545. else throw 'Assertion failed: title input not found!';
  546. container.hidden = true;
  547. }
  548. }).observe(dynaForm, { childList: true });
  549. const isLightTheme = ['postmod', 'shiro', 'layer_cake', 'proton', 'red_light', '2iUn3'].some(hasStyleSheet);
  550. if (isLightTheme) console.log('Light Gazelle theme detected');
  551. const isDarkTheme = ['kuro', 'minimal', 'red_dark', 'Vinyl'].some(hasStyleSheet);
  552. if (isDarkTheme) console.log('Dark Gazelle theme detected');
  553. const container = document.createElement('DIV');
  554. container.style = 'position: fixed; top: 64pt; right: 10pt; padding: 5pt; border-radius: 50%; z-index: 999;';
  555. container.style.backgroundColor = `#${isDarkTheme ? '2f4f4f' : 'b8860b'}80`;
  556. const bcButton = document.createElement('BUTTON'), img = document.createElement('IMG');
  557. bcButton.id = 'import-from-bandcamp';
  558. bcButton.style = `
  559. padding: 10px; color: white; background-color: white; cursor: pointer;
  560. border: none; border-radius: 50%; transition: background-color 200ms;
  561. `;
  562. bcButton.dataset.backgroundColor = bcButton.style.backgroundColor;
  563. bcButton.setDisabled = function(disabled = true) {
  564. this.disabled = disabled;
  565. this.style.opacity = disabled ? 0.5 : 1;
  566. this.style.cursor = disabled ? 'not-allowed' : 'pointer';
  567. };
  568. bcButton.onclick = function(evt) {
  569. this.setDisabled(true);
  570. this.style.backgroundColor = 'red';
  571. const torrentGroup = { group: {
  572. name: title.value,
  573. musicInfo: { },
  574. releaseType: parseInt(form.elements.namedItem('releasetype').value),
  575. year: parseInt(form.elements.namedItem('year').value),
  576. } };
  577. for (let artist of form.querySelectorAll('input[name="artists[]"]')) {
  578. const importance = ['artists', 'with', 'composers', 'conductor', 'dj', 'remixedby', 'producer']
  579. [parseInt(artist.nextElementSibling.value) - 1];
  580. if (!importance || !(artist = artist.value.trim())) continue;
  581. if (!(importance in torrentGroup.group.musicInfo)) torrentGroup.group.musicInfo[importance] = [ ];
  582. torrentGroup.group.musicInfo[importance].push({ name: artist });
  583. }
  584. const remasterYear = parseInt(form.elements.namedItem('remaster_year').value);
  585. if (remasterYear > 0) torrentGroup.torrents = [{ remasterYear: remasterYear }];
  586. fetchBandcampDetails(torrentGroup).then(function(bcRelease) {
  587. const tags = form.elements.namedItem('tags'), image = form.elements.namedItem('image'),
  588. description = form.elements.namedItem('album_desc') || form.elements.namedItem('description');
  589. if (tags != null && bcRelease.tags instanceof TagManager && bcRelease.tags.length > 0 && GM_getValue('update_tags', true)
  590. && (!tags.value || !(Number(GM_getValue('preserve_tags', 0)) > 1))) {
  591. let bcTags = Array.from(form.querySelectorAll('input[name="artists[]"]'), input => input.value.trim()).filter(Boolean);
  592. let labels = form.elements.namedItem('remaster_record_label') || form.elements.namedItem('record_label');
  593. if (labels != null && (labels = labels.value.trim().split('/').map(label => label.trim())).length > 0) {
  594. Array.prototype.push.apply(bcTags, labels);
  595. Array.prototype.push.apply(bcTags, labels.map(function(label) {
  596. const bareLabel = label.replace(/(?:\s+(?:under license.+|Records|Recordings|(?:Ltd|Inc)\.?))+$/, '');
  597. if (bareLabel != label) return bareLabel;
  598. }).filter(Boolean));
  599. }
  600. bcTags = new TagManager(...bcTags);
  601. bcTags = Array.from(bcRelease.tags).filter(tag => !bcTags.includes(tag));
  602. getVerifiedTags(bcTags).then(function(bcVerifiedTags) {
  603. if (bcVerifiedTags.length <= 0) return;
  604. if (Number(GM_getValue('preserve_tags', 0)) > 0) {
  605. const mergedTags = new TagManager(tags.value, ...bcVerifiedTags);
  606. tags.value = mergedTags.toString();
  607. } else tags.value = bcVerifiedTags.join(', ');
  608. });
  609. }
  610. if (image != null && bcRelease.image && GM_getValue('update_image', true) && (!image.value || !GM_getValue('preserve_image', false))) {
  611. image.value = bcRelease.image;
  612. imageHostHelper.then(ihh => { ihh.rehostImageLinks([bcRelease.image]).then(ihh.singleImageGetter).then(rehostedUrl =>
  613. { image.value = rehostedUrl }) });
  614. }
  615. if (description != null && GM_getValue('update_description', true)) {
  616. const body = importToBody(bcRelease, description.value);
  617. if (body != description.value) description.value = body;
  618. }
  619. }, reason => { if (!['Cancelled'].includes(reason)) alert(reason) }).then(() => {
  620. this.style.backgroundColor = this.dataset.backgroundColor;
  621. this.setDisabled(false);
  622. });
  623. };
  624. bcButton.onmouseenter = bcButton.onmouseleave = function(evt) {
  625. if (evt.relatedTarget == evt.currentTarget || evt.currentTarget.disabled) return false;
  626. evt.currentTarget.style.backgroundColor = evt.type == 'mouseenter' ? 'orange'
  627. : evt.currentTarget.dataset.backgroundColor || null;
  628. };
  629. bcButton.title = 'Import description, cover image and tags from Bandcamp';
  630. img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAAbFBMVEX////3///v///v9//m9//m9/fe9/fe7/fW7/fO7/fF7/fF5ve95u+15u+13u+t3u+l3u+l3uac1uaU1uaM1uaMzuaEzt57zt57xd5zxd5rxd5jvdZavdZSvdZStdZKtdZKtc5Ctc5Crc4ZpcWSSeq2AAAAAXRSTlMAQObYZgAAAAlwSFlzAAALEgAACxIB0t1+/AAAAoBJREFUeJzt2mtvgjAUBuCC93sUdR/2/3/bsqlbNqfzVpgGExXa02N5ZVly+gVBpU+a0retVtUfl6oABCAAAQhAAAIQgAAEIAABCEAAArjjs60oUSpI0pNCx/jFBxA8Ve7QkmV9eXkHYAKrX7/5ACptVP3xSvsAprAGSGZXJ2xAo4GqX39dn7EBY1gDqHcfQKuGql5/3JxyAZPw/CIJCh7Vpw+gG56/r4oe4/ntnZkAXA+Iv30AA1T1Si8yF3iAIawBDisfwAhVvdLz7BUWoA9rgN3GBzBBVa/0LHeJAQg6pwYo/Pyfjpu9DyCdBiDGAf2av7sbUGu6jbyiV4kPADcPUfkewAA066jqb2OYDXhUDHMBndDxAXbJxDAXEMHmAZkYZgK6IeT5P5ZDNoV4gEsPKDoOJJkY5gFwMbw3PYJuAC6G9Y8P4JExzALgYni79QFMA+LNu8r1YpAPqLRhg9BaW98iAGkKIcYBwzyEATjHMGAeEC8NMewGAFfDlkGQBjRxQ4A5BFyAMS6FzDHoAHRg22faOA1wAiLcYtA4EXIB+rh5CN0ANsCogpoHaEsM04AhZh2gqBQiAQNYD9jbYpgERKjqyUGYAPRwMbzzAZQSwwQAF8MxEcMEAJhC7gYwAOrpnixgHNBLBjIPOK+GEeMAFcNWAHBPloxhKwCXQnQM2wDdsmLYBhiVFcMWAC6G95wemAcAGyC7J8sCDEH7gcRqmAYcYxg1D7AuBilAVGYKmQA9WBc07MkyAMAY5vaAG0C5MWwAlBvDecCjfhplA57THgAYB0JeCmQBC9iutGspYAGw0htf/tV/SAQgAAEIQAACEIAABCAAAQhAAAJ4SPkFdtLUKHgfCmoAAAAASUVORK5CYII=' // https://s4.bcbits.com/img/favicon/apple-touch-icon.png
  631. img.width = 32;
  632. bcButton.append(img);
  633. container.append(bcButton);
  634. checkFields();
  635. document.body.append(container);
  636. break;
  637. }
  638. }