Bandcamp script (bandcamp.com only)

A discography player for bandcamp.com and manager for your played albums

目前为 2023-07-13 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Bandcamp script (bandcamp.com only)
  3. // @description A discography player for bandcamp.com and manager for your played albums
  4. // @namespace https://openuserjs.org/users/cuzi
  5. // @supportURL https://github.com/cvzi/Bandcamp-script-deluxe-edition/issues
  6. // @icon https://raw.githubusercontent.com/cvzi/Bandcamp-script-deluxe-edition/master/images/icon.png
  7. // @contributionURL https://github.com/cvzi/Bandcamp-script-deluxe-edition#donate
  8. // @require https://unpkg.com/json5@2.1.0/dist/index.min.js
  9. // @require https://openuserjs.org/src/libs/cuzi/GeniusLyrics.js
  10. // @require https://unpkg.com/react@18/umd/react.development.js
  11. // @require https://unpkg.com/react-dom@18/umd/react-dom.development.js
  12. // @run-at document-start
  13. // @match https://bandcamp.com/*
  14. // @match https://*.bandcamp.com/*
  15. // @match https://campexplorer.io/*
  16. // @exclude https://bandcamp.com/videoframe*
  17. // @exclude https://bandcamp.com/EmbeddedPlayer*
  18. // @connect bandcamp.com
  19. // @connect *.bandcamp.com
  20. // @connect bcbits.com
  21. // @connect *.bcbits.com
  22. // @connect genius.com
  23. // @version 1.30.1
  24. // @homepage https://github.com/cvzi/Bandcamp-script-deluxe-edition
  25. // @author cuzi
  26. // @license MIT
  27. // @grant GM.xmlHttpRequest
  28. // @grant GM.setValue
  29. // @grant GM.getValue
  30. // @grant GM.notification
  31. // @grant GM_download
  32. // @grant GM.registerMenuCommand
  33. // @grant GM_registerMenuCommand
  34. // @grant GM_addStyle
  35. // @grant GM_setClipboard
  36. // @grant unsafeWindow
  37. // ==/UserScript==
  38.  
  39. // ==OpenUserJS==
  40. // @author cuzi
  41. // ==/OpenUserJS==
  42.  
  43. /*
  44. MIT License
  45.  
  46. Copyright (c) 2020 cvzi
  47.  
  48. Permission is hereby granted, free of charge, to any person obtaining a copy
  49. of this software and associated documentation files (the "Software"), to deal
  50. in the Software without restriction, including without limitation the rights
  51. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  52. copies of the Software, and to permit persons to whom the Software is
  53. furnished to do so, subject to the following conditions:
  54.  
  55. The above copyright notice and this permission notice shall be included in all
  56. copies or substantial portions of the Software.
  57.  
  58. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  59. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  60. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  61. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  62. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  63. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  64. SOFTWARE.
  65. */
  66.  
  67. /* globals React, ReactDOM */
  68. (function (React, ReactDOM) {
  69. 'use strict';
  70.  
  71. function _interopNamespaceDefault(e) {
  72. var n = Object.create(null);
  73. if (e) {
  74. Object.keys(e).forEach(function (k) {
  75. if (k !== 'default') {
  76. var d = Object.getOwnPropertyDescriptor(e, k);
  77. Object.defineProperty(n, k, d.get ? d : {
  78. enumerable: true,
  79. get: function () { return e[k]; }
  80. });
  81. }
  82. });
  83. }
  84. n.default = e;
  85. return Object.freeze(n);
  86. }
  87.  
  88. var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
  89. var ReactDOM__namespace = /*#__PURE__*/_interopNamespaceDefault(ReactDOM);
  90.  
  91. /*
  92. Compatibility adaptions for Violentmonkey https://github.com/violentmonkey/violentmonkey
  93. */
  94.  
  95. if (typeof GM.registerMenuCommand !== 'function') {
  96. if (typeof GM_registerMenuCommand === 'function') {
  97. GM.registerMenuCommand = GM_registerMenuCommand;
  98. } else {
  99. console.warn('Neither GM.registerMenuCommand nor GM_registerMenuCommand are available');
  100. }
  101. }
  102.  
  103. function _defineProperty(obj, key, value) {
  104. key = _toPropertyKey(key);
  105. if (key in obj) {
  106. Object.defineProperty(obj, key, {
  107. value: value,
  108. enumerable: true,
  109. configurable: true,
  110. writable: true
  111. });
  112. } else {
  113. obj[key] = value;
  114. }
  115. return obj;
  116. }
  117. function _toPrimitive(input, hint) {
  118. if (typeof input !== "object" || input === null) return input;
  119. var prim = input[Symbol.toPrimitive];
  120. if (prim !== undefined) {
  121. var res = prim.call(input, hint || "default");
  122. if (typeof res !== "object") return res;
  123. throw new TypeError("@@toPrimitive must return a primitive value.");
  124. }
  125. return (hint === "string" ? String : Number)(input);
  126. }
  127. function _toPropertyKey(arg) {
  128. var key = _toPrimitive(arg, "string");
  129. return typeof key === "symbol" ? key : String(key);
  130. }
  131.  
  132. function _extends() {
  133. _extends = Object.assign ? Object.assign.bind() : function (target) {
  134. for (var i = 1; i < arguments.length; i++) {
  135. var source = arguments[i];
  136. for (var key in source) {
  137. if (Object.prototype.hasOwnProperty.call(source, key)) {
  138. target[key] = source[key];
  139. }
  140. }
  141. }
  142. return target;
  143. };
  144. return _extends.apply(this, arguments);
  145. }
  146.  
  147. function _assertThisInitialized(self) {
  148. if (self === void 0) {
  149. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  150. }
  151. return self;
  152. }
  153.  
  154. function _setPrototypeOf(o, p) {
  155. _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
  156. o.__proto__ = p;
  157. return o;
  158. };
  159. return _setPrototypeOf(o, p);
  160. }
  161.  
  162. function _inheritsLoose(subClass, superClass) {
  163. subClass.prototype = Object.create(superClass.prototype);
  164. subClass.prototype.constructor = subClass;
  165. _setPrototypeOf(subClass, superClass);
  166. }
  167.  
  168. var safeIsNaN = Number.isNaN || function ponyfill(value) {
  169. return typeof value === 'number' && value !== value;
  170. };
  171. function isEqual(first, second) {
  172. if (first === second) {
  173. return true;
  174. }
  175. if (safeIsNaN(first) && safeIsNaN(second)) {
  176. return true;
  177. }
  178. return false;
  179. }
  180. function areInputsEqual(newInputs, lastInputs) {
  181. if (newInputs.length !== lastInputs.length) {
  182. return false;
  183. }
  184. for (var i = 0; i < newInputs.length; i++) {
  185. if (!isEqual(newInputs[i], lastInputs[i])) {
  186. return false;
  187. }
  188. }
  189. return true;
  190. }
  191. function memoizeOne(resultFn, isEqual) {
  192. if (isEqual === void 0) {
  193. isEqual = areInputsEqual;
  194. }
  195. var lastThis;
  196. var lastArgs = [];
  197. var lastResult;
  198. var calledOnce = false;
  199. function memoized() {
  200. var newArgs = [];
  201. for (var _i = 0; _i < arguments.length; _i++) {
  202. newArgs[_i] = arguments[_i];
  203. }
  204. if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) {
  205. return lastResult;
  206. }
  207. lastResult = resultFn.apply(this, newArgs);
  208. calledOnce = true;
  209. lastThis = this;
  210. lastArgs = newArgs;
  211. return lastResult;
  212. }
  213. return memoized;
  214. }
  215.  
  216. // Animation frame based implementation of setTimeout.
  217. // Inspired by Joe Lambert, https://gist.github.com/joelambert/1002116#file-requesttimeout-js
  218. var hasNativePerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
  219. var now = hasNativePerformanceNow ? function () {
  220. return performance.now();
  221. } : function () {
  222. return Date.now();
  223. };
  224. function cancelTimeout(timeoutID) {
  225. cancelAnimationFrame(timeoutID.id);
  226. }
  227. function requestTimeout(callback, delay) {
  228. var start = now();
  229. function tick() {
  230. if (now() - start >= delay) {
  231. callback.call(null);
  232. } else {
  233. timeoutID.id = requestAnimationFrame(tick);
  234. }
  235. }
  236. var timeoutID = {
  237. id: requestAnimationFrame(tick)
  238. };
  239. return timeoutID;
  240. }
  241. var size = -1; // This utility copied from "dom-helpers" package.
  242.  
  243. function getScrollbarSize(recalculate) {
  244. if (recalculate === void 0) {
  245. recalculate = false;
  246. }
  247. if (size === -1 || recalculate) {
  248. var div = document.createElement('div');
  249. var style = div.style;
  250. style.width = '50px';
  251. style.height = '50px';
  252. style.overflow = 'scroll';
  253. document.body.appendChild(div);
  254. size = div.offsetWidth - div.clientWidth;
  255. document.body.removeChild(div);
  256. }
  257. return size;
  258. }
  259. var cachedRTLResult = null; // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
  260. // Chrome does not seem to adhere; its scrollLeft values are positive (measured relative to the left).
  261. // Safari's elastic bounce makes detecting this even more complicated wrt potential false positives.
  262. // The safest way to check this is to intentionally set a negative offset,
  263. // and then verify that the subsequent "scroll" event matches the negative offset.
  264. // If it does not match, then we can assume a non-standard RTL scroll implementation.
  265.  
  266. function getRTLOffsetType(recalculate) {
  267. if (recalculate === void 0) {
  268. recalculate = false;
  269. }
  270. if (cachedRTLResult === null || recalculate) {
  271. var outerDiv = document.createElement('div');
  272. var outerStyle = outerDiv.style;
  273. outerStyle.width = '50px';
  274. outerStyle.height = '50px';
  275. outerStyle.overflow = 'scroll';
  276. outerStyle.direction = 'rtl';
  277. var innerDiv = document.createElement('div');
  278. var innerStyle = innerDiv.style;
  279. innerStyle.width = '100px';
  280. innerStyle.height = '100px';
  281. outerDiv.appendChild(innerDiv);
  282. document.body.appendChild(outerDiv);
  283. if (outerDiv.scrollLeft > 0) {
  284. cachedRTLResult = 'positive-descending';
  285. } else {
  286. outerDiv.scrollLeft = 1;
  287. if (outerDiv.scrollLeft === 0) {
  288. cachedRTLResult = 'negative';
  289. } else {
  290. cachedRTLResult = 'positive-ascending';
  291. }
  292. }
  293. document.body.removeChild(outerDiv);
  294. return cachedRTLResult;
  295. }
  296. return cachedRTLResult;
  297. }
  298. var IS_SCROLLING_DEBOUNCE_INTERVAL$1 = 150;
  299. var defaultItemKey$1 = function defaultItemKey(index, data) {
  300. return index;
  301. }; // In DEV mode, this Set helps us only log a warning once per component instance.
  302. function createListComponent(_ref) {
  303. var _class;
  304. var getItemOffset = _ref.getItemOffset,
  305. getEstimatedTotalSize = _ref.getEstimatedTotalSize,
  306. getItemSize = _ref.getItemSize,
  307. getOffsetForIndexAndAlignment = _ref.getOffsetForIndexAndAlignment,
  308. getStartIndexForOffset = _ref.getStartIndexForOffset,
  309. getStopIndexForStartIndex = _ref.getStopIndexForStartIndex,
  310. initInstanceProps = _ref.initInstanceProps,
  311. shouldResetStyleCacheOnItemSizeChange = _ref.shouldResetStyleCacheOnItemSizeChange,
  312. validateProps = _ref.validateProps;
  313. return _class = /*#__PURE__*/function (_PureComponent) {
  314. _inheritsLoose(List, _PureComponent);
  315.  
  316. // Always use explicit constructor for React components.
  317. // It produces less code after transpilation. (#26)
  318. // eslint-disable-next-line no-useless-constructor
  319. function List(props) {
  320. var _this;
  321. _this = _PureComponent.call(this, props) || this;
  322. _this._instanceProps = initInstanceProps(_this.props, _assertThisInitialized(_this));
  323. _this._outerRef = void 0;
  324. _this._resetIsScrollingTimeoutId = null;
  325. _this.state = {
  326. instance: _assertThisInitialized(_this),
  327. isScrolling: false,
  328. scrollDirection: 'forward',
  329. scrollOffset: typeof _this.props.initialScrollOffset === 'number' ? _this.props.initialScrollOffset : 0,
  330. scrollUpdateWasRequested: false
  331. };
  332. _this._callOnItemsRendered = void 0;
  333. _this._callOnItemsRendered = memoizeOne(function (overscanStartIndex, overscanStopIndex, visibleStartIndex, visibleStopIndex) {
  334. return _this.props.onItemsRendered({
  335. overscanStartIndex: overscanStartIndex,
  336. overscanStopIndex: overscanStopIndex,
  337. visibleStartIndex: visibleStartIndex,
  338. visibleStopIndex: visibleStopIndex
  339. });
  340. });
  341. _this._callOnScroll = void 0;
  342. _this._callOnScroll = memoizeOne(function (scrollDirection, scrollOffset, scrollUpdateWasRequested) {
  343. return _this.props.onScroll({
  344. scrollDirection: scrollDirection,
  345. scrollOffset: scrollOffset,
  346. scrollUpdateWasRequested: scrollUpdateWasRequested
  347. });
  348. });
  349. _this._getItemStyle = void 0;
  350. _this._getItemStyle = function (index) {
  351. var _this$props = _this.props,
  352. direction = _this$props.direction,
  353. itemSize = _this$props.itemSize,
  354. layout = _this$props.layout;
  355. var itemStyleCache = _this._getItemStyleCache(shouldResetStyleCacheOnItemSizeChange && itemSize, shouldResetStyleCacheOnItemSizeChange && layout, shouldResetStyleCacheOnItemSizeChange && direction);
  356. var style;
  357. if (itemStyleCache.hasOwnProperty(index)) {
  358. style = itemStyleCache[index];
  359. } else {
  360. var _offset = getItemOffset(_this.props, index, _this._instanceProps);
  361. var size = getItemSize(_this.props, index, _this._instanceProps); // TODO Deprecate direction "horizontal"
  362.  
  363. var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
  364. var isRtl = direction === 'rtl';
  365. var offsetHorizontal = isHorizontal ? _offset : 0;
  366. itemStyleCache[index] = style = {
  367. position: 'absolute',
  368. left: isRtl ? undefined : offsetHorizontal,
  369. right: isRtl ? offsetHorizontal : undefined,
  370. top: !isHorizontal ? _offset : 0,
  371. height: !isHorizontal ? size : '100%',
  372. width: isHorizontal ? size : '100%'
  373. };
  374. }
  375. return style;
  376. };
  377. _this._getItemStyleCache = void 0;
  378. _this._getItemStyleCache = memoizeOne(function (_, __, ___) {
  379. return {};
  380. });
  381. _this._onScrollHorizontal = function (event) {
  382. var _event$currentTarget = event.currentTarget,
  383. clientWidth = _event$currentTarget.clientWidth,
  384. scrollLeft = _event$currentTarget.scrollLeft,
  385. scrollWidth = _event$currentTarget.scrollWidth;
  386. _this.setState(function (prevState) {
  387. if (prevState.scrollOffset === scrollLeft) {
  388. // Scroll position may have been updated by cDM/cDU,
  389. // In which case we don't need to trigger another render,
  390. // And we don't want to update state.isScrolling.
  391. return null;
  392. }
  393. var direction = _this.props.direction;
  394. var scrollOffset = scrollLeft;
  395. if (direction === 'rtl') {
  396. // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
  397. // This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
  398. // It's also easier for this component if we convert offsets to the same format as they would be in for ltr.
  399. // So the simplest solution is to determine which browser behavior we're dealing with, and convert based on it.
  400. switch (getRTLOffsetType()) {
  401. case 'negative':
  402. scrollOffset = -scrollLeft;
  403. break;
  404. case 'positive-descending':
  405. scrollOffset = scrollWidth - clientWidth - scrollLeft;
  406. break;
  407. }
  408. } // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.
  409.  
  410. scrollOffset = Math.max(0, Math.min(scrollOffset, scrollWidth - clientWidth));
  411. return {
  412. isScrolling: true,
  413. scrollDirection: prevState.scrollOffset < scrollLeft ? 'forward' : 'backward',
  414. scrollOffset: scrollOffset,
  415. scrollUpdateWasRequested: false
  416. };
  417. }, _this._resetIsScrollingDebounced);
  418. };
  419. _this._onScrollVertical = function (event) {
  420. var _event$currentTarget2 = event.currentTarget,
  421. clientHeight = _event$currentTarget2.clientHeight,
  422. scrollHeight = _event$currentTarget2.scrollHeight,
  423. scrollTop = _event$currentTarget2.scrollTop;
  424. _this.setState(function (prevState) {
  425. if (prevState.scrollOffset === scrollTop) {
  426. // Scroll position may have been updated by cDM/cDU,
  427. // In which case we don't need to trigger another render,
  428. // And we don't want to update state.isScrolling.
  429. return null;
  430. } // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.
  431.  
  432. var scrollOffset = Math.max(0, Math.min(scrollTop, scrollHeight - clientHeight));
  433. return {
  434. isScrolling: true,
  435. scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',
  436. scrollOffset: scrollOffset,
  437. scrollUpdateWasRequested: false
  438. };
  439. }, _this._resetIsScrollingDebounced);
  440. };
  441. _this._outerRefSetter = function (ref) {
  442. var outerRef = _this.props.outerRef;
  443. _this._outerRef = ref;
  444. if (typeof outerRef === 'function') {
  445. outerRef(ref);
  446. } else if (outerRef != null && typeof outerRef === 'object' && outerRef.hasOwnProperty('current')) {
  447. outerRef.current = ref;
  448. }
  449. };
  450. _this._resetIsScrollingDebounced = function () {
  451. if (_this._resetIsScrollingTimeoutId !== null) {
  452. cancelTimeout(_this._resetIsScrollingTimeoutId);
  453. }
  454. _this._resetIsScrollingTimeoutId = requestTimeout(_this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL$1);
  455. };
  456. _this._resetIsScrolling = function () {
  457. _this._resetIsScrollingTimeoutId = null;
  458. _this.setState({
  459. isScrolling: false
  460. }, function () {
  461. // Clear style cache after state update has been committed.
  462. // This way we don't break pure sCU for items that don't use isScrolling param.
  463. _this._getItemStyleCache(-1, null);
  464. });
  465. };
  466. return _this;
  467. }
  468. List.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
  469. validateSharedProps$1(nextProps, prevState);
  470. validateProps(nextProps);
  471. return null;
  472. };
  473. var _proto = List.prototype;
  474. _proto.scrollTo = function scrollTo(scrollOffset) {
  475. scrollOffset = Math.max(0, scrollOffset);
  476. this.setState(function (prevState) {
  477. if (prevState.scrollOffset === scrollOffset) {
  478. return null;
  479. }
  480. return {
  481. scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',
  482. scrollOffset: scrollOffset,
  483. scrollUpdateWasRequested: true
  484. };
  485. }, this._resetIsScrollingDebounced);
  486. };
  487. _proto.scrollToItem = function scrollToItem(index, align) {
  488. if (align === void 0) {
  489. align = 'auto';
  490. }
  491. var _this$props2 = this.props,
  492. itemCount = _this$props2.itemCount,
  493. layout = _this$props2.layout;
  494. var scrollOffset = this.state.scrollOffset;
  495. index = Math.max(0, Math.min(index, itemCount - 1)); // The scrollbar size should be considered when scrolling an item into view, to ensure it's fully visible.
  496. // But we only need to account for its size when it's actually visible.
  497. // This is an edge case for lists; normally they only scroll in the dominant direction.
  498.  
  499. var scrollbarSize = 0;
  500. if (this._outerRef) {
  501. var outerRef = this._outerRef;
  502. if (layout === 'vertical') {
  503. scrollbarSize = outerRef.scrollWidth > outerRef.clientWidth ? getScrollbarSize() : 0;
  504. } else {
  505. scrollbarSize = outerRef.scrollHeight > outerRef.clientHeight ? getScrollbarSize() : 0;
  506. }
  507. }
  508. this.scrollTo(getOffsetForIndexAndAlignment(this.props, index, align, scrollOffset, this._instanceProps, scrollbarSize));
  509. };
  510. _proto.componentDidMount = function componentDidMount() {
  511. var _this$props3 = this.props,
  512. direction = _this$props3.direction,
  513. initialScrollOffset = _this$props3.initialScrollOffset,
  514. layout = _this$props3.layout;
  515. if (typeof initialScrollOffset === 'number' && this._outerRef != null) {
  516. var outerRef = this._outerRef; // TODO Deprecate direction "horizontal"
  517.  
  518. if (direction === 'horizontal' || layout === 'horizontal') {
  519. outerRef.scrollLeft = initialScrollOffset;
  520. } else {
  521. outerRef.scrollTop = initialScrollOffset;
  522. }
  523. }
  524. this._callPropsCallbacks();
  525. };
  526. _proto.componentDidUpdate = function componentDidUpdate() {
  527. var _this$props4 = this.props,
  528. direction = _this$props4.direction,
  529. layout = _this$props4.layout;
  530. var _this$state = this.state,
  531. scrollOffset = _this$state.scrollOffset,
  532. scrollUpdateWasRequested = _this$state.scrollUpdateWasRequested;
  533. if (scrollUpdateWasRequested && this._outerRef != null) {
  534. var outerRef = this._outerRef; // TODO Deprecate direction "horizontal"
  535.  
  536. if (direction === 'horizontal' || layout === 'horizontal') {
  537. if (direction === 'rtl') {
  538. // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
  539. // This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
  540. // So we need to determine which browser behavior we're dealing with, and mimic it.
  541. switch (getRTLOffsetType()) {
  542. case 'negative':
  543. outerRef.scrollLeft = -scrollOffset;
  544. break;
  545. case 'positive-ascending':
  546. outerRef.scrollLeft = scrollOffset;
  547. break;
  548. default:
  549. var clientWidth = outerRef.clientWidth,
  550. scrollWidth = outerRef.scrollWidth;
  551. outerRef.scrollLeft = scrollWidth - clientWidth - scrollOffset;
  552. break;
  553. }
  554. } else {
  555. outerRef.scrollLeft = scrollOffset;
  556. }
  557. } else {
  558. outerRef.scrollTop = scrollOffset;
  559. }
  560. }
  561. this._callPropsCallbacks();
  562. };
  563. _proto.componentWillUnmount = function componentWillUnmount() {
  564. if (this._resetIsScrollingTimeoutId !== null) {
  565. cancelTimeout(this._resetIsScrollingTimeoutId);
  566. }
  567. };
  568. _proto.render = function render() {
  569. var _this$props5 = this.props,
  570. children = _this$props5.children,
  571. className = _this$props5.className,
  572. direction = _this$props5.direction,
  573. height = _this$props5.height,
  574. innerRef = _this$props5.innerRef,
  575. innerElementType = _this$props5.innerElementType,
  576. innerTagName = _this$props5.innerTagName,
  577. itemCount = _this$props5.itemCount,
  578. itemData = _this$props5.itemData,
  579. _this$props5$itemKey = _this$props5.itemKey,
  580. itemKey = _this$props5$itemKey === void 0 ? defaultItemKey$1 : _this$props5$itemKey,
  581. layout = _this$props5.layout,
  582. outerElementType = _this$props5.outerElementType,
  583. outerTagName = _this$props5.outerTagName,
  584. style = _this$props5.style,
  585. useIsScrolling = _this$props5.useIsScrolling,
  586. width = _this$props5.width;
  587. var isScrolling = this.state.isScrolling; // TODO Deprecate direction "horizontal"
  588.  
  589. var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
  590. var onScroll = isHorizontal ? this._onScrollHorizontal : this._onScrollVertical;
  591. var _this$_getRangeToRend = this._getRangeToRender(),
  592. startIndex = _this$_getRangeToRend[0],
  593. stopIndex = _this$_getRangeToRend[1];
  594. var items = [];
  595. if (itemCount > 0) {
  596. for (var _index = startIndex; _index <= stopIndex; _index++) {
  597. items.push(React.createElement(children, {
  598. data: itemData,
  599. key: itemKey(_index, itemData),
  600. index: _index,
  601. isScrolling: useIsScrolling ? isScrolling : undefined,
  602. style: this._getItemStyle(_index)
  603. }));
  604. }
  605. } // Read this value AFTER items have been created,
  606. // So their actual sizes (if variable) are taken into consideration.
  607.  
  608. var estimatedTotalSize = getEstimatedTotalSize(this.props, this._instanceProps);
  609. return React.createElement(outerElementType || outerTagName || 'div', {
  610. className: className,
  611. onScroll: onScroll,
  612. ref: this._outerRefSetter,
  613. style: _extends({
  614. position: 'relative',
  615. height: height,
  616. width: width,
  617. overflow: 'auto',
  618. WebkitOverflowScrolling: 'touch',
  619. willChange: 'transform',
  620. direction: direction
  621. }, style)
  622. }, React.createElement(innerElementType || innerTagName || 'div', {
  623. children: items,
  624. ref: innerRef,
  625. style: {
  626. height: isHorizontal ? '100%' : estimatedTotalSize,
  627. pointerEvents: isScrolling ? 'none' : undefined,
  628. width: isHorizontal ? estimatedTotalSize : '100%'
  629. }
  630. }));
  631. };
  632. _proto._callPropsCallbacks = function _callPropsCallbacks() {
  633. if (typeof this.props.onItemsRendered === 'function') {
  634. var itemCount = this.props.itemCount;
  635. if (itemCount > 0) {
  636. var _this$_getRangeToRend2 = this._getRangeToRender(),
  637. _overscanStartIndex = _this$_getRangeToRend2[0],
  638. _overscanStopIndex = _this$_getRangeToRend2[1],
  639. _visibleStartIndex = _this$_getRangeToRend2[2],
  640. _visibleStopIndex = _this$_getRangeToRend2[3];
  641. this._callOnItemsRendered(_overscanStartIndex, _overscanStopIndex, _visibleStartIndex, _visibleStopIndex);
  642. }
  643. }
  644. if (typeof this.props.onScroll === 'function') {
  645. var _this$state2 = this.state,
  646. _scrollDirection = _this$state2.scrollDirection,
  647. _scrollOffset = _this$state2.scrollOffset,
  648. _scrollUpdateWasRequested = _this$state2.scrollUpdateWasRequested;
  649. this._callOnScroll(_scrollDirection, _scrollOffset, _scrollUpdateWasRequested);
  650. }
  651. } // Lazily create and cache item styles while scrolling,
  652. // So that pure component sCU will prevent re-renders.
  653. // We maintain this cache, and pass a style prop rather than index,
  654. // So that List can clear cached styles and force item re-render if necessary.
  655. ;
  656.  
  657. _proto._getRangeToRender = function _getRangeToRender() {
  658. var _this$props6 = this.props,
  659. itemCount = _this$props6.itemCount,
  660. overscanCount = _this$props6.overscanCount;
  661. var _this$state3 = this.state,
  662. isScrolling = _this$state3.isScrolling,
  663. scrollDirection = _this$state3.scrollDirection,
  664. scrollOffset = _this$state3.scrollOffset;
  665. if (itemCount === 0) {
  666. return [0, 0, 0, 0];
  667. }
  668. var startIndex = getStartIndexForOffset(this.props, scrollOffset, this._instanceProps);
  669. var stopIndex = getStopIndexForStartIndex(this.props, startIndex, scrollOffset, this._instanceProps); // Overscan by one item in each direction so that tab/focus works.
  670. // If there isn't at least one extra item, tab loops back around.
  671.  
  672. var overscanBackward = !isScrolling || scrollDirection === 'backward' ? Math.max(1, overscanCount) : 1;
  673. var overscanForward = !isScrolling || scrollDirection === 'forward' ? Math.max(1, overscanCount) : 1;
  674. return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(itemCount - 1, stopIndex + overscanForward)), startIndex, stopIndex];
  675. };
  676. return List;
  677. }(React.PureComponent), _class.defaultProps = {
  678. direction: 'ltr',
  679. itemData: undefined,
  680. layout: 'vertical',
  681. overscanCount: 2,
  682. useIsScrolling: false
  683. }, _class;
  684. } // NOTE: I considered further wrapping individual items with a pure ListItem component.
  685. // This would avoid ever calling the render function for the same index more than once,
  686. // But it would also add the overhead of a lot of components/fibers.
  687. // I assume people already do this (render function returning a class component),
  688. // So my doing it would just unnecessarily double the wrappers.
  689.  
  690. var validateSharedProps$1 = function validateSharedProps(_ref2, _ref3) {
  691. _ref2.children;
  692. _ref2.direction;
  693. _ref2.height;
  694. _ref2.layout;
  695. _ref2.innerTagName;
  696. _ref2.outerTagName;
  697. _ref2.width;
  698. _ref3.instance;
  699. };
  700. var FixedSizeList = /*#__PURE__*/createListComponent({
  701. getItemOffset: function getItemOffset(_ref, index) {
  702. var itemSize = _ref.itemSize;
  703. return index * itemSize;
  704. },
  705. getItemSize: function getItemSize(_ref2, index) {
  706. var itemSize = _ref2.itemSize;
  707. return itemSize;
  708. },
  709. getEstimatedTotalSize: function getEstimatedTotalSize(_ref3) {
  710. var itemCount = _ref3.itemCount,
  711. itemSize = _ref3.itemSize;
  712. return itemSize * itemCount;
  713. },
  714. getOffsetForIndexAndAlignment: function getOffsetForIndexAndAlignment(_ref4, index, align, scrollOffset, instanceProps, scrollbarSize) {
  715. var direction = _ref4.direction,
  716. height = _ref4.height,
  717. itemCount = _ref4.itemCount,
  718. itemSize = _ref4.itemSize,
  719. layout = _ref4.layout,
  720. width = _ref4.width;
  721. // TODO Deprecate direction "horizontal"
  722. var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
  723. var size = isHorizontal ? width : height;
  724. var lastItemOffset = Math.max(0, itemCount * itemSize - size);
  725. var maxOffset = Math.min(lastItemOffset, index * itemSize);
  726. var minOffset = Math.max(0, index * itemSize - size + itemSize + scrollbarSize);
  727. if (align === 'smart') {
  728. if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) {
  729. align = 'auto';
  730. } else {
  731. align = 'center';
  732. }
  733. }
  734. switch (align) {
  735. case 'start':
  736. return maxOffset;
  737. case 'end':
  738. return minOffset;
  739. case 'center':
  740. {
  741. // "Centered" offset is usually the average of the min and max.
  742. // But near the edges of the list, this doesn't hold true.
  743. var middleOffset = Math.round(minOffset + (maxOffset - minOffset) / 2);
  744. if (middleOffset < Math.ceil(size / 2)) {
  745. return 0; // near the beginning
  746. } else if (middleOffset > lastItemOffset + Math.floor(size / 2)) {
  747. return lastItemOffset; // near the end
  748. } else {
  749. return middleOffset;
  750. }
  751. }
  752. case 'auto':
  753. default:
  754. if (scrollOffset >= minOffset && scrollOffset <= maxOffset) {
  755. return scrollOffset;
  756. } else if (scrollOffset < minOffset) {
  757. return minOffset;
  758. } else {
  759. return maxOffset;
  760. }
  761. }
  762. },
  763. getStartIndexForOffset: function getStartIndexForOffset(_ref5, offset) {
  764. var itemCount = _ref5.itemCount,
  765. itemSize = _ref5.itemSize;
  766. return Math.max(0, Math.min(itemCount - 1, Math.floor(offset / itemSize)));
  767. },
  768. getStopIndexForStartIndex: function getStopIndexForStartIndex(_ref6, startIndex, scrollOffset) {
  769. var direction = _ref6.direction,
  770. height = _ref6.height,
  771. itemCount = _ref6.itemCount,
  772. itemSize = _ref6.itemSize,
  773. layout = _ref6.layout,
  774. width = _ref6.width;
  775. // TODO Deprecate direction "horizontal"
  776. var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
  777. var offset = startIndex * itemSize;
  778. var size = isHorizontal ? width : height;
  779. var numVisibleItems = Math.ceil((size + scrollOffset - offset) / itemSize);
  780. return Math.max(0, Math.min(itemCount - 1, startIndex + numVisibleItems - 1 // -1 is because stop index is inclusive
  781. ));
  782. },
  783.  
  784. initInstanceProps: function initInstanceProps(props) {// Noop
  785. },
  786. shouldResetStyleCacheOnItemSizeChange: true,
  787. validateProps: function validateProps(_ref7) {
  788. _ref7.itemSize;
  789. }
  790. });
  791.  
  792. /* globals GM */
  793. function Explorer(root, hooks) {
  794. function runHooks(name, ...args) {
  795. if (!(name in hooks)) {
  796. return;
  797. }
  798. if (!Array.isArray(hooks[name])) {
  799. hooks[name] = [hooks[name]];
  800. }
  801. return Promise.all(hooks[name].map(f => f(...args)));
  802. }
  803. class AlbumListItem extends React__namespace.Component {
  804. constructor(props) {
  805. super(props);
  806. _defineProperty(this, "handleAlbumClick", ev => {
  807. const targetStyle = ev.target.style;
  808. targetStyle.cursor = document.body.style.cursor = 'wait';
  809. const url = this.state.TralbumData.url;
  810. window.setTimeout(function () {
  811. runHooks('playAlbumFromUrl', url).then(function () {
  812. targetStyle.cursor = document.body.style.cursor = '';
  813. });
  814. }, 1);
  815. });
  816. _defineProperty(this, "handleContextMenu", ev => {
  817. ev.preventDefault();
  818. ev.target.classList.add('selected');
  819. const TralbumData = this.state.TralbumData;
  820. const url = TralbumData.url;
  821. if (!confirm(`Delete album "${TralbumData.current.title}" by ${TralbumData.artist}?`)) {
  822. ev.target.classList.remove('selected');
  823. return;
  824. }
  825. window.setTimeout(() => {
  826. runHooks('deletePermanentTralbum', url).then(function () {
  827. ev.target.classList.remove('selected');
  828. ev.target.style.visibility = 'hidden';
  829. });
  830. }, 1);
  831. });
  832. this.state = {
  833. TralbumData: props.data.library[Object.keys(props.data.library)[props.index]]
  834. };
  835. }
  836. render() {
  837. return /*#__PURE__*/React__namespace.createElement("div", {
  838. className: `albumListItem ${this.props.index % 2 ? 'albumListItemOdd' : ''}`,
  839. onClick: this.handleAlbumClick,
  840. onContextMenu: this.handleContextMenu,
  841. title: "Click to play",
  842. style: this.props.style
  843. }, this.state.TralbumData.artist, " - ", this.state.TralbumData.current.title);
  844. }
  845. }
  846. class AlbumList extends React__namespace.Component {
  847. constructor(props) {
  848. super(props);
  849. this.state = {
  850. library: {},
  851. isLoading: false,
  852. error: null
  853. };
  854. if (!this.props.getKey) {
  855. throw Error('<AlbumList> needs a getKey property');
  856. }
  857. }
  858. componentDidMount() {
  859. this.setState({
  860. isLoading: true
  861. });
  862. GM.getValue(this.props.getKey, '{}').then(s => JSON.parse(s)).then(data => this.setState({
  863. library: data,
  864. isLoading: false
  865. })).catch(error => this.setState({
  866. error,
  867. isLoading: false
  868. }));
  869. }
  870. render() {
  871. const {
  872. library,
  873. isLoading,
  874. error
  875. } = this.state;
  876. if (error) {
  877. return /*#__PURE__*/React__namespace.createElement("p", null, error.message);
  878. }
  879. if (isLoading) {
  880. return /*#__PURE__*/React__namespace.createElement("p", null, "Loading ...");
  881. }
  882. return /*#__PURE__*/React__namespace.createElement(FixedSizeList, {
  883. className: "List",
  884. height: 600,
  885. itemCount: Object.keys(library).length,
  886. itemSize: 35
  887. //width={600}
  888. ,
  889. itemData: {
  890. library: library
  891. }
  892. }, AlbumListItem);
  893. }
  894. }
  895. this.render = function () {
  896. ReactDOM__namespace.createRoot(root).render( /*#__PURE__*/React__namespace.createElement(AlbumList, {
  897. getKey: "tralbumlibrary"
  898. }));
  899. };
  900. }
  901.  
  902. var discographyplayerCSS = ".cll{clear:left}.clb{clear:both}#discographyplayer{z-index:1010;position:fixed;bottom:0;height:83px;width:100%;padding-top:3px;background:#fff;color:#505958;border-top:1px solid rgba(0,0,0,.15);font:13px/1.231 \"Helvetica Neue\",Helvetica,Arial,sans-serif;transition:bottom .5s}#discographyplayer a:link,#discographyplayer a:visited{color:#0687f5;text-decoration:none;cursor:pointer}#discographyplayer a:hover{color:#0687f5;text-decoration:underline;cursor:pointer}#discographyplayer .nowPlaying .cover,#discographyplayer .nowPlaying .info{display:inline-block;vertical-align:top}#discographyplayer .nowPlaying img{width:60px;height:60px;margin-top:4px;margin-left:4px;margin-bottom:4px}#discographyplayer .nowPlaying .info{line-height:18px;margin-left:8px;margin-top:8px;max-width:calc(100% - 76px);border:0 solid #000;padding:0;width:auto;max-height:auto;overflow-y:hidden}#discographyplayer .nowPlaying .info .album,#discographyplayer .nowPlaying .info .title{font-size:13px;font-weight:400;color:#0687f5;margin:0;padding:0}#discographyplayer .currentlyPlaying{display:inline-block;vertical-align:top;overflow:hidden;transition:margin-left 3s ease-in-out;width:99%}#discographyplayer .nextInRow{display:inline-block;vertical-align:top;width:0%;overflow:hidden;transition:width 6s ease-in-out}#discographyplayer .durationDisplay{margin-top:24px;float:left}#discographyplayer .downloadlink:link{display:block;float:right;margin-top:22px;font-size:15px;padding:0 3px;color:#0687f5;border:1px solid #0687f5;transition:color .3s ease-in-out,border-color .3s ease-in-out}#discographyplayer .downloadlink:hover{text-decoration:none;background-color:#0687f5;color:#fff;border:1px solid #fff}#discographyplayer .downloadlink.downloading{color:#f0f;border-color:#f0f;animation:downloadrotation 3s infinite linear;cursor:wait}@keyframes downloadrotation{from{transform:rotate(0)}to{transform:rotate(359deg)}}#discographyplayer .controls{margin-top:10px;width:auto;float:left}#discographyplayer .controls>*{display:inline-block;cursor:pointer;border:1px solid #d9d9d9;padding:11px;margin-right:4px;height:18px;width:17px;transition:background-color .1s}#discographyplayer .controls>:hover{background-color:#0687f52b}#discographyplayer .playpause .play{width:0;height:0;border-top:9px inset transparent;border-bottom:9px inset transparent;border-left:15px solid #222;cursor:pointer;margin-left:2px}#discographyplayer .playpause .pause{border:0;border-left:5px solid #2d2d2d;border-right:5px solid #2d2d2d;height:18px;width:4px;margin-right:2px;margin-left:1px}#discographyplayer .playpause .busy{background-image:url(https://bandcamp.com/img/playerbusy-noborder.gif);background-position:50% 50%;background-repeat:no-repeat;border:none;height:30px;margin:0 0 0 -3px;width:25px;overflow:hidden;background-size:contain}#discographyplayer .shuffleswitch .shufflebutton{background-size:cover;background-position-y:0px;filter:drop-shadow(#FFFF 0px 0px 0px);transition:filter .5s;border:0;height:13px;width:20px;margin-top:4px}#discographyplayer .shuffleswitch .shufflebutton.active{filter:drop-shadow(#0060F2 1px 1px 2px)}#discographyplayer .arrowbutton{border:0;height:13px;width:20px;margin-top:4px;background:url(https://bandcamp.com/img/nextprev.png) 0 0/40px 12px no-repeat transparent;background-position-x:0px;cursor:pointer}#discographyplayer .arrowbutton.next-icon{background-position:100% 0}#discographyplayer .arrowbutton.prevalbum-icon{border-right:3px solid #2d2d2d}#discographyplayer .arrowbutton.nextalbum-icon{background-position:100% 0;border-left:3px solid #2d2d2d}#timeline{width:100%;background:rgba(50,50,50,.4);margin-top:5px;border-left:1px solid #000;border-right:1px solid #000}#playhead{width:10px;height:10px;border-radius:50%;background:#323232;cursor:pointer}.bufferbaranimation{transition:width 1s}#bufferbar{position:absolute;width:0;height:10px;background:rgba(0,0,0,.1)}#discographyplayer .playlist{position:relative;width:100%;display:inline-block;max-height:80px;overflow:auto;list-style:none;margin:0;padding:0 5px 0 5px;scrollbar-color:rgba(50,50,50,0.4) white;background:#fff}#discographyplayer_contextmenu{position:absolute;box-shadow:#000000b0 2px 2px 2px;background-color:#fff;border:#619aa9 2px solid;z-index:1011}#discographyplayer_contextmenu .contextmenu_submenu{cursor:pointer;padding:2px;border:1px solid #619aa9}#discographyplayer_contextmenu .contextmenu_submenu:hover{background-color:#619aa9;color:#fff;border:1px solid #fff}#discographyplayer .playlist .isselected{border:1px solid red}#discographyplayer .playlist .playlistentry{cursor:pointer;margin:1px 0}#discographyplayer .playlist .playlistentry .duration{float:right}#discographyplayer .playlist .playing{background:#619aa950}#discographyplayer .playlist .playlistheading{background:rgba(50,50,50,.4);margin:3px 0}#discographyplayer .playlist .playlistheading a:hover,#discographyplayer .playlist .playlistheading a:link,#discographyplayer .playlist .playlistheading a:visited{color:#eee;cursor:pointer}#discographyplayer .playlist .playlistheading a.notloaded{color:#ccc}#discographyplayer .playlist .playlistheading.notloaded{cursor:copy}#discographyplayer .vol{float:left;position:relative;width:100px;margin-left:1em;margin-top:1em}#discographyplayer .vol-icon-wrapper{font-size:20px;cursor:pointer;width:27px}#discographyplayer .vol-slider{width:60px;height:10px;position:relative;cursor:pointer}#discographyplayer .vol>*{display:inline-block;vertical-align:middle}#discographyplayer .vol-bg{background:rgba(50,50,50,.4);width:100%;margin-top:4px;height:3px;position:absolute}#discographyplayer .vol-amt{margin-top:4px;height:3px;position:absolute;background:#323232}#discographyplayer .vol-control-outer{height:100%;position:relative;margin-left:-3px;margin-right:5px}#discographyplayer .collect{float:left;margin-left:1em}#discographyplayer .{cursor:default;margin-top:.5em}#discographyplayer .collect-wishlist .wishlist-add{cursor:pointer}#discographyplayer .collect-listened{cursor:pointer;margin-top:.5em;margin-left:2px}#discographyplayer .collect .icon{height:13px;width:14px;display:inline-block;position:relative;top:2px}#discographyplayer .collect .add-item-icon{background-position:0 -73px}#discographyplayer .collect .collected-item-icon{background-position:-28px -73px}#discographyplayer .collect .own-item-icon{background-position:-42px -73px}#discographyplayer .collect .wishlist-add,#discographyplayer .collect .wishlist-collected,#discographyplayer .collect .wishlist-own,#discographyplayer .collect .wishlist-saving{display:none}#discographyplayer .collect .wishlist-add:hover .add-item-icon{background-position:-56px -73px}#discographyplayer .collect .wishlist-add .add-item-label:hover{text-decoration:underline}#discographyplayer .collect .listened,#discographyplayer .collect .listened-saving,#discographyplayer .collect .mark-listened{display:none}#discographyplayer .collect .listened .listened-symbol{color:#00dc32;text-shadow:1px 0 #ddd,-1px 0 #ddd,0 -1px #ddd,0 1px #ddd}#discographyplayer .collect .mark-listened .mark-listened-symbol{color:#fff;text-shadow:1px 0 #959595,-1px 0 #959595,0 -1px #959595,0 1px #959595}#discographyplayer .collect .mark-listened:hover .mark-listened-symbol{text-shadow:1px 0 #0af,-1px 0 #0af,0 -1px #0af,0 1px #0af}#discographyplayer .collect .mark-listened:hover .mark-listened-label{text-decoration:underline}#discographyplayer .closebutton,#discographyplayer .minimizebutton{position:absolute;top:1px;right:1px;border:1px solid #505958;color:#505958;font-size:10px;box-shadow:0 0 2px #505958;cursor:pointer;opacity:0;transition:opacity .3s;min-width:8px;min-height:13px;text-align:center}#discographyplayer .minimizebutton{right:13px}#discographyplayer .minimizebutton .minimized{display:none}#discographyplayer .minimizebutton.minimized .maximized{display:none}#discographyplayer .minimizebutton.minimized .minimized{display:inline}#discographyplayer:hover .closebutton,#discographyplayer:hover .minimizebutton{opacity:1}#discographyplayer .col{float:left;min-height:1px;position:relative}#discographyplayer .col25{width:25%}#discographyplayer .col35{width:35%}#discographyplayer .col30{width:30%}#discographyplayer .col15{width:14%}#discographyplayer .col20{width:20%}#discographyplayer .colcontrols{user-select:none}#discographyplayer .colvolumecontrols{margin-left:10px}.albumIsCurrentlyPlaying{border:2px solid #0f0}.albumIsCurrentlyPlaying+.art-play{display:none}.dig-deeper-item .albumIsCurrentlyPlaying,.music-grid-item .albumIsCurrentlyPlaying{border:none}.albumIsCurrentlyPlayingIndicator{display:none}.dig-deeper-item .albumIsCurrentlyPlayingIndicator,.music-grid-item .albumIsCurrentlyPlayingIndicator{position:absolute;display:block;width:74px;height:54px;left:50%;top:50%;margin-left:-36px;margin-top:-27px;opacity:.5;transition:opacity .2s}.albumIsCurrentlyPlayingIndicator .currentlyPlayingBg{position:absolute;width:100%;height:100%;left:0;top:0;background:#000;border-radius:4px}.albumIsCurrentlyPlayingIndicator .currentlyPlayingIcon{position:absolute;width:10px;height:20px;left:28px;top:17px;border-width:0 5px;border-color:#fff;border-style:solid}@media (max-width:1600px){#discographyplayer .controls>*{padding:4px 11px 5px 11px;height:18px}#discographyplayer .durationDisplay{margin-top:0}#discographyplayer .downloadlink:link{margin-top:0}}@media (max-width:1170px){#discographyplayer .colcontrols{width:39%}#discographyplayer .colvolumecontrols{display:none}}";
  903.  
  904. var discographyplayerSidebarCSS = "@media (min-width:1600px){#menubar-wrapper:hover{z-index:1100}#discographyplayer{display:block;bottom:0;height:100vh;max-height:100vh;width:calc((100vw - 915px - 35px)/ 2);right:0;border-left:1px solid #0007;padding-left:1px}#discographyplayer .playlist{height:calc(100vh - 80px - 80px - 50px - 13px);max-height:calc(100vh - 80px - 80px - 50px - 13px)}#discographyplayer .playlist .playlistentry{overflow-x:hidden}#discographyplayer .col25{width:98%}#discographyplayer .col.nowPlaying{height:70px}#discographyplayer .col.col25.colcontrols{height:85px}#discographyplayer .col35{width:97%}#discographyplayer .col15{width:96%}#discographyplayer .colvolumecontrols{height:50px}#bufferbar,#playhead{height:25px;border-radius:0}#discographyplayer .audioplayer a.downloadlink{position:fixed;bottom:5px;right:5px;z-index:10}#discographyplayer .minimizebutton{display:none}#discographyplayer .currentlyPlaying{transition:margin-top 1s ease-in-out;width:99%;height:99%}#discographyplayer .nextInRow{height:0%;width:99%;transition:height 1s ease-in-out}}";
  905.  
  906. var pastreleasesCSS = "#pastreleases{position:fixed;bottom:1%;left:10px;background:#d5dce4;color:#033162;font-size:10pt;border:1px solid #033162;z-index:200;opacity:0;transition:opacity .7s;overflow:auto}#pastreleases .tablediv{display:table;position:relative}#pastreleases .entry,#pastreleases .header{display:table-row}#pastreleases .entry>*,#pastreleases .header>*{display:table-cell;line-height:21pt}#pastreleases .upcoming{cursor:pointer;font-size:x-small}#pastreleases .controls{cursor:pointer;position:absolute;top:0;right:1px;line-height:11pt}#pastreleases .entry:link{position:relative;border-top:1px solid #033162;color:#033162;text-decoration:none}#pastreleases .entry:nth-child(odd){background:#c5ccd4}#pastreleases .entry:hover,#pastreleases .entry:visited{color:#033162;text-decoration:none}#pastreleases .entry.future{display:none;background:#9fc2ea}#pastreleases .entry.future:nth-child(odd){background:#8fc2e1}#pastreleases .entry .image{background-size:contain;width:21pt;height:21pt}#pastreleases .entry:hover .image{display:block;position:fixed;bottom:10px;top:50%;left:50%;margin-right:-50%;transform:translate(-50%,-50%);width:350px;height:350px;background:#000;border:5px solid #fff}#pastreleases .entry time{padding-right:2px}#pastreleases .entry .title{padding-left:2px;border-left:1px solid #47a2bd;font-size:1em}#pastreleases .remove{font-family:sans-serif;color:#97174e;font-size:small;padding-right:3px}";
  907.  
  908. var darkmodeCSS = "#centerWrapper #pgBd #trackInfoInner{display:flex;flex-direction:column}#centerWrapper #pgBd #trackInfoInner>.tralbumCommands{order:1}#centerWrapper #pgBd #rightColumn{display:flex;flex-direction:column}#centerWrapper #pgBd #rightColumn>#showography{order:1}.ui-widget-overlay{display:none}.ui-dialog.ui-widget.ui-widget-content.ui-corner-all.nu-dialog.no-title{position:fixed!important;top:0!important;right:0!important;bottom:auto!important;left:auto!important}.inline_player .nextbutton,.inline_player .prevbutton,svg{filter:invert(90%)}a{color:#da5!important}.trackYear,button{color:#ac6!important}div#collection-container.collection-container,div.home{background:#000!important}div.area_text,div.sort_controls,div.text,span{color:#ccc!important}div#dlg0_h.hd,div#pgBd.yui-skin-sam,div.blogunit-details-section,div.collection-item-details-container{background:var(--pgBdColor)!important}div.collection-item-artist,h1{color:#ccc!important}DIV.track_number.secondaryText,div.collection-item-title,div.message,h2{color:#fff!important}h3{color:#ffed80!important}DIV.tralbumData.tralbum-credits{color:#ccc!important}DIV#license.info,DIV.tralbumData.tralbum-about,DIV.tralbumData.tralbum-feed,li{color:#806300!important}button.sc-button.sc-button-small.sc-button-responsive.sc-button-addtoset{color:#000!important}div#fan-suggestions.dotted-section.mine,div.bcweekly-bd,div.collection-item-gallery-container,div.collection-stats.dotted-section.mine{background:#222!important}p{color:#aaa!important}div.sound__soundActions{background:0 0!important}button.sc-button.sc-button-small.sc-button-responsive.sc-button-addtoset{color:#111!important}div.ft.fakeFt{background:#555!important}div.bd.footerless{background:#999!important}.walkthrough ol{background-color:#373737}.walkthrough .button{background:#262626;border:#262626}.fan-banner.empty.owner{background-color:#373737}#menubar,#pgFt,.menubar-outer{background-color:#26423b!important;border-bottom:dotted #000 1px!important}#menubar-wrapper{background-color:#000;border-bottom:dotted #000 1px!important}#menubar input#search-field{margin:0;height:21px;line-height:21px;width:222px;font-family:\"Helvetica Neue\",Arial,sans-serif;color:#fff;font-size:13px;padding:0 21px 0 3px;-webkit-user-select:text;text-align:center;background-color:#282828;border:1px solid #282828;outline:0;border-radius:3px}#menubar input#search-field.focused{background-color:#282828;border:1px solid #282828}#menubar.menubar-2018 .hoverable:hover{background:#11607582!important}.fan-bio .edit-profile a{border:1px solid #373737;border-radius:5px;outline:0;background:#373737;color:#aaa;font-weight:500;padding:5px 9px;font-size:11px;line-height:15px;text-transform:uppercase;display:inline-block}.grids{color:#fff;margin:0 0 100px}.recommendations-container{background-color:#373737;border-top:dotted #373737 1px}.fan-container .top.editing{border-bottom:1px solid #2a2a2a;background-color:#191919}.ui-dialog.nu-dialog .ui-dialog-titlebar{padding:15px 20px 12px;background-color:#26423b!important;border-bottom:1px solid #26423b!important}.ui-dialog-titlebar *{color:#fff!important}.ui-dialog-content{color:#ddd!important}.ui-widget-content{border:1px solid #373;background:#373737!important;color:#ddd!important}.external-follow-confirm .ui-dialog-buttonset button,.mailing-list-opt-in .ui-dialog-buttonset button{background:#26423b!important}.external-follow-confirm .ui-dialog-buttonset button:last-child,.mailing-list-opt-in.band .ui-dialog-buttonset button:last-child{background:#0002!important;border:2px solid #26423b!important}#follow-unfollow{background:0 0!important}#follow-unfollow.following{background:#26423b!important;border-color:#26423b!important}#follow-unfollow>div{color:#ac6!important}#follow-unfollow.following>div{background:#26423b!important}.app-promo-desktop,.bcdaily,.discover,.email-intake,.notable{background-color:#262626}.bcdaily .bcdaily-story{min-height:280px;background:#373737}.notable-item{background-color:#373737}.item-page{background:#373737;border:1px solid #373737}.follow-fan-btn{background-color:#373737;border:1px solid #373737}.spotlight-bio,.spotlight-button,.spotlight-link,.spotlight-location,.spotlight-name{color:#fff}.aotd-large{background:#373737}.factoid-title{color:#46c5d5}#autocomplete-results.autocompleted{background:#262626;border:1px solid #262626;color:#fff}.searchwidget.keyboard-focus input[type=text]:focus{background:#262626;box-shadow:0 0}.discover-detail-inner{background-color:#373737}body.wordpress{background:#262626}.wordpress .sidebar .textwidget{color:#fff}.wordpress h1 a{display:block;height:60px;background-size:242px 28px;background-position:24.6% 50%}p{color:#fff!important}.wordpress #content{color:#fff}#dash-container .follow-band,#dash-container .follow-discover,#dash-container .follow-fan{border:1px solid #373737;background:linear-gradient(to bottom,#373737 0,#373737 100%)}html{background:#1e1e1e!important}#stories-vm .story-innards{background-color:#373737}.pane{color:#c7c7c7}#settings-menubar{border-right:1px solid #383838}#settings-menubar li{border-left:1px solid #383838;border-bottom:1px solid #383838;border-top:1px solid #383838}.share_dialog.ui-dialog .ui-dialog-content{background-color:#262626}.share_dialog .section_head{color:#fff}.buy-dlg{color:#fff}.pg-ft{background-color:#000}#lang-picker-vm{border-radius:10px}#menubar>ul>li .logo{background:url('https://www.dropbox.com/s/8s7km8r329l7qy7/bandcamp-logo-gray.png?dl=1') 0 0 no-repeat;background-size:contain;height:20px;margin-top:15px;width:85px}.hd-logo{background:transparent url('https://www.dropbox.com/s/8s7km8r329l7qy7/bandcamp-logo-gray.png?dl=1') no-repeat;background-size:100%;margin-top:24px;height:25px;width:156px}.wordpress h1 a{display:block;text-indent:-999em;background:url('https://www.dropbox.com/s/mx80o2eenp43l0o/bandcamp-daily-retina-dark-theme.png?dl=1') no-repeat;height:60px;background-size:242px 28px;background-position:24.6% 50%}#pgBd{color:#fff}.download-bottom-area{border-top:none;background:0 0}.download .formats-container{border:1px solid #373737;background-color:#373737}.download .formats{list-style:none;color:#888;padding:0;background-color:#373737;width:170px;z-index:2;cursor:default}.download .formats li:hover{background-color:#262626}html{scrollbar-color:#222 #26423b}::-webkit-scrollbar{height:13px}::-webkit-scrollbar-thumb{background:#26423b;border:1px solid #4a4a4a}::-webkit-scrollbar-thumb:hover{background:#316d4b}::-webkit-scrollbar-thumb:active{background:#316d4b}::-webkit-scrollbar-track{background:#4a4a4a}::-webkit-scrollbar-track:hover{background:#4a4a4a}::-webkit-scrollbar-track:active{background:#4a4a4a}::-webkit-scrollbar-corner{background:#4a4a4a}body{background-color:#000!important;color:#fff!important}#propOpenWrapper{background-color:var(--propOpenWrapperBackgroundColor)!important;transition:background-color .5s}.bcdaily-thumb-img,img{filter:brightness(70%)}.bcdaily-thumb-img:hover,img:hover{filter:none}img.imageviewer_image{filter:none}.bclogo svg{filter:brightness(60%)}.inline_player .playbutton.busy::after{opacity:.3;background-image:url('https://bandcamp.com/img/loading-dark.gif')}.inline_player .nextsongcontrolbutton,.inline_player .playbutton,.inline_player .volumeButton,.track_list .play_status{background-color:#686868;border-color:#595959}.nextsongcontrolbutton .nextsongcontrolicon{filter:drop-shadow(#090909b3 1px 1px 2px)}.nextsongcontrolbutton.active .nextsongcontrolicon{filter:drop-shadow(#a3f204 1px 1px 2px)!important}.hidden .nextsongcontrolbutton{display:none}.inline_player .progbar .thumb{background-color:#000;border-color:#ccc}.inline_player .nextbutton,.inline_player .prevbutton{opacity:.7}.track_list tr.lyricsRow td[colspan] div{color:#f8f8f8}input[type=password],input[type=text],textarea{background-color:#121f12!important;color:#40b333!important}.carousel-player-inner{background-color:#26423b}.carousel-player-inner .progress-bar{background-color:#26423b}#carousel-player .queue.show{background-color:#26423b}#carousel-player .queue.show li.active{background-color:#528679}#autocomplete-results .see-all{background-color:#f3f3f345!important}.deluxemenu{color:#c9ebfb!important;background:#00042f!important}.deluxemenu button{background:#1c1494}.deluxeexportmenu table tr>td{color:#00a1c6!important}.deluxeexportmenu table tr>td:nth-child(3){color:#006bc6!important}.deluxemenu fieldset{border:1px solid #fffa!important;box-shadow:1px 1px 3px #fff5!important}.deluxemenu fieldset legend{color:#fffa!important}#discographyplayer{background-color:#26423b!important;color:#869593!important}#discographyplayer .playlist{background:#26423b!important}#discographyplayer .playlist .playing{background:#619aa9db!important}#timeline{background:rgba(34,57,42,.69)!important}#bufferbar{background:rgba(77,79,76,.59)!important}#playhead{background:#2a6c21!important}#discographyplayer .playlist{scrollbar-color:#222 #26423b!important}#discographyplayer_contextmenu{box-shadow:#ffffff50 2px 2px 2px;background-color:#162d27;border:#619aa9 2px solid;color:#c2aa4a}#discographyplayer_contextmenu .contextmenu_submenu{cursor:pointer;padding:2px;background-color:#162d27;color:#c2aa4a;border:1px solid transparent}#discographyplayer_contextmenu .contextmenu_submenu:hover{background-color:#619aa9;color:#fff;border:1px solid #fff}#band-navbar{background-color:#333!important}.hd.corp-home{background-color:#26423b}#hub .bd-section.top-section{opacity:.8}#s-daily{background:#262626!important}.franchise-description{color:#d7d072}.footer-gradient{background-image:linear-gradient(to bottom,#262626,#5e5e5e)}#s-daily dailyfooter{background-color:#5e5e5e}#s-daily dailyfooter h2{-webkit-text-stroke:2px #257110!important}#s-daily a.pagination-link{-webkit-text-stroke:2px #257110!important}#s-daily a.pagination-link .back-text{-webkit-text-stroke:2px #1c6c3f!important}article-title{color:#e3e3e3}.mpmerchformats{color:#909090}article-footer{color:#909090}article>article-end{filter:invert(75%)}article .icon{filter:invert(50%)}.salesfeed .item-inner:hover{background-color:#0e738c!important}.hd.header-rework-2018 .hd-sub-head .blue-gradient{background:-webkit-linear-gradient(left,#da5,#daf)!important}.factoid .dots{filter:brightness(300%)}.bdp_check_onlinkhover_container_shown{background-color:#26423ba8!important}.bdp_check_onlinkhover_container:hover{background-color:#2d7d39a8!important;box-shadow:#2db91f7a 0 0 5px}#pastreleases{background-color:#154a86!important}#pastreleases .entry:nth-child(odd){background-color:#3e6c9f!important}#pastreleases .entry.future{background-color:#4783c8!important}#pastreleases .entry.future:nth-child(odd){background-color:#11447d!important}#queueloadingindicator{background-color:#154a86!important}.sidebar .shortcuts{background:#0000;border-color:#0000}";
  909.  
  910. var geniusCSS = "#myconfigwin39457845{z-index:2060!important;position:fixed!important}#myconfigwin39457845 h1{margin:5px}#myconfigwin39457845 .divAutoShow{display:none}#myconfigwin39457845 button{background-color:#cacaca!important;color:#000!important;border:2px outset!important;padding:1px!important;font-size:1.2em!important}#lyricsiframe{opacity:.1;transition:opacity 2s;margin:0;padding:0;position:relative}.lyricsnavbar{font-size:.7em;text-align:right;padding:0 10px 0 0!important}.lyricsnavbar a:link,.lyricsnavbar a:visited,.lyricsnavbar span{color:#606060;text-decoration:none;transition:color .4s}.lyricsnavbar a:hover,.lyricsnavbar span:hover{color:#9026e0;text-decoration:none}.loadingspinner{color:#000;font-size:12px;line-height:15px;width:15px!important;height:15px!important;padding:2px!important}.loadingspinnerholder{z-index:10;cursor:progress;position:relative;width:20px!important;height:20px!important}.searchresultlist{margin:0!important;padding:0!important;border:1px solid #000;border-radius:3px;width:450px!important}.searchresultlist ol{list-style:none;padding:0!important;margin:0}.searchresultlist ol li div{width:auto!important}";
  911.  
  912. var exportMenuHTML = "<h2>Export played albums</h2>\n <h1 class=\"drophint\">Drop to restore from backup</h1>\n Available fields per album:<br>\n <table>\n <tr>\n <td>%artist%</td>\n <td>Artist name</td>\n <td>Jay-X</td>\n </tr>\n <tr>\n <td>%title%</td>\n <td>Song title</td>\n <td>Classic song</td>\n </tr>\n <tr>\n <td>%cover%</td>\n <td>Cover image url</td>\n <td>https://f4.bcbits.com/img/a2588527047_2.jpg</td>\n </tr>\n <tr>\n <td>%url%</td>\n <td>Album url</td>\n <td>petrolgirls.bandcamp.com/album/cut-stitch</td>\n </tr>\n <tr>\n <td>%releaseDate% / %releaseUnix% / %releaseTimestamp%</td>\n <td>Release date</td>\n <td>2019-02-07T14:01:59.100Z / 1549548119 / 1549548119100</td>\n </tr>\n <tr>\n <td>%listenedDate% / %listenedUnix% / %listenedTimestamp%</td>\n <td>Played/Listened date</td>\n <td>2019-02-07T02:17:21.315Z / 1549505841 / 1549505841315</td>\n </tr>\n <tr>\n <td>%releaseY% / %releaseYYYY%</td>\n <td>Release: Year</td>\n <td>19 / 2019</td>\n </tr>\n <tr>\n <td>%releaseM% / %releaseMM% / %releaseMon% / %releaseMonth%</td>\n <td>Release: Month</td>\n <td>2 / 02 / Feb / February</td>\n </tr>\n <tr>\n <td>%releaseD% / %releaseDD%</td>\n <td>Release: Day of month</td>\n <td>7 / 07</td>\n </tr>\n <tr>\n <td>%releaseDay%</td>\n <td>Release: Day of week</td>\n <td>Friday</td>\n </tr>\n <tr>\n <td>%listenedY% / %listenedYYYY%</td>\n <td>Played: Year</td>\n <td>19 / 2019</td>\n </tr>\n <tr>\n <td>%listenedM% / %listenedMM% / %listenedMon% / %listenedMonth%</td>\n <td>Played: Month</td>\n <td>2 / 02 / Feb / February</td>\n </tr>\n <tr>\n <td>%listenedD% / %listenedDD%</td>\n <td>Played: Day of month</td>\n <td>7 / 07</td>\n </tr>\n <tr>\n <td>%listenedDay%</td>\n <td>Played: Day of week</td>\n <td>Friday</td>\n </tr>\n\n </table>\n";
  913.  
  914. var speakerIconMuteSrc = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAoAQMAAACCSesyAAAABlBMVEUAAAA1NTVzRZghAAAAAXRSTlMAQObYZgAAAK1JREFUGNMtzzEOwjAMBdAgJMKWlYlcpGqvxVC1zgl6A3qRSmXrNYo6dE3FQCRCzXeCl+cvefBXB1Iyx0fiMOukNyTcKpJcVCT5asngzHRkZqX0RKtHWtwL2M19gmIO7ivEIkawl43AtqmFrmqEaUwsfSlsmZAZbOKe6f90jTBOCX5mfC3sITHEQnD7RbWAz/iM3RvvaqZ1RjMm49EFBNCSicCSLgHaWaCxAczpB9BXgdGWyYXIAAAAAElFTkSuQmCC";
  915.  
  916. var speakerIconLowSrc = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAoCAMAAACPWYlDAAAAM1BMVEUAAABqampqampqampqampqampqampqampqampqampqampqampqampqampqampqampqampPcCe2AAAAEHRSTlMAN4Xs4SoS0bxHeJEgpm5gLbFq2AAAALlJREFUOMvF1MsKwzAMRNGxKz+bx/z/1xYl0EJIQLPqXUSLcBAmOLivFCiNRmbEy/QqgtXOo4RYxSiBjZTASgksnRIoRg1MRsB8feMFpIR695UeSp1sS4mD4Y9WhQ1vf74FgEMUAaD7CgUMkk0B1WcVAI5DqBuScgYVrD6XOCg+DHHQfcw4yOeCMNhPFgfHi025D5vZhAJw38i/HsBzWQXYVYDURIC6igCYKsAwXi5O6J9sUMrWEv7VB3zHKzcAIgoLAAAAAElFTkSuQmCC";
  917.  
  918. var speakerIconMiddleSrc = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAoCAMAAACPWYlDAAAANlBMVEUAAABqampqampqampqampqampqampqampqampqampqampqampqampqampqampqampqampqamrDZ907AAAAEXRSTlMANoQS7CRH3nPQtpDAnFSpYGW9KtUAAAEQSURBVDjLxZTbloMwCEUhhNy8lf//2elAx+XKNJU8db9EXW6JBxTegwwz7FUkgJ8gTyKBE1pFQfCBWaaEIjIlbNILjARDuEkvFJGYeHR/ll5gDQx5GGcvJD3MdDFCPJFOQCSyixvR4LFXoYlU3l8nfC/obipZzg0cFRZ5soA1nulesKYw6lnxCNC0RLU9OQQNNf8NLzkE+l3J9uQSQNNSTdhdoZiAHiGZ4K9w6Op/BxRNabHFIay6I5u/w9EHy/81TDvdCg+xULMOoWP4gs1eswIOAUuOgYKcBTyNA4s08kVI4WT4TScYEP4JmukGQx6xEwBrXOADWC+CCzomBKPMCpDipAC86u8R/FDIFeFb/AD0fTaBQdge8wAAAABJRU5ErkJggg==";
  919.  
  920. var speakerIconHighSrc = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAoCAMAAACPWYlDAAAAOVBMVEUAAABqampqampqampqampqampqampqampqampqampqampqampqampqampqampqampqampqampqampHCtmUAAAAEnRSTlMAhTXgE+5yutBAH0yQKqibV2MOLOh8AAABXElEQVQ4y8WUW5aEIAxEeb/UVrP/xc5Mimk9IGn96vrhiLmkCBB1rWVRTzQlIv0gfqZfeXeeKkK4i8Qyx1S2ZLdRvLHUATw1XccHog4oxB4x0WilFijZIQMl14WXSC0QiPw0YWbuim+pBRaY2etU578DsLYtsPriKP8WNYDJqnhEOiT/O39NA+VIlMpWPzBqCZhQGfiMKrE3CTAzKoPKFYBGAhQTS+avUDCIgIqcIp08rTIwsW0N9y9wIuDYPTw5DkwyoLhaDkcQkOhzhlCB/QaQT0C5kQH7zOb2HhasOWOIn6sUcVQeF9Xi4AUA9a+XaTMYBGDHFcTKqcYVAdDnuxf+L4hkKVir62+rAjgRwJuGMePf3TDrQ6M3HWCs77e6A/gtR6epJmi1+wZQOfmVNzBoliY1AKfxl30Mcq8LoPaBgUIHqIjOOlI+mlaVm9PaxPc92aon0jZl9S39AOlqRk93STxjAAAAAElFTkSuQmCC";
  921.  
  922. /* globals GM, GM_addStyle, GM_download, GM_setClipboard, unsafeWindow, MouseEvent, JSON5, MediaMetadata, Response, geniusLyrics, Blob */
  923.  
  924. // TODO Mark as played automatically when played
  925. // TODO custom CSS
  926.  
  927. const BACKUP_REMINDER_DAYS = 35;
  928. const TRALBUM_CACHE_HOURS = 2;
  929. let NOTIFICATION_TIMEOUT = 3000;
  930. const CHROME = navigator.userAgent.indexOf('Chrome') !== -1;
  931. const CAMPEXPLORER = document.location.hostname === 'campexplorer.io';
  932. const BANDCAMPDOMAIN = document.location.hostname === 'bandcamp.com' || document.location.hostname.endsWith('.bandcamp.com');
  933. let BANDCAMP = BANDCAMPDOMAIN;
  934. const NOEMOJI = CHROME && navigator.userAgent.match(/Windows (NT)? [4-9]/i);
  935. const DEFAULTSKIPTIME = 10; /* Seek time to skip in seconds by default */
  936. const SCRIPT_NAME = 'Bandcamp script (Deluxe Edition)';
  937. const LYRICS_EMPTY_PATH = '/robots.txt';
  938. const PLAYER_URL = 'https://bandcamp.com/robots.txt?player';
  939. const ONEHOUR = 3600000;
  940. let darkModeInjected = false;
  941. let storeTralbumDataPermanentlySwitch = true;
  942. const allFeatures = {
  943. discographyplayer: {
  944. name: 'Enable player on discography page',
  945. default: true
  946. },
  947. tagSearchPlayer: {
  948. name: 'Enable custom player on tag search page',
  949. default: true
  950. },
  951. albumPageVolumeBar: {
  952. name: 'Enable volume slider/shuffle/repeat on album page',
  953. default: true
  954. },
  955. albumPageAutoRepeatAll: {
  956. name: 'Always "repeat all" on album page',
  957. default: false
  958. },
  959. albumPageLyrics: {
  960. name: 'Show lyrics from genius.com on album page',
  961. default: true
  962. },
  963. markasplayed: {
  964. name: 'Show "mark as played" link on discography player',
  965. default: true
  966. },
  967. markasplayedEverywhere: {
  968. name: 'Show "mark as played" link everywhere',
  969. default: true
  970. },
  971. /* markasplayedAuto: {
  972. name: '(NOT YET IMPLEMENTED) Automatically "mark as played" once a song was played for',
  973. default: false
  974. }, */
  975. thetimehascome: {
  976. name: 'Circumvent "The time has come to open thy wallet" limit',
  977. default: true
  978. },
  979. albumPageDownloadLinks: {
  980. name: 'Show download links on album page',
  981. default: true
  982. },
  983. discographyplayerDownloadLink: {
  984. name: 'Show download link on discography player',
  985. default: true
  986. },
  987. discographyplayerSidebar: {
  988. name: 'Show discography player as a sidebar on the right',
  989. default: false
  990. },
  991. discographyplayerFullHeightPlaylist: {
  992. name: 'Extend discography player playlist to full screen height on mouse over',
  993. default: true
  994. },
  995. discographyplayerPersist: {
  996. name: 'Recover discography player on next page',
  997. default: true
  998. },
  999. backupReminder: {
  1000. name: 'Remind me to backup my played albums every month',
  1001. default: true
  1002. },
  1003. nextSongNotifications: {
  1004. name: 'Show a notification when a new song starts',
  1005. default: false
  1006. },
  1007. releaseReminder: {
  1008. name: 'Show new releases that I have saved',
  1009. default: true
  1010. },
  1011. keepLibrary: {
  1012. name: 'Store all visited or played albums',
  1013. default: true
  1014. },
  1015. darkMode: {
  1016. name: (CHROME ? '🅳🅐🆁🅺🅼🅞🅳🅴' : '🅳🅰🆁🅺🅼🅾🅳🅴') + ' - enable <a href="https://userstyles.org/styles/171538/bandcamp-in-dark">dark theme by Simonus</a>',
  1017. default: false
  1018. },
  1019. showAlbumID: {
  1020. name: 'Show album ID on album page',
  1021. default: false
  1022. },
  1023. feedShowOnlyNewReleases: {
  1024. name: 'Show only new releases in the feed',
  1025. default: false
  1026. },
  1027. feedShowAudioControls: {
  1028. name: 'Show play/pause/seek-bar in the feed',
  1029. default: true
  1030. },
  1031. customReleaseDateFormat: {
  1032. name: 'Format release date on album page',
  1033. default: false
  1034. }
  1035. };
  1036. const moreSettings = {
  1037. darkMode: {
  1038. true: async function populateDarkModeSettings(container) {
  1039. let darkModeValue = await GM.getValue('darkmode', '1');
  1040. const onChange = async function () {
  1041. const input = this;
  1042. window.setTimeout(() => parentQuery(input, 'fieldset').classList.add('breathe'), 0);
  1043. document.getElementById('bcsde_mode_auto_status').innerHTML = '';
  1044. document.getElementById('bcsde_mode_const_time_from').classList.remove('errorblink');
  1045. document.getElementById('bcsde_mode_const_time_to').classList.remove('errorblink');
  1046. if (document.getElementById('bcsde_mode_always').checked) {
  1047. darkModeValue = '1';
  1048. } else if (document.getElementById('bcsde_mode_const_time').checked) {
  1049. let from = document.getElementById('bcsde_mode_const_time_from').value;
  1050. let to = document.getElementById('bcsde_mode_const_time_to').value;
  1051. const mFrom = from.match(/([0-2]?\d:[0-5]\d)/);
  1052. const mTo = to.match(/([0-2]?\d:[0-5]\d)/);
  1053. if (mFrom && mTo) {
  1054. from = mFrom[1];
  1055. to = mTo[1];
  1056. document.getElementById('bcsde_mode_const_time_from').value = from;
  1057. document.getElementById('bcsde_mode_const_time_to').value = to;
  1058. darkModeValue = `2#${from}->${to}`;
  1059. } else {
  1060. if (!mFrom) {
  1061. document.getElementById('bcsde_mode_const_time_from').classList.add('errorblink');
  1062. }
  1063. if (!mTo) {
  1064. document.getElementById('bcsde_mode_const_time_to').classList.add('errorblink');
  1065. }
  1066. }
  1067. } else if (document.getElementById('bcsde_mode_auto').checked) {
  1068. let myPosition = null;
  1069. let sunData = null;
  1070. try {
  1071. myPosition = await getGPSLocation();
  1072. sunData = suntimes(new Date(), myPosition.latitude, myPosition.longitude);
  1073. } catch (e) {
  1074. document.getElementById('bcsde_mode_auto_status').innerHTML = 'Error:\n' + e;
  1075. }
  1076. if (myPosition && sunData) {
  1077. const data = Object.assign(myPosition, sunData);
  1078. darkModeValue = '3#' + JSON.stringify(data);
  1079. document.getElementById('bcsde_mode_auto_status').innerHTML = `Source: ${data.source}
  1080. Location: ${data.latitude}, ${data.longitude}
  1081. Sunrise: ${data.sunrise.toLocaleTimeString()}
  1082. Sunset: ${data.sunset.toLocaleTimeString()}`;
  1083. }
  1084. }
  1085. await GM.setValue('darkmode', darkModeValue);
  1086. window.setTimeout(() => parentQuery(input, 'fieldset').classList.remove('breathe'), 50);
  1087. };
  1088. const radioAlways = container.appendChild(document.createElement('input'));
  1089. radioAlways.setAttribute('type', 'radio');
  1090. radioAlways.setAttribute('name', 'mode');
  1091. radioAlways.setAttribute('value', 'always');
  1092. radioAlways.setAttribute('id', 'bcsde_mode_always');
  1093. radioAlways.checked = darkModeValue.startsWith('1');
  1094. radioAlways.addEventListener('change', onChange);
  1095. const labelAlways = container.appendChild(document.createElement('label'));
  1096. labelAlways.setAttribute('for', 'bcsde_mode_always');
  1097. labelAlways.appendChild(document.createTextNode('Always'));
  1098. container.appendChild(document.createElement('br'));
  1099. const radioConstTime = container.appendChild(document.createElement('input'));
  1100. radioConstTime.setAttribute('type', 'radio');
  1101. radioConstTime.setAttribute('name', 'mode');
  1102. radioConstTime.setAttribute('value', 'const_time');
  1103. radioConstTime.setAttribute('id', 'bcsde_mode_const_time');
  1104. radioConstTime.checked = darkModeValue.startsWith('2');
  1105. radioConstTime.addEventListener('change', onChange);
  1106. let [from, to] = ['22:00', '06:00'];
  1107. if (darkModeValue.startsWith('2')) {
  1108. [from, to] = darkModeValue.substring(2).split('->');
  1109. }
  1110. const labelConstTime = container.appendChild(document.createElement('label'));
  1111. labelConstTime.setAttribute('for', 'bcsde_mode_const_time');
  1112. labelConstTime.appendChild(document.createTextNode('Time'));
  1113. const labelConstTimeFrom = container.appendChild(document.createElement('label'));
  1114. labelConstTimeFrom.setAttribute('for', 'bcsde_mode_const_time_from');
  1115. labelConstTimeFrom.appendChild(document.createTextNode(' from '));
  1116. const inputConstTimeFrom = container.appendChild(document.createElement('input'));
  1117. inputConstTimeFrom.setAttribute('type', 'text');
  1118. inputConstTimeFrom.setAttribute('value', from);
  1119. inputConstTimeFrom.setAttribute('id', 'bcsde_mode_const_time_from');
  1120. inputConstTimeFrom.addEventListener('change', onChange);
  1121. const labelConstTimeTo = container.appendChild(document.createElement('label'));
  1122. labelConstTimeTo.setAttribute('for', 'bcsde_mode_const_time_to');
  1123. labelConstTimeTo.appendChild(document.createTextNode(' to '));
  1124. const inputConstTimeTo = container.appendChild(document.createElement('input'));
  1125. inputConstTimeTo.setAttribute('type', 'text');
  1126. inputConstTimeTo.setAttribute('value', to);
  1127. inputConstTimeTo.setAttribute('id', 'bcsde_mode_const_time_to');
  1128. inputConstTimeTo.addEventListener('change', onChange);
  1129. container.appendChild(document.createElement('br'));
  1130. const radioAuto = container.appendChild(document.createElement('input'));
  1131. radioAuto.setAttribute('type', 'radio');
  1132. radioAuto.setAttribute('name', 'mode');
  1133. radioAuto.setAttribute('value', 'auto');
  1134. radioAuto.setAttribute('id', 'bcsde_mode_auto');
  1135. radioAuto.checked = darkModeValue.startsWith('3');
  1136. radioAuto.addEventListener('change', onChange);
  1137. const labelAuto = container.appendChild(document.createElement('label'));
  1138. labelAuto.setAttribute('for', 'bcsde_mode_auto');
  1139. labelAuto.appendChild(document.createTextNode('Auto (sunset till sunrise)'));
  1140. const preAutoStatus = container.appendChild(document.createElement('pre'));
  1141. preAutoStatus.setAttribute('id', 'bcsde_mode_auto_status');
  1142. preAutoStatus.setAttribute('style', 'font-family:monospace');
  1143. return 'Dark theme details';
  1144. }
  1145. },
  1146. discographyplayerSidebar: {
  1147. true: function checkScreenSize(container) {
  1148. if (!window.matchMedia('(min-width: 1600px)').matches) {
  1149. const span = container.appendChild(document.createElement('span'));
  1150. span.appendChild(document.createTextNode('Your screen/browser window is not wide enough for this option. Width of at least 1600px required'));
  1151. container.style.opacity = 1;
  1152. } else {
  1153. container.style.opacity = 0;
  1154. }
  1155. return fullfill();
  1156. },
  1157. false: function removeContainerAboutScreenSize(container) {
  1158. container.style.opacity = 0;
  1159. return fullfill();
  1160. }
  1161. },
  1162. nextSongNotifications: {
  1163. true: async function populateNotificationSettings(container) {
  1164. const onChange = async function () {
  1165. const input = this;
  1166. document.getElementById('bcsde_notification_timeout').classList.remove('errorblink');
  1167. let seconds = -1;
  1168. try {
  1169. seconds = parseFloat(document.getElementById('bcsde_notification_timeout').value.trim());
  1170. } catch (e) {
  1171. seconds = -1;
  1172. }
  1173. if (seconds < 0) {
  1174. document.getElementById('bcsde_notification_timeout').classList.add('errorblink');
  1175. } else {
  1176. NOTIFICATION_TIMEOUT = parseInt(1000.0 * seconds);
  1177. await GM.setValue('notification_timeout', NOTIFICATION_TIMEOUT);
  1178. input.style.boxShadow = '2px 2px 5px #0a0f';
  1179. window.setTimeout(function resetBoxShadowTimeout() {
  1180. input.style.boxShadow = '';
  1181. }, 3000);
  1182. }
  1183. };
  1184. const labelTimeout = container.appendChild(document.createElement('label'));
  1185. labelTimeout.setAttribute('for', 'bcsde_notification_timeout');
  1186. labelTimeout.appendChild(document.createTextNode('Show for '));
  1187. const inputTimeout = container.appendChild(document.createElement('input'));
  1188. inputTimeout.setAttribute('type', 'text');
  1189. inputTimeout.setAttribute('size', '3');
  1190. inputTimeout.setAttribute('value', (await GM.getValue('notification_timeout', NOTIFICATION_TIMEOUT)) / 1000.0);
  1191. inputTimeout.setAttribute('id', 'bcsde_notification_timeout');
  1192. inputTimeout.addEventListener('change', onChange);
  1193. const labelPostTimeout = container.appendChild(document.createElement('label'));
  1194. labelPostTimeout.setAttribute('for', 'bcsde_notification_timeout');
  1195. labelPostTimeout.appendChild(document.createTextNode(' seconds (0 = show until manually closed or default value of browser)'));
  1196. }
  1197. },
  1198. customReleaseDateFormat: {
  1199. true: async function populateCustomReleaseDateFormatSettings(container) {
  1200. const defaultFormat = '%YYYY%.%MM%.%DD%';
  1201. const onChange = async function () {
  1202. const input = this;
  1203. document.getElementById('bcsde_custom_release_date_format_str').classList.remove('errorblink');
  1204. let format = defaultFormat;
  1205. const customFormat = document.getElementById('bcsde_custom_release_date_format_str').value;
  1206. if (customFormat && customFormat.trim()) {
  1207. format = customFormat.trim();
  1208. await GM.setValue('custom_release_date_format_str', format);
  1209. input.style.boxShadow = '2px 2px 5px #0a0f';
  1210. window.setTimeout(function resetBoxShadowTimeout() {
  1211. input.style.boxShadow = '';
  1212. }, 3000);
  1213. } else {
  1214. document.getElementById('bcsde_custom_release_date_format_str').classList.add('errorblink');
  1215. }
  1216. };
  1217. const onKeyUp = function () {
  1218. let format = '';
  1219. const customFormat = document.getElementById('bcsde_custom_release_date_format_str').value;
  1220. const preview = document.getElementById('bcsde_custom_release_date_preview');
  1221. if (customFormat && customFormat.trim()) {
  1222. format = customFormat.trim();
  1223. preview.textContent = 'Preview: ' + customDateFormatter(format, new Date(981154800000));
  1224. } else {
  1225. preview.textContent = 'Preview:';
  1226. }
  1227. };
  1228. const labelFormat = container.appendChild(document.createElement('label'));
  1229. labelFormat.setAttribute('for', 'bcsde_custom_release_date_format_str');
  1230. labelFormat.appendChild(document.createTextNode('Custom format: '));
  1231. const inputFormat = container.appendChild(document.createElement('input'));
  1232. inputFormat.setAttribute('type', 'text');
  1233. inputFormat.setAttribute('size', '40');
  1234. inputFormat.setAttribute('value', await GM.getValue('custom_release_date_format_str', defaultFormat));
  1235. inputFormat.setAttribute('id', 'bcsde_custom_release_date_format_str');
  1236. inputFormat.addEventListener('change', onChange);
  1237. inputFormat.addEventListener('change', onKeyUp);
  1238. inputFormat.addEventListener('keyup', onKeyUp);
  1239. container.appendChild(document.createElement('br'));
  1240. const preview = container.appendChild(document.createElement('span'));
  1241. preview.setAttribute('id', 'bcsde_custom_release_date_preview');
  1242. preview.readOnly = true;
  1243. container.appendChild(document.createElement('br'));
  1244. const link = container.appendChild(document.createElement('a'));
  1245. link.setAttribute('target', '_blank');
  1246. link.setAttribute('href', 'https://github.com/cvzi/Bandcamp-script-deluxe-edition/issues/284#issuecomment-1563394077');
  1247. link.appendChild(document.createTextNode('Format options: %DD%, %MM%, %YYYY%, ...'));
  1248. onKeyUp();
  1249. }
  1250. }
  1251. };
  1252. let player, audio, currentDuration, timeline, playhead, bufferbar;
  1253. let onPlayHead = false;
  1254. const spriteRepeatShuffle = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACUAAABgCAMAAACt1UvuAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAA2UExURQAAAP////39/Tw8PP///////w4ODv////7+/v7+/k5OTktLS35+fiAgIJSUlAAAABAQECoqKpxAnVsAAAAPdFJOUwAxQ05UJGkKBRchgWiOOufd5UcAAAKrSURBVEjH7ZfrkqQgDIUbFLmphPd/2T2EgNqNzlTt7o+p3dR0d5V+JOGEYzkvZ63nsNY6517XCPIrjIDvXF7qL24ao5QynesIllDKE1MpJdom1UDBQIQlE+HmEipVIk+6cqVqQYivlq/loBJFDa6WnaitbbnMtFHnOF1niDJJX14pPa+cOm0l3Vohyuus8xpkj9ih1nPke6iaO6KV323XqwhRON4tQ3GedakNYYQqslaO+yv9xs64Lh2rX8sWeSISzVWTk8ROJmmU9MTl1PvEnHBmzXRSzvhhuqJAzjlJY9eJCVWljKwcESbL+fbTYK0NWx0IGodyvKCACqp6VqMNlguhktbxMqHdI5k7ps1SsiTxPO0YDgojkZPIysl+617cy8rUkIfPflMY4IaKLZfHhSoPn782iQJC5tIX2nfNQseGG4eoe3T1+kXh7j1j/H6W9TbC65ZxR2S0frKePUWYlhbY/hTkvL6aiKPApCRTeoxNTvUTI16r1DqPAqrGVR0UT/ojwGByJ6qO8S32HQ6wJ8r4TwFdyGnx7kzVM8l/nZpwRwkm1GAKC+5oKflMzY3aUm4rBpSsd17pVv2Bsn739ivqFWK2bhD2TE0wwTKM3Knu2puo1PJ8blqu7TEXVY1wgvGQwYN6HKJR0WGjYqxheN/lCpOzd/GlHX+gHyEe/SE/qpyV+sKPfqdEhzVv/OjwwC3zlefnnR+9YW+5Zz86fzjw3o+f1NCP9oMa+fGeOvnR2brH/378B/xI9A0/UjUjSfyOH2GzCDOuKavyUUM/eryMFjNOIMrHD/1o4di0GlCkp8IP/RjwglRSCKX9yI845VGXqwc18KOtWq3mSr35EQVnHbnzC3X144I3d7Wj6xuq+hH7gwz4PvY48GP9p8i2Vzus/dt+pB/nx18MUmsLM2EHrwAAAABJRU5ErkJggg==')";
  1255. function humanDuration(duration) {
  1256. let hours = parseInt(duration / 3600);
  1257. if (!hours) {
  1258. hours = '';
  1259. } else {
  1260. hours += ':';
  1261. }
  1262. duration %= 3600;
  1263. let minutes = parseInt(duration / 60);
  1264. minutes = (minutes < 10 ? '0' : '') + minutes;
  1265. duration %= 60;
  1266. let seconds = parseInt(duration);
  1267. if (duration - seconds >= 0.5) {
  1268. seconds++;
  1269. }
  1270. seconds = (seconds < 10 ? '0' : '') + seconds;
  1271. return `${hours}${minutes}:${seconds}`;
  1272. }
  1273. function humanBytes(bytes, precision) {
  1274. bytes = parseInt(bytes, 10);
  1275. if (bytes === 0) {
  1276. return '0 Byte';
  1277. }
  1278. const k = 1024;
  1279. const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  1280. const i = Math.floor(Math.log(bytes) / Math.log(k));
  1281. return parseFloat((bytes / Math.pow(k, i)).toPrecision(2)) + ' ' + sizes[i];
  1282. }
  1283. function addLogVolume(mediaElement) {
  1284. if (!Object.hasOwnProperty.call(mediaElement, 'logVolume')) {
  1285. Object.defineProperty(mediaElement, 'logVolume', {
  1286. get() {
  1287. return Math.log((Math.E - 1) * this.volume + 1);
  1288. },
  1289. set(percentage) {
  1290. this.volume = (Math.exp(percentage) - 1) / (Math.E - 1);
  1291. }
  1292. });
  1293. }
  1294. }
  1295. function sleep(t) {
  1296. return new Promise(resolve => setTimeout(resolve, t));
  1297. }
  1298. function randomIndex(max) {
  1299. // Random int from interval [0,max)
  1300. return Math.floor(Math.random() * Math.floor(max));
  1301. }
  1302. function padd(n, width, filler) {
  1303. let s;
  1304. for (s = n.toString(); s.length < width; s = filler + s);
  1305. return s;
  1306. }
  1307. function metricPrefix(n, decimals, k) {
  1308. // From http://stackoverflow.com/a/18650828
  1309. if (n <= 0) {
  1310. return String(n);
  1311. }
  1312. k = k || 1000;
  1313. const dm = decimals <= 0 ? 0 : decimals || 2;
  1314. const sizes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
  1315. const i = Math.floor(Math.log(n) / Math.log(k));
  1316. return parseFloat((n / Math.pow(k, i)).toFixed(dm)) + sizes[i];
  1317. }
  1318. function fixFilename(s) {
  1319. const forbidden = '*"/\\[]:|,<>?\n\t\0'.split('');
  1320. forbidden.forEach(function (char) {
  1321. s = s.replace(char, '');
  1322. });
  1323. return s;
  1324. }
  1325. function fullfill(x) {
  1326. return new Promise(resolve => resolve(x));
  1327. }
  1328. function customDateFormatter(format, date) {
  1329. const fields = {
  1330. '%isoDate%': () => date.toISOString(),
  1331. '%unix%': () => parseInt(date.getTime() / 1000),
  1332. '%YY%': () => date.getFullYear().toString().substring(2),
  1333. '%YYYY%': () => date.getFullYear(),
  1334. '%M%': () => date.getMonth() + 1,
  1335. '%MM%': () => padd(date.getMonth() + 1, 2, '0'),
  1336. '%Mon%': () => date.toLocaleString(undefined, {
  1337. month: 'short'
  1338. }),
  1339. '%Month%': () => date.toLocaleString(undefined, {
  1340. month: 'long'
  1341. }),
  1342. '%D%': () => date.getDate(),
  1343. '%DD%': () => padd(date.getDate(), 2, '0'),
  1344. '%Da%': () => date.toLocaleString(undefined, {
  1345. weekday: 'short'
  1346. }),
  1347. '%Day%': () => date.toLocaleString(undefined, {
  1348. weekday: 'long'
  1349. }),
  1350. '%Dord%': () => date.getDate() + (date.getDate() % 10 === 1 && date.getDate() !== 11 ? 'st' : date.getDate() % 10 === 2 && date.getDate() !== 12 ? 'nd' : date.getDate() % 10 === 3 && date.getDate() !== 13 ? 'rd' : 'th'),
  1351. '%json%': () => date.toJSON()
  1352. };
  1353. for (const field in fields) {
  1354. if (format.includes(field)) {
  1355. try {
  1356. format = format.replace(field, fields[field]());
  1357. } catch (e) {
  1358. console.error('customDateFormatter: Could not format replace "' + field + '": ' + e);
  1359. }
  1360. }
  1361. }
  1362. return format;
  1363. }
  1364. const stylesToInsert = [];
  1365. function addStyle(css) {
  1366. if (GM_addStyle && css) {
  1367. return GM_addStyle(css);
  1368. } else {
  1369. if (css) {
  1370. stylesToInsert.push(css);
  1371. }
  1372. const head = document.head ? document.head : document.documentElement;
  1373. if (head) {
  1374. let style = document.createElement('style');
  1375. if (style) {
  1376. while (stylesToInsert.length) {
  1377. head.append(style);
  1378. style.type = 'text/css';
  1379. style.appendChild(document.createTextNode(stylesToInsert.shift()));
  1380. style = document.createElement('style');
  1381. }
  1382. return fullfill(style);
  1383. }
  1384. }
  1385. // document was not ready, wait
  1386. return new Promise(resolve => window.setTimeout(() => addStyle(false).then(resolve), 100));
  1387. }
  1388. }
  1389. function css2rgb(colorStr) {
  1390. const div = document.body.appendChild(document.createElement('div'));
  1391. div.style.color = colorStr;
  1392. const m = window.getComputedStyle(div).color.match(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i);
  1393. div.remove();
  1394. if (m) {
  1395. m.shift();
  1396. return m;
  1397. }
  1398. return null;
  1399. }
  1400. function base64encode(s) {
  1401. // from https://gist.github.com/stubbetje/229984
  1402. const base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('');
  1403. const l = s.length;
  1404. let o = '';
  1405. for (let i = 0; i < l; i++) {
  1406. const byte0 = s.charCodeAt(i++) & 0xff;
  1407. const byte1 = s.charCodeAt(i++) & 0xff;
  1408. const byte2 = s.charCodeAt(i) & 0xff;
  1409. o += base64[byte0 >> 2];
  1410. o += base64[(byte0 & 0x3) << 4 | byte1 >> 4];
  1411. const t = i - l;
  1412. if (t >= 0) {
  1413. if (t === 0) {
  1414. o += base64[(byte1 & 0x0f) << 2 | byte2 >> 6];
  1415. o += base64[64];
  1416. } else {
  1417. o += base64[64];
  1418. o += base64[64];
  1419. }
  1420. } else {
  1421. o += base64[(byte1 & 0x0f) << 2 | byte2 >> 6];
  1422. o += base64[byte2 & 0x3f];
  1423. }
  1424. }
  1425. return o;
  1426. }
  1427. function decodeHTMLentities(input) {
  1428. return new window.DOMParser().parseFromString(input, 'text/html').documentElement.textContent;
  1429. }
  1430. function timeSince(date) {
  1431. // https://stackoverflow.com/a/72973090/
  1432. const MINUTE = 60;
  1433. const HOUR = MINUTE * 60;
  1434. const DAY = HOUR * 24;
  1435. const WEEK = DAY * 7;
  1436. const MONTH = DAY * 30;
  1437. const YEAR = DAY * 365;
  1438. const secondsAgo = Math.round((Date.now() - Number(date)) / 1000);
  1439. if (secondsAgo < MINUTE) {
  1440. return secondsAgo + ` second${secondsAgo !== 1 ? 's' : ''} ago`;
  1441. }
  1442. let divisor;
  1443. let unit = '';
  1444. if (secondsAgo < HOUR) {
  1445. [divisor, unit] = [MINUTE, 'minute'];
  1446. } else if (secondsAgo < DAY) {
  1447. [divisor, unit] = [HOUR, 'hour'];
  1448. } else if (secondsAgo < WEEK) {
  1449. [divisor, unit] = [DAY, 'day'];
  1450. } else if (secondsAgo < MONTH) {
  1451. [divisor, unit] = [WEEK, 'week'];
  1452. } else if (secondsAgo < YEAR) {
  1453. [divisor, unit] = [MONTH, 'month'];
  1454. } else {
  1455. [divisor, unit] = [YEAR, 'year'];
  1456. }
  1457. const count = Math.floor(secondsAgo / divisor);
  1458. return `${count} ${unit}${count > 1 ? 's' : ''} ago`;
  1459. }
  1460. function nowInTimeRange(range) {
  1461. // Format: range = 'hh:mm->hh:mm'
  1462. const m = range.match(/(\d{1,2}):(\d{1,2})->(\d{1,2}):(\d{1,2})/);
  1463. const [fromHours, fromMinutes, toHours, toMinutes] = [parseInt(m[1]), parseInt(m[2]), parseInt(m[3]), parseInt(m[4])];
  1464. const now = new Date();
  1465. const from = new Date();
  1466. from.setHours(fromHours);
  1467. from.setMinutes(fromMinutes);
  1468. const to = new Date();
  1469. to.setHours(toHours);
  1470. to.setMinutes(toMinutes);
  1471. if (to - from < 0) {
  1472. to.setDate(to.getDate() + 1);
  1473. }
  1474. return now > from && now < to;
  1475. }
  1476. function nowInBetween(from, to) {
  1477. const time = new Date();
  1478. const start = from.getHours() * 60 + from.getMinutes();
  1479. const end = to.getHours() * 60 + to.getMinutes();
  1480. const now = time.getHours() * 60 + time.getMinutes();
  1481. if (start >= end) {
  1482. return start <= now && now >= end || start >= now && now <= end;
  1483. } else {
  1484. return start <= now && now <= end;
  1485. }
  1486. }
  1487. function loadCrossSiteImage(url) {
  1488. return new Promise(function downloadCrossSiteImage(resolve, reject) {
  1489. const canvas = document.createElement('canvas');
  1490. const ctx = canvas.getContext('2d');
  1491. const img0 = document.createElement('img'); // Load the image in a <img> to get the dimensions
  1492. img0.addEventListener('load', function onImgLoad() {
  1493. if (img0.height === 0 || img0.width === 0) {
  1494. reject(new Error('loadCrossSiteImage("$url") Error: Could not load image in <img>'));
  1495. return;
  1496. }
  1497. canvas.height = img0.height;
  1498. canvas.width = img0.width;
  1499. // Download image data
  1500. GM.xmlHttpRequest({
  1501. method: 'GET',
  1502. overrideMimeType: 'text/plain; charset=x-user-defined',
  1503. url,
  1504. onload: function (resp) {
  1505. // Create a data url image
  1506. const dataurl = 'data:image/jpeg;base64,' + base64encode(resp.responseText);
  1507. const img1 = document.createElement('img');
  1508. img1.addEventListener('load', function () {
  1509. // Load data url image into canvas
  1510. ctx.drawImage(img1, 0, 0);
  1511. resolve(canvas);
  1512. });
  1513. img1.src = dataurl;
  1514. },
  1515. onerror: function (response) {
  1516. console.error('loadCrossSiteImage("' + url + '") Error: ' + response.status + '\n' + ('error' in response ? response.error : ''));
  1517. reject(new Error('error' in response ? response.error : 'loadCrossSiteImage failed'));
  1518. }
  1519. });
  1520. });
  1521. img0.src = url;
  1522. });
  1523. }
  1524. function removeViaQuerySelector(parent, selector) {
  1525. if (typeof selector === 'undefined') {
  1526. selector = parent;
  1527. parent = document;
  1528. }
  1529. for (let el = parent.querySelector(selector); el; el = parent.querySelector(selector)) {
  1530. el.remove();
  1531. }
  1532. }
  1533. function firstChildWithText(parent) {
  1534. for (let i = 0; i < parent.childNodes.length; i++) {
  1535. const node = parent.childNodes[i];
  1536. if (node.nodeType === window.Node.TEXT_NODE && node.nodeValue.trim()) {
  1537. return node;
  1538. } else if (node.childNodes.length) {
  1539. const r = firstChildWithText(node);
  1540. if (r) {
  1541. return r;
  1542. }
  1543. }
  1544. }
  1545. return false;
  1546. }
  1547. function parentQuery(node, q) {
  1548. const parents = [node.parentElement];
  1549. node = node.parentElement.parentElement;
  1550. while (node) {
  1551. const lst = node.querySelectorAll(q);
  1552. for (let i = 0; i < lst.length; i++) {
  1553. if (parents.indexOf(lst[i]) !== -1) {
  1554. return lst[i];
  1555. }
  1556. }
  1557. parents.push(node);
  1558. node = node.parentElement;
  1559. }
  1560. return null;
  1561. }
  1562. function suntimes(date, lat, lng) {
  1563. // According to "Predicting Sunrise and Sunset Times" by Donald A. Teets:
  1564. // https://www.maa.org/sites/default/files/teets09010341463.pdf
  1565. lat = lat * Math.PI / 180.0;
  1566. const dayOfYear = Math.round((date - new Date(date).setMonth(0, 0)) / 86400000);
  1567. const sunDist = 149598000.0;
  1568. const radius = 6378.0;
  1569. const epsilon = 0.409;
  1570. const thetha = 2 * Math.PI / 365.25 * (dayOfYear - 80);
  1571. const n = 720 - 10 * Math.sin(2 * thetha) + 8 * Math.sin(2 * Math.PI / 365.25 * dayOfYear);
  1572. const z = sunDist * Math.sin(thetha) * Math.sin(epsilon);
  1573. const rp = Math.sqrt(sunDist * sunDist - z * z);
  1574. const t0 = 1440 / (2 * Math.PI) * Math.acos((radius - z * Math.sin(lat)) / (rp * Math.cos(lat)));
  1575. const sunriseMin = n - t0 - 5 - 4.0 * lng % 15.0 - date.getTimezoneOffset();
  1576. const sunsetMin = sunriseMin + 2 * t0;
  1577. const sunrise = new Date(date);
  1578. sunrise.setHours(sunriseMin / 60, Math.round(sunriseMin % 60));
  1579. const sunset = new Date(date);
  1580. sunset.setHours(sunsetMin / 60, Math.round(sunsetMin % 60));
  1581. return {
  1582. sunrise,
  1583. sunset
  1584. };
  1585. }
  1586. function fromISO6709(s) {
  1587. // Format: s = '+-DDMM+-DDDMM'
  1588. // Format: s = '+-DDMMSS+-DDDMMSS'
  1589. function convert(iso, negative) {
  1590. const mm = iso % 100;
  1591. const dd = iso / 100;
  1592. return (dd + mm / 60) * (negative ? -1 : 1);
  1593. }
  1594. const m = s.match(/([+-])(\d+)([+-])(\d+)/);
  1595. const lat = convert(parseInt(m[2]), m[1] === '-');
  1596. const lng = convert(parseInt(m[4]), m[3] === '-');
  1597. return {
  1598. latitude: lat,
  1599. longitude: lng
  1600. };
  1601. }
  1602. function getGPSLocation() {
  1603. return new Promise(function downloadCrossSiteImage(resolve, reject) {
  1604. navigator.geolocation.getCurrentPosition(function onSuccess(position) {
  1605. resolve({
  1606. source: `navigator.geolocation@${new Date(position.timestamp).toLocaleString()}`,
  1607. latitude: position.coords.latitude,
  1608. longitude: position.coords.longitude
  1609. });
  1610. }, function onError(err) {
  1611. console.error('getGPSLocation Error:', err);
  1612. const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
  1613. console.debug('getGPSLocation: Timezone: ' + tz);
  1614. GM.xmlHttpRequest({
  1615. method: 'GET',
  1616. url: 'https://raw.githubusercontent.com/iospirit/NSTimeZone-ISCLLocation/master/zone.tab',
  1617. onload: function (response) {
  1618. if (response.responseText.indexOf(tz) !== -1) {
  1619. const line = response.responseText.split(tz)[0].split('\n').pop();
  1620. const myPosition = fromISO6709(line);
  1621. myPosition.source = 'Browser timezone ' + tz;
  1622. resolve(myPosition);
  1623. } else if (response.status !== 200) {
  1624. reject(new Error('Could not download time zone locations: http status=' + response.status));
  1625. } else {
  1626. reject(new Error('Unkown time zone location: ' + tz));
  1627. }
  1628. },
  1629. onerror: function (response) {
  1630. reject(new Error('Could not download time zone locations: ' + response.error));
  1631. }
  1632. });
  1633. });
  1634. });
  1635. }
  1636. const _dateOptions = {
  1637. year: 'numeric',
  1638. month: 'short',
  1639. day: 'numeric'
  1640. };
  1641. const _dateOptionsWithoutYear = {
  1642. month: 'short',
  1643. day: 'numeric'
  1644. };
  1645. const _dateOptionsNumericWithoutYear = {
  1646. year: '2-digit',
  1647. month: '2-digit',
  1648. day: '2-digit'
  1649. };
  1650. function dateFormater(date) {
  1651. if (date.getFullYear() === new Date().getFullYear()) {
  1652. return date.toLocaleDateString(undefined, _dateOptionsWithoutYear);
  1653. } else {
  1654. return date.toLocaleDateString(undefined, _dateOptions);
  1655. }
  1656. }
  1657. function dateFormaterRelease(date) {
  1658. return date.toLocaleDateString(undefined, _dateOptionsWithoutYear) + ', ' + date.getFullYear();
  1659. }
  1660. function dateFormaterNumeric(date) {
  1661. return date.toLocaleDateString(undefined, _dateOptionsNumericWithoutYear);
  1662. }
  1663. let enabledFeaturesLoaded = false;
  1664. function getEnabledFeatures(enabledFeaturesValue) {
  1665. for (const feature in allFeatures) {
  1666. allFeatures[feature].enabled = allFeatures[feature].default;
  1667. }
  1668. if (enabledFeaturesValue !== false) {
  1669. const enabledFeatures = JSON.parse(enabledFeaturesValue);
  1670. if (enabledFeatures.constructor === Object) {
  1671. for (const feature in enabledFeatures) {
  1672. if (feature in allFeatures) {
  1673. allFeatures[feature].enabled = enabledFeatures[feature].enabled;
  1674. }
  1675. }
  1676. }
  1677. }
  1678. enabledFeaturesLoaded = true;
  1679. return allFeatures;
  1680. }
  1681. function findUserProfileUrl() {
  1682. if (document.querySelector('#collection-main a')) {
  1683. return document.querySelector('#collection-main a').href;
  1684. }
  1685. return 'https://bandcamp.com/login';
  1686. }
  1687. let ivRestoreVolume;
  1688. function getStoredVolume(callbackIfVolumeExists) {
  1689. GM.getValue('volume', '0.7').then(str => {
  1690. return parseFloat(str);
  1691. }).then(function storedVolumeLoaded(volume) {
  1692. if (!Number.isNaN(volume) && volume > 0.0) {
  1693. callbackIfVolumeExists(volume);
  1694. }
  1695. });
  1696. }
  1697. function restoreVolume() {
  1698. getStoredVolume(function getStoredVolumeCallback(volume) {
  1699. const restoreVolumeInterval = function restoreInterval() {
  1700. const audios = document.querySelectorAll('audio,video');
  1701. if (audios.length > 0) {
  1702. let paused = true;
  1703. audios.forEach(function (media) {
  1704. addLogVolume(media);
  1705. paused = paused && media.paused;
  1706. media.logVolume = volume;
  1707. });
  1708. if (!paused) {
  1709. // Clear interval once audio is actually playing
  1710. window.clearInterval(ivRestoreVolume);
  1711. }
  1712. // Update volume bar on tag player (by double clicking mute button)
  1713. const muteWrapper = document.querySelector('.vol-icon-wrapper');
  1714. if (muteWrapper) {
  1715. const mouseDownEvent = new MouseEvent('mousedown', {
  1716. view: unsafeWindow,
  1717. bubbles: true,
  1718. cancelable: true
  1719. });
  1720. muteWrapper.dispatchEvent(mouseDownEvent);
  1721. muteWrapper.dispatchEvent(mouseDownEvent);
  1722. }
  1723. }
  1724. };
  1725. restoreVolumeInterval();
  1726. ivRestoreVolume = window.setInterval(restoreVolumeInterval, 500);
  1727. });
  1728. window.setTimeout(function clearRestoreInterval() {
  1729. window.clearInterval(ivRestoreVolume);
  1730. }, 7000);
  1731. }
  1732. function findPreviousAlbumCover(currentUrl) {
  1733. const currentKey = albumKey(currentUrl);
  1734. const as = document.querySelectorAll('.music-grid .music-grid-item a[href*="/album/"],.music-grid .music-grid-item a[href*="/track/"]');
  1735. let last = false;
  1736. let found = false;
  1737. for (let i = 0; i < as.length; i++) {
  1738. if (last && albumKey(as[i].href) === currentKey) {
  1739. found = last;
  1740. break;
  1741. }
  1742. last = as[i];
  1743. }
  1744. if (found) {
  1745. return playAlbumFromCover.apply(found, null);
  1746. }
  1747. return false;
  1748. }
  1749. function findNextAlbumCover(currentUrl) {
  1750. const currentKey = albumKey(currentUrl);
  1751. const as = document.querySelectorAll('.music-grid .music-grid-item a[href*="/album/"],.music-grid .music-grid-item a[href*="/track/"]');
  1752. let isNext = false;
  1753. for (let i = 0; i < as.length; i++) {
  1754. if (isNext) {
  1755. playAlbumFromCover.apply(as[i], null);
  1756. return true;
  1757. }
  1758. if (albumKey(as[i].href) === currentKey) {
  1759. isNext = true;
  1760. }
  1761. }
  1762. return false;
  1763. }
  1764. const shufflePlayed = [];
  1765. function musicPlayerNextSong(next) {
  1766. const current = player.querySelector('.playlist .playing');
  1767. if (!next) {
  1768. if (player.querySelector('.shufflebutton').classList.contains('active')) {
  1769. // Shuffle mode
  1770. const allLoadedSongs = document.querySelectorAll('.playlist .playlistentry');
  1771. // Set a random song (that is not the current song and not in shufflePlayed)
  1772. let index = null;
  1773. for (let i = 0; i < 10; i++) {
  1774. index = randomIndex(allLoadedSongs.length);
  1775. const file = allLoadedSongs[index].dataset.file;
  1776. if (file !== current.dataset.file && shufflePlayed.indexOf(file) !== -1) {
  1777. break;
  1778. }
  1779. }
  1780. next = allLoadedSongs[index];
  1781. shufflePlayed.push(next.dataset.file);
  1782. } else {
  1783. // Normal mode
  1784. next = current.nextElementSibling;
  1785. while (next) {
  1786. if ('file' in next.dataset) {
  1787. break;
  1788. }
  1789. next = next.nextElementSibling;
  1790. }
  1791. }
  1792. }
  1793. if (next) {
  1794. current.classList.remove('playing');
  1795. next.classList.add('playing');
  1796. musicPlayerPlaySong(next);
  1797. } else {
  1798. // End of playlist reached
  1799. if (findNextAlbumCover(current.dataset.albumUrl) === false) {
  1800. const notloaded = player.querySelector('.playlist .playlistheading a.notloaded');
  1801. if (notloaded) {
  1802. // Unloaded albums in playlist
  1803. const url = notloaded.href;
  1804. notloaded.remove();
  1805. cachedTralbumData(url).then(function onCachedTralbumDataLoaded(TralbumData) {
  1806. if (TralbumData) {
  1807. addAlbumToPlaylist(TralbumData);
  1808. } else {
  1809. playAlbumFromUrl(url);
  1810. }
  1811. });
  1812. } else {
  1813. audio.pause();
  1814. audio.currentTime -= 1;
  1815. musicPlayerOnTimeUpdate();
  1816. window.alert('End of playlist reached');
  1817. }
  1818. }
  1819. }
  1820. }
  1821. let ivSlideInNextSong;
  1822. function musicPlayerPlaySong(next, startTime) {
  1823. currentDuration = next.dataset.duration;
  1824. player.querySelector('.durationDisplay .current').innerHTML = '-';
  1825. player.querySelector('.durationDisplay .total').innerHTML = humanDuration(currentDuration);
  1826. audio.src = next.dataset.file;
  1827. if (typeof startTime !== 'undefined' && startTime !== false) {
  1828. audio.currentTime = startTime;
  1829. }
  1830. bufferbar.classList.remove('bufferbaranimation');
  1831. window.setTimeout(function bufferbaranimationWidth() {
  1832. bufferbar.style.width = '0px';
  1833. window.setTimeout(function bufferbaranimationClass() {
  1834. bufferbar.classList.add('bufferbaranimation');
  1835. }, 10);
  1836. }, 0);
  1837. const key = albumKey(next.dataset.albumUrl);
  1838.  
  1839. // Meta
  1840. const currentlyPlaying = document.querySelector('.currentlyPlaying');
  1841. const nextInRow = player.querySelector('.nextInRow');
  1842. nextInRow.querySelector('.cover').href = next.dataset.albumUrl;
  1843. nextInRow.querySelector('.cover img').src = next.dataset.albumCover;
  1844. nextInRow.querySelector('.info .link').href = next.dataset.albumUrl;
  1845. nextInRow.querySelector('.info .title').innerHTML = next.dataset.title;
  1846. nextInRow.querySelector('.info .artist').innerHTML = next.dataset.artist;
  1847. nextInRow.querySelector('.info .album').innerHTML = next.dataset.album;
  1848.  
  1849. // Favicon
  1850. musicPlayerFavicon(next.dataset.albumCover.replace(/_\d.jpg$/, '_3.jpg'));
  1851.  
  1852. // Wishlist
  1853. const collectWishlist = player.querySelector('.collect-wishlist');
  1854. collectWishlist.dataset.albumUrl = next.dataset.albumUrl;
  1855. player.querySelectorAll('.collect-wishlist>*').forEach(function (e) {
  1856. e.style.display = 'none';
  1857. });
  1858. if (next.dataset.isPurchased === 'true') {
  1859. player.querySelector('.collect-wishlist .wishlist-own').style.display = 'inline-block';
  1860. collectWishlist.dataset.wishlist = 'own';
  1861. } else if (next.dataset.inWishlist === 'true') {
  1862. player.querySelector('.collect-wishlist .wishlist-collected').style.display = 'inline-block';
  1863. collectWishlist.dataset.wishlist = 'collected';
  1864. } else {
  1865. // Always show whishlist button for whole album
  1866. player.querySelector('.collect-wishlist .wishlist-add').style.display = 'inline-block';
  1867. player.querySelector('.collect-wishlist .wishlist-add .album').style.display = 'inline';
  1868. collectWishlist.dataset.wishlist = 'add';
  1869. if (next.dataset.isDownloadable === 'true' && next.dataset.trackUrl) {
  1870. // Only show wishlist button for single track if the track is downloadable and there is a track url
  1871. collectWishlist.dataset.trackUrl = next.dataset.trackUrl;
  1872. player.querySelector('.collect-wishlist .wishlist-add .track').style.display = 'inline';
  1873. player.querySelector('.collect-wishlist .wishlist-add .slash').style.display = 'inline';
  1874. } else {
  1875. player.querySelector('.collect-wishlist .wishlist-add .track').style.display = 'none';
  1876. player.querySelector('.collect-wishlist .wishlist-add .slash').style.display = 'none';
  1877. }
  1878. }
  1879.  
  1880. // Played/Listened
  1881. const collectListened = player.querySelector('.collect-listened');
  1882. if (allFeatures.markasplayed.enabled && collectListened) {
  1883. collectListened.dataset.albumUrl = next.dataset.albumUrl;
  1884. player.querySelectorAll('.collect-listened>*').forEach(function (e) {
  1885. e.style.display = 'none';
  1886. });
  1887. GM.getValue('myalbums', '{}').then(function myalbumsLoaded(str) {
  1888. const myalbums = JSON.parse(str);
  1889. if (key in myalbums && 'listened' in myalbums[key] && myalbums[key].listened) {
  1890. player.querySelector('.collect-listened .listened').style.display = 'inline-block';
  1891. const date = new Date(myalbums[key].listened);
  1892. const since = timeSince(date);
  1893. player.querySelector('.collect-listened .listened').title = since + ' ago\nClick to mark as NOT played';
  1894. collectListened.dataset.listened = myalbums[key].listened;
  1895. } else {
  1896. player.querySelector('.collect-listened .mark-listened').style.display = 'inline-block';
  1897. collectListened.dataset.listened = false;
  1898. }
  1899. });
  1900. } else if (collectListened) {
  1901. collectListened.remove();
  1902. }
  1903.  
  1904. // Notification
  1905. if (allFeatures.nextSongNotifications.enabled && 'notification' in GM) {
  1906. GM.notification({
  1907. title: document.location.host,
  1908. text: next.dataset.title + '\nby ' + next.dataset.artist + '\nfrom ' + next.dataset.album,
  1909. image: next.dataset.albumCover,
  1910. highlight: false,
  1911. silent: true,
  1912. timeout: NOTIFICATION_TIMEOUT,
  1913. onclick: musicPlayerNext
  1914. });
  1915. }
  1916.  
  1917. // Media hub
  1918. if ('mediaSession' in navigator) {
  1919. navigator.mediaSession.metadata = new MediaMetadata({
  1920. title: next.dataset.title,
  1921. artist: next.dataset.artist,
  1922. album: next.dataset.album,
  1923. artwork: [{
  1924. src: next.dataset.albumCover,
  1925. sizes: '350x350',
  1926. type: 'image/jpeg'
  1927. }]
  1928. });
  1929. navigator.mediaSession.setActionHandler('previoustrack', musicPlayerPrev);
  1930. navigator.mediaSession.setActionHandler('nexttrack', musicPlayerNext);
  1931. navigator.mediaSession.setActionHandler('play', _ => audio.play());
  1932. navigator.mediaSession.setActionHandler('pause', _ => audio.pause());
  1933. navigator.mediaSession.setActionHandler('seekbackward', function (event) {
  1934. const skipTime = event.seekOffset || DEFAULTSKIPTIME;
  1935. audio.currentTime = Math.max(audio.currentTime - skipTime, 0);
  1936. musicPlayerUpdatePositionState();
  1937. });
  1938. navigator.mediaSession.setActionHandler('seekforward', function (event) {
  1939. const skipTime = event.seekOffset || DEFAULTSKIPTIME;
  1940. audio.currentTime = Math.min(audio.currentTime + skipTime, audio.duration || currentDuration);
  1941. musicPlayerUpdatePositionState();
  1942. });
  1943. try {
  1944. navigator.mediaSession.setActionHandler('stop', _ => musicPlayerClose());
  1945. } catch (error) {
  1946. console.warn('Warning! The "stop" media session action is not supported.');
  1947. }
  1948. try {
  1949. navigator.mediaSession.setActionHandler('seekto', function (event) {
  1950. if (event.fastSeek && 'fastSeek' in audio) {
  1951. audio.fastSeek(event.seekTime);
  1952. return;
  1953. }
  1954. audio.currentTime = event.seekTime;
  1955. musicPlayerUpdatePositionState();
  1956. });
  1957. } catch (error) {
  1958. console.warn('Warning! The "seekto" media session action is not supported.');
  1959. }
  1960. }
  1961.  
  1962. // Download link
  1963. const downloadLink = player.querySelector('.downloadlink');
  1964. if (allFeatures.discographyplayerDownloadLink.enabled) {
  1965. downloadLink.href = next.dataset.file;
  1966. downloadLink.download = (next.dataset.trackNumber > 9 ? '' : '0') + next.dataset.trackNumber + '. ' + fixFilename(next.dataset.artist + ' - ' + next.dataset.title) + '.mp3';
  1967. downloadLink.style.display = 'block';
  1968. } else {
  1969. downloadLink.style.display = 'none';
  1970. }
  1971.  
  1972. // Show "playing" indication on album covers
  1973. let coverLinkPattern = albumPath(next.dataset.albumUrl);
  1974. if (document.location.href.split('.')[0] !== next.dataset.albumUrl.split('.')[0]) {
  1975. /*
  1976. Subdomain is different from album subdomain -> multiple artists on this page, use full url to detect albums.
  1977. Otherwise albums with the same name but a different artist name will be highlighted.
  1978. This would happen quite often on search results.
  1979. */
  1980. coverLinkPattern = albumKey(next.dataset.albumUrl);
  1981. }
  1982. document.querySelectorAll('img.albumIsCurrentlyPlaying').forEach(img => img.classList.remove('albumIsCurrentlyPlaying'));
  1983. document.querySelectorAll('.albumIsCurrentlyPlayingIndicator').forEach(div => div.remove());
  1984. document.querySelectorAll('a[href*="' + coverLinkPattern + '"] img,.info>a[href*="' + coverLinkPattern + '"]').forEach(function (img) {
  1985. let node = img;
  1986. while (node) {
  1987. if (node.id === 'discographyplayer') {
  1988. return;
  1989. }
  1990. if (node === document.body) {
  1991. break;
  1992. }
  1993. node = node.parentNode;
  1994. }
  1995. if (img.tagName === 'A') {
  1996. img = img.parentNode.parentNode.querySelector('.art img');
  1997. }
  1998. img.classList.add('albumIsCurrentlyPlaying');
  1999. if (!img.parentNode.querySelector('.albumIsCurrentlyPlayingIndicator')) {
  2000. const indicator = img.parentNode.appendChild(document.createElement('div'));
  2001. indicator.classList.add('albumIsCurrentlyPlayingIndicator');
  2002. indicator.addEventListener('click', function (ev) {
  2003. ev.preventDefault();
  2004. ev.stopPropagation();
  2005. if (!musicPlayerPlay()) {
  2006. // Album is now paused -> Remove indicators
  2007. document.querySelectorAll('img.albumIsCurrentlyPlaying').forEach(img => img.classList.remove('albumIsCurrentlyPlaying'));
  2008. document.querySelectorAll('.albumIsCurrentlyPlayingIndicator').forEach(div => div.remove());
  2009. }
  2010. });
  2011. indicator.appendChild(document.createElement('div')).classList.add('currentlyPlayingBg');
  2012. indicator.appendChild(document.createElement('div')).classList.add('currentlyPlayingIcon');
  2013. }
  2014. });
  2015.  
  2016. // Animate
  2017. if (allFeatures.discographyplayerSidebar.enabled && window.matchMedia('(min-width: 1600px)').matches) {
  2018. // Slide up
  2019. currentlyPlaying.style.marginTop = -parseInt(currentlyPlaying.clientHeight + 1) + 'px';
  2020. nextInRow.style.height = '99%';
  2021. nextInRow.style.width = '99%';
  2022. window.clearTimeout(ivSlideInNextSong);
  2023. ivSlideInNextSong = window.setTimeout(function slideInSongInterval() {
  2024. currentlyPlaying.remove();
  2025. const clone = nextInRow.cloneNode(true);
  2026. clone.style.height = '0%';
  2027. clone.className = 'nextInRow';
  2028. nextInRow.className = 'currentlyPlaying';
  2029. nextInRow.parentNode.appendChild(clone);
  2030. }, 600);
  2031. } else {
  2032. // Slide to the left
  2033. currentlyPlaying.style.marginLeft = -parseInt(currentlyPlaying.clientWidth + 1) + 'px';
  2034. nextInRow.style.height = '99%';
  2035. nextInRow.style.width = '99%';
  2036. window.clearTimeout(ivSlideInNextSong);
  2037. ivSlideInNextSong = window.setTimeout(function slideInSongInterval() {
  2038. currentlyPlaying.remove();
  2039. const clone = nextInRow.cloneNode(true);
  2040. clone.style.width = '0%';
  2041. clone.className = 'nextInRow';
  2042. nextInRow.className = 'currentlyPlaying';
  2043. nextInRow.parentNode.appendChild(clone);
  2044. }, 7 * 1000);
  2045. }
  2046. window.setTimeout(() => player.querySelector('.playlist .playing').scrollIntoView({
  2047. block: 'nearest'
  2048. }), 200);
  2049. }
  2050. function musicPlayerPlay() {
  2051. if (audio.paused) {
  2052. audio.play().then(_ => musicPlayerUpdatePositionState());
  2053. musicPlayerCookieChannelSendStop();
  2054. return true;
  2055. } else {
  2056. audio.pause();
  2057. document.querySelectorAll('img.albumIsCurrentlyPlaying').forEach(img => img.classList.remove('albumIsCurrentlyPlaying'));
  2058. document.querySelectorAll('.albumIsCurrentlyPlayingIndicator').forEach(div => div.remove());
  2059. return false;
  2060. }
  2061. }
  2062. function musicPlayerStop() {
  2063. if (!audio.paused) {
  2064. audio.pause();
  2065. }
  2066. }
  2067. function musicPlayerPrev() {
  2068. musicPlayerShowBusy();
  2069. const current = player.querySelector('.playlist .playing');
  2070. let prev = current.previousElementSibling;
  2071. while (prev) {
  2072. if ('file' in prev.dataset) {
  2073. break;
  2074. }
  2075. prev = prev.previousElementSibling;
  2076. }
  2077. if (prev) {
  2078. musicPlayerNextSong(prev);
  2079. }
  2080. }
  2081. function musicPlayerNext() {
  2082. musicPlayerShowBusy();
  2083. musicPlayerNextSong();
  2084. }
  2085. function musicPlayerPrevAlbum() {
  2086. audio.pause();
  2087. window.setTimeout(function musicPlayerPrevAlbumTimeout() {
  2088. musicPlayerShowBusy();
  2089. const url = player.querySelector('.playlist .playing').dataset.albumUrl;
  2090. if (!findPreviousAlbumCover(url)) {
  2091. // Find previous album in playlist
  2092. let prev = false;
  2093. const as = player.querySelectorAll('.playlist .playlistheading a');
  2094. for (let i = 0; i < as.length; i++) {
  2095. if (albumKey(as[i].href) === albumKey(url)) {
  2096. if (i > 0) {
  2097. prev = as[i - 1];
  2098. }
  2099. break;
  2100. }
  2101. }
  2102. if (prev) {
  2103. prev.parentNode.click();
  2104. } else {
  2105. // Just play first song in playlist
  2106. player.querySelector('.playlist .playlistentry').click();
  2107. }
  2108. }
  2109. }, 10);
  2110. }
  2111. function musicPlayerNextAlbum() {
  2112. audio.pause();
  2113. window.setTimeout(function musicPlayerNextAlbumTimeout() {
  2114. musicPlayerShowBusy();
  2115. const r = findNextAlbumCover(player.querySelector('.playlist .playing').dataset.albumUrl);
  2116. if (r === false) {
  2117. // Find next album in playlist
  2118. let reachedPlaying = false;
  2119. let found = false;
  2120. const lis = player.querySelectorAll('.playlist li');
  2121. for (let i = 0; i < lis.length; i++) {
  2122. if (reachedPlaying && lis[i].classList.contains('playlistheading')) {
  2123. lis[i].click();
  2124. found = true;
  2125. break;
  2126. } else if (lis[i].classList.contains('playing')) {
  2127. reachedPlaying = true;
  2128. }
  2129. }
  2130. if (!found) {
  2131. audio.play().then(_ => musicPlayerUpdatePositionState());
  2132. window.alert('End of playlist reached');
  2133. }
  2134. }
  2135. }, 10);
  2136. }
  2137. function musicPlayerToggleShuffle() {
  2138. player.querySelector('.shufflebutton').classList.toggle('active');
  2139. if (player.querySelector('.shufflebutton').classList.contains('active')) {
  2140. if (!window.confirm('Would you like to shuffle all albums on this page?\n\n(It may take several minutes to load all albums into the playlist)')) {
  2141. return;
  2142. }
  2143.  
  2144. // Load all albums from page into the player
  2145. addAllAlbumsAsHeadings();
  2146.  
  2147. // Load unloaded items in playlist
  2148. let delay = 0;
  2149. // Disable permanent storage for speed
  2150. storeTralbumDataPermanentlySwitch = false;
  2151. let n = player.querySelectorAll('.playlist .playlistheading a.notloaded').length + 1;
  2152. if (n > 0) {
  2153. const queueLoadingIndicator = document.body.appendChild(document.createElement('div'));
  2154. queueLoadingIndicator.setAttribute('id', 'queueloadingindicator');
  2155. queueLoadingIndicator.style = 'position:fixed;top:1%;left:10px;background:#d5dce4;color:#033162;font-size:10pt;border:1px solid #033162;z-index:200;';
  2156. }
  2157. const updateLoadingIndicator = function () {
  2158. const div = document.getElementById('queueloadingindicator');
  2159. if (div) {
  2160. div.innerHTML = `Loading albums into playlist. ${--n} albums remaining...`;
  2161. if (n <= 0) {
  2162. div.remove();
  2163. storeTralbumDataPermanentlySwitch = allFeatures.keepLibrary.enabled;
  2164. }
  2165. }
  2166. };
  2167. window.setTimeout(updateLoadingIndicator, 1);
  2168. player.querySelectorAll('.playlist .playlistheading a.notloaded').forEach(async function (notloaded) {
  2169. const url = notloaded.href;
  2170. notloaded.remove();
  2171. cachedTralbumData(url).then(function onCachedTralbumDataLoaded(TralbumData) {
  2172. if (TralbumData) {
  2173. addAlbumToPlaylist(TralbumData, null);
  2174. window.setTimeout(updateLoadingIndicator, 10);
  2175. } else {
  2176. // Delay to avoid rate limit
  2177. window.setTimeout(() => playAlbumFromUrl(url, null).then(updateLoadingIndicator), delay * 1000);
  2178. delay += 4;
  2179. }
  2180. });
  2181. });
  2182. }
  2183. }
  2184. function musicPlayerOnTimelineClick(ev) {
  2185. musicPlayerMovePlayHead(ev);
  2186. const timelineWidth = timeline.offsetWidth - playhead.offsetWidth;
  2187. const clickPercent = (ev.clientX - timeline.getBoundingClientRect().left) / timelineWidth;
  2188. audio.currentTime = currentDuration * clickPercent;
  2189. }
  2190. function musicPlayerOnTimeUpdate() {
  2191. const playpause = player.querySelector('.playpause');
  2192. const timelineWidth = timeline.offsetWidth - playhead.offsetWidth;
  2193. const playPercent = timelineWidth * (audio.currentTime / currentDuration);
  2194. playhead.style.marginLeft = playPercent + 'px';
  2195. if (audio.currentTime === currentDuration) {
  2196. playpause.querySelector('.play').style.display = 'none';
  2197. playpause.querySelector('.busy').style.display = '';
  2198. playpause.querySelector('.pause').style.display = 'none';
  2199. if ('mediaSession' in navigator) {
  2200. navigator.mediaSession.playbackState = 'none';
  2201. }
  2202. } else if (audio.paused) {
  2203. playpause.querySelector('.play').style.display = '';
  2204. playpause.querySelector('.busy').style.display = 'none';
  2205. playpause.querySelector('.pause').style.display = 'none';
  2206. if (document.title.startsWith('\u25B6\uFE0E ')) {
  2207. document.title = document.title.substring(3);
  2208. }
  2209. if ('mediaSession' in navigator) {
  2210. navigator.mediaSession.playbackState = 'paused';
  2211. }
  2212. } else {
  2213. playpause.querySelector('.play').style.display = 'none';
  2214. playpause.querySelector('.busy').style.display = 'none';
  2215. playpause.querySelector('.pause').style.display = '';
  2216. if (!document.title.startsWith('\u25B6\uFE0E ')) {
  2217. document.title = '\u25B6\uFE0E ' + document.title;
  2218. }
  2219. if ('mediaSession' in navigator) {
  2220. navigator.mediaSession.playbackState = 'playing';
  2221. }
  2222. }
  2223. player.querySelector('.durationDisplay .current').innerHTML = humanDuration(audio.currentTime);
  2224. }
  2225. function musicPlayerUpdateBufferBar() {
  2226. if (currentDuration) {
  2227. if (audio.buffered.length > 0) {
  2228. bufferbar.style.width = Math.min(100, 1 + parseInt(100 * audio.buffered.end(0) / currentDuration)) + '%';
  2229. } else {
  2230. bufferbar.style.width = '100%';
  2231. }
  2232. } else {
  2233. bufferbar.style.width = '0px';
  2234. }
  2235. }
  2236. function musicPlayerShowBusy(ev) {
  2237. const playpause = player.querySelector('.playpause');
  2238. playpause.querySelector('.play').style.display = 'none';
  2239. playpause.querySelector('.busy').style.display = '';
  2240. playpause.querySelector('.pause').style.display = 'none';
  2241. }
  2242. function musicPlayerMovePlayHead(event) {
  2243. const newMargLeft = event.clientX - timeline.getBoundingClientRect().left;
  2244. const timelineWidth = timeline.offsetWidth - playhead.offsetWidth;
  2245. if (newMargLeft >= 0 && newMargLeft <= timelineWidth) {
  2246. playhead.style.marginLeft = newMargLeft + 'px';
  2247. }
  2248. if (newMargLeft < 0) {
  2249. playhead.style.marginLeft = '0px';
  2250. }
  2251. if (newMargLeft > timelineWidth) {
  2252. playhead.style.marginLeft = timelineWidth + 'px';
  2253. }
  2254. }
  2255. function musicPlayerOnPlayheadMouseDown() {
  2256. onPlayHead = true;
  2257. window.addEventListener('mousemove', musicPlayerMovePlayHead, true);
  2258. audio.removeEventListener('timeupdate', musicPlayerOnTimeUpdate, false);
  2259. }
  2260. function musicPlayerOnPlayheadMouseUp(event) {
  2261. if (onPlayHead) {
  2262. musicPlayerMovePlayHead(event);
  2263. window.removeEventListener('mousemove', musicPlayerMovePlayHead, true);
  2264. // change current time
  2265. const timelineWidth = timeline.offsetWidth - playhead.offsetWidth;
  2266. const clickPercent = (event.clientX - timeline.getBoundingClientRect().left) / timelineWidth;
  2267. audio.currentTime = currentDuration * clickPercent;
  2268. audio.addEventListener('timeupdate', musicPlayerOnTimeUpdate, false);
  2269. }
  2270. onPlayHead = false;
  2271. }
  2272. function musicPlayerOnVolumeClick(ev) {
  2273. const volSlider = player.querySelector('.vol-slider');
  2274. const sliderWidth = volSlider.offsetWidth;
  2275. const percent = (ev.clientX - volSlider.getBoundingClientRect().left) / sliderWidth;
  2276. audio.logVolume = percent > 0.9 ? 1.0 : percent;
  2277. GM.setValue('volume', audio.logVolume);
  2278. }
  2279. function musicPlayerOnVolumeWheel(ev) {
  2280. ev.preventDefault();
  2281. const direction = Math.min(Math.max(-1.0, ev.deltaY), 1.0);
  2282. audio.logVolume = Math.min(Math.max(0.0, audio.logVolume - 0.05 * direction), 1.0);
  2283. GM.setValue('volume', audio.logVolume);
  2284. }
  2285. function musicPlayerOnMuteClick(ev) {
  2286. if (audio.logVolume < 0.01) {
  2287. if ('lastvolume' in audio.dataset && audio.dataset.lastvolume) {
  2288. audio.logVolume = audio.dataset.lastvolume;
  2289. GM.setValue('volume', audio.logVolume);
  2290. } else {
  2291. audio.logVolume = 1.0;
  2292. }
  2293. } else {
  2294. audio.dataset.lastvolume = audio.logVolume;
  2295. audio.logVolume = 0.0;
  2296. }
  2297. }
  2298. function musicPlayerOnVolumeChanged(ev) {
  2299. let icons;
  2300. if (NOEMOJI) {
  2301. const muteIcon = `<img style="width:20px" src="${speakerIconMuteSrc}" alt="\uD83D\uDD07">`;
  2302. const lowIcon = `<img style="width:20px" src="${speakerIconLowSrc}" alt="\uD83D\uDD07">`;
  2303. const middleIcon = `<img style="width:20px" src="${speakerIconMiddleSrc}" alt="\uD83D\uDD07">`;
  2304. const highIcon = `<img style="width:20px" src="${speakerIconHighSrc}" alt="\uD83D\uDD07">`;
  2305. icons = [muteIcon, lowIcon, middleIcon, highIcon];
  2306. } else {
  2307. icons = ['\uD83D\uDD07', '\uD83D\uDD08', '\uD83D\uDD09', '\uD83D\uDD0A'];
  2308. }
  2309. const percent = audio.logVolume;
  2310. const volSlider = player.querySelector('.vol-slider');
  2311. volSlider.querySelector('.vol-amt').style.width = parseInt(100 * percent) + '%';
  2312. const volIconWrapper = player.querySelector('.vol-icon-wrapper');
  2313. volIconWrapper.title = 'Mute (' + parseInt(percent * 100) + '%)';
  2314. if (percent < 0.05) {
  2315. volIconWrapper.innerHTML = icons[0];
  2316. } else if (percent < 0.3) {
  2317. volIconWrapper.innerHTML = icons[1];
  2318. } else if (percent < 0.8) {
  2319. volIconWrapper.innerHTML = icons[2];
  2320. } else {
  2321. volIconWrapper.innerHTML = icons[3];
  2322. }
  2323. }
  2324. function musicPlayerOnEnded(ev) {
  2325. musicPlayerNextSong();
  2326. window.setTimeout(() => player.querySelector('.playlist .playing').scrollIntoView({
  2327. block: 'nearest'
  2328. }), 200);
  2329. }
  2330. function musicPlayerOnPlaylistClick(ev, contextMenuRoot) {
  2331. const li = this;
  2332. if (ev.ctrlKey && player.querySelector('.playlist .isselected')) {
  2333. // Select multiple with ctrlKey
  2334. ev.preventDefault();
  2335. musicPlayerContextMenuCtrl.call(li, ev);
  2336. return;
  2337. }
  2338. if (ev.shiftKey && musicPlayerContextMenuLastSelectedLi && musicPlayerContextMenuLastSelectedLi.classList.contains('isselected')) {
  2339. // Select multiple with shift key
  2340. ev.preventDefault();
  2341. if (musicPlayerContextMenuShift.call(li, ev)) {
  2342. return;
  2343. }
  2344. }
  2345. musicPlayerNextSong(li);
  2346. if (contextMenuRoot) {
  2347. contextMenuRoot.remove();
  2348. }
  2349. }
  2350. function removeSelectedFromPlaylist(ev, contextMenuRoot) {
  2351. player.querySelectorAll('.playlist .isselected').forEach(function (li) {
  2352. if (li.classList.contains('playlistentry')) {
  2353. let walk = li.previousElementSibling;
  2354. let remainingTrackN = 0;
  2355. while (walk.classList.contains('playlistentry')) {
  2356. remainingTrackN++;
  2357. walk = walk.previousElementSibling;
  2358. }
  2359. walk = li.nextElementSibling;
  2360. while (walk.classList.contains('playlistentry')) {
  2361. remainingTrackN++;
  2362. walk = walk.nextElementSibling;
  2363. }
  2364. if (remainingTrackN === 0) {
  2365. // If this is last song of album, then remove also album
  2366. walk = li.previousElementSibling;
  2367. while (walk) {
  2368. if (walk.classList.contains('playlistheading')) {
  2369. walk.remove();
  2370. break;
  2371. }
  2372. walk = walk.previousElementSibling;
  2373. }
  2374. }
  2375. // Remove track
  2376. li.remove();
  2377. } else {
  2378. // Remove album
  2379. let next = li.nextElementSibling;
  2380. while (next && next.classList.contains('playlistentry')) {
  2381. next.remove();
  2382. next = li.nextElementSibling;
  2383. }
  2384. li.remove();
  2385. }
  2386. });
  2387. if (contextMenuRoot) {
  2388. contextMenuRoot.remove();
  2389. }
  2390. }
  2391. function musicPlayerOnPlaylistHeadingClick(ev, contextMenuRoot) {
  2392. const li = this;
  2393. const a = li.querySelector('a[href]');
  2394. if (a && a.classList.contains('notloaded')) {
  2395. const url = a.href;
  2396. cachedTralbumData(url).then(function onCachedTralbumDataLoaded(TralbumData) {
  2397. li.remove();
  2398. if (TralbumData) {
  2399. addAlbumToPlaylist(TralbumData);
  2400. } else {
  2401. playAlbumFromUrl(url);
  2402. }
  2403. });
  2404. } else if (a && li.nextElementSibling) {
  2405. li.nextElementSibling.click();
  2406. }
  2407. if (contextMenuRoot) {
  2408. contextMenuRoot.remove();
  2409. }
  2410. }
  2411. let musicPlayerContextMenuLastSelectedLi = null;
  2412. function musicPlayerContextMenuCtrl(ev) {
  2413. const li = this;
  2414. li.classList.toggle('isselected');
  2415. if (li.classList.contains('isselected')) {
  2416. musicPlayerContextMenuLastSelectedLi = li;
  2417. }
  2418. }
  2419. function musicPlayerContextMenuShift(ev) {
  2420. const li = this;
  2421. // Find the last selected element (i.e. in which direction we need to go)
  2422. let dir = 0;
  2423. let walk = li.previousElementSibling;
  2424. while (walk && dir === 0) {
  2425. if (walk === musicPlayerContextMenuLastSelectedLi) {
  2426. dir = -1;
  2427. }
  2428. walk = walk.previousElementSibling;
  2429. }
  2430. walk = li.nextElementSibling;
  2431. while (walk && dir === 0) {
  2432. if (walk === musicPlayerContextMenuLastSelectedLi) {
  2433. dir = 1;
  2434. break;
  2435. }
  2436. walk = walk.nextElementSibling;
  2437. }
  2438. // Select every track in-between
  2439. if (dir === -1) {
  2440. walk = li.previousElementSibling;
  2441. while (walk !== musicPlayerContextMenuLastSelectedLi) {
  2442. if (walk.classList.contains('playlistentry')) {
  2443. walk.classList.add('isselected');
  2444. }
  2445. walk = walk.previousElementSibling;
  2446. }
  2447. li.classList.add('isselected');
  2448. return true;
  2449. } else if (dir === 1) {
  2450. walk = li.nextElementSibling;
  2451. while (walk !== musicPlayerContextMenuLastSelectedLi) {
  2452. if (walk.classList.contains('playlistentry')) {
  2453. walk.classList.add('isselected');
  2454. }
  2455. walk = walk.nextElementSibling;
  2456. }
  2457. li.classList.add('isselected');
  2458. return true;
  2459. } else {
  2460. return false;
  2461. }
  2462. }
  2463. function musicPlayerContextMenu(ev) {
  2464. const li = this;
  2465. if (ev.ctrlKey && player.querySelector('.playlist .isselected')) {
  2466. // Select multiple with ctrl key
  2467. musicPlayerContextMenuCtrl.call(li, ev);
  2468. return;
  2469. }
  2470. if (ev.shiftKey && musicPlayerContextMenuLastSelectedLi && musicPlayerContextMenuLastSelectedLi.classList.contains('isselected')) {
  2471. // Select multiple with shift key
  2472. if (musicPlayerContextMenuShift.call(li, ev)) {
  2473. return;
  2474. }
  2475. }
  2476. player.querySelectorAll('.playlist .isselected').forEach(e => e.classList.remove('isselected'));
  2477. const oldMenu = document.getElementById('discographyplayer_contextmenu');
  2478. if (oldMenu) {
  2479. removeViaQuerySelector('#discographyplayer_contextmenu');
  2480. if (li.dataset.id && li.dataset.id === oldMenu.dataset.id) {
  2481. return;
  2482. }
  2483. }
  2484. li.classList.add('isselected');
  2485. musicPlayerContextMenuLastSelectedLi = li;
  2486. const div = document.body.appendChild(document.createElement('div'));
  2487. li.dataset.id = Math.random();
  2488. div.dataset.id = li.dataset.id;
  2489. div.setAttribute('id', 'discographyplayer_contextmenu');
  2490. div.style.left = ev.pageX + 11 + 'px';
  2491. div.style.top = ev.pageY + 'px';
  2492. const menuEntries = [];
  2493. if (li.classList.contains('playlistentry') || li.classList.contains('playlistheading')) {
  2494. menuEntries.push(['Remove selected', 'Remove selected tracks or albums from playlist\nSelect more with CTRL + Right click', removeSelectedFromPlaylist]);
  2495. }
  2496. if (li.classList.contains('playlistentry')) {
  2497. menuEntries.push(['Play track', 'Start playback', musicPlayerOnPlaylistClick]);
  2498. }
  2499. if (li.classList.contains('playlistheading')) {
  2500. menuEntries.push(['Play album', 'Start playback', musicPlayerOnPlaylistHeadingClick]);
  2501. }
  2502. menuEntries.forEach(function (menuEntry) {
  2503. const subMenu = div.appendChild(document.createElement('div'));
  2504. subMenu.classList.add('contextmenu_submenu');
  2505. subMenu.appendChild(document.createTextNode(menuEntry[0]));
  2506. subMenu.setAttribute('title', menuEntry[1]);
  2507. subMenu.addEventListener('click', function (clickEvent) {
  2508. menuEntry[2].call(li, clickEvent, div);
  2509. });
  2510. });
  2511. }
  2512. function musicPlayerOnPlaylistContextMenu(ev) {
  2513. ev.preventDefault();
  2514. musicPlayerContextMenu.call(this, ev);
  2515. }
  2516. function musicPlayerOnPlaylistHeadingContextMenu(ev) {
  2517. ev.preventDefault();
  2518. musicPlayerContextMenu.call(this, ev);
  2519. }
  2520. function musicPlayerFavicon(url) {
  2521. removeViaQuerySelector(document.head, 'link[rel*=icon]');
  2522. const link = document.createElement('link');
  2523. link.type = 'image/x-icon';
  2524. link.rel = 'shortcut icon';
  2525. link.href = url;
  2526. document.head.appendChild(link);
  2527. }
  2528. function musicPlayerCollectWishlistClick(ev) {
  2529. ev.preventDefault();
  2530. if (player.querySelector('.collect-wishlist').dataset === 'own') {
  2531. return;
  2532. }
  2533. let url = player.querySelector('.collect-wishlist').dataset.albumUrl;
  2534. if (this.classList.contains('track') && player.querySelector('.collect-wishlist').dataset.trackUrl) {
  2535. // Wishlist track
  2536. url = player.querySelector('.collect-wishlist').dataset.trackUrl;
  2537. }
  2538. player.querySelectorAll('.collect-wishlist>*').forEach(function (e) {
  2539. e.style.display = 'none';
  2540. });
  2541. window.open(url + '#collect-wishlist');
  2542. }
  2543. async function musicPlayerCollectListenedClick(ev) {
  2544. ev.preventDefault();
  2545. const collectListened = player.querySelector('.collect-listened');
  2546. const url = collectListened.dataset.albumUrl;
  2547. window.setTimeout(function musicPlayerCollectListenedResetTimeout() {
  2548. player.querySelectorAll('.collect-listened>*').forEach(function (e) {
  2549. e.style.display = 'none';
  2550. });
  2551. player.querySelector('.collect-listened .listened-saving').style.display = 'inline-block';
  2552. player.querySelector('.collect-listened').style.cursor = 'wait';
  2553. }, 0);
  2554. let albumData = await myAlbumsGetAlbum(url);
  2555. if (!albumData) {
  2556. albumData = await myAlbumsNewFromUrl(url, {});
  2557. }
  2558. if (albumData.listened) {
  2559. albumData.listened = false;
  2560. } else {
  2561. albumData.listened = new Date().toJSON();
  2562. }
  2563. collectListened.dataset.listened = albumData.listened;
  2564. await myAlbumsUpdateAlbum(albumData);
  2565. player.querySelectorAll('.collect-listened>*').forEach(function (e) {
  2566. e.style.display = 'none';
  2567. });
  2568. if (albumData.listened) {
  2569. player.querySelector('.collect-listened .listened').style.display = 'inline-block';
  2570. } else {
  2571. player.querySelector('.collect-listened .mark-listened').style.display = 'inline-block';
  2572. }
  2573. player.querySelector('.collect-listened').style.cursor = '';
  2574. window.setTimeout(makeAlbumLinksGreat, 100);
  2575. }
  2576. function musicPlayerUpdatePositionState() {
  2577. if ('mediaSession' in navigator && 'setPositionState' in navigator.mediaSession) {
  2578. navigator.mediaSession.setPositionState({
  2579. duration: audio.duration || currentDuration || 180,
  2580. playbackRate: audio.playbackRate,
  2581. position: audio.currentTime
  2582. });
  2583. }
  2584. }
  2585. function musicPlayerCookieChannel(onStopEventCb) {
  2586. if (!BANDCAMPDOMAIN) {
  2587. return;
  2588. }
  2589. window.addEventListener('message', function onMessage(event) {
  2590. // Receive messages from the cookie channel event handler
  2591. if (event.origin === document.location.protocol + '//' + document.location.hostname && event.data && typeof event.data === 'object' && 'discographyplayerCookiechannelPlaylist' in event.data && event.data.discographyplayerCookiechannelPlaylist.length >= 2 && event.data.discographyplayerCookiechannelPlaylist[1] === 'stop') {
  2592. onStopEventCb(event.data.discographyplayerCookiechannelPlaylist);
  2593. }
  2594. });
  2595. const script = document.createElement('script');
  2596. script.innerHTML = `
  2597. if(typeof Cookie !== 'undefined') {
  2598. var channel = new Cookie.CommChannel('playlist')
  2599. channel.send('stop')
  2600. channel.subscribe(function(a,b) {
  2601. window.postMessage({'discographyplayerCookiechannelPlaylist': b}, document.location.href)
  2602. })
  2603. channel.startListening()
  2604. window.addEventListener('message', function onMessage (event) {
  2605. // Receive messages from the user script
  2606. if (event.origin === document.location.protocol + '//' + document.location.hostname
  2607. && event.data && typeof(event.data) === 'object' && 'discographyplayerCookiechannelPlaylist' in event.data
  2608. && event.data.discographyplayerCookiechannelPlaylist === 'sendstop') {
  2609. channel.send('stop')
  2610. }
  2611. })
  2612. window.addEventListener('unload', function(event) {
  2613. channel.cleanup()
  2614. })
  2615. }
  2616. `;
  2617. document.head.appendChild(script);
  2618. }
  2619. function musicPlayerCookieChannelSendStop(onStopEventCb) {
  2620. if (BANDCAMPDOMAIN) {
  2621. window.postMessage({
  2622. discographyplayerCookiechannelPlaylist: 'sendstop'
  2623. }, document.location.href);
  2624. }
  2625. }
  2626. function musicPlayerSaveState() {
  2627. // Add remaining albums as headings
  2628. addAllAlbumsAsHeadings();
  2629. // Remove context menu and selection, we don't want to restore those
  2630. player.querySelectorAll('.playlist .isselected').forEach(e => e.classList.remove('isselected'));
  2631. removeViaQuerySelector('#discographyplayer_contextmenu');
  2632. let startPlaybackIndex = false;
  2633. const playlistEntries = player.querySelectorAll('.playlist .playlistentry');
  2634. for (let i = 0; i < playlistEntries.length; i++) {
  2635. if (playlistEntries[i].classList.contains('playing')) {
  2636. startPlaybackIndex = i;
  2637. break;
  2638. }
  2639. }
  2640. const startPlaybackTime = audio.currentTime;
  2641. return GM.setValue('musicPlayerState', JSON.stringify({
  2642. time: new Date().getTime(),
  2643. htmlPlaylist: player.querySelector('.playlist').innerHTML,
  2644. startPlayback: !audio.paused,
  2645. startPlaybackIndex,
  2646. startPlaybackTime,
  2647. shuffleActive: player.querySelector('.shufflebutton').classList.contains('active')
  2648. }));
  2649. }
  2650. function musicPlayerRestoreState(state) {
  2651. if (!allFeatures.discographyplayerPersist.enabled) {
  2652. return;
  2653. }
  2654. if (state.time + 1000 * 30 < new Date().getTime()) {
  2655. // Saved state expires after 30 seconds
  2656. return;
  2657. }
  2658.  
  2659. // Re-create music player
  2660. musicPlayerCreate();
  2661. player.querySelector('.playlist').innerHTML = state.htmlPlaylist;
  2662. const playlistEntries = player.querySelectorAll('.playlist .playlistentry');
  2663. playlistEntries.forEach(function addPlaylistEntryOnClick(li) {
  2664. li.addEventListener('click', musicPlayerOnPlaylistClick);
  2665. li.addEventListener('contextmenu', musicPlayerOnPlaylistContextMenu);
  2666. });
  2667. player.querySelectorAll('.playlist .playlistheading').forEach(function addPlaylistHeadingEntryOnClick(li) {
  2668. li.addEventListener('click', musicPlayerOnPlaylistHeadingClick);
  2669. li.addEventListener('contextmenu', musicPlayerOnPlaylistHeadingContextMenu);
  2670. });
  2671. if (state.startPlaybackIndex !== false) {
  2672. player.querySelectorAll('.playlist .playing').forEach(function (el) {
  2673. el.classList.remove('playing');
  2674. });
  2675. playlistEntries[state.startPlaybackIndex].classList.add('playing');
  2676. window.setTimeout(() => player.querySelector('.playlist .playing').scrollIntoView({
  2677. block: 'nearest'
  2678. }), 200);
  2679. }
  2680. // Start playback
  2681. if (state.startPlayback && state.startPlaybackIndex !== false) {
  2682. musicPlayerPlaySong(playlistEntries[state.startPlaybackIndex], state.startPlaybackTime);
  2683. }
  2684. if ('shuffleActive' in state && state.shuffleActive) {
  2685. player.querySelector('.shufflebutton').classList.add('active');
  2686. }
  2687. }
  2688. function musicPlayerToggleMinimize(ev, hide) {
  2689. if (hide || player.style.bottom !== '-57px') {
  2690. player.style.bottom = '-57px';
  2691. this.classList.add('minimized');
  2692. } else {
  2693. player.style.bottom = '0px';
  2694. this.classList.remove('minimized');
  2695. }
  2696. }
  2697. function musicPlayerPlaylistFullHeight() {
  2698. // Extend the playlist to the full height of the window
  2699. if ('mode' in this.dataset && this.dataset.mode === 'full_height') {
  2700. // Already in full height mode
  2701. return;
  2702. }
  2703. // Store width so it does not change on multiple mouse-overs
  2704. this.dataset.mode = 'full_height';
  2705. let width = this.clientWidth;
  2706. if ('width' in this.dataset) {
  2707. width = this.dataset.width;
  2708. } else {
  2709. this.dataset.width = width;
  2710. }
  2711. // Set CSS to full height
  2712. this.style.position = 'fixed';
  2713. this.style.maxHeight = '100%';
  2714. this.style.height = '100%';
  2715. this.style.maxWidth = `${width}px`;
  2716. this.style.width = `${width}px`;
  2717. this.style.top = '0px';
  2718. }
  2719. function musicPlayerPlaylistNormalHeight() {
  2720. // Revert the playlist to the normal height of the discography player
  2721. if ('mode' in this.dataset && this.dataset.mode !== 'full_height') {
  2722. // Already in normal height mode
  2723. return;
  2724. }
  2725. if (document.getElementById('discographyplayer_contextmenu')) {
  2726. // Context menu is open, don't change the height
  2727. return;
  2728. }
  2729. this.dataset.mode = 'normal';
  2730.  
  2731. // Revert CSS
  2732. this.style.position = '';
  2733. this.style.maxHeight = '';
  2734. this.style.maxWidth = '';
  2735. this.style.top = '';
  2736. }
  2737. function musicPlayerClose() {
  2738. if (player) {
  2739. player.style.display = 'none';
  2740. }
  2741. if (audio) {
  2742. audio.pause();
  2743. }
  2744. document.querySelectorAll('img.albumIsCurrentlyPlaying').forEach(img => img.classList.remove('albumIsCurrentlyPlaying'));
  2745. document.querySelectorAll('.albumIsCurrentlyPlayingIndicator').forEach(div => div.remove());
  2746. }
  2747. function musicPlayerCreate() {
  2748. if (player) {
  2749. player.style.display = 'block';
  2750. return;
  2751. }
  2752. musicPlayerCookieChannel(_ => musicPlayerStop());
  2753. const img1px = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mOsmLZvJgAFwQJn5VVZ5QAAAABJRU5ErkJggg==';
  2754. const listenedListUrl = findUserProfileUrl() + '#listened-tab';
  2755. const checkSymbol = NOEMOJI ? '✓' : '✔';
  2756. player = document.createElement('div');
  2757. document.body.appendChild(player);
  2758. player.id = 'discographyplayer';
  2759. player.innerHTML = `
  2760. <div class="col col25 nowPlaying">
  2761. <div class="currentlyPlaying">
  2762. <a class="cover" target="_blank" href="#">
  2763. <img src="${img1px}">
  2764. </a>
  2765. <div class="info">
  2766. <a class="link" target="_blank" href="#">
  2767. <div class="title">◧◩◨▧■□▩</div>
  2768. <div class="artist">by <span>◩▧◧□ ◩◨▧ ■◩▩</span></div>
  2769. <div>from <span class="album">◨■■▩ ▧◨□</span></div>
  2770. </a>
  2771. </div>
  2772. </div>
  2773. <div class="nextInRow">
  2774. <a class="cover" target="_blank" href="#">
  2775. <img src="${img1px}">
  2776. </a>
  2777. <div class="info">
  2778. <a class="link" target="_blank" href="#">
  2779. <div class="title">◧◩◨▧■□▩</div>
  2780. <div>by <span class="artist">◩▧◧□ ◩◨▧ ■◩▩</span></div>
  2781. <div>from <span class="album">◨■■▩ ▧◨□</span></div>
  2782. </a>
  2783. </div>
  2784. </div>
  2785. </div>
  2786. <div class="col col25 colcontrols">
  2787. <audio autoplay="autoplay" preload="auto"></audio>
  2788. <div class="audioplayer">
  2789. <div id="timeline">
  2790. <div id="bufferbar" class="bufferbaranimation"></div>
  2791. <div id="playhead"></div>
  2792. </div>
  2793. <div class="controls">
  2794.  
  2795. <div class="prevalbum" title="Previous album">
  2796. <div class="arrowbutton prevalbum-icon"></div>
  2797. </div>
  2798.  
  2799. <div class="prev" title="Previous song">
  2800. <div class="arrowbutton prev-icon"></div>
  2801. </div>
  2802.  
  2803. <div class="playpause" title="Play/Pause">
  2804. <div class="play" style="display: none;"></div>
  2805. <div class="busy" style="display: none;"></div>
  2806. <div class="pause" style=""></div>
  2807. </div>
  2808.  
  2809. <div class="next" title="Next song">
  2810. <div class="arrowbutton next-icon"></div>
  2811. </div>
  2812.  
  2813. <div class="nextalbum" title="Next album">
  2814. <div class="arrowbutton nextalbum-icon"></div>
  2815. </div>
  2816.  
  2817. <div class="shuffleswitch" title="Shuffle">
  2818. <div class="shufflebutton" style="background-image:${spriteRepeatShuffle}"></div>
  2819. </div>
  2820.  
  2821. </div>
  2822. <div class="durationDisplay"><span class="current">-</span>/<span class="total">-</span></div>
  2823.  
  2824. <a class="downloadlink" title="Download mp3">
  2825. </a>
  2826. <br class="clb">
  2827. </div>
  2828. </div>
  2829. <div class="col col35">
  2830. <ol class="playlist"></ol>
  2831. </div>
  2832. <div class="col col15 colcontrols colvolumecontrols">
  2833.  
  2834. <div class="vol">
  2835. <div class="vol-icon-wrapper" title="Mute">
  2836. 🔊
  2837. </div>
  2838. <div class="vol-slider">
  2839. <div class="vol-amt" style="width: 100%;"></div>
  2840. <div class="vol-bg"></div>
  2841. </div>
  2842. </div>
  2843.  
  2844. <div class="collect">
  2845. <div class="collect-wishlist">
  2846. <a class="wishlist-default" href="https://bandcamp.com/wishlist">Wishlist</a>
  2847.  
  2848. <span class="wishlist-add">
  2849. <span class="bc-ui2 icon add-item-icon"></span>
  2850. <span class="add-item-label track" title="Add this song to your wishlist">Add song</span>
  2851. <span class="slash">/</span>
  2852. <span class="add-item-label album" title="Add this album to your wishlist">Add album to wishlist</span>
  2853. </span>
  2854. <span class="wishlist-collected">
  2855. <span class="bc-ui2 icon collected-item-icon"></span>
  2856. <span>In Wishlist</span>
  2857. </span>
  2858. <span class="wishlist-own" title="You own this album">
  2859. <span class="bc-ui2 icon own-item-icon"></span>
  2860. <span>You own this</span>
  2861. </span>
  2862. <span class="wishlist-saving">
  2863. Saving....
  2864. </span>
  2865. </div>
  2866. <div class="collect-listened">
  2867. <a class="listened-default" href="${listenedListUrl}">
  2868. Played albums
  2869. </a>
  2870. <span class="listened" title="Mark album as NOT played">
  2871. <span class="listened-symbol">${checkSymbol}</span>
  2872. <span class="listened-label">Played</span>
  2873. </span>
  2874. <span class="mark-listened" title="Mark album as played">
  2875. <span class="mark-listened-symbol">${checkSymbol}</span>
  2876. <span class="mark-listened-label">Mark as played</span>
  2877. </span>
  2878. <span class="listened-saving">
  2879. Saving...
  2880. </span>
  2881. </div>
  2882. </div>
  2883.  
  2884. <br class="cll">
  2885. <div class="minimizebutton">
  2886. <span class="minimized" title="Maximize player">&uarr;</span>
  2887. <span class="maximized" title="Minimize player">&darr;</span>
  2888. </div>
  2889. <div class="closebutton" title="Close player">x</div>
  2890. </div>`;
  2891. addStyle(discographyplayerCSS);
  2892. if (allFeatures.discographyplayerSidebar.enabled) {
  2893. // Sidebar discographyplayer
  2894. addStyle(discographyplayerSidebarCSS);
  2895. }
  2896. audio = player.querySelector('audio');
  2897. addLogVolume(audio);
  2898. getStoredVolume(function setVolumeCallback(volume) {
  2899. audio.logVolume = volume;
  2900. });
  2901. playhead = player.querySelector('#playhead');
  2902. bufferbar = player.querySelector('#bufferbar');
  2903. timeline = player.querySelector('#timeline');
  2904. player.querySelector('.minimizebutton').addEventListener('click', musicPlayerToggleMinimize);
  2905. player.querySelector('.closebutton').addEventListener('click', musicPlayerClose);
  2906. audio.addEventListener('ended', musicPlayerOnEnded);
  2907. audio.addEventListener('timeupdate', musicPlayerOnTimeUpdate);
  2908. audio.addEventListener('volumechange', musicPlayerOnVolumeChanged);
  2909. audio.addEventListener('canplaythrough', function onCanPlayThrough() {
  2910. currentDuration = audio.duration;
  2911. player.querySelector('.durationDisplay .total').innerHTML = humanDuration(currentDuration);
  2912. });
  2913. timeline.addEventListener('click', musicPlayerOnTimelineClick, false);
  2914. playhead.addEventListener('mousedown', musicPlayerOnPlayheadMouseDown, false);
  2915. window.addEventListener('mouseup', musicPlayerOnPlayheadMouseUp, false);
  2916. player.querySelector('.prevalbum').addEventListener('click', musicPlayerPrevAlbum);
  2917. player.querySelector('.prev').addEventListener('click', musicPlayerPrev);
  2918. player.querySelector('.playpause').addEventListener('click', musicPlayerPlay);
  2919. player.querySelector('.next').addEventListener('click', musicPlayerNext);
  2920. player.querySelector('.nextalbum').addEventListener('click', musicPlayerNextAlbum);
  2921. player.querySelector('.shuffleswitch').addEventListener('click', musicPlayerToggleShuffle);
  2922. player.querySelector('.vol-slider').addEventListener('click', musicPlayerOnVolumeClick);
  2923. player.querySelector('.vol').addEventListener('wheel', musicPlayerOnVolumeWheel, {
  2924. passive: false
  2925. });
  2926. player.querySelector('.vol-icon-wrapper').addEventListener('click', musicPlayerOnMuteClick);
  2927. player.querySelector('.collect-wishlist .track').addEventListener('click', musicPlayerCollectWishlistClick);
  2928. player.querySelector('.collect-wishlist .album').addEventListener('click', musicPlayerCollectWishlistClick);
  2929. player.querySelector('.collect-listened').addEventListener('click', musicPlayerCollectListenedClick);
  2930. player.querySelector('.downloadlink').addEventListener('click', function onDownloadLinkClick(ev) {
  2931. const addSpinner = el => el.classList.add('downloading');
  2932. const removeSpinner = el => el.classList.remove('downloading');
  2933. downloadMp3FromLink(ev, this, addSpinner, removeSpinner);
  2934. });
  2935. if (allFeatures.discographyplayerFullHeightPlaylist.enabled && !allFeatures.discographyplayerSidebar.enabled) {
  2936. player.querySelector('.playlist').addEventListener('mouseover', musicPlayerPlaylistFullHeight);
  2937. player.querySelector('.playlist').addEventListener('mouseout', musicPlayerPlaylistNormalHeight);
  2938. }
  2939. if (NOEMOJI) {
  2940. player.querySelector('.downloadlink').innerHTML = '↓';
  2941. }
  2942. window.addEventListener('unload', function onPageUnLoad(ev) {
  2943. if (allFeatures.discographyplayerPersist.enabled && player.style.display !== 'none' && !audio.paused) {
  2944. musicPlayerSaveState();
  2945. }
  2946. });
  2947. window.setInterval(musicPlayerUpdateBufferBar, 1200);
  2948. }
  2949. function addHeadingToPlaylist(title, url, albumLoaded) {
  2950. musicPlayerCreate();
  2951. let content = document.createTextNode('💽 ' + title);
  2952. if (url) {
  2953. const a = document.createElement('a');
  2954. a.href = url;
  2955. a.target = '_blank';
  2956. a.appendChild(content);
  2957. content = a;
  2958. a.className = albumLoaded ? 'loaded' : 'notloaded';
  2959. a.title = 'Open album page';
  2960. }
  2961. const li = document.createElement('li');
  2962. li.appendChild(content);
  2963. li.className = 'playlistheading';
  2964. if (!albumLoaded) {
  2965. li.className += ' notloaded';
  2966. li.title = 'Load album into playlist';
  2967. }
  2968. li.addEventListener('click', musicPlayerOnPlaylistHeadingClick);
  2969. li.addEventListener('contextmenu', musicPlayerOnPlaylistHeadingContextMenu);
  2970. player.querySelector('.playlist').appendChild(li);
  2971. }
  2972. function addToPlaylist(startPlayback, data) {
  2973. musicPlayerCreate();
  2974. const li = document.createElement('li');
  2975. if (data.trackNumber != null && data.trackNumber !== 'null') {
  2976. li.appendChild(document.createTextNode((data.trackNumber > 9 ? '' : '0') + data.trackNumber + '. ' + data.artist + ' - ' + data.title));
  2977. } else {
  2978. li.appendChild(document.createTextNode(data.artist + ' - ' + data.title));
  2979. }
  2980. const span = document.createElement('span');
  2981. span.className = 'duration';
  2982. span.appendChild(document.createTextNode(humanDuration(data.duration)));
  2983. li.appendChild(span);
  2984. li.value = data.trackNumber;
  2985. li.dataset.file = data.file;
  2986. li.dataset.title = data.title;
  2987. li.dataset.trackNumber = data.trackNumber;
  2988. li.dataset.duration = data.duration;
  2989. li.dataset.artist = data.artist;
  2990. li.dataset.album = data.album;
  2991. li.dataset.albumUrl = data.albumUrl;
  2992. li.dataset.albumCover = data.albumCover;
  2993. li.dataset.inWishlist = data.inWishlist;
  2994. li.dataset.isPurchased = data.isPurchased;
  2995. li.dataset.isDownloadable = data.isDownloadable;
  2996. li.dataset.trackUrl = data.trackUrl;
  2997. li.addEventListener('click', musicPlayerOnPlaylistClick);
  2998. li.addEventListener('contextmenu', musicPlayerOnPlaylistContextMenu);
  2999. li.className = 'playlistentry';
  3000. player.querySelector('.playlist').appendChild(li);
  3001. if (startPlayback) {
  3002. player.querySelectorAll('.playlist .playing').forEach(function (el) {
  3003. el.classList.remove('playing');
  3004. });
  3005. li.classList.add('playing');
  3006. musicPlayerPlaySong(li);
  3007. window.setTimeout(() => player.querySelector('.playlist .playing').scrollIntoView({
  3008. block: 'nearest'
  3009. }), 200);
  3010. }
  3011. }
  3012. function addAlbumToPlaylist(TralbumData, startPlaybackIndex = 0) {
  3013. let i = 0;
  3014. const artist = TralbumData.artist;
  3015. const album = TralbumData.current.title;
  3016. const albumUrl = document.location.protocol + '//' + albumKey(TralbumData.url);
  3017. const albumCover = `https://f4.bcbits.com/img/a${TralbumData.art_id}_2.jpg`;
  3018. addHeadingToPlaylist(album, 'url' in TralbumData ? TralbumData.url : false, true);
  3019. let streamable = 0;
  3020. for (const key in TralbumData.trackinfo) {
  3021. const track = TralbumData.trackinfo[key];
  3022. if (!track.file) {
  3023. continue;
  3024. }
  3025. const trackNumber = track.track_num;
  3026. const file = track.file[Object.keys(track.file)[0]];
  3027. const title = track.title;
  3028. const duration = track.duration;
  3029. const trackUrl = track.title_link;
  3030. const inWishlist = 'tralbum_collect_info' in TralbumData && 'is_collected' in TralbumData.tralbum_collect_info && TralbumData.tralbum_collect_info.is_collected;
  3031. const isDownloadable = track.is_downloadable === true;
  3032. const isPurchased = 'tralbum_collect_info' in TralbumData && 'is_purchased' in TralbumData.tralbum_collect_info && TralbumData.tralbum_collect_info.is_purchased;
  3033. addToPlaylist(startPlaybackIndex === i++, {
  3034. file,
  3035. title,
  3036. trackNumber,
  3037. trackUrl,
  3038. duration,
  3039. artist,
  3040. album,
  3041. albumUrl,
  3042. albumCover,
  3043. inWishlist,
  3044. isDownloadable,
  3045. isPurchased
  3046. });
  3047. streamable++;
  3048. }
  3049. if (streamable === 0) {
  3050. const li = document.createElement('li');
  3051. li.appendChild(document.createTextNode((NOEMOJI ? '\u27C1' : '\uD83D\uDE22') + ' Album is not streamable'));
  3052. player.querySelector('.playlist').appendChild(li);
  3053. }
  3054. player.querySelectorAll('.playlist .playlistheading a.notloaded').forEach(function (el) {
  3055. // Move unloaded items to the end
  3056. el.parentNode.parentNode.appendChild(el.parentNode);
  3057. });
  3058. }
  3059. function addAllAlbumsAsHeadings() {
  3060. const as = document.querySelectorAll('.music-grid .music-grid-item a[href*="/album/"],.music-grid .music-grid-item a[href*="/track/"]');
  3061. const lis = player.querySelectorAll('.playlist .playlistentry');
  3062. const unloadedAs = player.querySelectorAll('.playlist .playlistheading.notloaded a');
  3063. const isAlreadyInPlaylist = function (url) {
  3064. for (let i = 0; i < lis.length; i++) {
  3065. if (albumKey(lis[i].dataset.albumUrl) === albumKey(url)) {
  3066. return true;
  3067. }
  3068. }
  3069. for (let i = 0; i < unloadedAs.length; i++) {
  3070. if (albumKey(unloadedAs[i].href) === albumKey(url)) {
  3071. return true;
  3072. }
  3073. }
  3074. return false;
  3075. };
  3076. for (let i = 0; i < as.length; i++) {
  3077. const url = as[i].href;
  3078. // Check if already in playlist
  3079. if (!isAlreadyInPlaylist(url)) {
  3080. const title = ('textContent' in as[i].dataset ? as[i].dataset.textContent : as[i].querySelector('.title').textContent).trim();
  3081. addHeadingToPlaylist(title, url, false);
  3082. }
  3083. }
  3084. }
  3085. let getTralbumDataDelay = 0;
  3086. function getTralbumData(url, retry = true) {
  3087. return new Promise(function getTralbumDataPromise(resolve, reject) {
  3088. GM.xmlHttpRequest({
  3089. method: 'GET',
  3090. url,
  3091. onload: function getTralbumDataOnLoad(response) {
  3092. if (!response.responseText || response.responseText.indexOf('400 Bad Request') !== -1) {
  3093. let msg = '';
  3094. try {
  3095. msg = response.responseText.split('<center>')[1].split('</center>')[0];
  3096. } catch (e) {
  3097. msg = response.responseText;
  3098. }
  3099. window.alert('An error occured. Please clear your cookies of bandcamp.com and try again.\n\nOriginal error:\n' + msg);
  3100. reject(new Error('Too many cookies'));
  3101. return;
  3102. }
  3103. if (!response.responseText || response.responseText.indexOf('429 Too Many Requests') !== -1) {
  3104. if (retry) {
  3105. retry = false;
  3106. getTralbumDataDelay += 3;
  3107. const delay = getTralbumDataDelay;
  3108. console.warn(`getTralbumData(): 429 Too Many Requests. Trying again in ${delay} seconds`);
  3109. window.setTimeout(() => getTralbumDataPromise(resolve, reject), delay * 1000);
  3110. return;
  3111. }
  3112. let msg = '';
  3113. try {
  3114. msg = response.responseText.split('<center>')[1].split('</center>')[0];
  3115. } catch (e) {
  3116. msg = response.responseText;
  3117. }
  3118. window.alert('An error occured. You\'re probably being rate limited by bandcamp.\n\nOriginal error:\n' + msg);
  3119. reject(new Error('429 Too Many Requests'));
  3120. return;
  3121. }
  3122. let TralbumData = null;
  3123. try {
  3124. if (response.responseText.indexOf('var TralbumData =') !== -1) {
  3125. TralbumData = JSON5.parse(response.responseText.split('var TralbumData =')[1].split('\n};\n')[0].replace(/"\s+\+\s+"/, '') + '\n}');
  3126. } else if (response.responseText.indexOf('data-tralbum="') !== -1) {
  3127. const str = decodeHTMLentities(response.responseText.split('data-tralbum="')[1].split('"')[0]);
  3128. TralbumData = JSON.parse(str);
  3129. if (retry && TralbumData && 'url' in TralbumData && Object.keys(TralbumData).length === 1) {
  3130. retry = false;
  3131. // Discography page -> try to get first album
  3132. console.debug('getTralbumDataPromise(), Not a album page, try to find first album');
  3133. const firstAlbumM = response.responseText.split('id="music-grid"')[1].match(/<a.*?href="(.*?(album|track)\/.+?)"/);
  3134. if (firstAlbumM && firstAlbumM[1]) {
  3135. let firstAlbumUrl = firstAlbumM[1];
  3136. if (!firstAlbumUrl.startsWith('http')) {
  3137. const hostname = new window.URL(response.finalUrl).hostname;
  3138. if (firstAlbumUrl.startsWith('/')) {
  3139. firstAlbumUrl = `https://${hostname}${firstAlbumUrl}`;
  3140. } else {
  3141. firstAlbumUrl = `https://${hostname}/${firstAlbumUrl}`;
  3142. }
  3143. }
  3144. if (url !== firstAlbumUrl) {
  3145. url = firstAlbumUrl;
  3146. console.debug('getTralbumDataPromise(), Not a album page, new url=', url);
  3147. window.setTimeout(() => getTralbumDataPromise(resolve, reject), 500);
  3148. return;
  3149. }
  3150. }
  3151. }
  3152.  
  3153. // Try to add tralbum_collect_info / TralbumCollectInfo
  3154. if (TralbumData && response.responseText.indexOf('data-tralbum-collect-info="') !== -1) {
  3155. const collectInfoStr = decodeHTMLentities(response.responseText.split('data-tralbum-collect-info="')[1].split('"')[0]);
  3156. TralbumData.tralbum_collect_info = JSON.parse(collectInfoStr);
  3157. }
  3158. }
  3159. } catch (e) {
  3160. window.alert('An error occured when parsing TralbumData from url=' + url + '.\n\nOriginal error:\n' + e);
  3161. reject(e);
  3162. return;
  3163. }
  3164. if (TralbumData) {
  3165. correctTralbumData(TralbumData, response.responseText);
  3166. resolve(TralbumData);
  3167. } else {
  3168. const msg = 'Could not parse TralbumData from url=' + url;
  3169. window.alert(msg);
  3170. console.error(response.responseText);
  3171. reject(new Error(msg));
  3172. }
  3173. },
  3174. onerror: function getTralbumDataOnError(response) {
  3175. console.error('getTralbumData(' + url + ') in onerror() Error: ' + response.status + '\nResponse:\n' + response.responseText + '\n' + ('error' in response ? response.error : ''));
  3176. reject(new Error('error' in response ? response.error : 'getTralbumData failed with GM.xmlHttpRequest.onerror'));
  3177. }
  3178. });
  3179. });
  3180. }
  3181. function correctTralbumData(TralbumDataObj, html) {
  3182. const TralbumData = JSON.parse(JSON.stringify(TralbumDataObj));
  3183. // Corrections for single tracks
  3184. if (TralbumData.current.type === 'track' && TralbumData.current.title.toLowerCase().indexOf('single') === -1) {
  3185. TralbumData.current.title += ' - Single';
  3186. }
  3187. for (let i = 0; i < TralbumData.trackinfo.length; i++) {
  3188. if (TralbumData.trackinfo[i].track_num === null) {
  3189. TralbumData.trackinfo[i].track_num = i + 1;
  3190. }
  3191. }
  3192. // Add tags from html
  3193. if (html && html.indexOf('tags-inline-label') !== -1) {
  3194. const m = html.split('tags-inline-label')[1].split('</div>')[0].match(/\/tag\/[^"]+"/g);
  3195. if (m && m.length > 0) {
  3196. TralbumData.tags = [];
  3197. m.forEach(function (t) {
  3198. t = t.split('/').pop();
  3199. t = t.substring(0, t.length - 1);
  3200. TralbumData.tags.push(t);
  3201. });
  3202. }
  3203. }
  3204. // Remove stuff we don't use to save storage space
  3205. delete TralbumData.current.require_email_0;
  3206. delete TralbumData.current.audit;
  3207. delete TralbumData.current.download_pref;
  3208. delete TralbumData.current.set_price;
  3209. delete TralbumData.current.killed;
  3210. delete TralbumData.current.auto_repriced;
  3211. delete TralbumData.current.minimum_price_nonzero;
  3212. delete TralbumData.current.minimum_price;
  3213. delete TralbumData.current.purchase_url;
  3214. delete TralbumData.current.new_desc_format;
  3215. delete TralbumData.current.private;
  3216. delete TralbumData.current.is_set_price;
  3217. delete TralbumData.current.require_email;
  3218. delete TralbumData.current.upc;
  3219. delete TralbumData.packages;
  3220. delete TralbumData.last_subscription_item;
  3221. delete TralbumData.last_subscription_item;
  3222. delete TralbumData.has_discounts;
  3223. delete TralbumData.is_bonus;
  3224. delete TralbumData.play_cap_data;
  3225. delete TralbumData.client_id_sig;
  3226. delete TralbumData.is_purchased;
  3227. delete TralbumData.items_purchased;
  3228. delete TralbumData.is_private_stream;
  3229. delete TralbumData.is_band_member;
  3230. delete TralbumData.licensed_version_ids;
  3231. delete TralbumData.package_associated_license_id;
  3232. for (let i = 0; i < TralbumData.trackinfo.length; i++) {
  3233. delete TralbumData.trackinfo[i].is_draft;
  3234. delete TralbumData.trackinfo[i].album_preorder;
  3235. delete TralbumData.trackinfo[i].unreleased_track;
  3236. delete TralbumData.trackinfo[i].encoding_error;
  3237. delete TralbumData.trackinfo[i].video_mobile_url;
  3238. delete TralbumData.trackinfo[i].encoding_pending;
  3239. delete TralbumData.trackinfo[i].video_poster_url;
  3240. delete TralbumData.trackinfo[i].video_source_type;
  3241. delete TralbumData.trackinfo[i].video_source_id;
  3242. delete TralbumData.trackinfo[i].video_mobile_url;
  3243. delete TralbumData.trackinfo[i].video_caption;
  3244. delete TralbumData.trackinfo[i].video_featured;
  3245. delete TralbumData.trackinfo[i].video_id;
  3246. for (const attr in TralbumData.trackinfo[i]) {
  3247. if (TralbumData.trackinfo[i][attr] === null) {
  3248. delete TralbumData.trackinfo[i][attr];
  3249. }
  3250. }
  3251. }
  3252. for (const attr in TralbumData) {
  3253. if (TralbumData[attr] === null) {
  3254. delete TralbumData[attr];
  3255. }
  3256. }
  3257. return TralbumData;
  3258. }
  3259. function albumKey(url) {
  3260. if (url.startsWith('/')) {
  3261. url = document.location.hostname + url;
  3262. }
  3263. if (url.indexOf('://') !== -1) {
  3264. url = url.split('://')[1];
  3265. }
  3266. if (url.indexOf('#') !== -1) {
  3267. url = url.split('#')[0];
  3268. }
  3269. if (url.indexOf('?') !== -1) {
  3270. url = url.split('?')[0];
  3271. }
  3272. return url;
  3273. }
  3274. function albumPath(url) {
  3275. if (url.startsWith('/')) {
  3276. return albumKey(url);
  3277. }
  3278. const a = document.createElement('a');
  3279. a.href = url;
  3280. return a.pathname;
  3281. }
  3282. async function cacheSet(gmKey, expires, key, value) {
  3283. const cache = JSON.parse(await GM.getValue(gmKey, '{}'));
  3284. const now = new Date().getTime();
  3285. for (const prop in cache) {
  3286. // Delete cached values, that are older than `expires`
  3287. if (now - new Date(cache[prop].time).getTime() > expires) {
  3288. delete cache[prop];
  3289. }
  3290. }
  3291. const data = {
  3292. value,
  3293. time: new Date().toJSON()
  3294. };
  3295. cache[key] = data;
  3296. await GM.setValue(gmKey, JSON.stringify(cache));
  3297. }
  3298. async function cacheGet(gmKey, expires, key, defaultsTo = null) {
  3299. const cache = JSON.parse(await GM.getValue(gmKey, '{}'));
  3300. const now = new Date().getTime();
  3301. for (const prop in cache) {
  3302. // Delete cached values, that are older than `expires`
  3303. if (now - new Date(cache[prop].time).getTime() > expires) {
  3304. delete cache[prop];
  3305. continue;
  3306. }
  3307. if (prop === key) {
  3308. return cache[prop].value;
  3309. }
  3310. }
  3311. return defaultsTo;
  3312. }
  3313. async function storeTralbumData(TralbumData) {
  3314. const expires = TRALBUM_CACHE_HOURS * ONEHOUR;
  3315. const cache = JSON.parse(await GM.getValue('tralbumdata', '{}'));
  3316. for (const prop in cache) {
  3317. // Delete cached values, that are older than 2 hours
  3318. if (new Date().getTime() - new Date(cache[prop].time).getTime() > expires) {
  3319. delete cache[prop];
  3320. }
  3321. }
  3322. TralbumData.time = new Date().toJSON();
  3323. cache[albumKey(TralbumData.url)] = TralbumData;
  3324. await GM.setValue('tralbumdata', JSON.stringify(cache));
  3325. storeTralbumDataPermanently(TralbumData);
  3326. }
  3327. async function cachedTralbumData(url) {
  3328. const expires = TRALBUM_CACHE_HOURS * ONEHOUR;
  3329. const key = albumKey(url);
  3330. const cache = JSON.parse(await GM.getValue('tralbumdata', '{}'));
  3331. for (const prop in cache) {
  3332. // Delete cached values, that are older than 2 hours
  3333. if (new Date().getTime() - new Date(cache[prop].time).getTime() > expires) {
  3334. delete cache[prop];
  3335. continue;
  3336. }
  3337. if (prop === key) {
  3338. return cache[prop];
  3339. }
  3340. }
  3341. return false;
  3342. }
  3343. async function storeTralbumDataPermanently(TralbumData) {
  3344. if (!storeTralbumDataPermanentlySwitch) {
  3345. return;
  3346. }
  3347. const library = JSON.parse(await GM.getValue('tralbumlibrary', '{}'));
  3348. const key = albumKey(TralbumData.url);
  3349. if (key in library) {
  3350. library[key] = Object.assign(library[key], TralbumData);
  3351. } else {
  3352. library[key] = TralbumData;
  3353. }
  3354. await GM.setValue('tralbumlibrary', JSON.stringify(library));
  3355. }
  3356. async function deletePermanentTralbum(url) {
  3357. const library = JSON.parse(await GM.getValue('tralbumlibrary', '{}'));
  3358. const key = albumKey(url);
  3359. if (key in library) {
  3360. delete library[key];
  3361. await GM.setValue('tralbumlibrary', JSON.stringify(library));
  3362. return key;
  3363. }
  3364. return null;
  3365. }
  3366. function playAlbumFromCover(ev, url) {
  3367. let parent = this;
  3368. if (!url) {
  3369. for (let j = 0; parent.tagName !== 'A' && j < 20; j++) {
  3370. parent = parent.parentNode;
  3371. }
  3372. url = parent.href;
  3373. }
  3374. parent.classList.add('discographyplayer_currentalbum');
  3375.  
  3376. // Check if already in playlist
  3377. if (player) {
  3378. musicPlayerCreate();
  3379. const lis = player.querySelectorAll('.playlist .playlistentry');
  3380. for (let i = 0; i < lis.length; i++) {
  3381. if (albumKey(lis[i].dataset.albumUrl) === albumKey(url)) {
  3382. lis[i].click();
  3383. return;
  3384. }
  3385. }
  3386. }
  3387.  
  3388. // Load data
  3389. cachedTralbumData(url).then(function onCachedTralbumDataLoaded(TralbumData) {
  3390. if (TralbumData) {
  3391. addAlbumToPlaylist(TralbumData);
  3392. } else {
  3393. playAlbumFromUrl(url);
  3394. }
  3395. });
  3396. }
  3397. function playAlbumFromUrl(url, startPlaybackIndex = 0) {
  3398. if (!url.startsWith('http')) {
  3399. url = document.location.protocol + '//' + url;
  3400. }
  3401. return getTralbumData(url).then(function onGetTralbumDataLoaded(TralbumData) {
  3402. storeTralbumData(TralbumData);
  3403. return addAlbumToPlaylist(TralbumData, startPlaybackIndex);
  3404. }).catch(function onGetTralbumDataError(e) {
  3405. window.alert('Could not play and load album data from url:\n' + url + '\n' + ('error' in e ? e.error : e));
  3406. console.error(e);
  3407. });
  3408. }
  3409. async function myAlbumsGetAlbum(url) {
  3410. const key = albumKey(url);
  3411. const data = JSON.parse(await GM.getValue('myalbums', '{}'));
  3412. if (key in data) {
  3413. return data[key];
  3414. } else {
  3415. return false;
  3416. }
  3417. }
  3418. async function myAlbumsUpdateAlbum(albumData) {
  3419. const key = albumKey(albumData.url);
  3420. const data = JSON.parse(await GM.getValue('myalbums', '{}'));
  3421. if (key in data) {
  3422. data[key] = Object.assign(data[key], albumData);
  3423. } else {
  3424. data[key] = albumData;
  3425. }
  3426. await GM.setValue('myalbums', JSON.stringify(data));
  3427. }
  3428. async function myAlbumsNewFromUrl(url, fallback) {
  3429. // Get data from cache or load from url
  3430. url = albumKey(url);
  3431. const albumData = fallback || {};
  3432. let TralbumData = await cachedTralbumData(url);
  3433. if (!TralbumData) {
  3434. try {
  3435. TralbumData = await getTralbumData(document.location.protocol + '//' + url);
  3436. } catch (e) {
  3437. console.error('myAlbumsNewFromUrl() Could not load album data from url:\n' + url);
  3438. }
  3439. if (TralbumData) {
  3440. storeTralbumData(TralbumData);
  3441. }
  3442. }
  3443. if (TralbumData) {
  3444. albumData.artist = TralbumData.artist;
  3445. albumData.title = TralbumData.current.title;
  3446. albumData.albumCover = `https://f4.bcbits.com/img/a${TralbumData.art_id}_2.jpg`;
  3447. albumData.releaseDate = TralbumData.current.release_date;
  3448. }
  3449. albumData.url = url;
  3450. albumData.listened = false;
  3451. return albumData;
  3452. }
  3453. function makeAlbumCoversGreat() {
  3454. if (!('makeAlbumCoversGreat' in document.head.dataset)) {
  3455. document.head.dataset.makeAlbumCoversGreat = true;
  3456. const campExplorerCSS = `
  3457. .music-grid-item {
  3458. position: relative
  3459. }
  3460. .music-grid-item .art-play {
  3461. margin-top: -50px;
  3462. }
  3463. `;
  3464. addStyle(`
  3465. .music-grid-item .art-play {
  3466. position: absolute;
  3467. width: 74px;
  3468. height: 54px;
  3469. left: 50%;
  3470. top: 50%;
  3471. margin-left: -36px;
  3472. margin-top: -27px;
  3473. opacity: 0;
  3474. transition: opacity 0.2s;
  3475. }
  3476. .music-grid-item .art-play-bg {
  3477. position: absolute;
  3478. width: 100%;
  3479. height: 100%;
  3480. left: 0;
  3481. top: 0;
  3482. background: #000;
  3483. border-radius: 4px;
  3484. }
  3485. .music-grid-item .art-play-icon {
  3486. position: absolute;
  3487. width: 0;
  3488. height: 0;
  3489. left: 28px;
  3490. top: 17px;
  3491. border-width: 10px 0 10px 17px;
  3492. border-color: transparent transparent transparent #fff;
  3493. border-style: dashed dashed dashed solid;
  3494. }
  3495. .music-grid-item:hover .art-play {
  3496. opacity: 0.6;
  3497. }
  3498.  
  3499. ${CAMPEXPLORER ? campExplorerCSS : ''}
  3500. `);
  3501. }
  3502. const onclick = function onclick(ev) {
  3503. ev.preventDefault();
  3504. playAlbumFromCover.apply(this, ev);
  3505. };
  3506. const artPlay = document.createElement('div');
  3507. artPlay.className = 'art-play';
  3508. artPlay.innerHTML = '<div class="art-play-bg"></div><div class="art-play-icon"></div>';
  3509. if (CAMPEXPLORER) {
  3510. document.querySelectorAll('ul.albums').forEach(e => e.classList.add('music-grid'));
  3511. document.querySelectorAll('ul.albums li.album').forEach(e => e.classList.add('music-grid-item'));
  3512. }
  3513.  
  3514. // Albums, single tracks, artists, label etc
  3515. const imgs = document.querySelectorAll('.music-grid .music-grid-item a[href] img');
  3516. for (let i = 0; i < imgs.length; i++) {
  3517. if (imgs[i].parentNode.getElementsByClassName('art-play').length) {
  3518. continue;
  3519. }
  3520. imgs[i].addEventListener('click', onclick);
  3521.  
  3522. // Add play overlay
  3523. const clone = artPlay.cloneNode(true);
  3524. clone.addEventListener('click', onclick);
  3525. imgs[i].parentNode.appendChild(clone);
  3526. }
  3527. }
  3528. function makeTagSearchCoversGreat() {
  3529. const onclick = function onclick(ev) {
  3530. ev.preventDefault();
  3531. const a = this.parentNode.querySelector('.info a[href]');
  3532. playAlbumFromCover.call(this, ev, a.href);
  3533. };
  3534. document.querySelectorAll('.dig-deeper-item').forEach(function (div) {
  3535. const artDiv = div.querySelector('div.art');
  3536. const dumbArtCopy = artDiv.cloneNode(true);
  3537. artDiv.parentNode.replaceChild(dumbArtCopy, artDiv);
  3538. dumbArtCopy.addEventListener('click', onclick);
  3539. });
  3540. }
  3541. async function makeAlbumLinksGreat(parentElement) {
  3542. const doc = parentElement || document;
  3543. const myalbums = JSON.parse(await GM.getValue('myalbums', '{}'));
  3544. if (!('makeAlbumLinksGreat' in document.head.dataset)) {
  3545. document.head.dataset.makeAlbumLinksGreat = true;
  3546. addStyle(`
  3547. .bdp_check_onlinkhover_container { z-index:1002; position:absolute; display:none }
  3548. .bdp_check_onlinkhover_container_shown { display:block; background-color:rgba(255,255,255,0.9); padding:0px 2px 0px 0px; border-radius:5px }
  3549. .bdp_check_onlinkhover_container:hover { position:absolute; transition: all 300ms linear; background-color:rgba(255,255,255,0.9); padding:0px 10px 0px 7px; border-radius:5px }
  3550. .bdp_check_onchecked_container { z-index:-1; position:absolute; opacity:0.0; margin-top:-2px}
  3551. a:hover .bdp_check_onchecked_container { z-index:1002; position:absolute; transition: opacity 300ms linear; opacity:1.0}
  3552.  
  3553. .bdp_check_onlinkhover_symbol {color:rgba(0,0,50,0.7)}
  3554. .bdp_check_onlinkhover_text {color:rgba(0,0,50,0.7)}
  3555. .bdp_check_onlinkhover_container:hover .bdp_check_onlinkhover_symbol { color:rgba(0,0,100,1.0) }
  3556. .bdp_check_onlinkhover_container:hover .bdp_check_onlinkhover_text { color:rgba(0,100,0,1.0)}
  3557. .bdp_check_onchecked_symbol { color:rgba(0,100,0,0.8) }
  3558. .bdp_check_onchecked_text { color:rgba(150,200,150,0.8) }
  3559.  
  3560. a:hover .bdp_check_onchecked_symbol { text-shadow: 1px 1px #fff; color:rgba(0,50,0,1.0); transition: all 300ms linear }
  3561. a:hover .bdp_check_onchecked_text { text-shadow: 1px 1px #000; color:rgba(200,255,200,0.8); transition: all 300ms linear }
  3562.  
  3563. `);
  3564. }
  3565. const excluded = [...document.querySelectorAll('#carousel-player .now-playing a')];
  3566. excluded.push(...document.querySelectorAll('#discographyplayer a'));
  3567. excluded.push(...document.querySelectorAll('#pastreleases a'));
  3568.  
  3569. /*
  3570. <div class="bdp_check_container bdp_check_onlinkhover_container"><span class="bdp_check_onlinkhover_symbol">\u2610</span> <span class="bdp_check_onlinkhover_text">Check</span></div>
  3571. <div class="bdp_check_container bdp_check_onlinkhover_container"><span class="bdp_check_onlinkhover_symbol">\u1f5f9</span> <span class="bdp_check_onlinkhover_text">Check</span></div>
  3572. <span class="bdp_check_onchecked_symbol">\u2611</span> TITLE <div class="bdp_check_container bdp_check_onchecked_container"><span class="bdp_check_onchecked_text">Played</span></div>
  3573. */
  3574.  
  3575. const onClickSetListened = async function onClickSetListenedAsync(ev) {
  3576. ev.preventDefault();
  3577. let parentA = this;
  3578. for (let j = 0; parentA.tagName !== 'A' && j < 20; j++) {
  3579. parentA = parentA.parentNode;
  3580. }
  3581. window.setTimeout(function showSavingLabel() {
  3582. parentA.style.cursor = 'wait';
  3583. parentA.querySelector('.bdp_check_container').innerHTML = 'Saving...';
  3584. }, 0);
  3585. const url = parentA.href;
  3586. let albumData = await myAlbumsGetAlbum(url);
  3587. if (!albumData) {
  3588. albumData = await myAlbumsNewFromUrl(url, {
  3589. title: this.dataset.textContent
  3590. });
  3591. }
  3592. albumData.listened = new Date().toJSON();
  3593. await myAlbumsUpdateAlbum(albumData);
  3594. window.setTimeout(function hideSavingLabel() {
  3595. parentA.style.cursor = '';
  3596. makeAlbumLinksGreat();
  3597. }, 100);
  3598. };
  3599. const onClickRemoveListened = async function onClickRemoveListenedAsync(ev) {
  3600. ev.preventDefault();
  3601. let parentA = this;
  3602. for (let j = 0; parentA.tagName !== 'A' && j < 20; j++) {
  3603. parentA = parentA.parentNode;
  3604. }
  3605. window.setTimeout(function showSavingLabel() {
  3606. parentA.style.cursor = 'wait';
  3607. parentA.querySelector('.bdp_check_container').innerHTML = 'Saving...';
  3608. }, 0);
  3609. const url = parentA.href;
  3610. const albumData = await myAlbumsGetAlbum(url);
  3611. if (albumData) {
  3612. albumData.listened = false;
  3613. await myAlbumsUpdateAlbum(albumData);
  3614. }
  3615. window.setTimeout(function hideSavingLabel() {
  3616. parentA.style.cursor = '';
  3617. makeAlbumLinksGreat();
  3618. }, 100);
  3619. };
  3620. const mouseOverLink = function onMouseOverLink(ev) {
  3621. const bdpCheckOnlinkhoverContainer = this.querySelector('.bdp_check_onlinkhover_container');
  3622. if (bdpCheckOnlinkhoverContainer) {
  3623. bdpCheckOnlinkhoverContainer.classList.add('bdp_check_onlinkhover_container_shown');
  3624. }
  3625. };
  3626. const mouseOutLink = function onMouseOutLink(ev) {
  3627. const a = this;
  3628. a.dataset.iv = window.setTimeout(function mouseOutLinkTimeout() {
  3629. const div = a.querySelector('.bdp_check_onlinkhover_container');
  3630. if (div) {
  3631. div.classList.remove('bdp_check_onlinkhover_container_shown');
  3632. div.dataset.iv = a.dataset.iv;
  3633. }
  3634. }, 1000);
  3635. };
  3636. const mouseMoveLink = function onMouseLoveLink(ev) {
  3637. if ('iv' in this.dataset) {
  3638. window.clearTimeout(this.dataset.iv);
  3639. }
  3640. };
  3641. const mouseOverDivCheck = function onMouseOverDivCheck(ev) {
  3642. const bdpCheckOnlinkhoverSymbol = this.querySelector('.bdp_check_onlinkhover_symbol');
  3643. if (bdpCheckOnlinkhoverSymbol) {
  3644. bdpCheckOnlinkhoverSymbol.innerText = NOEMOJI ? '\u2611' : '\uD83D\uDDF9';
  3645. }
  3646. if ('iv' in this.dataset) {
  3647. window.clearTimeout(this.dataset.iv);
  3648. }
  3649. };
  3650. const mouseOutDivCheck = function onMouseOutDivCheck(ev) {
  3651. const bdpCheckOnlinkhoverSymbol = this.querySelector('.bdp_check_onlinkhover_symbol');
  3652. if (bdpCheckOnlinkhoverSymbol) {
  3653. bdpCheckOnlinkhoverSymbol.innerText = '\u2610';
  3654. }
  3655. };
  3656. const divCheck = document.createElement('div');
  3657. divCheck.setAttribute('class', 'bdp_check_container bdp_check_onlinkhover_container');
  3658. divCheck.setAttribute('title', 'Mark as played');
  3659. divCheck.innerHTML = '<span class="bdp_check_onlinkhover_symbol">\u2610</span> <span class="bdp_check_onlinkhover_text">Check</span>';
  3660. const divChecked = document.createElement('div');
  3661. divChecked.setAttribute('class', 'bdp_check_container bdp_check_onchecked_container');
  3662. divChecked.innerHTML = '<span class="bdp_check_onchecked_text">Played</span>';
  3663. const spanChecked = document.createElement('span');
  3664. spanChecked.appendChild(document.createTextNode('\u2611 '));
  3665. spanChecked.setAttribute('class', 'bdp_check_onchecked_symbol');
  3666. const a = doc.querySelectorAll('a[href*="/album/"],.music-grid .music-grid-item a[href*="/track/"]');
  3667. let lastKey = '';
  3668. for (let i = 0; i < a.length; i++) {
  3669. if (excluded.indexOf(a[i]) !== -1) {
  3670. continue;
  3671. }
  3672. const key = albumKey(a[i].href);
  3673. if (key === lastKey) {
  3674. // Skip multiple consequent links to same album
  3675. continue;
  3676. }
  3677. const textContent = a[i].textContent.trim();
  3678. if (!textContent) {
  3679. // Skip album covers only
  3680. continue;
  3681. }
  3682. let div;
  3683. if (a[i].dataset.textContent) {
  3684. removeViaQuerySelector(a[i], '.bdp_check_onlinkhover_container');
  3685. removeViaQuerySelector(a[i], '.bdp_check_onchecked_container');
  3686. removeViaQuerySelector(a[i], '.bdp_check_onchecked_symbol');
  3687. } else {
  3688. a[i].dataset.textContent = textContent;
  3689. a[i].addEventListener('mouseover', mouseOverLink);
  3690. a[i].addEventListener('mousemove', mouseMoveLink);
  3691. a[i].addEventListener('mouseout', mouseOutLink);
  3692. }
  3693. if (key in myalbums && 'listened' in myalbums[key] && myalbums[key].listened) {
  3694. div = divChecked.cloneNode(true);
  3695. div.addEventListener('click', onClickRemoveListened);
  3696. const date = new Date(myalbums[key].listened);
  3697. const since = timeSince(date);
  3698. const dateStr = dateFormater(date);
  3699. div.title = since + ' ago\nClick to mark as NOT played';
  3700. div.querySelector('.bdp_check_onchecked_text').appendChild(document.createTextNode(' ' + dateStr));
  3701. const span = spanChecked.cloneNode(true);
  3702. span.title = since + ' ago\nClick to mark as NOT played';
  3703. span.addEventListener('click', onClickRemoveListened);
  3704. const firstText = firstChildWithText(a[i]) || a[i].firstChild;
  3705. firstText.parentNode.insertBefore(span, firstText);
  3706. } else {
  3707. div = divCheck.cloneNode(true);
  3708. div.addEventListener('mouseover', mouseOverDivCheck);
  3709. div.addEventListener('mouseout', mouseOutDivCheck);
  3710. div.addEventListener('click', onClickSetListened);
  3711. }
  3712. a[i].appendChild(div);
  3713. lastKey = key;
  3714. }
  3715. }
  3716. function removeTheTimeHasComeToOpenThyHeartWallet() {
  3717. if ('theTimeHasComeToOpenThyHeartWallet' in document.head.dataset) {
  3718. return;
  3719. }
  3720. document.head.dataset.theTimeHasComeToOpenThyHeartWallet = true;
  3721. document.head.appendChild(document.createElement('script')).innerHTML = `
  3722. Log.debug("theTimeHasComeToOpenThyHeartWallet: start...")
  3723. function removeViaQuerySelector (parent, selector) {
  3724. if (typeof selector === 'undefined') {
  3725. selector = parent
  3726. parent = document
  3727. }
  3728. for (let el = parent.querySelector(selector); el; el = parent.querySelector(selector)) {
  3729. el.remove()
  3730. }
  3731. }
  3732. if (typeof TralbumData !== 'undefined') {
  3733. if (TralbumData.play_cap_data) {
  3734. TralbumData.play_cap_data.streaming_limit = 100
  3735. TralbumData.play_cap_data.streaming_limits_enabled = false
  3736. }
  3737. for(let i = 0; i < TralbumData.trackinfo.length; i++) {
  3738. TralbumData.trackinfo[i].is_capped = false
  3739. TralbumData.trackinfo[i].play_count = 1
  3740. }
  3741.  
  3742. /* // Alternative would be create new player
  3743. TralbumLimits.onPlayerInit = () => true
  3744. TralbumLimits.updatePlayCounts = () => true
  3745. Player.init(TralbumData, AlbumPage.onPlayerInit);
  3746. */
  3747.  
  3748. // Update player with modified TralbumData
  3749. Player.update(TralbumData)
  3750. Log.debug("theTimeHasComeToOpenThyHeartWallet: player updated")
  3751. }
  3752.  
  3753. // Restore lyrics onClick
  3754. function parentByClassName(node, className) {
  3755. while(!node.parentNode.classList.contains(className)) {
  3756. node = node.parentNode
  3757. if (node.parentNode === document.documentElement) {
  3758. return null
  3759. }
  3760. }
  3761. return node.parentNode
  3762. }
  3763. /*
  3764. // seems this is no longer necessary
  3765. function onLyricsClick (ev) {
  3766. ev.preventDefault()
  3767. const tr = parentByClassName(this, 'track_row_view')
  3768. if (tr.classList.contains('current_track')) {
  3769. parentByClassName(tr, 'track_list').classList.toggle('auto_lyrics')
  3770. } else {
  3771. tr.classList.toggle('showlyrics')
  3772. }
  3773. }
  3774. document.querySelectorAll('#track_table .track_row_view .info_link a').forEach(function (a) {
  3775. a.addEventListener('click', onLyricsClick)
  3776. })
  3777. */
  3778.  
  3779. // Hide popup (not really needed, but won't hurt)
  3780. window.setInterval(function() {
  3781. if(document.getElementById('play-limits-dialog-cancel-btn')) {
  3782. document.getElementById('play-limits-dialog-cancel-btn').click()
  3783. window.setTimeout(function() {
  3784. removeViaQuerySelector(document, '.ui-dialog.ui-widget')
  3785. removeViaQuerySelector(document, '.ui-widget-overlay')
  3786. }, 100)
  3787. }
  3788. }, 3000)
  3789. Log.debug("theTimeHasComeToOpenThyHeartWallet: done!")
  3790. `;
  3791. }
  3792. function makeCarouselPlayerGreatAgain() {
  3793. if (player) {
  3794. // Hide/minimize discography player
  3795. const closePlayerOnCarouselIv = window.setInterval(function closePlayerOnCarouselInterval() {
  3796. if (!document.getElementById('carousel-player') || document.getElementById('carousel-player').getClientRects()[0].bottom - window.innerHeight > 0) {
  3797. return;
  3798. }
  3799. if (player.style.display === 'none') {
  3800. // Put carousel player back down in normal position, because discography player is hidden forever
  3801. document.getElementById('carousel-player').style.bottom = '0px';
  3802. window.clearInterval(closePlayerOnCarouselIv);
  3803. } else if (!player.style.bottom) {
  3804. // Minimize discography player and push carousel player up above the minimized player
  3805. musicPlayerToggleMinimize.call(player.querySelector('.minimizebutton'), null, true);
  3806. document.getElementById('carousel-player').style.bottom = player.clientHeight - 57 + 'px';
  3807. }
  3808. }, 5000);
  3809. }
  3810. let addListenedButtonToCarouselPlayerLast = null;
  3811. const addListenedButtonToCarouselPlayer = function listenedButtonOnCarouselPlayer() {
  3812. const url = document.querySelector('#carousel-player a[href]') ? albumKey(document.querySelector('#carousel-player a[href]').href) : null;
  3813. if (url && addListenedButtonToCarouselPlayerLast === url) {
  3814. return;
  3815. }
  3816. if (!url) {
  3817. console.error('No url found in carousel player: `#carousel-player a[href]`');
  3818. return;
  3819. }
  3820. addListenedButtonToCarouselPlayerLast = url;
  3821. removeViaQuerySelector('#carousel-player .carousellistenedstatus');
  3822. const a = document.createElement('a');
  3823. a.className = 'carousellistenedstatus';
  3824. a.addEventListener('click', ev => ev.preventDefault());
  3825. document.querySelector('#carousel-player .controls-extra').insertBefore(a, document.querySelector('#carousel-player .controls-extra').firstChild);
  3826. a.innerHTML = '<span class="listenedstatus">Loading...</span>';
  3827. a.href = 'https://' + url;
  3828. makeAlbumLinksGreat(a.parentNode).then(function () {
  3829. removeViaQuerySelector(a, '.listenedstatus');
  3830. const span = document.createElement('span');
  3831. span.addEventListener('click', function () {
  3832. const span = this;
  3833. span.parentNode.querySelector('.bdp_check_container').click();
  3834. window.setTimeout(function () {
  3835. if (span.parentNode.querySelector('.bdp_check_container').textContent.indexOf('Played') !== -1) {
  3836. span.parentNode.innerHTML = 'Listened';
  3837. } else {
  3838. span.parentNode.innerHTML = 'Unplayed';
  3839. }
  3840. }, 3000);
  3841. });
  3842. if (a.querySelector('.bdp_check_onchecked_text')) {
  3843. span.className = 'listenedstatus listened';
  3844. span.innerHTML = '<span class="listened-symbol">✓</span> <span class="listened-label">Played</span>';
  3845. } else {
  3846. span.className = 'listenedstatus mark-listened';
  3847. span.innerHTML = '<span class="mark-listened-symbol">✓</span> <span class="mark-listened-label">Mark as played</span>';
  3848. }
  3849. a.insertBefore(span, a.firstChild);
  3850. a.dataset.textContent = document.querySelector('#carousel-player .now-playing .info a .artist span').textContent + ' - ' + document.querySelector('#carousel-player .now-playing .info a .title').textContent;
  3851. });
  3852. };
  3853. let lastMediaHubMeta = [null, null];
  3854. const onNotificationClick = function () {
  3855. if (!document.querySelector('#carousel-player .transport .next-icon').classList.contains('disabled')) {
  3856. document.querySelector('#carousel-player .transport .next-icon').click();
  3857. }
  3858. };
  3859. const updateChromePositionState = function () {
  3860. const audio = document.querySelector('body>audio');
  3861. if (audio && 'mediaSession' in navigator && 'setPositionState' in navigator.mediaSession) {
  3862. navigator.mediaSession.setPositionState({
  3863. duration: audio.duration || 180,
  3864. playbackRate: audio.playbackRate,
  3865. position: audio.currentTime
  3866. });
  3867. }
  3868. };
  3869. const addChromeMediaHubToCarouselPlayer = function chromeMediaHubToCarouselPlayer() {
  3870. const title = document.querySelector('#carousel-player .info-progress span[data-bind*="trackTitle"]').textContent.trim();
  3871. const artwork = document.querySelector('#carousel-player .now-playing img').src;
  3872. if (lastMediaHubMeta[0] === title && lastMediaHubMeta[1] === artwork) {
  3873. return;
  3874. }
  3875. lastMediaHubMeta = [title, artwork];
  3876. const artist = document.querySelector('#carousel-player .now-playing .artist span').textContent.trim();
  3877. const album = document.querySelector('#carousel-player .now-playing .title').textContent.trim();
  3878.  
  3879. // Notification
  3880. if (allFeatures.nextSongNotifications.enabled && 'notification' in GM) {
  3881. GM.notification({
  3882. title: document.location.host,
  3883. text: title + '\nby ' + artist + '\nfrom ' + album,
  3884. image: artwork,
  3885. highlight: false,
  3886. silent: true,
  3887. timeout: NOTIFICATION_TIMEOUT,
  3888. onclick: onNotificationClick
  3889. });
  3890. }
  3891.  
  3892. // Media hub
  3893. if ('mediaSession' in navigator) {
  3894. const audio = document.querySelector('body>audio');
  3895. if (audio) {
  3896. navigator.mediaSession.playbackState = !audio.paused ? 'playing' : 'paused';
  3897. updateChromePositionState();
  3898. }
  3899. navigator.mediaSession.metadata = new MediaMetadata({
  3900. title,
  3901. artist,
  3902. album,
  3903. artwork: [{
  3904. src: artwork,
  3905. sizes: '350x350',
  3906. type: 'image/jpeg'
  3907. }]
  3908. });
  3909. if (!document.querySelector('#carousel-player .transport .prev-icon').classList.contains('disabled')) {
  3910. navigator.mediaSession.setActionHandler('previoustrack', () => document.querySelector('#carousel-player .transport .prev-icon').click());
  3911. } else {
  3912. navigator.mediaSession.setActionHandler('previoustrack', null);
  3913. }
  3914. if (!document.querySelector('#carousel-player .transport .next-icon').classList.contains('disabled')) {
  3915. navigator.mediaSession.setActionHandler('nexttrack', () => document.querySelector('#carousel-player .transport .next-icon').click());
  3916. } else {
  3917. navigator.mediaSession.setActionHandler('nexttrack', null);
  3918. }
  3919. const playButton = document.querySelector('#carousel-player .playpause .play');
  3920. if (playButton && playButton.style.display === 'none') {
  3921. navigator.mediaSession.setActionHandler('play', null);
  3922. navigator.mediaSession.setActionHandler('pause', function () {
  3923. document.querySelector('#carousel-player .playpause').click();
  3924. navigator.mediaSession.playbackState = 'paused';
  3925. });
  3926. } else {
  3927. navigator.mediaSession.setActionHandler('play', function () {
  3928. document.querySelector('#carousel-player .playpause').click();
  3929. navigator.mediaSession.playbackState = 'playing';
  3930. });
  3931. navigator.mediaSession.setActionHandler('pause', null);
  3932. }
  3933. if (audio) {
  3934. navigator.mediaSession.setActionHandler('seekbackward', function (event) {
  3935. const skipTime = event.seekOffset || DEFAULTSKIPTIME;
  3936. audio.currentTime = Math.max(audio.currentTime - skipTime, 0);
  3937. updateChromePositionState();
  3938. });
  3939. navigator.mediaSession.setActionHandler('seekforward', function (event) {
  3940. const skipTime = event.seekOffset || DEFAULTSKIPTIME;
  3941. audio.currentTime = Math.min(audio.currentTime + skipTime, audio.duration);
  3942. updateChromePositionState();
  3943. });
  3944. try {
  3945. navigator.mediaSession.setActionHandler('stop', function () {
  3946. audio.pause();
  3947. audio.currentTime = 0;
  3948. navigator.mediaSession.playbackState = 'paused';
  3949. });
  3950. } catch (error) {
  3951. console.warn('Warning! The "stop" media session action is not supported.');
  3952. }
  3953. try {
  3954. navigator.mediaSession.setActionHandler('seekto', function (event) {
  3955. if (event.fastSeek && 'fastSeek' in audio) {
  3956. audio.fastSeek(event.seekTime);
  3957. return;
  3958. }
  3959. audio.currentTime = event.seekTime;
  3960. updateChromePositionState();
  3961. });
  3962. } catch (error) {
  3963. console.warn('Warning! The "seekto" media session action is not supported.');
  3964. }
  3965. }
  3966. }
  3967. };
  3968. window.setInterval(function addListenedButtonToCarouselPlayerInterval() {
  3969. if (!document.getElementById('carousel-player') || document.getElementById('carousel-player').getClientRects()[0].bottom - window.innerHeight > 0) {
  3970. return;
  3971. }
  3972. addListenedButtonToCarouselPlayer();
  3973. addChromeMediaHubToCarouselPlayer();
  3974. }, 2000);
  3975. addStyle(`
  3976. #carousel-player a.carousellistenedstatus:link,#carousel-player a.carousellistenedstatus:visited,#carousel-player a.carousellistenedstatus:hover{
  3977. text-decoration:none;
  3978. cursor:default
  3979. }
  3980. #carousel-player .listened .listened-symbol{
  3981. color:rgb(0,220,50);
  3982. text-shadow:1px 0px #DDD,-1px 0px #DDD,0px -1px #DDD,0px 1px #DDD
  3983. }
  3984. #carousel-player .mark-listened .mark-listened-symbol{
  3985. color:#FFF;
  3986. text-shadow:1px 0px #959595,-1px 0px #959595,0px -1px #959595,0px 1px #959595
  3987. }
  3988. #carousel-player .mark-listened:hover .mark-listened-symbol{
  3989. text-shadow:1px 0px #0AF,-1px 0px #0AF,0px -1px #0AF,0px 1px #0AF
  3990. }
  3991. `);
  3992. }
  3993. async function addListenedButtonToCollectControls() {
  3994. const lastLi = document.querySelector('.share-panel-wrapper-desktop ul li');
  3995. if (!lastLi) {
  3996. window.setTimeout(addListenedButtonToCollectControls, 300);
  3997. return;
  3998. }
  3999. const checkSymbol = NOEMOJI ? '✓' : '✔';
  4000. const myalbums = JSON.parse(await GM.getValue('myalbums', '{}'));
  4001. const key = albumKey(document.location.href);
  4002. const listened = key in myalbums && 'listened' in myalbums[key] && myalbums[key].listened;
  4003. const onClickSetListened = async function onClickSetListenedAsync(ev) {
  4004. ev.preventDefault();
  4005. let parent = this;
  4006. for (let j = 0; parent.tagName !== 'LI' && j < 20; j++) {
  4007. parent = parent.parentNode;
  4008. }
  4009. window.setTimeout(function showSavingLabel() {
  4010. parent.style.cursor = 'wait';
  4011. parent.innerHTML = 'Saving...';
  4012. }, 0);
  4013. const url = document.location.href;
  4014. let albumData = await myAlbumsGetAlbum(url);
  4015. if (!albumData) {
  4016. albumData = await myAlbumsNewFromUrl(url, {
  4017. title: this.dataset.textContent
  4018. });
  4019. }
  4020. albumData.listened = new Date().toJSON();
  4021. await myAlbumsUpdateAlbum(albumData);
  4022. window.setTimeout(addListenedButtonToCollectControls, 100);
  4023. };
  4024. const onClickRemoveListened = async function onClickRemoveListenedAsync(ev) {
  4025. ev.preventDefault();
  4026. let parent = this;
  4027. for (let j = 0; parent.tagName !== 'LI' && j < 20; j++) {
  4028. parent = parent.parentNode;
  4029. }
  4030. window.setTimeout(function showSavingLabel() {
  4031. parent.style.cursor = 'wait';
  4032. parent.innerHTML = 'Saving...';
  4033. }, 0);
  4034. const url = document.location.href;
  4035. const albumData = await myAlbumsGetAlbum(url);
  4036. if (albumData) {
  4037. albumData.listened = false;
  4038. await myAlbumsUpdateAlbum(albumData);
  4039. }
  4040. window.setTimeout(addListenedButtonToCollectControls, 100);
  4041. };
  4042. removeViaQuerySelector('#discographyplayer_sharepanel');
  4043. const li = lastLi.parentNode.appendChild(document.createElement('li'));
  4044. const button = li.appendChild(document.createElement('span'));
  4045. const icon = button.appendChild(document.createElement('span'));
  4046. const a = button.appendChild(document.createElement('a'));
  4047. li.setAttribute('id', 'discographyplayer_sharepanel');
  4048. a.addEventListener('click', ev => ev.preventDefault());
  4049. icon.className = 'sharepanelchecksymbol';
  4050. if (listened) {
  4051. const date = new Date(listened);
  4052. const since = timeSince(date);
  4053. button.title = since + '\nClick to mark as NOT played';
  4054. button.addEventListener('click', onClickRemoveListened);
  4055. icon.style.color = 'rgb(0,220,50)';
  4056. icon.style.textShadow = '1px 0px #DDD,-1px 0px #DDD,0px -1px #DDD,0px 1px #DDD';
  4057. icon.style.paddingRight = '5px';
  4058. icon.appendChild(document.createTextNode(checkSymbol));
  4059. a.appendChild(document.createTextNode('Played'));
  4060. li.appendChild(document.createTextNode(' - '));
  4061. const link = li.appendChild(document.createElement('span'));
  4062. const viewLink = link.appendChild(document.createElement('a'));
  4063. viewLink.href = findUserProfileUrl() + '#listened-tab';
  4064. viewLink.title = 'View list of played albums';
  4065. viewLink.appendChild(document.createTextNode('view'));
  4066. } else {
  4067. button.title = 'Click to mark as played';
  4068. button.addEventListener('click', onClickSetListened);
  4069. try {
  4070. icon.style.color = window.getComputedStyle(document.getElementById('pgBd')).backgroundColor;
  4071. icon.style.textShadow = '1px 0px #959595,-1px 0px #959595,0px -1px #959595,0px 1px #959595';
  4072. icon.style.paddingRight = '5px';
  4073. } catch (e) {
  4074. icon.style.color = '#959595';
  4075. icon.style.fontWeight = 700;
  4076. }
  4077. icon.appendChild(document.createTextNode(checkSymbol));
  4078. a.appendChild(document.createTextNode('Unplayed'));
  4079. }
  4080. }
  4081. function makeListenedListTabLink() {
  4082. const grid = document.getElementById('grids').appendChild(document.createElement('div'));
  4083. grid.className = 'grid';
  4084. grid.id = 'listened-grid';
  4085. const inner = grid.appendChild(document.createElement('div'));
  4086. inner.className = 'inner';
  4087. inner.innerHTML = 'Loading...';
  4088. const li = document.querySelector('ol#grid-tabs').appendChild(document.createElement('li'));
  4089. li.id = 'listenedlisttablink';
  4090. li.dataset.tab = 'listened';
  4091. li.setAttribute('data-grid-id', 'listened-grid');
  4092. const span = li.appendChild(document.createElement('span'));
  4093. span.className = 'tab-title';
  4094. span.appendChild(document.createTextNode('played'));
  4095. const count = span.appendChild(document.createElement('span'));
  4096. count.className = 'count';
  4097. GM.getValue('myalbums', '{}').then(function myalbumsLoaded(str) {
  4098. let n = 0;
  4099. const myalbums = JSON.parse(str);
  4100. for (const key in myalbums) {
  4101. if (myalbums[key].listened) {
  4102. n++;
  4103. }
  4104. }
  4105. count.appendChild(document.createTextNode(n));
  4106. });
  4107. li.addEventListener('click', showListenedListTab);
  4108. return li;
  4109. }
  4110. async function showListenedListTab() {
  4111. if (document.getElementById('owner-controls')) document.getElementById('owner-controls').style.display = 'none';
  4112. if (document.getElementById('wishlist-controls')) document.getElementById('wishlist-controls').style.display = 'none';
  4113. const grid = document.getElementById('listened-grid');
  4114. const gridActive = document.querySelector('#grids .grid.active');
  4115. if (gridActive && gridActive !== grid) {
  4116. gridActive.classList.remove('active');
  4117. }
  4118. grid.classList.add('active');
  4119. const tabLink = document.getElementById('listenedlisttablink');
  4120. const tabLinkActive = document.querySelector('#grid-tab li.active');
  4121. if (tabLinkActive && tabLinkActive !== tabLink) {
  4122. tabLinkActive.classList.remove('active');
  4123. }
  4124. tabLink.classList.add('active');
  4125. if (grid.querySelector('.collection-items')) {
  4126. return;
  4127. }
  4128. grid.innerHTML = '';
  4129. const collectionItems = grid.appendChild(document.createElement('div'));
  4130. collectionItems.className = 'collection-items';
  4131. const collectionGrid = collectionItems.appendChild(document.createElement('ol'));
  4132. collectionGrid.className = 'collection-grid';
  4133. const myalbums = JSON.parse(await GM.getValue('myalbums', '{}'));
  4134. for (const key in myalbums) {
  4135. const albumData = myalbums[key];
  4136. if (!albumData.listened) {
  4137. continue;
  4138. }
  4139. const artist = albumData.artist || 'Unkown artist';
  4140. const title = albumData.title || 'Unkown title';
  4141. const albumCover = albumData.albumCover || 'https://bandcamp.com/img/0.gif';
  4142. const url = key;
  4143. const date = new Date(albumData.listened);
  4144. const since = timeSince(date);
  4145. const dateStr = dateFormater(date);
  4146. let releaseDate;
  4147. if ('releaseDate' in albumData) {
  4148. releaseDate = dateFormaterRelease(new Date(albumData.releaseDate));
  4149. } else {
  4150. releaseDate = 'Unknown';
  4151. }
  4152. const li = collectionGrid.appendChild(document.createElement('li'));
  4153. li.className = 'collection-item-container';
  4154. li.innerHTML = `
  4155. <div class="collection-item-gallery-container">
  4156. <span class="bc-ui2 collect-item-icon-alt"></span>
  4157. <div class="collection-item-art-container">
  4158. <img class="collection-item-art" alt="" src="${albumCover}">
  4159. </div>
  4160. <div class="collection-title-details">
  4161. <a target="_blank" href="https://${url}" class="item-link">
  4162. <div class="collection-item-title">${title}</div>
  4163. <div class="collection-item-artist">by ${artist}</div>
  4164. </a>
  4165. </div>
  4166. <div class="collection-item-fav-track">
  4167. <span title="${since} ago" class="favoriteTrackLabel">played</span>
  4168. <div title="${since} ago">
  4169. <span class="fav-track-link">${dateStr}</span>
  4170. </div>
  4171. <span class="favoriteTrackLabel">released</span>
  4172. <div>
  4173. <span class="fav-track-link">${releaseDate}</span>
  4174. </div>
  4175. </div>
  4176. </div>
  4177. `;
  4178. }
  4179. }
  4180. function addVolumeBarToAlbumPage() {
  4181. // Do not add if one of these scripts already added a volume bar
  4182. // https://openuserjs.org/scripts/cuzi/Bandcamp_Volume_Bar
  4183. // https://openuserjs.org/scripts/Mranth0ny62/Bandcamp_Volume_Bar
  4184. // https://openuserjs.org/scripts/ArtificialInput/Bandcamp_Volume_Bar
  4185. // https://greasyfork.org/en/scripts/11047-bandcamp-volume-bar/
  4186. // https://greasyfork.org/en/scripts/38012-bandcamp-volume-bar/
  4187. if (document.querySelector('.volumeControl')) {
  4188. return false;
  4189. }
  4190. if (!document.querySelector('#trackInfoInner .playbutton')) {
  4191. return;
  4192. }
  4193. addStyle(`
  4194. /* Hide if inline_player is hidden */
  4195. .hidden .volumeButton,.hidden .volumeControl,.hidden .volumeLabel{
  4196. display:none
  4197. }
  4198.  
  4199. .volumeButton {
  4200. display: inline-block;
  4201. user-select:none;
  4202. background: #fff;
  4203. border: 1px solid #d9d9d9;
  4204. border-radius: 2px;
  4205. cursor: pointer;
  4206. min-height: 50px;
  4207. min-width: 54px;
  4208. text-align:center;
  4209. margin-top:5px;
  4210. }
  4211.  
  4212. .volumeSymbol {
  4213. margin-top: 16px;
  4214. font-size: 30px;
  4215. color:#222;
  4216. font-weight:bolder;
  4217. transform: rotate(-90deg);
  4218. text-shadow: rgb(255, 255, 255) 0px 0px 0px;
  4219. transition: text-shadow linear 300ms;
  4220. }
  4221. .volumeControl {
  4222. display:inline-block;
  4223. user-select:none;
  4224. top:5px;
  4225. }
  4226. .volumeLabel {
  4227. display:inline-block;
  4228. }
  4229.  
  4230. .nextsongcontrolbutton {
  4231. background:#fff;
  4232. border:1px solid #d9d9d9;
  4233. border-radius:2px;
  4234. cursor:pointer;
  4235. height:24px;
  4236. width:35px;
  4237. margin-top:2px;
  4238. margin-left:80px;
  4239. float:left;
  4240. text-align:center
  4241. }
  4242.  
  4243. .nextsongcontrolicon {
  4244. background-size:cover;
  4245. background-image:${spriteRepeatShuffle};
  4246. width:31px;
  4247. height:20px;
  4248. filter:drop-shadow(#FFF 1px 1px 2px);
  4249. display:inline-block;
  4250. margin-top:1px;
  4251. transition: filter 500ms;
  4252. }
  4253. .nextsongcontrolbutton.active .nextsongcontrolicon {
  4254. filter:drop-shadow(#0060F2 1px 1px 2px);
  4255. }
  4256.  
  4257. `);
  4258. const playbutton = document.querySelector('#trackInfoInner .playbutton');
  4259. const volumeButton = playbutton.cloneNode(true);
  4260. document.querySelector('#trackInfoInner .inline_player').appendChild(volumeButton);
  4261. volumeButton.classList.replace('playbutton', 'volumeButton');
  4262. volumeButton.style.width = playbutton.clientWidth + 'px';
  4263. const volumeSymbol = volumeButton.appendChild(document.createElement('div'));
  4264. volumeSymbol.className = 'volumeSymbol';
  4265. volumeSymbol.appendChild(document.createTextNode(CHROME ? '\uD83D\uDD5B' : '\u23F2'));
  4266. const progbar = document.querySelector('#trackInfoInner .progbar_cell .progbar');
  4267. const volumeBar = progbar.cloneNode(true);
  4268. document.querySelector('#trackInfoInner .inline_player').appendChild(volumeBar);
  4269. volumeBar.classList.add('volumeControl');
  4270. volumeBar.style.width = Math.max(200, progbar.clientWidth) + 'px';
  4271. const thumb = volumeBar.querySelector('.thumb');
  4272. thumb.setAttribute('id', 'deluxe_thumb');
  4273. const progbarFill = volumeBar.querySelector('.progbar_fill');
  4274. const volumeLabel = document.createElement('div');
  4275. document.querySelector('#trackInfoInner .inline_player').appendChild(volumeLabel);
  4276. volumeLabel.classList.add('volumeLabel');
  4277. let dragging = false;
  4278. let dragPos;
  4279. const width100 = volumeBar.clientWidth - (thumb.clientWidth + 2); // 2px border
  4280. const rot0 = CHROME ? -180 : -90;
  4281. const rot100 = CHROME ? 350 : 265 - rot0;
  4282. const blue0 = 180;
  4283. const blue100 = 75;
  4284. const green0 = 90;
  4285. const green100 = 100;
  4286. const audioAlbumPage = document.querySelector('body>audio');
  4287. addLogVolume(audioAlbumPage);
  4288. const volumeBarPos = volumeBar.getBoundingClientRect().left;
  4289. const displayVolume = function updateDisplayVolume() {
  4290. const level = audioAlbumPage.logVolume;
  4291. volumeLabel.innerHTML = parseInt(level * 100.0) + '%';
  4292. thumb.style.left = width100 * level + 'px';
  4293. progbarFill.style.width = parseInt(level * 100.0) + '%';
  4294. volumeSymbol.style.transform = 'rotate(' + (level * rot100 + rot0) + 'deg)';
  4295. if (level > 0.005) {
  4296. volumeSymbol.style.textShadow = 'rgb(0, ' + (level * green100 + green0) + ', ' + (level * blue100 + blue0) + ') 0px 0px 4px';
  4297. volumeSymbol.style.color = '#03a';
  4298. } else {
  4299. volumeSymbol.style.textShadow = 'rgb(255, 255, 255) 0px 0px 0px';
  4300. volumeSymbol.style.color = '#222';
  4301. }
  4302. };
  4303. thumb.addEventListener('mousedown', function thumbMouseDown(ev) {
  4304. if (ev.button === 0) {
  4305. dragging = true;
  4306. dragPos = ev.offsetX;
  4307. }
  4308. });
  4309. volumeBar.addEventListener('mouseup', function thumbMouseUp(ev) {
  4310. if (ev.button !== 0) {
  4311. return;
  4312. }
  4313. ev.preventDefault();
  4314. ev.stopPropagation();
  4315. if (!dragging) {
  4316. // Click on volume bar without dragging:
  4317. audioAlbumPage.muted = false;
  4318. audioAlbumPage.logVolume = Math.max(0.0, Math.min(1.0, (ev.pageX - volumeBarPos) / width100));
  4319. displayVolume();
  4320. }
  4321. dragging = false;
  4322. GM.setValue('volume', audioAlbumPage.logVolume);
  4323. });
  4324. document.addEventListener('mouseup', function documentMouseUp(ev) {
  4325. if (ev.button === 0 && dragging) {
  4326. dragging = false;
  4327. ev.preventDefault();
  4328. ev.stopPropagation();
  4329. GM.setValue('volume', audioAlbumPage.logVolume);
  4330. }
  4331. });
  4332. document.addEventListener('mousemove', function documentMouseMove(ev) {
  4333. if (ev.button === 0 && dragging) {
  4334. ev.preventDefault();
  4335. ev.stopPropagation();
  4336. audioAlbumPage.muted = false;
  4337. audioAlbumPage.logVolume = Math.max(0.0, Math.min(1.0, (ev.pageX - volumeBarPos - dragPos) / width100));
  4338. displayVolume();
  4339. }
  4340. });
  4341. const onWheel = function onMouseWheel(ev) {
  4342. ev.preventDefault();
  4343. const direction = Math.min(Math.max(-1.0, ev.deltaY), 1.0);
  4344. audioAlbumPage.logVolume = Math.min(Math.max(0.0, audioAlbumPage.logVolume - 0.05 * direction), 1.0);
  4345. displayVolume();
  4346. GM.setValue('volume', audioAlbumPage.logVolume);
  4347. };
  4348. volumeButton.addEventListener('wheel', onWheel, {
  4349. passive: false
  4350. });
  4351. volumeBar.addEventListener('wheel', onWheel, {
  4352. passive: false
  4353. });
  4354. volumeButton.addEventListener('click', function onVolumeButtonClick(ev) {
  4355. if (audioAlbumPage.logVolume < 0.01) {
  4356. if ('lastvolume' in audioAlbumPage.dataset && audioAlbumPage.dataset.lastvolume) {
  4357. audioAlbumPage.logVolume = audioAlbumPage.dataset.lastvolume;
  4358. GM.setValue('volume', audioAlbumPage.logVolume);
  4359. } else {
  4360. audioAlbumPage.logVolume = 1.0;
  4361. }
  4362. } else {
  4363. audioAlbumPage.dataset.lastvolume = audioAlbumPage.logVolume;
  4364. audioAlbumPage.logVolume = 0.0;
  4365. }
  4366. displayVolume();
  4367. });
  4368. displayVolume();
  4369. window.clearInterval(ivRestoreVolume);
  4370.  
  4371. // Repeat/shuffle buttons
  4372. const playnextcontrols = document.querySelector('#trackInfoInner .inline_player').appendChild(document.createElement('div'));
  4373.  
  4374. // Show repeat button
  4375. const repeatButton = playnextcontrols.appendChild(document.createElement('div'));
  4376. repeatButton.classList.add('nextsongcontrolbutton', 'repeat');
  4377. repeatButton.setAttribute('title', 'Repeat');
  4378. const repeatButtonIcon = repeatButton.appendChild(document.createElement('div'));
  4379. repeatButtonIcon.classList.add('nextsongcontrolicon');
  4380. repeatButton.dataset.repeat = 'none';
  4381. repeatButtonIcon.style.backgroundPositionY = '-20px';
  4382. repeatButton.addEventListener('click', function () {
  4383. const posY = this.getElementsByClassName('nextsongcontrolicon')[0].style.backgroundPositionY;
  4384. if (posY === '-20px') {
  4385. this.getElementsByClassName('nextsongcontrolicon')[0].style.backgroundPositionY = '-40px';
  4386. this.classList.toggle('active');
  4387. this.dataset.repeat = 'one';
  4388. } else if (posY === '-40px') {
  4389. this.getElementsByClassName('nextsongcontrolicon')[0].style.backgroundPositionY = '-60px';
  4390. this.dataset.repeat = 'all';
  4391. } else {
  4392. this.getElementsByClassName('nextsongcontrolicon')[0].style.backgroundPositionY = '-20px';
  4393. this.classList.toggle('active');
  4394. this.dataset.repeat = 'none';
  4395. }
  4396. });
  4397. if (allFeatures.albumPageAutoRepeatAll.enabled) {
  4398. repeatButton.click();
  4399. repeatButton.click();
  4400. }
  4401.  
  4402. // Show shuffle button
  4403. const shuffleButton = playnextcontrols.appendChild(document.createElement('div'));
  4404. if (document.querySelectorAll('#track_table a div').length > 2) {
  4405. shuffleButton.classList.add('nextsongcontrolbutton', 'shuffle');
  4406. shuffleButton.setAttribute('title', 'Shuffle');
  4407. const shuffleButtonIcon = shuffleButton.appendChild(document.createElement('div'));
  4408. shuffleButtonIcon.classList.add('nextsongcontrolicon');
  4409. shuffleButtonIcon.style.backgroundPositionY = '0px';
  4410. shuffleButton.addEventListener('click', function () {
  4411. this.classList.toggle('active');
  4412. });
  4413. }
  4414. const findLastSongIndex = function () {
  4415. const allDiv = document.querySelectorAll('#track_table a div');
  4416. const nextDiv = document.querySelector('#track_table a div.playing');
  4417. if (!nextDiv) {
  4418. return allDiv.length - 1;
  4419. }
  4420. for (let i = 1; i < allDiv.length; i++) {
  4421. if (allDiv[i] === nextDiv) {
  4422. return i - 1;
  4423. }
  4424. }
  4425. return -1;
  4426. };
  4427. const albumPageAudioOnEnded = function (ev) {
  4428. const allDiv = document.querySelectorAll('#track_table a div');
  4429. if (repeatButton.dataset.repeat === 'one') {
  4430. // Click on last song again
  4431. if (allDiv.length > 0) {
  4432. allDiv[findLastSongIndex()].click();
  4433. } else {
  4434. // No tracklist, click on play button
  4435. document.querySelector('#trackInfoInner .inline_player .playbutton').click();
  4436. }
  4437. } else if (shuffleButton.classList.contains('active') && allDiv.length > 1) {
  4438. // Find last song
  4439. const lastSongIndex = findLastSongIndex();
  4440. // Set a random song (that is not the last song)
  4441. let index = lastSongIndex;
  4442. while (index === lastSongIndex) {
  4443. index = randomIndex(allDiv.length);
  4444. }
  4445. if (index !== lastSongIndex + 1) {
  4446. allDiv[index].click();
  4447. }
  4448. } else if (repeatButton.dataset.repeat === 'all') {
  4449. if (findLastSongIndex() === allDiv.length - 1) {
  4450. if (allDiv[0]) {
  4451. allDiv[0].click(); // Click on first song's play button
  4452. } else {
  4453. // No tracklist, click on play button
  4454. document.querySelector('#trackInfoInner .inline_player .playbutton').click();
  4455. }
  4456. }
  4457. }
  4458. };
  4459. let lastMediaHubTitle = null;
  4460. const onNotificationClick = function () {
  4461. if (!document.querySelector('#trackInfoInner .inline_player .nextbutton').classList.contains('hiddenelem')) {
  4462. document.querySelector('#trackInfoInner .inline_player .nextbutton').click();
  4463. }
  4464. };
  4465. const updateChromePositionState = function () {
  4466. if (audioAlbumPage && 'mediaSession' in navigator && 'setPositionState' in navigator.mediaSession) {
  4467. navigator.mediaSession.setPositionState({
  4468. duration: audioAlbumPage.duration || 180,
  4469. playbackRate: audioAlbumPage.playbackRate,
  4470. position: audioAlbumPage.currentTime
  4471. });
  4472. }
  4473. };
  4474. const albumPageUpdateMediaHubListener = function albumPageUpdateMediaHub() {
  4475. const TralbumData = unsafeWindow.TralbumData;
  4476. const title = document.querySelector('#trackInfoInner .inline_player .title').textContent.trim();
  4477. if (lastMediaHubTitle === title) {
  4478. return;
  4479. }
  4480. lastMediaHubTitle = title;
  4481.  
  4482. // Notification
  4483. if (allFeatures.nextSongNotifications.enabled && 'notification' in GM) {
  4484. GM.notification({
  4485. title: document.location.host,
  4486. text: title + '\nby ' + TralbumData.artist + '\nfrom ' + TralbumData.current.title,
  4487. image: `https://f4.bcbits.com/img/a${TralbumData.current.art_id}_2.jpg`,
  4488. highlight: false,
  4489. silent: true,
  4490. timeout: NOTIFICATION_TIMEOUT,
  4491. onclick: onNotificationClick
  4492. });
  4493. }
  4494.  
  4495. // Media hub
  4496. if ('mediaSession' in navigator) {
  4497. if (audioAlbumPage) {
  4498. navigator.mediaSession.playbackState = !audioAlbumPage.paused ? 'playing' : 'paused';
  4499. updateChromePositionState();
  4500. }
  4501.  
  4502. // Pre load image to get dimension
  4503. const cover = document.createElement('img');
  4504. cover.onload = function onCoverLoaded() {
  4505. navigator.mediaSession.metadata = new MediaMetadata({
  4506. title,
  4507. artist: TralbumData.artist,
  4508. album: TralbumData.current.title,
  4509. artwork: [{
  4510. src: cover.src,
  4511. sizes: `${cover.width}x${cover.height}`,
  4512. type: 'image/jpeg'
  4513. }]
  4514. });
  4515. };
  4516. cover.src = `https://f4.bcbits.com/img/a${TralbumData.current.art_id}_2.jpg`;
  4517. if (!document.querySelector('#trackInfoInner .inline_player .prevbutton').classList.contains('hiddenelem')) {
  4518. navigator.mediaSession.setActionHandler('previoustrack', () => document.querySelector('#trackInfoInner .inline_player .prevbutton').click());
  4519. } else {
  4520. navigator.mediaSession.setActionHandler('previoustrack', null);
  4521. }
  4522. if (!document.querySelector('#trackInfoInner .inline_player .nextbutton').classList.contains('hiddenelem')) {
  4523. navigator.mediaSession.setActionHandler('nexttrack', () => document.querySelector('#trackInfoInner .inline_player .nextbutton').click());
  4524. } else {
  4525. navigator.mediaSession.setActionHandler('nexttrack', null);
  4526. }
  4527. if (audioAlbumPage) {
  4528. navigator.mediaSession.setActionHandler('play', function () {
  4529. audioAlbumPage.play();
  4530. navigator.mediaSession.playbackState = 'playing';
  4531. });
  4532. navigator.mediaSession.setActionHandler('pause', function () {
  4533. audioAlbumPage.pause();
  4534. navigator.mediaSession.playbackState = 'paused';
  4535. });
  4536. navigator.mediaSession.setActionHandler('seekbackward', function (event) {
  4537. const skipTime = event.seekOffset || DEFAULTSKIPTIME;
  4538. audioAlbumPage.currentTime = Math.max(audioAlbumPage.currentTime - skipTime, 0);
  4539. updateChromePositionState();
  4540. });
  4541. navigator.mediaSession.setActionHandler('seekforward', function (event) {
  4542. const skipTime = event.seekOffset || DEFAULTSKIPTIME;
  4543. audioAlbumPage.currentTime = Math.min(audioAlbumPage.currentTime + skipTime, audioAlbumPage.duration);
  4544. updateChromePositionState();
  4545. });
  4546. try {
  4547. navigator.mediaSession.setActionHandler('stop', function () {
  4548. audioAlbumPage.pause();
  4549. audioAlbumPage.currentTime = 0;
  4550. navigator.mediaSession.playbackState = 'paused';
  4551. });
  4552. } catch (error) {
  4553. console.warn('Warning! The "stop" media session action is not supported.');
  4554. }
  4555. try {
  4556. navigator.mediaSession.setActionHandler('seekto', function (event) {
  4557. if (event.fastSeek && 'fastSeek' in audioAlbumPage) {
  4558. audioAlbumPage.fastSeek(event.seekTime);
  4559. return;
  4560. }
  4561. audioAlbumPage.currentTime = event.seekTime;
  4562. updateChromePositionState();
  4563. });
  4564. } catch (error) {
  4565. console.warn('Warning! The "seekto" media session action is not supported.');
  4566. }
  4567. }
  4568. }
  4569. };
  4570. audioAlbumPage.addEventListener('ended', albumPageAudioOnEnded);
  4571. audioAlbumPage.addEventListener('play', albumPageUpdateMediaHubListener);
  4572. audioAlbumPage.addEventListener('ended', albumPageUpdateMediaHubListener);
  4573. }
  4574. function clickAddToWishlist() {
  4575. const wishButton = document.querySelector('#collect-item>*');
  4576. if (!wishButton) {
  4577. window.setTimeout(clickAddToWishlist, 300);
  4578. return;
  4579. }
  4580. wishButton.click();
  4581. if (document.querySelector('#collection-main a')) {
  4582. // if logged in, the click should be successful, so try to close the window
  4583. window.setTimeout(window.close, 1000);
  4584. }
  4585. }
  4586. function addReleaseDateButton() {
  4587. const TralbumData = unsafeWindow.TralbumData;
  4588. const now = new Date();
  4589. const releaseDate = new Date(TralbumData.current.release_date);
  4590. const days = parseInt(Math.ceil((releaseDate - now) / (1000 * 60 * 60 * 24)));
  4591. if (releaseDate < now) {
  4592. return; // Release date is in the past
  4593. }
  4594.  
  4595. const key = albumKey(TralbumData.url);
  4596. addStyle(`
  4597. .releaseReminderButton {
  4598. font-size:13px;
  4599. font-weight:700;
  4600. cursor:pointer;
  4601. transition: border 500ms, padding 500ms
  4602. }
  4603. .releaseReminderButton.active {
  4604. border-radius:5px;
  4605. padding:0px 5px;
  4606. border:#3fb32f66 solid 2px
  4607. }
  4608. .releaseReminderButton:hover .releaseLabel {
  4609. text-decoration:underline
  4610. }
  4611. `);
  4612. const div = document.querySelector('.share-collect-controls').appendChild(document.createElement('div'));
  4613. div.style = 'margin-top:4px';
  4614. const span = div.appendChild(document.createElement('span'));
  4615. span.className = 'custom-link-color releaseReminderButton';
  4616. span.title = 'Releases ' + dateFormaterRelease(releaseDate);
  4617. const daysStr = days === 1 ? 'tomorrow' : `in ${days} days`;
  4618. span.innerHTML = `<span>\u23F0</span> <span class="releaseLabel">Notify <time datetime="${releaseDate.toISOString()}">${daysStr}</time></span>`;
  4619. span.addEventListener('click', ev => toggleReleaseReminder(ev, span));
  4620. GM.getValue('releasereminder', '{}').then(function (str) {
  4621. const releaseReminderData = JSON.parse(str);
  4622. if (key in releaseReminderData) {
  4623. span.classList.add('active');
  4624. span.innerHTML = `<span>\u23F0</span> <span class="releaseLabel">Reminder set (<time datetime="${releaseDate.toISOString()}">${daysStr}</time>)</span>`;
  4625. }
  4626. });
  4627. }
  4628. async function toggleReleaseReminder(ev, span) {
  4629. const TralbumData = unsafeWindow.TralbumData;
  4630. const key = albumKey(TralbumData.url);
  4631. const releaseReminderData = JSON.parse(await GM.getValue('releasereminder', '{}'));
  4632. if (key in releaseReminderData) {
  4633. delete releaseReminderData[key];
  4634. } else {
  4635. releaseReminderData[key] = {
  4636. albumCover: `https://f4.bcbits.com/img/a${TralbumData.art_id}_2.jpg`,
  4637. releaseDate: TralbumData.current.release_date,
  4638. artist: TralbumData.artist,
  4639. title: TralbumData.current.title
  4640. };
  4641. }
  4642. await GM.setValue('releasereminder', JSON.stringify(releaseReminderData));
  4643. if (span) {
  4644. const releaseDate = new Date(TralbumData.current.release_date);
  4645. const now = new Date();
  4646. const days = parseInt(Math.ceil((releaseDate - now) / (1000 * 60 * 60 * 24)));
  4647. const daysStr = days === 1 ? 'tomorrow' : `in ${days} days`;
  4648. if (key in releaseReminderData) {
  4649. span.classList.add('active');
  4650. span.innerHTML = `<span>\u23F0</span> <span class="releaseLabel">Reminder set (<time datetime="${releaseDate.toISOString()}">${daysStr}</time>)</span>`;
  4651. } else {
  4652. span.classList.remove('active');
  4653. span.innerHTML = `<span>\u23F0</span> <span class="releaseLabel">Notify <time datetime="${releaseDate.toISOString()}">${daysStr}</time></span>`;
  4654. }
  4655. }
  4656. }
  4657. async function removeReleaseReminder(ev) {
  4658. ev.preventDefault();
  4659. const key = this.parentNode.dataset.key;
  4660. const releaseReminderData = JSON.parse(await GM.getValue('releasereminder', '{}'));
  4661. if (key in releaseReminderData) {
  4662. delete releaseReminderData[key];
  4663. await GM.setValue('releasereminder', JSON.stringify(releaseReminderData));
  4664. }
  4665. this.parentNode.remove();
  4666. }
  4667. function maximizePastReleases() {
  4668. document.getElementById('pastreleases').style.opacity = 0.0;
  4669. window.setTimeout(() => showPastReleases(null, true), 500);
  4670. document.getElementById('pastreleases').removeEventListener('click', maximizePastReleases);
  4671. }
  4672. async function showPastReleases(ev, forceShow) {
  4673. let hideDate = await GM.getValue('pastreleaseshidden', false);
  4674. const releaseReminderData = JSON.parse(await GM.getValue('releasereminder', '{}'));
  4675. const releases = [];
  4676. let pastReleasesCounter = 0;
  4677. const now = new Date();
  4678. now.setHours(23);
  4679. now.setMinutes(59);
  4680. for (const key in releaseReminderData) {
  4681. releaseReminderData[key].key = key;
  4682. releaseReminderData[key].date = new Date(releaseReminderData[key].releaseDate);
  4683. releaseReminderData[key].past = now >= releaseReminderData[key].date;
  4684. if (releaseReminderData[key].past) {
  4685. pastReleasesCounter++;
  4686. }
  4687. releases.push(releaseReminderData[key]);
  4688. }
  4689. releases.sort((a, b) => b.date - a.date);
  4690. if (releases.length === 0 || pastReleasesCounter === 0) {
  4691. return;
  4692. }
  4693. if (!document.getElementById('pastreleases')) {
  4694. addStyle(pastreleasesCSS);
  4695. }
  4696. const div = document.body.appendChild(document.getElementById('pastreleases') || document.createElement('div'));
  4697. div.setAttribute('id', 'pastreleases');
  4698. div.style.maxHeight = document.documentElement.clientHeight - 50 + 'px';
  4699. div.style.maxWidth = document.documentElement.clientWidth - 100 + 'px';
  4700. if (document.getElementById('discographyplayer') && !allFeatures.discographyplayerSidebar.enabled) {
  4701. div.style.bottom = document.getElementById('discographyplayer').clientHeight + 10 + 'px';
  4702. }
  4703. window.setTimeout(function () {
  4704. div.style.opacity = 1.0;
  4705. }, 200);
  4706. div.innerHTML = '';
  4707. const table = div.appendChild(document.createElement('div'));
  4708. table.classList.add('tablediv');
  4709. const firstRow = table.appendChild(document.createElement('div'));
  4710. firstRow.classList.add('header');
  4711. firstRow.appendChild(document.createTextNode('\u23F0'));
  4712. firstRow.appendChild(document.createElement('span'));
  4713. if (!forceShow && hideDate && !isNaN(hideDate = new Date(hideDate)) && new Date() - hideDate < 1000 * 60 * 60) {
  4714. firstRow.appendChild(document.createTextNode(`${pastReleasesCounter} release` + (pastReleasesCounter === 1 ? '' : 's')));
  4715. table.addEventListener('click', maximizePastReleases);
  4716. return;
  4717. } else {
  4718. GM.setValue('pastreleaseshidden', '');
  4719. }
  4720. const upcoming = firstRow.appendChild(document.createElement('span'));
  4721. if (releases.length !== pastReleasesCounter) {
  4722. upcoming.appendChild(document.createTextNode(' Show upcoming'));
  4723. upcoming.classList.add('upcoming');
  4724. upcoming.addEventListener('click', function () {
  4725. document.querySelectorAll('#pastreleases .future').forEach(function (el) {
  4726. el.style.display = 'table-row';
  4727. });
  4728. this.remove();
  4729. });
  4730. }
  4731. const controls = firstRow.appendChild(document.createElement('span'));
  4732. controls.classList.add('controls');
  4733. const refresh = controls.appendChild(document.createElement('span'));
  4734. refresh.setAttribute('title', 'Update');
  4735. refresh.addEventListener('click', function () {
  4736. document.getElementById('pastreleases').style.opacity = 0.0;
  4737. window.setTimeout(() => showPastReleases(null, true), 1200);
  4738. });
  4739. refresh.appendChild(document.createTextNode(NOEMOJI ? 'Refresh' : '⟳'));
  4740. const close = controls.appendChild(document.createElement('span'));
  4741. close.setAttribute('title', 'Hide');
  4742. close.addEventListener('click', function () {
  4743. GM.setValue('pastreleaseshidden', new Date().toJSON());
  4744. document.getElementById('pastreleases').style.opacity = 0.0;
  4745. window.setTimeout(function () {
  4746. document.getElementById('pastreleases').remove();
  4747. }, 700);
  4748. });
  4749. close.appendChild(document.createTextNode('X'));
  4750. releases.forEach(function (release) {
  4751. const days = parseInt(Math.ceil((release.date - now) / (1000 * 60 * 60 * 24)));
  4752. const daysStr = days === 1 ? 'tomorrow' : `in ${days} days`;
  4753. let title = `${release.artist} - ${release.title}`;
  4754. const entry = table.appendChild(document.createElement('a'));
  4755. entry.setAttribute('title', title);
  4756. entry.dataset.key = release.key;
  4757. entry.classList.add('entry');
  4758. entry.classList.add(release.past ? 'past' : 'future');
  4759. entry.setAttribute('href', document.location.protocol + '//' + release.key);
  4760. entry.setAttribute('target', '_blank');
  4761. const removeButton = entry.appendChild(document.createElement('span'));
  4762. removeButton.setAttribute('title', 'Remove album');
  4763. removeButton.classList.add('remove');
  4764. removeButton.appendChild(document.createTextNode(NOEMOJI ? 'X' : '╳'));
  4765. removeButton.addEventListener('click', removeReleaseReminder);
  4766. const time = entry.appendChild(document.createElement('time'));
  4767. time.setAttribute('datetime', release.date.toISOString());
  4768. time.setAttribute('title', 'Releases ' + dateFormaterRelease(release.date));
  4769. if (release.past) {
  4770. time.appendChild(document.createTextNode(dateFormaterNumeric(release.date)));
  4771. } else {
  4772. time.appendChild(document.createTextNode(daysStr));
  4773. }
  4774. const span = entry.appendChild(document.createElement('span'));
  4775. span.classList.add('title');
  4776. title = title.length < 60 ? title : title.substr(0, 57) + '…';
  4777. span.appendChild(document.createTextNode(' ' + title));
  4778. const image = entry.appendChild(document.createElement('div'));
  4779. image.classList.add('image');
  4780. image.style.backgroundRepeat = 'no-repeat';
  4781. image.style.backgroundSize = 'contain';
  4782. image.style.backgroundImage = `url(${release.albumCover})`;
  4783. });
  4784. }
  4785. function showTagSearchForm() {
  4786. const menuA = document.querySelector('#bcsde_tagsearchbutton');
  4787. menuA.style.display = 'none';
  4788. if (!document.getElementById('bcsde_tagsearchform')) {
  4789. addStyle(`
  4790. #bcsde_tagsearchform {
  4791. margin:0px 7px;
  4792. }
  4793. #bcsde_tagsearchform_tags {
  4794. display: inline-block;
  4795. list-style: none;
  4796. padding: 0;
  4797. }
  4798. #bcsde_tagsearchform_tags li {
  4799. display:inline;
  4800. background:#f2eaea8a;
  4801. border: 1px solid rgb(225, 45, 5);
  4802. border-radius: 15px;
  4803. padding: 2px 10px 2px 2px;
  4804. font-size: 13px;
  4805. font-weight: 500;
  4806. }
  4807. #bcsde_tagsearchform_tags li svg {
  4808. filter: invert(100%);
  4809. fill:rgb(225, 45, 5);
  4810. vertical-align: middle;
  4811. }
  4812. #bcsde_tagsearchform_tags li .checkmark-icon {
  4813. display:inline-block;
  4814. }
  4815. #bcsde_tagsearchform_tags li .close-icon {
  4816. display:none;
  4817. }
  4818. #bcsde_tagsearchform_tags li:hover .checkmark-icon {
  4819. display:none;
  4820. }
  4821. #bcsde_tagsearchform_tags li:hover .close-icon {
  4822. display:inline-block;
  4823. }
  4824. #bcsde_tagsearchform button {
  4825. margin: 3px;
  4826. color: black !important;
  4827. }
  4828. #bcsde_tagsearchform_input {
  4829. background-color: #DFDFDF;
  4830. padding: 10px 30px 10px 10px;
  4831. font-size: 14px;
  4832. border: none;
  4833. width: 150px;
  4834. color: #333;
  4835. margin: 6px 0;
  4836. border-radius: 3px;
  4837. box-sizing: border-box;
  4838. input-select:auto;
  4839. -webkit-user-select:auto;
  4840. }
  4841. #bcsde_tagsearchform_suggestions {
  4842. list-style: none;
  4843. margin: 0;
  4844. position: absolute;
  4845. z-index: 10;
  4846. background: #FFF;
  4847. visibility: hidden;
  4848. border: 1px solid #000;
  4849. font-weight: normal;
  4850. padding: 8px 0;
  4851. opacity:0;
  4852. transition:visibility 200ms linear,opacity 200ms linear;
  4853. ${darkModeModeCurrent === true ? 'filter: invert(85%);' : ''}
  4854. }
  4855. #bcsde_tagsearchform_suggestions.visible {
  4856. visibility:visible;
  4857. opacity:1;
  4858. }
  4859. #bcsde_tagsearchform_suggestions li {
  4860. padding: 8px 10px;
  4861. cursor: pointer;
  4862. list-style: none;
  4863. margin: 0;
  4864. display: list-item;
  4865. text-align: left;
  4866. }
  4867. #bcsde_tagsearchform_suggestions li:hover,#bcsde_tagsearchform_suggestions li:focus {
  4868. background: #F3F3F3;
  4869. }
  4870. `);
  4871. const div = document.createElement('div');
  4872. div.setAttribute('id', 'bcsde_tagsearchform');
  4873. menuA.parentNode.appendChild(div);
  4874. const tagsHolder = div.appendChild(document.createElement('ul'));
  4875. tagsHolder.setAttribute('id', 'bcsde_tagsearchform_tags');
  4876. const m = document.location.href.match(/\/tag\/([A-Za-z0-9-]+)(\?tab=all_releases&t=(.+))?/); // https://bandcamp.com/tag/metal?tab=all_releases&t=post-punk%2Cdark
  4877. const tags = [];
  4878. if (m) {
  4879. tags.push(m[1]);
  4880. if (m[3]) {
  4881. tags.push(...m[3].split('&')[0].split('#')[0].split('%2C'));
  4882. }
  4883. }
  4884. tags.forEach(tag => {
  4885. tagsHolder.appendChild(tagSearchLabel(tag, tag.replace('-', ' ')));
  4886. });
  4887. const button = div.appendChild(document.createElement('button'));
  4888. button.appendChild(document.createTextNode('Go'));
  4889. button.addEventListener('click', openTagSearch);
  4890. const input = div.appendChild(document.createElement('input'));
  4891. input.setAttribute('type', 'text');
  4892. input.setAttribute('id', 'bcsde_tagsearchform_input');
  4893. input.setAttribute('placeholder', 'tag search');
  4894. input.addEventListener('keyup', tagSearchInputChange);
  4895. const suggestions = div.appendChild(document.createElement('ol'));
  4896. suggestions.setAttribute('id', 'bcsde_tagsearchform_suggestions');
  4897. if (document.querySelector('#corphome-autocomplete-form ul.hd-nav.corp-nav .log-in-link')) {
  4898. // Homepage and not logged in -> make some room by removing the other list items from the nav
  4899. document.querySelectorAll('#corphome-autocomplete-form ul.hd-nav.corp-nav>li:not([class~="menubar-item-tag-search"])').forEach(listItem => listItem.remove());
  4900. }
  4901. } else {
  4902. document.querySelector('#bcsde_tagsearchform').style.display = '';
  4903. }
  4904. }
  4905. function tagSearchLabel(tagNormName, tagName) {
  4906. const li = document.createElement('li');
  4907. li.dataset.tagNormName = tagNormName;
  4908. li.dataset.name = tagName;
  4909. const remove = li.appendChild(document.createElement('span'));
  4910. remove.addEventListener('click', function () {
  4911. this.parentNode.remove();
  4912. });
  4913. remove.innerHTML = `
  4914. <svg class="checkmark-icon" width="16" height="16" viewBox="0 0 24 24">
  4915. <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#material-done"></use>
  4916. </svg>
  4917. <svg class="close-icon" width="16" height="16" viewBox="0 0 24 24">
  4918. <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#material-close"></use>
  4919. </svg>
  4920. `;
  4921. li.appendChild(document.createTextNode(tagName));
  4922. return li;
  4923. }
  4924. let ivTagSearchInput = null;
  4925. function tagSearchInputChange(ev) {
  4926. clearInterval(ivTagSearchInput);
  4927. if (ev.key === 'Enter') {
  4928. const input = document.getElementById('bcsde_tagsearchform_input');
  4929. if (input.value) {
  4930. useTagSuggestion(null, input.value);
  4931. return;
  4932. }
  4933. }
  4934. ivTagSearchInput = window.setTimeout(showTagSuggestions, 300);
  4935. }
  4936. function showTagSuggestions() {
  4937. const input = document.getElementById('bcsde_tagsearchform_input');
  4938. const suggestions = document.getElementById('bcsde_tagsearchform_suggestions');
  4939. if (!input.value.trim()) {
  4940. suggestions.classList.remove('visible');
  4941. return;
  4942. }
  4943. getTagSuggestions(input.value).then(data => {
  4944. let found = false;
  4945. if (data.ok && 'matching_tags' in data) {
  4946. suggestions.innerHTML = '';
  4947. suggestions.classList.add('visible');
  4948. suggestions.style.left = input.offsetLeft + 'px';
  4949. data.matching_tags.forEach(result => {
  4950. found = true;
  4951. const li = suggestions.appendChild(document.createElement('li'));
  4952. li.dataset.tagNormName = result.tag_norm_name;
  4953. li.dataset.name = result.tag_name;
  4954. li.addEventListener('click', useTagSuggestion);
  4955. li.appendChild(document.createTextNode(result.tag_name));
  4956. });
  4957. }
  4958. if (!found) {
  4959. if (input.value.trim()) {
  4960. const li = suggestions.appendChild(document.createElement('li'));
  4961. li.dataset.tagNormName = input.value.replace(/\s+/, '-');
  4962. li.dataset.name = input.value;
  4963. li.addEventListener('click', useTagSuggestion);
  4964. li.appendChild(document.createTextNode(input.value));
  4965. } else {
  4966. suggestions.classList.remove('visible');
  4967. }
  4968. }
  4969. });
  4970. }
  4971. function useTagSuggestion(ev, str = null) {
  4972. const suggestions = document.getElementById('bcsde_tagsearchform_suggestions');
  4973. const tagsHolder = document.getElementById('bcsde_tagsearchform_tags');
  4974. const input = document.getElementById('bcsde_tagsearchform_input');
  4975. let tagNormName;
  4976. let name;
  4977. if (str) {
  4978. // Use str
  4979. tagNormName = str.replace(/\s+/, '-');
  4980. name = str;
  4981. } else {
  4982. // Use tag that was clicked
  4983. tagNormName = this.dataset.tagNormName;
  4984. name = this.dataset.name;
  4985. }
  4986. tagsHolder.appendChild(tagSearchLabel(tagNormName, name));
  4987. suggestions.classList.remove('visible');
  4988. input.value = '';
  4989. input.focus();
  4990. }
  4991. function getTagSuggestions(query) {
  4992. const url = 'https://bandcamp.com/api/fansignup/1/search_tag';
  4993. return new Promise(function getTagSuggestionsPromise(resolve, reject) {
  4994. GM.xmlHttpRequest({
  4995. method: 'POST',
  4996. data: JSON.stringify({
  4997. count: 20,
  4998. search_term: query
  4999. }),
  5000. url,
  5001. onload: function getTagSuggestionsOnLoad(response) {
  5002. if (!response.responseText || response.responseText.indexOf('400 Bad Request') !== -1) {
  5003. reject(new Error('Tag suggestions error: Too many cookies'));
  5004. return;
  5005. }
  5006. if (!response.responseText || response.responseText.indexOf('429 Too Many Requests') !== -1) {
  5007. reject(new Error('Tag suggestions error: 429 Too Many Requests'));
  5008. return;
  5009. }
  5010. let result = null;
  5011. try {
  5012. result = JSON.parse(response.responseText);
  5013. } catch (e) {
  5014. console.debug(response.responseText);
  5015. reject(e);
  5016. return;
  5017. }
  5018. resolve(result);
  5019. },
  5020. onerror: function getTagSuggestionsOnError(response) {
  5021. reject(new Error('error' in response ? response.error : 'getTagSuggestions failed with GM.xmlHttpRequest.onerror'));
  5022. }
  5023. });
  5024. });
  5025. }
  5026. function openTagSearch() {
  5027. // https://bandcamp.com/tag/metal?tab=all_releases&t=post-punk%2Cdark
  5028. this.innerHTML = 'Loading...';
  5029. const tagsHolder = document.getElementById('bcsde_tagsearchform_tags');
  5030. const tags = [...new Set(Array.from(tagsHolder.querySelectorAll('li')).map(li => li.dataset.tagNormName))];
  5031. if (!tags) {
  5032. return;
  5033. }
  5034. const url = `https://bandcamp.com/tag/${tags.shift()}?tab=all_releases&t=${tags.join('%2C')}`;
  5035. document.location.href = url;
  5036. }
  5037. function mainMenu(startBackup) {
  5038. addStyle(`
  5039. .deluxemenu {
  5040. position:fixed;
  5041. height:auto;
  5042. overflow:auto;
  5043. top:20px;
  5044. left:20px;
  5045. z-index:1102;
  5046. padding:5px;
  5047. transition: left 1s;
  5048. border:2px solid black;
  5049. border-radius:10px;
  5050. color:black;
  5051. background:white;
  5052. }
  5053. .deluxemenu input{
  5054. box-shadow: 2px 2px 5px #5555;
  5055. transition: box-shadow 500ms;
  5056. }
  5057. .deluxemenu fieldset{
  5058. border: 1px solid #000a;
  5059. border-radius: 4px;
  5060. box-shadow: 1px 1px 3px #0005;
  5061. }
  5062. .deluxemenu fieldset legend{
  5063. margin-left: 10px;
  5064. color: #000a
  5065. }
  5066. .breathe {
  5067. animation: breathe 1.5s linear infinite
  5068. }
  5069. @keyframes breathe {
  5070. 50% { opacity: 0.3 }
  5071. }
  5072. .errorblink {
  5073. animation: errorblink 1.5s linear infinite;
  5074. border: 2px solid red;
  5075. }
  5076. @keyframes errorblink {
  5077. 50% { border-color:#6a0c41 }
  5078. }
  5079. .deluxemenu ul {
  5080. margin: 0px;
  5081. padding: 0px 0px 0px 10px;
  5082. list-style:disc;
  5083. }
  5084. .deluxemenu ul li{
  5085. margin: 0px;
  5086. padding: 0px;
  5087. }
  5088. `);
  5089. if (startBackup === true) {
  5090. exportMenu();
  5091. return;
  5092. }
  5093. if (document.querySelector('.deluxemenu')) {
  5094. return;
  5095. }
  5096.  
  5097. // Blur background
  5098. if (document.getElementById('centerWrapper')) {
  5099. document.getElementById('centerWrapper').style.filter = 'blur(4px)';
  5100. }
  5101. const main = document.body.appendChild(document.createElement('div'));
  5102. main.className = 'deluxemenu';
  5103. main.innerHTML = `<h2>${SCRIPT_NAME}</h2>
  5104. Source code license: <a target="_blank" href="https://github.com/cvzi/Bandcamp-script-deluxe-edition/blob/master/LICENSE">MIT</a><br>
  5105. Support: <a target="_blank" href="https://github.com/cvzi/Bandcamp-script-deluxe-edition">github.com/cvzi/Bandcamp-script-deluxe-edition</a><br>
  5106. Dark theme based on: <a target="_blank" href="https://userstyles.org/styles/171538/bandcamp-in-dark">"Bandcamp In Dark"</a> by <a target="_blank" href="https://userstyles.org/users/563391">Simonus</a><br>
  5107. Dev &amp; build tools used: <a target="_blank" href="https://github.com/cvzi/Bandcamp-script-deluxe-edition/blob/master/package.json#L43-L71">package.json</a><br>
  5108. Emoji: <a target="_blank" href="https://github.com/hfg-gmuend/openmoji">OpenMoji</a><br>
  5109. Javascript libraries used:<br><ul>
  5110. <li><a target="_blank" href="https://json5.org/">JSON5 - JSON for Humans</a> (MIT license)</li>
  5111. <li><a target="_blank" href="https://github.com/facebook/react">React</a> (MIT license)</li>
  5112. <li><a target="_blank" href="https://github.com/cvzi/genius-lyrics-userscript/">GeniusLyrics.js</a> (GPLv3)</li>
  5113. </ul>
  5114. <h3>Options</h3>
  5115. `;
  5116. window.setTimeout(function moveMenuIntoView() {
  5117. main.style.maxHeight = document.documentElement.clientHeight - 150 + 'px';
  5118. main.style.maxWidth = document.documentElement.clientWidth - 40 + 'px';
  5119. main.style.left = Math.max(20, 0.5 * (document.body.clientWidth - main.clientWidth)) + 'px';
  5120. }, 0);
  5121. Promise.all([GM.getValue('volume', '0.7'), GM.getValue('myalbums', '{}'), GM.getValue('tralbumdata', '{}'), GM.getValue('enabledFeatures', false), GM.getValue('markasplayedThreshold', '10s')]).then(function allPromisesLoaded(values) {
  5122. // let volume = parseFloat(values[0])
  5123. // volume = Number.isNaN(volume) ? 0.7 : volume
  5124. const myalbums = JSON.parse(values[1]);
  5125. const tralbumdata = JSON.parse(values[2]);
  5126. getEnabledFeatures(values[3]);
  5127. const markasplayedThreshold = values[4];
  5128. const checkboxOnChange = async function onCheckboxChange() {
  5129. const input = this;
  5130. getEnabledFeatures(await GM.getValue('enabledFeatures', false));
  5131. allFeatures[input.name].enabled = input.checked;
  5132. await GM.setValue('enabledFeatures', JSON.stringify(allFeatures));
  5133. input.style.boxShadow = '2px 2px 5px #0a0f';
  5134. window.setTimeout(function resetBoxShadowTimeout() {
  5135. input.style.boxShadow = '';
  5136. }, 3000);
  5137. updateMoreVisibility();
  5138. };
  5139. const thresholdOnChange = async function onThresholdChange() {
  5140. const input = this;
  5141. let value = input.value.trim();
  5142. const m = value.match(/^(\d+)(s|%)$/);
  5143. if (m && parseInt(m[1]) >= 0 && (m[2] === 's' || parseInt(m[1]) <= 100)) {
  5144. value = m[1] + m[2];
  5145. } else if (value.match(/^\d+$/) && parseInt(value.split('\n')[0]) >= 0) {
  5146. value = value.split('\n')[0] + 's';
  5147. } else {
  5148. window.alert('Format does not match!\nChoose either a time in seconds e.g. 10s or a percentage e.g. 50%');
  5149. return;
  5150. }
  5151. await GM.setValue('markasplayedThreshold', value);
  5152. input.value = value;
  5153. input.style.boxShadow = '2px 2px 5px #0a0f';
  5154. window.setTimeout(function resetBoxShadowTimeout() {
  5155. input.style.boxShadow = '';
  5156. }, 3000);
  5157. };
  5158. const updateMoreVisibility = function () {
  5159. for (const feature in allFeatures) {
  5160. if (document.getElementById('feature_' + feature + '_more_on')) {
  5161. document.getElementById('feature_' + feature + '_more_on').style.display = allFeatures[feature].enabled ? 'block' : 'none';
  5162. }
  5163. if (document.getElementById('feature_' + feature + '_more_off')) {
  5164. document.getElementById('feature_' + feature + '_more_off').style.display = allFeatures[feature].enabled ? 'none' : 'block';
  5165. }
  5166. }
  5167. };
  5168. for (const feature in allFeatures) {
  5169. const div = main.appendChild(document.createElement('div'));
  5170. const checkbox = div.appendChild(document.createElement('input'));
  5171. checkbox.type = 'checkbox';
  5172. checkbox.id = 'feature_' + feature;
  5173. checkbox.name = feature;
  5174. checkbox.checked = allFeatures[feature].enabled;
  5175. const label = div.appendChild(document.createElement('label'));
  5176. label.setAttribute('for', 'feature_' + feature);
  5177. label.innerHTML = allFeatures[feature].name;
  5178. checkbox.addEventListener('change', checkboxOnChange);
  5179. if (feature === 'markasplayedAuto') {
  5180. main.appendChild(document.createTextNode(' '));
  5181. const inputThreshold = div.appendChild(document.createElement('input'));
  5182. inputThreshold.type = 'text';
  5183. inputThreshold.value = markasplayedThreshold;
  5184. inputThreshold.size = 3;
  5185. inputThreshold.title = 'For example: 10s or 50%';
  5186. inputThreshold.id = 'feature_' + feature + '_threshold';
  5187. div.appendChild(document.createTextNode(' '));
  5188. const label = div.appendChild(document.createElement('label'));
  5189. label.setAttribute('for', 'feature_' + feature + '_threshold');
  5190. label.innerHTML = 'seconds or percentage.';
  5191. inputThreshold.addEventListener('change', thresholdOnChange);
  5192. }
  5193. if (feature in moreSettings) {
  5194. if (typeof moreSettings[feature] === 'function') {
  5195. const moreSettinsContainer = main.appendChild(document.createElement('fieldset'));
  5196. moreSettings[feature](moreSettinsContainer).then(function (v) {
  5197. if (v) {
  5198. moreSettinsContainer.appendChild(document.createElement('legend')).appendChild(document.createTextNode(v));
  5199. }
  5200. });
  5201. } else {
  5202. if ('true' in moreSettings[feature]) {
  5203. const moreSettinsContainerOn = main.appendChild(document.createElement('fieldset'));
  5204. moreSettinsContainerOn.setAttribute('id', 'feature_' + feature + '_more_on');
  5205. moreSettinsContainerOn.style.display = allFeatures[feature].enabled ? 'block' : 'none';
  5206. moreSettings[feature].true(moreSettinsContainerOn).then(function (v) {
  5207. if (v) {
  5208. moreSettinsContainerOn.appendChild(document.createElement('legend')).appendChild(document.createTextNode(v));
  5209. }
  5210. });
  5211. }
  5212. if ('false' in moreSettings[feature]) {
  5213. const moreSettinsContainerOff = main.appendChild(document.createElement('fieldset'));
  5214. moreSettinsContainerOff.setAttribute('id', 'feature_' + feature + '_more_off');
  5215. moreSettinsContainerOff.style.display = allFeatures[feature].enabled ? 'none' : 'block';
  5216. moreSettings[feature].false(moreSettinsContainerOff).then(function (v) {
  5217. if (v) {
  5218. moreSettinsContainerOff.appendChild(document.createElement('legend')).appendChild(document.createTextNode(v));
  5219. }
  5220. });
  5221. }
  5222. }
  5223. }
  5224. }
  5225.  
  5226. // Hint
  5227. main.appendChild(document.createElement('br'));
  5228. const p = main.appendChild(document.createElement('p'));
  5229. p.appendChild(document.createTextNode('Changes may require a page reload (F5)'));
  5230.  
  5231. // Bottom buttons
  5232. main.appendChild(document.createElement('br'));
  5233. const buttons = main.appendChild(document.createElement('div'));
  5234. const closeButton = buttons.appendChild(document.createElement('button'));
  5235. closeButton.appendChild(document.createTextNode('Close'));
  5236. closeButton.style.color = 'black';
  5237. closeButton.addEventListener('click', function onCloseButtonClick() {
  5238. document.querySelector('.deluxemenu').remove();
  5239. // Un-blur background
  5240. if (document.getElementById('centerWrapper')) {
  5241. document.getElementById('centerWrapper').style.filter = '';
  5242. }
  5243. });
  5244. const clearCacheButton = buttons.appendChild(document.createElement('button'));
  5245. clearCacheButton.appendChild(document.createTextNode('Clear cache'));
  5246. clearCacheButton.style.color = 'black';
  5247. clearCacheButton.addEventListener('click', function onClearCacheButtonClick() {
  5248. Promise.all([GM.setValue('genius_selectioncache', '{}'), GM.setValue('genius_requestcache', '{}'), GM.setValue('tralbumdata', '{}')]).then(function showClearedLabel() {
  5249. clearCacheButton.innerHTML = 'Cleared';
  5250. });
  5251. });
  5252. Promise.all([GM.getValue('genius_selectioncache', '{}'), GM.getValue('genius_requestcache', '{}')]).then(function (values) {
  5253. JSON.stringify(tralbumdata);
  5254. const bytesN = values[0].length - 2 + values[1].length - 2 + JSON.stringify(tralbumdata).length - 2;
  5255. const bytes = metricPrefix(bytesN, 1, 1024) + 'Bytes';
  5256. clearCacheButton.replaceChild(document.createTextNode('Clear cache (' + bytes + ')'), clearCacheButton.firstChild);
  5257. });
  5258. let myalbumsLength = 0;
  5259. for (const key in myalbums) {
  5260. if (myalbums[key].listened) {
  5261. myalbumsLength++;
  5262. }
  5263. }
  5264. const exportButton = buttons.appendChild(document.createElement('button'));
  5265. exportButton.appendChild(document.createTextNode('Export played albums (' + myalbumsLength + ')'));
  5266. exportButton.style.color = 'black';
  5267. exportButton.addEventListener('click', function onExportButtonClick() {
  5268. document.querySelector('.deluxemenu').remove();
  5269. exportMenu();
  5270. });
  5271. main.appendChild(document.createElement('br'));
  5272. main.appendChild(document.createElement('br'));
  5273. const donateLink = main.appendChild(document.createElement('a'));
  5274. const donateButton = donateLink.appendChild(document.createElement('button'));
  5275. donateButton.appendChild(document.createTextNode('\u2764\uFE0F Donate & Support'));
  5276. donateButton.style.color = '#e81224';
  5277. donateLink.setAttribute('href', 'https://cvzi.github.io/.github/');
  5278. donateLink.setAttribute('target', '_blank');
  5279. main.appendChild(document.createElement('br'));
  5280. main.appendChild(document.createElement('br'));
  5281. const developerButton = main.appendChild(document.createElement('button'));
  5282. developerButton.appendChild(document.createTextNode('Developer options'));
  5283. developerButton.style.color = 'black';
  5284. developerButton.addEventListener('click', function onDeveloperButtonClick() {
  5285. document.querySelector('.deluxemenu').remove();
  5286. developerMenu();
  5287. });
  5288. });
  5289. window.setTimeout(function moveMenuIntoView() {
  5290. let moveLeft = 0;
  5291. main.style.maxHeight = document.documentElement.clientHeight - 40 + 'px';
  5292. main.style.maxWidth = document.documentElement.clientWidth - 40 + 'px';
  5293. if (document.querySelector('#discographyplayer')) {
  5294. if (document.querySelector('#discographyplayer').clientHeight < 100) {
  5295. main.style.maxHeight = document.documentElement.clientHeight - 150 + 'px';
  5296. main.style.maxWidth = document.documentElement.clientWidth - 40 + 'px';
  5297. } else if (document.querySelector('#discographyplayer').clientHeight > 300) {
  5298. main.style.maxHeight = document.documentElement.clientHeight - 40 + 'px';
  5299. main.style.maxWidth = document.documentElement.clientWidth - 40 - document.querySelector('#discographyplayer').clientWidth + 'px';
  5300. moveLeft = document.querySelector('#discographyplayer').clientWidth + 20;
  5301. }
  5302. }
  5303. window.setTimeout(function () {
  5304. main.style.left = Math.max(20, 0.5 * (document.body.clientWidth - main.clientWidth) - moveLeft) + 'px';
  5305. }, 10);
  5306. }, 10);
  5307. }
  5308. function developerMenu() {
  5309. // Blur background
  5310. if (document.getElementById('centerWrapper')) {
  5311. document.getElementById('centerWrapper').style.filter = 'blur(4px)';
  5312. }
  5313. const main = document.body.appendChild(document.createElement('div'));
  5314. main.className = 'deluxedeveloper deluxemenu';
  5315. window.setTimeout(function moveMenuIntoView() {
  5316. main.style.maxHeight = document.documentElement.clientHeight - 40 + 'px';
  5317. main.style.maxWidth = document.documentElement.clientWidth - 40 + 'px';
  5318. main.style.left = Math.max(20, 0.5 * (document.body.clientWidth - main.clientWidth)) + 'px';
  5319. }, 0);
  5320. const h2 = main.appendChild(document.createElement('h2'));
  5321. h2.appendChild(document.createTextNode('Developer options'));
  5322. const table = main.appendChild(document.createElement('table'));
  5323.  
  5324. // Bottom buttons
  5325. main.appendChild(document.createElement('br'));
  5326. main.appendChild(document.createElement('br'));
  5327. const buttons = main.appendChild(document.createElement('div'));
  5328. const closeButton = buttons.appendChild(document.createElement('button'));
  5329. closeButton.appendChild(document.createTextNode('Close'));
  5330. closeButton.style.color = 'black';
  5331. closeButton.addEventListener('click', function onCloseButtonClick() {
  5332. document.querySelector('.deluxedeveloper').remove();
  5333. // Un-blur background
  5334. if (document.getElementById('centerWrapper')) {
  5335. document.getElementById('centerWrapper').style.filter = '';
  5336. }
  5337. });
  5338. let tr;
  5339. let td;
  5340. let input;
  5341. GM.getValue('myalbums', '{}').then(function myalbumsLoaded(myalbumsStr) {
  5342. const myalbums = JSON.parse(myalbumsStr);
  5343. const listenedAlbums = [];
  5344. for (const key in myalbums) {
  5345. if (myalbums[key].listened) {
  5346. listenedAlbums.push(myalbums[key]);
  5347. }
  5348. }
  5349. tr = table.appendChild(document.createElement('tr'));
  5350. td = tr.appendChild(document.createElement('td'));
  5351. td.appendChild(document.createTextNode('"myalbums" listened records'));
  5352. td = tr.appendChild(document.createElement('td'));
  5353. input = td.appendChild(document.createElement('input'));
  5354. input.type = 'text';
  5355. input.value = listenedAlbums.length.toString();
  5356. input.readOnly = true;
  5357. input.style.width = '200px';
  5358. tr = table.appendChild(document.createElement('tr'));
  5359. td = tr.appendChild(document.createElement('td'));
  5360. td.appendChild(document.createTextNode('"myalbums" string length'));
  5361. td = tr.appendChild(document.createElement('td'));
  5362. input = td.appendChild(document.createElement('input'));
  5363. input.type = 'text';
  5364. input.value = myalbumsStr.length.toString();
  5365. input.readOnly = true;
  5366. input.style.width = '200px';
  5367. tr = table.appendChild(document.createElement('tr'));
  5368. td = tr.appendChild(document.createElement('td'));
  5369. td.appendChild(document.createTextNode('"myalbums" size'));
  5370. td = tr.appendChild(document.createElement('td'));
  5371. input = td.appendChild(document.createElement('input'));
  5372. input.type = 'text';
  5373. input.value = humanBytes(new Blob([myalbumsStr]).size);
  5374. input.readOnly = true;
  5375. input.style.width = '200px';
  5376. });
  5377. GM.getValue('tralbumdata', '{}').then(function tralbumdataLoaded(tralbumdataStr) {
  5378. const tralbumdata = JSON.parse(tralbumdataStr);
  5379. tr = table.appendChild(document.createElement('tr'));
  5380. td = tr.appendChild(document.createElement('td'));
  5381. td.appendChild(document.createTextNode('"tralbumdataStr" entries'));
  5382. td = tr.appendChild(document.createElement('td'));
  5383. input = td.appendChild(document.createElement('input'));
  5384. input.type = 'text';
  5385. input.value = Object.keys(tralbumdata).length.toString();
  5386. input.readOnly = true;
  5387. input.style.width = '200px';
  5388. tr = table.appendChild(document.createElement('tr'));
  5389. td = tr.appendChild(document.createElement('td'));
  5390. td.appendChild(document.createTextNode('"tralbumdataStr" string length'));
  5391. td = tr.appendChild(document.createElement('td'));
  5392. input = td.appendChild(document.createElement('input'));
  5393. input.type = 'text';
  5394. input.value = tralbumdataStr.length.toString();
  5395. input.readOnly = true;
  5396. input.style.width = '200px';
  5397. tr = table.appendChild(document.createElement('tr'));
  5398. td = tr.appendChild(document.createElement('td'));
  5399. td.appendChild(document.createTextNode('"tralbumdataStr" size'));
  5400. td = tr.appendChild(document.createElement('td'));
  5401. input = td.appendChild(document.createElement('input'));
  5402. input.type = 'text';
  5403. input.value = humanBytes(new Blob([tralbumdataStr]).size);
  5404. input.readOnly = true;
  5405. input.style.width = '200px';
  5406. });
  5407. try {
  5408. GM.getValue('tralbumlibrary', '{}').then(function tralbumlibraryLoaded(tralbumlibraryStr) {
  5409. const tralbumlibrary = JSON.parse(tralbumlibraryStr);
  5410. tr = table.appendChild(document.createElement('tr'));
  5411. td = tr.appendChild(document.createElement('td'));
  5412. td.appendChild(document.createTextNode('"tralbumlibraryStr" entries'));
  5413. td = tr.appendChild(document.createElement('td'));
  5414. input = td.appendChild(document.createElement('input'));
  5415. input.type = 'text';
  5416. input.value = Object.keys(tralbumlibrary).length.toString();
  5417. input.readOnly = true;
  5418. input.style.width = '200px';
  5419. tr = table.appendChild(document.createElement('tr'));
  5420. td = tr.appendChild(document.createElement('td'));
  5421. td.appendChild(document.createTextNode('"tralbumlibraryStr" string length'));
  5422. td = tr.appendChild(document.createElement('td'));
  5423. input = td.appendChild(document.createElement('input'));
  5424. input.type = 'text';
  5425. input.value = tralbumlibraryStr.length.toString();
  5426. input.readOnly = true;
  5427. input.style.width = '200px';
  5428. tr = table.appendChild(document.createElement('tr'));
  5429. td = tr.appendChild(document.createElement('td'));
  5430. td.appendChild(document.createTextNode('"tralbumlibraryStr" size'));
  5431. td = tr.appendChild(document.createElement('td'));
  5432. input = td.appendChild(document.createElement('input'));
  5433. input.type = 'text';
  5434. input.value = humanBytes(new Blob([tralbumlibraryStr]).size);
  5435. input.readOnly = true;
  5436. input.style.width = '200px';
  5437. });
  5438. } catch (e) {
  5439. tr = table.appendChild(document.createElement('tr'));
  5440. td = tr.appendChild(document.createElement('td'));
  5441. td.appendChild(document.createTextNode('"tralbumlibraryStr"'));
  5442. td = tr.appendChild(document.createElement('td'));
  5443. td.appendChild(document.createTextNode('Error: ' + e.toString()));
  5444. }
  5445. window.setTimeout(function moveMenuIntoView() {
  5446. main.style.maxHeight = document.documentElement.clientHeight - 40 + 'px';
  5447. main.style.maxWidth = document.documentElement.clientWidth - 40 + 'px';
  5448. main.style.left = Math.max(20, 0.5 * (document.body.clientWidth - main.clientWidth)) + 'px';
  5449. }, 500);
  5450. }
  5451. function exportMenu(showClearButton) {
  5452. addStyle(`
  5453. .deluxeexportmenu table {
  5454. }
  5455.  
  5456. .deluxeexportmenu table tr>td {
  5457. color:black
  5458. }
  5459. .deluxeexportmenu table tr>td:nth-child(3) {
  5460. color:silver
  5461. }
  5462. .deluxeexportmenu textarea.animated{
  5463. box-shadow: 2px 2px 5px #5555;
  5464. transition: box-shadow 500ms;
  5465. }
  5466. .deluxeexportmenu .drophint {
  5467. position:absolute;
  5468. top:10%;
  5469. left:30%;
  5470. color:#0097ff;
  5471. font-size:3em;
  5472. display:none;
  5473. }
  5474. `);
  5475.  
  5476. // Blur background
  5477. if (document.getElementById('centerWrapper')) {
  5478. document.getElementById('centerWrapper').style.filter = 'blur(4px)';
  5479. }
  5480. const main = document.body.appendChild(document.createElement('div'));
  5481. main.className = 'deluxeexportmenu deluxemenu';
  5482. main.innerHTML = exportMenuHTML;
  5483. const drophint = main.querySelector('.drophint');
  5484. window.setTimeout(function moveMenuIntoView() {
  5485. main.style.maxHeight = document.documentElement.clientHeight - 40 + 'px';
  5486. main.style.maxWidth = document.documentElement.clientWidth - 40 + 'px';
  5487. main.style.left = Math.max(20, 0.5 * (document.body.clientWidth - main.clientWidth)) + 'px';
  5488. }, 0);
  5489. GM.getValue('myalbums', '{}').then(function myalbumsLoaded(myalbumsStr) {
  5490. const myalbums = JSON.parse(myalbumsStr);
  5491. const listenedAlbums = [];
  5492. for (const key in myalbums) {
  5493. if (myalbums[key].listened) {
  5494. listenedAlbums.push(myalbums[key]);
  5495. }
  5496. }
  5497. main.querySelector('h2').appendChild(document.createTextNode(' (' + listenedAlbums.length + ' records)'));
  5498. let format = '%artist% - %title%';
  5499. const formatAlbum = function formatAlbumStr(format, myAlbum) {
  5500. const releaseDate = new Date(myAlbum.releaseDate);
  5501. const listenedDate = new Date(myAlbum.listened);
  5502. const fields = {
  5503. '%artist%': () => myAlbum.artist,
  5504. '%title%': () => myAlbum.title,
  5505. '%cover%': () => myAlbum.albumCover,
  5506. '%url%': () => myAlbum.url,
  5507. '%releaseDate%': () => releaseDate.toISOString(),
  5508. '%listenedDate%': () => listenedDate.toISOString(),
  5509. '%releaseUnix%': () => parseInt(releaseDate.getTime() / 1000),
  5510. '%listenedUnix%': () => parseInt(listenedDate.getTime() / 1000),
  5511. '%releaseTimestamp%': () => releaseDate.getTime(),
  5512. '%listenedTimestamp%': () => listenedDate.getTime(),
  5513. '%releaseY%': () => releaseDate.getFullYear().toString().substring(2),
  5514. '%releaseYYYY%': () => releaseDate.getFullYear(),
  5515. '%releaseM%': () => releaseDate.getMonth() + 1,
  5516. '%releaseMM%': () => padd(releaseDate.getMonth() + 1, 2, '0'),
  5517. '%releaseMon%': () => releaseDate.toLocaleString(undefined, {
  5518. month: 'short'
  5519. }),
  5520. '%releaseMonth%': () => releaseDate.toLocaleString(undefined, {
  5521. month: 'long'
  5522. }),
  5523. '%releaseD%': () => releaseDate.getDate(),
  5524. '%releaseDD%': () => padd(releaseDate.getDate(), 2, '0'),
  5525. '%releaseDay%': () => releaseDate.toLocaleString(undefined, {
  5526. weekday: 'long'
  5527. }),
  5528. '%listenedY%': () => listenedDate.getFullYear().toString().substring(2),
  5529. '%listenedYYYY%': () => listenedDate.getFullYear(),
  5530. '%listenedM%': () => listenedDate.getMonth() + 1,
  5531. '%listenedMM%': () => padd(listenedDate.getMonth() + 1, 2, '0'),
  5532. '%listenedMon%': () => listenedDate.toLocaleString(undefined, {
  5533. month: 'short'
  5534. }),
  5535. '%listenedMonth%': () => listenedDate.toLocaleString(undefined, {
  5536. month: 'long'
  5537. }),
  5538. '%listenedD%': () => listenedDate.getDate(),
  5539. '%listenedDD%': () => padd(listenedDate.getDate(), 2, '0'),
  5540. '%listenedDay%': () => listenedDate.toLocaleString(undefined, {
  5541. weekday: 'long'
  5542. }),
  5543. '%json%': () => JSON.stringify(myAlbum),
  5544. '%json5%': () => JSON5.stringify(myAlbum)
  5545. };
  5546. for (const field in fields) {
  5547. if (format.includes(field)) {
  5548. try {
  5549. format = format.replace(field, fields[field]());
  5550. } catch (e) {
  5551. console.error('Could not format replace "' + field + '": ' + e);
  5552. }
  5553. }
  5554. }
  5555. return format;
  5556. };
  5557. const sortBy = function sortByCmp(sortKey) {
  5558. const cmps = {
  5559. playedAsc: function playedAsc(a, b) {
  5560. return -cmps.playedDesc(a, b);
  5561. },
  5562. playedDesc: function playedDesc(a, b) {
  5563. try {
  5564. return new Date(b.listened) - new Date(a.listened);
  5565. } catch (e) {
  5566. return 0;
  5567. }
  5568. },
  5569. releasedAsc: function releasedAsc(a, b) {
  5570. return -cmps.releasedDesc(a, b);
  5571. },
  5572. releasedDesc: function releasedDesc(a, b) {
  5573. try {
  5574. return new Date(b.releaseDate) - new Date(a.releaseDate);
  5575. } catch (e) {
  5576. return 0;
  5577. }
  5578. },
  5579. artist: function artist(a, b, fallbackToTitle) {
  5580. const d = a.artist.localeCompare(b.artist);
  5581. if (d === 0 && fallbackToTitle) {
  5582. return cmps.title(a, b, false);
  5583. } else {
  5584. return d;
  5585. }
  5586. },
  5587. title: function title(a, b, fallbackToArtist) {
  5588. const d = a.title.localeCompare(b.title);
  5589. if (d === 0 && fallbackToArtist) {
  5590. return cmps.artist(a, b, false);
  5591. } else {
  5592. return d;
  5593. }
  5594. }
  5595. };
  5596. listenedAlbums.sort(cmps[sortKey]);
  5597. };
  5598. const generate = function generateStr() {
  5599. const textarea = document.getElementById('export_output');
  5600. window.setTimeout(function generateStrAnimation() {
  5601. textarea.classList.remove('animated');
  5602. textarea.style.boxShadow = '2px 2px 5px #00af';
  5603. }, 0);
  5604. let str;
  5605. if (format === '%backup%') {
  5606. str = myalbumsStr;
  5607. } else {
  5608. const sortSelect = document.getElementById('sort_select');
  5609. sortBy(sortSelect.options[sortSelect.selectedIndex].value);
  5610. str = [];
  5611. for (let i = 0; i < listenedAlbums.length; i++) {
  5612. str.push(formatAlbum(format, listenedAlbums[i]));
  5613. }
  5614. str = str.join(navigator.platform.startsWith('Win') ? '\r\n' : '\n');
  5615. }
  5616. window.setTimeout(function generateStrAnimationSuccess() {
  5617. textarea.value = str;
  5618. textarea.classList.add('animated');
  5619. textarea.style.boxShadow = '2px 2px 5px #0a0f';
  5620. }, 50);
  5621. window.setTimeout(function generateStrResetAnimation() {
  5622. textarea.style.boxShadow = '';
  5623. }, 3000);
  5624. return str;
  5625. };
  5626. const inputFormatOnChange = async function onInputFormatChange() {
  5627. const input = this;
  5628. const formatExample = document.getElementById('format_example');
  5629. format = input.value;
  5630. formatExample.value = listenedAlbums.length > 0 ? formatAlbum(format, listenedAlbums[0]) : '';
  5631. formatExample.style.boxShadow = '2px 2px 5px #0a0f';
  5632. window.setTimeout(function resetBoxShadow() {
  5633. formatExample.style.boxShadow = '';
  5634. }, 3000);
  5635. };
  5636. const importData = function importDate(data) {
  5637. GM.getValue('myalbums', '{}').then(function myalbumsLoaded(myalbumsStr) {
  5638. let myalbums = JSON.parse(myalbumsStr);
  5639. myalbums = Object.assign(myalbums, data);
  5640. return GM.setValue('myalbums', JSON.stringify(myalbums));
  5641. }).then(function myalbumsSaved() {
  5642. document.getElementById('exportmenu_close').click();
  5643. window.setTimeout(() => exportMenu(true), 50);
  5644. });
  5645. };
  5646. const handleFiles = async function handleFilesAsync(fileList) {
  5647. if (fileList.length === 0) {
  5648. console.debug('fileList is empty');
  5649. return;
  5650. }
  5651. let data;
  5652. try {
  5653. data = await new Response(fileList[0]).json();
  5654. } catch (e) {
  5655. window.alert('Could not load file:\n' + e);
  5656. return;
  5657. }
  5658. const n = Object.keys(data).length;
  5659. if (window.confirm('Found ' + n + ' albums. Continue import and overwrite existing albums?')) {
  5660. importData(data);
  5661. }
  5662. };
  5663. const inputTable = main.appendChild(document.createElement('table'));
  5664. let tr;
  5665. let td;
  5666. tr = inputTable.appendChild(document.createElement('tr'));
  5667. td = tr.appendChild(document.createElement('td'));
  5668. const label = td.appendChild(document.createElement('label'));
  5669. label.setAttribute('for', 'export_format');
  5670. label.appendChild(document.createTextNode('Format:'));
  5671. td = tr.appendChild(document.createElement('td'));
  5672. const inputFormat = td.appendChild(document.createElement('input'));
  5673. inputFormat.type = 'text';
  5674. inputFormat.value = format;
  5675. inputFormat.id = 'export_format';
  5676. inputFormat.style.width = '600px';
  5677. inputFormat.addEventListener('change', inputFormatOnChange);
  5678. inputFormat.addEventListener('keyup', inputFormatOnChange);
  5679. tr = inputTable.appendChild(document.createElement('tr'));
  5680. td = tr.appendChild(document.createElement('td'));
  5681. td.appendChild(document.createTextNode('Example:'));
  5682. td = tr.appendChild(document.createElement('td'));
  5683. const inputExample = td.appendChild(document.createElement('input'));
  5684. inputExample.type = 'text';
  5685. inputExample.value = listenedAlbums.length > 0 ? formatAlbum(format, listenedAlbums[0]) : '';
  5686. inputExample.readOnly = true;
  5687. inputExample.id = 'format_example';
  5688. inputExample.style.width = '600px';
  5689. td = tr.appendChild(document.createElement('td'));
  5690. td.appendChild(document.createTextNode('Sort by:'));
  5691. td = tr.appendChild(document.createElement('td'));
  5692. const sortSelect = td.appendChild(document.createElement('select'));
  5693. sortSelect.id = 'sort_select';
  5694. sortSelect.innerHTML = `
  5695. <option value="playedDesc">Recent play first</option>
  5696. <option value="playedAsc">Recent play last</option>
  5697. <option value="releasedDesc">Recent release first</option>
  5698. <option value="releasedAsc">Recent release last</option>
  5699. <option value="artist">Artist A-Z</option>
  5700. <option value="title">Title A-Z</option>
  5701. `;
  5702. tr = inputTable.appendChild(document.createElement('tr'));
  5703. td = tr.appendChild(document.createElement('td'));
  5704. td.setAttribute('colspan', '2');
  5705. const generateButton = td.appendChild(document.createElement('button'));
  5706. generateButton.appendChild(document.createTextNode('Generate'));
  5707. generateButton.addEventListener('click', ev => generate());
  5708. const exportButton = td.appendChild(document.createElement('button'));
  5709. exportButton.appendChild(document.createTextNode('Export to file'));
  5710. exportButton.title = 'Download as a text file';
  5711. exportButton.addEventListener('click', function onExportFileButtonClick() {
  5712. const dateSuffix = new Date().toISOString().split('T')[0];
  5713. document.getElementById('export_download_link').download = 'bandcampPlayedAlbums_' + dateSuffix + '.txt';
  5714. document.getElementById('export_download_link').href = 'data:text/plain,' + encodeURIComponent(generate());
  5715. window.setTimeout(() => document.getElementById('export_download_link').click(), 50);
  5716. });
  5717. const backupButton = td.appendChild(document.createElement('button'));
  5718. backupButton.title = 'Backup to JSON file. Can be restored on another browser';
  5719. backupButton.appendChild(document.createTextNode('Backup'));
  5720. backupButton.addEventListener('click', function onBackupButtonClick() {
  5721. format = '%backup%';
  5722. document.getElementById('export_format').value = format;
  5723. document.getElementById('format_example').value = 'JSON dictionary';
  5724. const dateSuffix = new Date().toISOString().split('T')[0];
  5725. document.getElementById('export_download_link').download = 'bandcampPlayedAlbums_' + dateSuffix + '.json';
  5726. document.getElementById('export_download_link').href = 'data:application/json,' + encodeURIComponent(generate());
  5727. document.getElementById('export_clear_button').style.display = '';
  5728. GM.setValue('myalbums_lastbackup', Object.keys(myalbums).length + '#####' + new Date().toJSON());
  5729. window.setTimeout(() => document.getElementById('export_download_link').click(), 50);
  5730. });
  5731. const restoreButton = td.appendChild(document.createElement('button'));
  5732. restoreButton.title = 'Restore from JSON file backup';
  5733. restoreButton.appendChild(document.createTextNode('Restore'));
  5734. restoreButton.addEventListener('click', function onBackupButtonClick() {
  5735. inputFile.click();
  5736. });
  5737. const clearButton = td.appendChild(document.createElement('button'));
  5738. clearButton.appendChild(document.createTextNode('Clear played albums'));
  5739. clearButton.id = 'export_clear_button';
  5740. if (showClearButton !== true) {
  5741. clearButton.style.display = 'none';
  5742. }
  5743. clearButton.addEventListener('click', function onClearButtonClick() {
  5744. if (window.confirm('Remove all played albums?\n\nThis cannot be undone.')) {
  5745. if (window.confirm('Are you sure? Delete all played albums?')) {
  5746. GM.setValue('myalbums', '{}').then(function myalbumsSaved() {
  5747. document.getElementById('exportmenu_close').click();
  5748. window.setTimeout(exportMenu, 50);
  5749. });
  5750. }
  5751. }
  5752. });
  5753. const downloadA = td.appendChild(document.createElement('a'));
  5754. downloadA.id = 'export_download_link';
  5755. downloadA.href = '#';
  5756. downloadA.download = 'bandcamp_played_albums.txt';
  5757. downloadA.target = '_blank';
  5758. const inputFile = td.appendChild(document.createElement('input'));
  5759. inputFile.type = 'file';
  5760. inputFile.id = 'input_file';
  5761. inputFile.accept = '.txt,plain/text,.json,application/json';
  5762. inputFile.style.display = 'none';
  5763. inputFile.addEventListener('change', function onFileChanged(ev) {
  5764. handleFiles(this.files);
  5765. }, false);
  5766. main.addEventListener('dragenter', function dragenter(ev) {
  5767. ev.stopPropagation();
  5768. ev.preventDefault();
  5769. main.style.backgroundColor = '#c6daf9';
  5770. drophint.style.left = main.clientWidth / 2 - drophint.clientWidth / 2 + 'px';
  5771. drophint.style.display = 'block';
  5772. }, false);
  5773. main.addEventListener('dragleave', function dragleave(ev) {
  5774. main.style.backgroundColor = 'white';
  5775. drophint.style.display = 'none';
  5776. }, false);
  5777. main.addEventListener('dragover', function dragover(ev) {
  5778. ev.stopPropagation();
  5779. ev.preventDefault();
  5780. main.style.backgroundColor = '#c6daf9';
  5781. drophint.style.display = 'block';
  5782. }, false);
  5783. main.addEventListener('drop', function drop(ev) {
  5784. ev.stopPropagation();
  5785. ev.preventDefault();
  5786. main.style.backgroundColor = 'white';
  5787. drophint.style.display = 'none';
  5788. handleFiles(ev.dataTransfer.files);
  5789. }, false);
  5790. tr = inputTable.appendChild(document.createElement('tr'));
  5791. td = tr.appendChild(document.createElement('td'));
  5792. td.setAttribute('colspan', '3');
  5793. const textarea = td.appendChild(document.createElement('textarea'));
  5794. textarea.id = 'export_output';
  5795. textarea.style.width = Math.max(500, main.clientWidth - 50) + 'px';
  5796.  
  5797. // Bottom buttons
  5798. main.appendChild(document.createElement('br'));
  5799. main.appendChild(document.createElement('br'));
  5800. const buttons = main.appendChild(document.createElement('div'));
  5801. const closeButton = buttons.appendChild(document.createElement('button'));
  5802. closeButton.appendChild(document.createTextNode('Close'));
  5803. closeButton.id = 'exportmenu_close';
  5804. closeButton.style.color = 'black';
  5805. closeButton.addEventListener('click', function onCloseButtonClick() {
  5806. document.querySelector('.deluxeexportmenu').remove();
  5807. // Un-blur background
  5808. if (document.getElementById('centerWrapper')) {
  5809. document.getElementById('centerWrapper').style.filter = '';
  5810. }
  5811. });
  5812. });
  5813. window.setTimeout(function moveMenuIntoView() {
  5814. main.style.maxHeight = document.documentElement.clientHeight - 40 + 'px';
  5815. main.style.maxWidth = document.documentElement.clientWidth - 40 + 'px';
  5816. main.style.left = Math.max(20, 0.5 * (document.body.clientWidth - main.clientWidth)) + 'px';
  5817. }, 0);
  5818. }
  5819. function checkBackupStatus() {
  5820. GM.getValue('myalbums_lastbackup', '').then(function myalbumsLastBackupLoaded(value) {
  5821. if (!value || !value.includes('#####')) {
  5822. // Set current date (install date) as initial value
  5823. GM.setValue('myalbums_lastbackup', '0#####' + new Date().toJSON());
  5824. return;
  5825. }
  5826. const parts = value.split('#####');
  5827. const n0 = parseInt(parts[0]);
  5828. const lastBackup = new Date(parts[1]);
  5829. if (new Date() - lastBackup > BACKUP_REMINDER_DAYS * 86400000) {
  5830. GM.getValue('myalbums', '{}').then(function myalbumsLoaded(str) {
  5831. const n1 = Object.keys(JSON.parse(str)).length;
  5832. if (Math.abs(n0 - n1) > 10) {
  5833. showBackupHint(lastBackup, Math.abs(n0 - n1));
  5834. }
  5835. });
  5836. }
  5837. });
  5838. }
  5839. function showBackupHint(lastBackup, changedRecords) {
  5840. const since = timeSince(lastBackup);
  5841. addStyle(`
  5842. .backupreminder {
  5843. position:fixed;
  5844. height:auto;
  5845. overflow:auto;
  5846. top:110%;
  5847. left:40%;
  5848. z-index:200;
  5849. padding:5px;
  5850. transition: top 1s;
  5851. border:2px solid black;
  5852. border-radius:10px;
  5853. color:black;
  5854. background:white;
  5855. }
  5856. `);
  5857.  
  5858. // Blur background
  5859. if (document.getElementById('centerWrapper')) {
  5860. document.getElementById('centerWrapper').style.filter = 'blur(4px)';
  5861. }
  5862. const main = document.body.appendChild(document.createElement('div'));
  5863. main.className = 'backupreminder';
  5864. main.innerHTML = `<h2>${SCRIPT_NAME}</h2>
  5865. <h1>Backup reminder</h1>
  5866. <p>
  5867. Your last backup was ${since} ago. Since then, you played ${changedRecords} albums.
  5868. </p>
  5869. `;
  5870. main.appendChild(document.createElement('br'));
  5871. const buttons = main.appendChild(document.createElement('div'));
  5872. const closeButton = buttons.appendChild(document.createElement('button'));
  5873. closeButton.appendChild(document.createTextNode('Close'));
  5874. closeButton.id = 'backupreminder_close';
  5875. closeButton.style.color = 'black';
  5876. closeButton.addEventListener('click', function onCloseButtonClick() {
  5877. document.querySelector('.backupreminder').remove();
  5878. // Un-blur background
  5879. if (document.getElementById('centerWrapper')) {
  5880. document.getElementById('centerWrapper').style.filter = '';
  5881. }
  5882. });
  5883. buttons.appendChild(document.createTextNode(' '));
  5884. const backupButton = buttons.appendChild(document.createElement('button'));
  5885. backupButton.appendChild(document.createTextNode('Start backup'));
  5886. backupButton.style.color = '#0687f5';
  5887. backupButton.addEventListener('click', function backupButtonClick() {
  5888. document.getElementById('backupreminder_close').click();
  5889. mainMenu(true);
  5890. });
  5891. buttons.appendChild(document.createTextNode(' '));
  5892. const ignoreButton = buttons.appendChild(document.createElement('button'));
  5893. ignoreButton.appendChild(document.createTextNode('Disable reminder'));
  5894. ignoreButton.style.color = 'black';
  5895. ignoreButton.addEventListener('click', async function ignoreButtonClick() {
  5896. getEnabledFeatures(await GM.getValue('enabledFeatures', false));
  5897. if (allFeatures.backupReminder.enabled) {
  5898. allFeatures.backupReminder.enabled = false;
  5899. }
  5900. await GM.setValue('enabledFeatures', JSON.stringify(allFeatures));
  5901. document.getElementById('backupreminder_close').click();
  5902. });
  5903. window.setTimeout(function moveMenuIntoView() {
  5904. main.style.maxHeight = document.documentElement.clientHeight - 40 + 'px';
  5905. main.style.maxWidth = document.documentElement.clientWidth - 40 + 'px';
  5906. main.style.left = Math.max(20, 0.5 * (document.documentElement.clientWidth - main.clientWidth)) + 'px';
  5907. main.style.top = Math.max(20, 0.3 * document.documentElement.clientHeight) + 'px';
  5908. }, 0);
  5909. }
  5910. function downloadMp3FromLink(ev, a, addSpinner, removeSpinner, noGM) {
  5911. const url = a.href;
  5912. if (GM_download && !noGM) {
  5913. // Use Tampermonkey GM_download function
  5914. console.debug('Using GM_download function');
  5915. ev.preventDefault();
  5916. addSpinner(a);
  5917. let GMdownloadStatus = 0;
  5918. GM_download({
  5919. url,
  5920. name: a.download || 'default.mp3',
  5921. onerror: function downloadMp3FromLinkOnError(e) {
  5922. console.debug('GM_download onerror:', e);
  5923. window.setTimeout(function () {
  5924. if (GMdownloadStatus !== 1) {
  5925. if (url.startsWith('data')) {
  5926. console.debug('GM_download failed with data url');
  5927. document.location.href = url;
  5928. } else {
  5929. console.debug('Trying again with GM_download disabled');
  5930. downloadMp3FromLink(ev, a, addSpinner, removeSpinner, true);
  5931. }
  5932. }
  5933. }, 1000);
  5934. },
  5935. ontimeout: function downloadMp3FromLinkOnTimeout() {
  5936. window.alert('Could not download via GM_download. Time out.');
  5937. document.location.href = url;
  5938. },
  5939. onload: function downloadMp3FromLinkOnLoad() {
  5940. console.debug('Successfully downloaded via GM_download');
  5941. GMdownloadStatus = 1;
  5942. window.setTimeout(() => removeSpinner(a), 500);
  5943. }
  5944. });
  5945. return;
  5946. }
  5947. if (!url.startsWith('http') || navigator.userAgent.indexOf('Chrome') !== -1) {
  5948. // Just open the link normally (no prevent default)
  5949. addSpinner(a);
  5950. window.setTimeout(() => removeSpinner(a), 1000);
  5951. return;
  5952. }
  5953.  
  5954. // Use GM.xmlHttpRequest to download and offer data uri
  5955. ev.preventDefault();
  5956. console.debug('Using GM.xmlHttpRequest to download and then offer data uri');
  5957. addSpinner(a);
  5958. GM.xmlHttpRequest({
  5959. method: 'GET',
  5960. overrideMimeType: 'text/plain; charset=x-user-defined',
  5961. url,
  5962. onload: function onMp3Load(response) {
  5963. console.debug('Successfully received data via GM.xmlHttpRequest, starting download');
  5964. a.href = 'data:audio/mpeg;base64,' + base64encode(response.responseText);
  5965. window.setTimeout(() => a.click(), 10);
  5966. },
  5967. onerror: function onMp3LoadError(response) {
  5968. window.alert('Could not download via GM.xmlHttpRequest');
  5969. document.location.href = url;
  5970. }
  5971. });
  5972. }
  5973. function addDownloadLinksToAlbumPage() {
  5974. addStyle(`
  5975. .download-col .downloaddisk:hover {
  5976. text-decoration:none
  5977. }
  5978. /* From http://www.designcouch.com/home/why/2013/05/23/dead-simple-pure-css-loading-spinner/ */
  5979. .downspinner {
  5980. height:16px;
  5981. width:16px;
  5982. margin:0px auto;
  5983. position:relative;
  5984. display:inline-block;
  5985. animation: spinnerrotation 3s infinite linear;
  5986. cursor:wait;
  5987. }
  5988. @keyframes spinnerrotation {
  5989. from {transform: rotate(0deg)}
  5990. to {transform: rotate(359deg)}
  5991. }`);
  5992. const addSpiner = function downloadLinksOnAlbumPageAddSpinner(el) {
  5993. el.style = '';
  5994. el.classList.add('downspinner');
  5995. };
  5996. const removeSpinner = function downloadLinksOnAlbumPageRemoveSpinner(el) {
  5997. el.classList.remove('downspinner');
  5998. el.style = 'background:#1cea1c; border-radius:5px; padding:1px; opacity:0.5';
  5999. };
  6000. const TralbumData = unsafeWindow.TralbumData;
  6001. if (TralbumData && TralbumData.hasAudio && !TralbumData.freeDownloadPage && TralbumData.trackinfo) {
  6002. const hoverdiv = document.querySelectorAll('.download-col div');
  6003. if (hoverdiv.length > 0) {
  6004. // Album page
  6005. for (let i = 0; i < TralbumData.trackinfo.length; i++) {
  6006. if (!NOEMOJI && hoverdiv[i].querySelector('a[href*="?action=download"]')) {
  6007. // Replace buy link with shopping cart emoji
  6008. hoverdiv[i].querySelector('a[href*="?action=download"]').innerHTML = '&#x1f6d2;';
  6009. hoverdiv[i].querySelector('a[href*="?action=download"]').title = 'buy track';
  6010. }
  6011. // Add download link
  6012. const t = TralbumData.trackinfo[i];
  6013. if (!t.file) {
  6014. continue;
  6015. }
  6016. const prop = Object.keys(t.file)[0]; // Just use the first file entry
  6017. const mp3 = t.file[prop].replace(/^\/\//, 'http://');
  6018. const a = document.createElement('a');
  6019. a.className = 'downloaddisk';
  6020. a.href = mp3;
  6021. a.download = (t.track_num == null ? '' : (t.track_num > 9 ? '' : '0') + t.track_num + '. ') + fixFilename(TralbumData.artist + ' - ' + t.title) + '.mp3';
  6022. a.title = 'Download ' + prop;
  6023. a.appendChild(document.createTextNode(NOEMOJI ? '\u2193' : '\uD83D\uDCBE'));
  6024. a.addEventListener('click', function onDownloadLinkClick(ev) {
  6025. downloadMp3FromLink(ev, this, addSpiner, removeSpinner);
  6026. });
  6027. hoverdiv[i].appendChild(a);
  6028. }
  6029. } else if (document.querySelector('#trackInfo .download-link')) {
  6030. // Single track page
  6031. const t = TralbumData.trackinfo[0];
  6032. if (!t.file) {
  6033. return;
  6034. }
  6035. const prop = Object.keys(t.file)[0];
  6036. const mp3 = t.file[prop].replace(/^\/\//, 'http://');
  6037. const a = document.createElement('a');
  6038. a.className = 'downloaddisk';
  6039. a.href = mp3;
  6040. a.download = (t.track_num == null ? '' : (t.track_num > 9 ? '' : '0') + t.track_num + '. ') + fixFilename(TralbumData.artist + ' - ' + t.title) + '.mp3';
  6041. a.title = 'Download ' + prop;
  6042. a.appendChild(document.createTextNode(NOEMOJI ? '\u2193' : '\uD83D\uDCBE'));
  6043. a.addEventListener('click', function onDownloadLinkClick(ev) {
  6044. downloadMp3FromLink(ev, this, addSpiner, removeSpinner);
  6045. });
  6046. document.querySelector('#trackInfo .download-link').parentNode.appendChild(a);
  6047. }
  6048. }
  6049. }
  6050. function addOpenDiscographyPlayerFromAlbumPage() {
  6051. // Open discrography player by clicking on top right corner of album art
  6052. // Shows the usual play button on hover
  6053. const xRatio = 0.7;
  6054. const yRatio = 0.3;
  6055. let rect = null;
  6056. const isInRatio = function isInRatio(ev) {
  6057. rect = rect || ev.target.getBoundingClientRect();
  6058. const x = ev.clientX - rect.left;
  6059. const y = ev.clientY - rect.top;
  6060. return x > rect.width * xRatio && y < rect.height * yRatio;
  6061. };
  6062. const a = document.querySelector('#tralbumArt a.popupImage');
  6063. if (!a) {
  6064. return;
  6065. }
  6066. const div = a.appendChild(document.createElement('div'));
  6067. div.classList.add('art-play');
  6068. div.innerHTML = '<div class="art-play-bg"></div><div class="art-play-icon"></div>';
  6069. a.classList.add('playFromAlbumPage');
  6070. addStyle(`
  6071. .playFromAlbumPage .art-play {
  6072. position: absolute;
  6073. width: 74px;
  6074. height: 54px;
  6075. right: 7%;
  6076. top: 15%;
  6077. margin-left: -36px;
  6078. margin-top: -27px;
  6079. opacity: 0.0;
  6080. transition: opacity 0.2s;
  6081. }
  6082. .playFromAlbumPage .art-play-bg {
  6083. position: absolute;
  6084. width: 100%;
  6085. height: 100%;
  6086. left: 0;
  6087. top: 0;
  6088. background: #000;
  6089. border-radius: 4px;
  6090. }
  6091. .playFromAlbumPage .art-play-icon {
  6092. position: absolute;
  6093. width: 0;
  6094. height: 0;
  6095. left: 28px;
  6096. top: 17px;
  6097. border-width: 10px 0 10px 17px;
  6098. border-color: transparent transparent transparent #fff;
  6099. border-style: dashed dashed dashed solid;
  6100. }
  6101. `);
  6102. a.addEventListener('click', function onAlbumArtClick(ev) {
  6103. if (isInRatio(ev)) {
  6104. // Open player
  6105. ev.preventDefault();
  6106. ev.stopPropagation();
  6107. if (unsafeWindow.TralbumData) {
  6108. addAlbumToPlaylist(unsafeWindow.TralbumData);
  6109. } else {
  6110. playAlbumFromUrl(document.location.href);
  6111. }
  6112. }
  6113. }, true);
  6114. a.addEventListener('mouseover', function onAlbumArtOver(ev) {
  6115. if (isInRatio(ev)) {
  6116. a.querySelector('.art-play').style.opacity = 0.7;
  6117. } else {
  6118. a.querySelector('.art-play').style.opacity = 0.0;
  6119. }
  6120. });
  6121. a.addEventListener('mousemove', function onAlbumArtOver(ev) {
  6122. if (isInRatio(ev)) {
  6123. a.querySelector('.art-play').style.opacity = 0.7;
  6124. } else {
  6125. a.querySelector('.art-play').style.opacity = 0.0;
  6126. }
  6127. });
  6128. a.addEventListener('mouseleave', function onAlbumArtOver(ev) {
  6129. rect = null;
  6130. a.querySelector('.art-play').style.opacity = 0.0;
  6131. });
  6132. }
  6133. function addLyricsToAlbumPage() {
  6134. // Load lyrics from html into TralbumData
  6135. const TralbumData = unsafeWindow.TralbumData;
  6136. function findInTralbumData(url) {
  6137. for (let i = 0; i < TralbumData.trackinfo.length; i++) {
  6138. const t = TralbumData.trackinfo[i];
  6139. if (url.endsWith(t.title_link)) {
  6140. return t;
  6141. }
  6142. }
  6143. return null;
  6144. }
  6145. const tracks = Array.from(document.querySelectorAll('#track_table .track_row_view .title a')).map(a => findInTralbumData(a.href));
  6146. document.querySelectorAll('#track_table .track_row_view .title a').forEach(function (a) {
  6147. const tr = parentQuery(a, 'tr[rel]');
  6148. const trackNum = tr.getAttribute('rel').split('tracknum=')[1];
  6149. const lyricsRow = document.querySelector('#track_table tr#lyrics_row_' + trackNum);
  6150. const lyricsLink = tr.querySelector('.geniuslink');
  6151. if (tr.querySelector('.info_link').innerHTML.indexOf('lyrics') === -1) {
  6152. // Hide info link if there are no lyrics
  6153. tr.querySelector('.info_link a[href*="/track/"]').innerHTML = '';
  6154. }
  6155. if (lyricsRow) {
  6156. const trackNum = parseInt(lyricsRow.id.split('lyrics_row_')[1]);
  6157. for (let i = 0; i < tracks.length; i++) {
  6158. if (trackNum === tracks[i].track_num) {
  6159. tracks[i].lyrics = lyricsRow.querySelector('div').textContent;
  6160. }
  6161. }
  6162. } else if (!lyricsLink) {
  6163. // Add genius link
  6164. const lyricsLink = tr.querySelector('.info_link').appendChild(document.createElement('a'));
  6165. lyricsLink.dataset.trackNum = trackNum;
  6166. lyricsLink.title = 'load lyrics from genius.com';
  6167. lyricsLink.href = '#geniuslyrics-' + trackNum;
  6168. lyricsLink.classList.add('geniuslink');
  6169. lyricsLink.appendChild(document.createTextNode('G'));
  6170. lyricsLink.style = 'color: black;background: rgb(255, 255, 100);border-radius: 50%;padding: 0px 3px;border: 1px solid black';
  6171. lyricsLink.addEventListener('click', function () {
  6172. loadGeniusLyrics(parseInt(this.dataset.trackNum));
  6173. });
  6174. }
  6175. });
  6176. }
  6177. let genius = null;
  6178. let geniusContainerTr = null;
  6179. let geniusTrackNum = -1;
  6180. let geniusArtistsArr = [];
  6181. let geniusTitle = '';
  6182. function geniusGetCleanLyricsContainer() {
  6183. geniusContainerTr.innerHTML = `
  6184. <td colspan="5">
  6185. <div></div>
  6186. </td>
  6187. `;
  6188. return geniusContainerTr.querySelector('div');
  6189. }
  6190. function geniusAddLyrics(force, beLessSpecific) {
  6191. genius.f.loadLyrics(force, beLessSpecific, geniusTitle, geniusArtistsArr, true);
  6192. }
  6193. function geniusHideLyrics() {
  6194. document.querySelectorAll('.loadingspinner').forEach(spinner => spinner.remove());
  6195. document.querySelectorAll('#track_table tr.showlyrics').forEach(e => e.classList.remove('showlyrics'));
  6196. }
  6197. function geniusSetFrameDimensions(container, iframe) {
  6198. const width = iframe.style.width = '500px';
  6199. const height = iframe.style.height = '650px';
  6200. if (genius.option.themeKey === 'spotify') {
  6201. iframe.style.backgroundColor = 'black';
  6202. } else {
  6203. iframe.style.backgroundColor = '';
  6204. }
  6205. return [width, height];
  6206. }
  6207. function geniusAddCss() {
  6208. addStyle(geniusCSS);
  6209. addStyle(`
  6210. #myconfigwin39457845 {
  6211. background-color:${darkModeModeCurrent === true ? '#a2a2a2' : 'white'} !important;
  6212. color:${darkModeModeCurrent === true ? 'white' : 'black'} !important;
  6213. }
  6214. #myconfigwin39457845 div {
  6215. background-color:${darkModeModeCurrent === true ? '#3E3E3E' : '#EFEFEF'} !important
  6216. }
  6217. .lyricsnavbar {
  6218. background:${darkModeModeCurrent === true ? '#7d7c7c' : '#fafafa'} !important;
  6219. }
  6220. `);
  6221. }
  6222. function geniusCreateSpinner(spinnerHolder) {
  6223. geniusContainerTr.querySelector('div').insertBefore(spinnerHolder, geniusContainerTr.querySelector('div').firstChild);
  6224. const spinner = spinnerHolder.appendChild(document.createElement('div'));
  6225. spinner.classList.add('loadingspinner');
  6226. return spinner;
  6227. }
  6228. function geniusShowSearchField(query) {
  6229. const b = geniusGetCleanLyricsContainer();
  6230. b.style.border = '1px solid black';
  6231. b.style.borderRadius = '3px';
  6232. b.style.padding = '5px';
  6233. b.appendChild(document.createTextNode('Search genius.com: '));
  6234. b.style.paddingRight = '15px';
  6235. const input = b.appendChild(document.createElement('input'));
  6236. input.className = 'SearchInputBox__input';
  6237. input.placeholder = 'Search genius.com...';
  6238. input.style = 'width: 300px;background-color: #F3F3F3;padding: 10px 30px 10px 10px;font-size: 14px; border: none;color: #333;margin: 6px 0;height: 17px;border-radius: 3px;';
  6239. const span = b.appendChild(document.createElement('span'));
  6240. span.style = 'cursor:pointer; margin-left: -25px;';
  6241. span.appendChild(document.createTextNode(' \uD83D\uDD0D'));
  6242. if (query) {
  6243. input.value = query;
  6244. } else if (genius.current.artists) {
  6245. input.value = genius.current.artists;
  6246. }
  6247. input.addEventListener('change', function onSearchLyricsButtonClick() {
  6248. if (input.value) {
  6249. genius.f.searchByQuery(input.value, b);
  6250. }
  6251. });
  6252. input.addEventListener('keyup', function onSearchLyricsKeyUp(ev) {
  6253. if (ev.keyCode === 13) {
  6254. ev.preventDefault();
  6255. if (input.value) {
  6256. genius.f.searchByQuery(input.value, b);
  6257. }
  6258. }
  6259. });
  6260. span.addEventListener('click', function onSearchLyricsKeyUp(ev) {
  6261. if (input.value) {
  6262. genius.f.searchByQuery(input.value, b);
  6263. }
  6264. });
  6265. input.focus();
  6266. }
  6267. function geniusListSongs(hits, container, query) {
  6268. if (!container) {
  6269. container = geniusGetCleanLyricsContainer();
  6270. }
  6271.  
  6272. // Back to search button
  6273. const backToSearchButton = document.createElement('a');
  6274. backToSearchButton.href = '#';
  6275. backToSearchButton.appendChild(document.createTextNode('Back to search'));
  6276. backToSearchButton.addEventListener('click', function backToSearchButtonClick(ev) {
  6277. ev.preventDefault();
  6278. if (query) {
  6279. geniusShowSearchField(query);
  6280. } else if (genius.current.artists) {
  6281. geniusShowSearchField(genius.current.artists + ' ' + genius.current.title);
  6282. } else {
  6283. geniusShowSearchField();
  6284. }
  6285. });
  6286. const separator = document.createElement('span');
  6287. separator.setAttribute('class', 'second-line-separator');
  6288. separator.setAttribute('style', 'padding:0px 3px');
  6289. separator.appendChild(document.createTextNode('•'));
  6290.  
  6291. // Hide button
  6292. const hideButton = document.createElement('a');
  6293. hideButton.href = '#';
  6294. hideButton.appendChild(document.createTextNode('Hide'));
  6295. hideButton.addEventListener('click', function hideButtonClick(ev) {
  6296. ev.preventDefault();
  6297. geniusHideLyrics();
  6298. });
  6299.  
  6300. // List search results
  6301. const trackhtml = '<div style="float:left;"><div class="onhover" style="margin-top:-0.25em;display:none"><span style="color:black;font-size:2.0em">🅖</span></div><div class="onout"><span style="font-size:1.5em">📄</span></div></div>' + '<div style="float:left; margin-left:5px">$artist • $title <br><span style="font-size:0.7em">👁 $stats.pageviews $lyrics_state</span></div><div style="clear:left;"></div>';
  6302. container.innerHTML = '<ol class="tracklist" style="font-size:1.15em"></ol>';
  6303. container.classList.add('searchresultlist');
  6304. if (darkModeModeCurrent === true) {
  6305. container.style.backgroundColor = '#262626';
  6306. container.style.position = 'relative';
  6307. }
  6308. container.insertBefore(hideButton, container.firstChild);
  6309. container.insertBefore(separator, container.firstChild);
  6310. container.insertBefore(backToSearchButton, container.firstChild);
  6311. const ol = container.querySelector('ol');
  6312. const searchresultsLengths = hits.length;
  6313. const title = genius.current.title;
  6314. const artists = genius.current.artists;
  6315. const onclick = function onclick() {
  6316. genius.f.rememberLyricsSelection(title, artists, this.dataset.hit);
  6317. genius.f.showLyrics(JSON.parse(this.dataset.hit), searchresultsLengths);
  6318. };
  6319. const mouseover = function onmouseover() {
  6320. this.querySelector('.onhover').style.display = 'block';
  6321. this.querySelector('.onout').style.display = 'none';
  6322. this.style.backgroundColor = darkModeModeCurrent === true ? 'rgb(70, 70, 70)' : 'rgb(200, 200, 200)';
  6323. };
  6324. const mouseout = function onmouseout() {
  6325. this.querySelector('.onhover').style.display = 'none';
  6326. this.querySelector('.onout').style.display = 'block';
  6327. this.style.backgroundColor = darkModeModeCurrent === true ? '#262626' : 'rgb(255, 255, 255)';
  6328. };
  6329. hits.forEach(function forEachHit(hit) {
  6330. const li = document.createElement('li');
  6331. if (darkModeModeCurrent === true) {
  6332. li.style.backgroundColor = '#262626';
  6333. }
  6334. li.style.cursor = 'pointer';
  6335. li.style.transition = 'background-color 0.2s';
  6336. li.style.padding = '3px';
  6337. li.style.margin = '2px';
  6338. li.style.borderRadius = '3px';
  6339. li.innerHTML = trackhtml.replace(/\$title/g, hit.result.title_with_featured).replace(/\$artist/g, hit.result.primary_artist.name).replace(/\$lyrics_state/g, hit.result.lyrics_state).replace(/\$stats\.pageviews/g, genius.f.metricPrefix(hit.result.stats.pageviews, 1));
  6340. li.dataset.hit = JSON.stringify(hit);
  6341. li.addEventListener('click', onclick);
  6342. li.addEventListener('mouseover', mouseover);
  6343. li.addEventListener('mouseout', mouseout);
  6344. ol.appendChild(li);
  6345. });
  6346. }
  6347. function geniusOnLyricsReady(song, container) {
  6348. container.parentNode.parentNode.dataset.loaded = 'loaded';
  6349. }
  6350. function geniusOnNoResults(songTitle, songArtistsArr) {
  6351. geniusContainerTr.dataset.loaded = 'loaded';
  6352. document.querySelectorAll('#track_table tr.showlyrics').forEach(e => e.classList.remove('showlyrics'));
  6353. document.querySelector(`#track_table tr[rel="tracknum=${geniusTrackNum}"]`).classList.add('showlyrics');
  6354. geniusShowSearchField(songArtistsArr.join(' ') + ' ' + songTitle);
  6355. }
  6356. let geniusAudio = null;
  6357. let geniusLastPos = null;
  6358. function geniusAudioTimeUpdate() {
  6359. if (!geniusAudio) {
  6360. geniusAudio = document.querySelector('body>audio[src]');
  6361. }
  6362. if (!geniusAudio) {
  6363. return;
  6364. }
  6365. const pos = geniusAudio.currentTime / geniusAudio.duration;
  6366. if (pos >= 0 && `${geniusLastPos}` !== `${pos}`) {
  6367. geniusLastPos = pos;
  6368. genius.f.scrollLyrics(pos);
  6369. }
  6370. }
  6371. function initGenius() {
  6372. if (!genius) {
  6373. genius = geniusLyrics({
  6374. GM: {
  6375. xmlHttpRequest: GM.xmlHttpRequest,
  6376. getValue: (name, defaultValue) => GM.getValue('genius_' + name, defaultValue),
  6377. setValue: (name, value) => GM.setValue('genius_' + name, value)
  6378. },
  6379. scriptName: SCRIPT_NAME,
  6380. scriptIssuesURL: 'https://github.com/cvzi/Bandcamp-script-deluxe-edition/issues',
  6381. scriptIssuesTitle: 'Report problem: github.com/cvzi/Bandcamp-script-deluxe-edition/issues',
  6382. domain: document.location.origin + '/',
  6383. emptyURL: document.location.origin + LYRICS_EMPTY_PATH,
  6384. addCss: geniusAddCss,
  6385. listSongs: geniusListSongs,
  6386. showSearchField: geniusShowSearchField,
  6387. addLyrics: geniusAddLyrics,
  6388. hideLyrics: geniusHideLyrics,
  6389. getCleanLyricsContainer: geniusGetCleanLyricsContainer,
  6390. setFrameDimensions: geniusSetFrameDimensions,
  6391. createSpinner: geniusCreateSpinner,
  6392. onLyricsReady: geniusOnLyricsReady,
  6393. onNoResults: geniusOnNoResults
  6394. });
  6395. document.addEventListener('timeupdate', geniusAudioTimeUpdate, true);
  6396. }
  6397. }
  6398. function loadGeniusLyrics(trackNum) {
  6399. // Toggle lyrics
  6400. geniusContainerTr = document.getElementById('lyrics_row_' + trackNum);
  6401. let tr;
  6402. if (geniusContainerTr) {
  6403. tr = document.querySelector(`#track_table tr[rel="tracknum=${trackNum}"]`);
  6404. if ('loaded' in geniusContainerTr.dataset && geniusContainerTr.dataset.loaded === 'loaded') {
  6405. if (tr.classList.contains('showlyrics')) {
  6406. // Hide lyrics if already loaded
  6407. document.querySelectorAll('#track_table tr.showlyrics').forEach(e => e.classList.remove('showlyrics'));
  6408. } else {
  6409. // Show lyrics again
  6410. document.querySelectorAll('#track_table tr.showlyrics').forEach(e => e.classList.remove('showlyrics'));
  6411. tr.classList.add('showlyrics');
  6412. }
  6413. return;
  6414. } else if (geniusTrackNum === trackNum) {
  6415. // Lyrics currently loading
  6416. console.debug('loadGeniusLyrics already loading trackNum=' + trackNum);
  6417. return;
  6418. }
  6419. }
  6420. geniusTrackNum = trackNum;
  6421. if (!geniusContainerTr) {
  6422. geniusContainerTr = document.createElement('tr');
  6423. geniusContainerTr.className = 'lyricsRow';
  6424. geniusContainerTr.setAttribute('id', 'lyrics_row_' + trackNum);
  6425. tr = document.querySelector(`#track_table tr[rel="tracknum=${trackNum}"]`);
  6426. if (tr.nextElementSibling) {
  6427. tr.parentNode.insertBefore(geniusContainerTr, tr.nextElementSibling);
  6428. } else {
  6429. tr.parentNode.appendChild(geniusContainerTr);
  6430. }
  6431. document.querySelectorAll('#track_table tr.showlyrics').forEach(e => e.classList.remove('showlyrics'));
  6432. tr.classList.add('showlyrics');
  6433. const spinnerHolder = geniusContainerTr.appendChild(document.createElement('div'));
  6434. spinnerHolder.classList.add('loadingspinnerholder');
  6435. const spinner = spinnerHolder.appendChild(document.createElement('div'));
  6436. spinner.classList.add('loadingspinner');
  6437. }
  6438. initGenius();
  6439. const track = unsafeWindow.TralbumData.trackinfo.find(t => t.track_num === trackNum);
  6440. geniusTitle = track.title;
  6441. geniusArtistsArr = unsafeWindow.TralbumData.artist.split(/&|,|ft\.?|feat\.?/).map(s => s.trim());
  6442. geniusAddLyrics();
  6443. }
  6444. let explorer = null;
  6445. async function showExplorer() {
  6446. if (explorer) {
  6447. explorer.style.display = 'block';
  6448. return explorer;
  6449. }
  6450. document.title = 'Explorer';
  6451. document.body.innerHTML = '';
  6452. explorer = document.body.appendChild(document.createElement('div'));
  6453. explorer.setAttribute('id', 'expRoot');
  6454. addStyle(`
  6455. #expRoot {
  6456. background:white;
  6457. color:black
  6458. }
  6459. #expRoot .albumListItem{
  6460. cursor:pointer;
  6461. background:#ddd;
  6462. display: flex;
  6463. align-items: center;
  6464. justify-content: center;
  6465. }
  6466. #expRoot .albumListItemOdd{
  6467. background:#eee
  6468. }
  6469. #expRoot .albumListItem:hover{
  6470. background:greenyellow
  6471. }
  6472.  
  6473. #expRoot .albumListItem.selected{
  6474. background:#aaa;
  6475. }
  6476.  
  6477. `);
  6478. new Explorer(document.getElementById('expRoot'), {
  6479. playAlbumFromUrl,
  6480. deletePermanentTralbum
  6481. }).render();
  6482. }
  6483. function appendMainMenuButtonTo(ul) {
  6484. addStyle(`
  6485. .menubar-item .menubar-symbol {
  6486. display:flex;
  6487. font-size:24px !important;
  6488. transition:transform 1s ease-out
  6489. }
  6490. .menubar-item .menubar-symbol:hover {
  6491. text-decoration:none
  6492. }
  6493. .menubar-item:hover .menubar-symbol-settings {
  6494. transform:rotate(1turn)
  6495. }
  6496. .menubar-item:hover .menubar-symbol-library {
  6497. transform:scale(-1, 1)
  6498. }
  6499. .menubar-item:hover .menubar-symbol-tag-search {
  6500. transform:scale(1.3)
  6501. }
  6502. `);
  6503. const liSettings = ul.insertBefore(document.createElement('li'), ul.firstChild);
  6504. liSettings.className = 'menubar-item hoverable';
  6505. liSettings.title = 'userscript settings - ' + SCRIPT_NAME;
  6506. const aSettings = liSettings.appendChild(document.createElement('a'));
  6507. aSettings.className = 'menubar-symbol menubar-symbol-settings';
  6508. aSettings.href = '#';
  6509. if (NOEMOJI) {
  6510. const img = aSettings.appendChild(document.createElement('img'));
  6511. img.style = 'display:inline; width:34px; vertical-align:middle;';
  6512. img.src = 'https://raw.githubusercontent.com/hfg-gmuend/openmoji/master/color/72x72/2699.png';
  6513. } else {
  6514. aSettings.appendChild(document.createTextNode('\u2699\uFE0F'));
  6515. }
  6516. liSettings.addEventListener('click', () => mainMenu());
  6517. if (allFeatures.keepLibrary.enabled) {
  6518. const liExplorer = ul.insertBefore(document.createElement('li'), ul.firstChild);
  6519. liExplorer.className = 'menubar-item hoverable';
  6520. liExplorer.title = 'library - ' + SCRIPT_NAME;
  6521. const aExplorer = liExplorer.appendChild(document.createElement('a'));
  6522. aExplorer.className = 'menubar-symbol menubar-symbol-library';
  6523. aExplorer.href = PLAYER_URL;
  6524. if (NOEMOJI) {
  6525. const img = aExplorer.appendChild(document.createElement('img'));
  6526. img.style = 'display:inline; width:34px; vertical-align:middle;';
  6527. img.src = 'https://raw.githubusercontent.com/hfg-gmuend/openmoji/master/color/72x72/1F5C3.png';
  6528. } else {
  6529. aExplorer.appendChild(document.createTextNode('\uD83D\uDDC3\uFE0F'));
  6530. }
  6531. aExplorer.target = '_blank';
  6532. // TODO open library in frame
  6533. // liExplorer.addEventListener('click', function (ev) {
  6534. // ev.preventDefault()
  6535. // openExplorer()
  6536. // })
  6537. }
  6538.  
  6539. const liSearch = ul.insertBefore(document.createElement('li'), ul.firstChild);
  6540. liSearch.className = 'menubar-item hoverable menubar-item-tag-search';
  6541. liSearch.title = 'tag search - ' + SCRIPT_NAME;
  6542. const aSearch = liSearch.appendChild(document.createElement('a'));
  6543. aSearch.className = 'menubar-symbol menubar-symbol-tag-search';
  6544. aSearch.href = '#';
  6545. if (NOEMOJI) {
  6546. aSearch.innerHTML = `
  6547. <svg width="22" height="22" viewBox="0 0 15 16" class="svg-icon" style="border: 2px solid #000000c4;border-radius: 30%;padding: 3px;">
  6548. <use xlink:href="#menubar-search-input-icon">
  6549. </svg>`;
  6550. } else {
  6551. aSearch.appendChild(document.createTextNode('\uD83D\uDD0D'));
  6552. }
  6553. aSearch.setAttribute('id', 'bcsde_tagsearchbutton');
  6554. aSearch.addEventListener('click', showTagSearchForm);
  6555. }
  6556. function appendMainMenuButtonLeftTo(leftOf) {
  6557. // Wait for the design to load images
  6558. window.setTimeout(() => {
  6559. const rect = leftOf.getBoundingClientRect();
  6560. const ul = document.createElement('ul');
  6561. ul.className = 'bcsde_settingsbar';
  6562. appendMainMenuButtonTo(document.body.appendChild(ul));
  6563. addStyle(`
  6564. .bcsde_settingsbar {position:absolute; top:-15px; left:${rect.right}px; list-style-type: none; padding:0; margin:0; opacity:0.6; transition:top 300ms}
  6565. .bcsde_settingsbar:hover {top:${rect.top}px}
  6566. .bcsde_settingsbar a:hover {text-decoration:none}
  6567. .bcsde_settingsbar li {float:left; padding:0; margin:0}`);
  6568. window.addEventListener('resize', function () {
  6569. ul.style.left = leftOf.getBoundingClientRect().right + 'px';
  6570. });
  6571. }, 500);
  6572. }
  6573. function humour() {
  6574. if (document.getElementById('salesfeed')) {
  6575. const salesfeedHumour = {};
  6576. salesfeedHumour.all = [`${SCRIPT_NAME} by cuzi, Dark theme by Simonus`, `Provide feedback for ${SCRIPT_NAME} on openuser.js or github.com`, `${SCRIPT_NAME} - nobody pays for software anymore 🙌🏽`];
  6577. salesfeedHumour.chosen = salesfeedHumour.all[0];
  6578. unsafeWindow.$('#pagedata').data('blob').salesfeed_humour = salesfeedHumour;
  6579. }
  6580. }
  6581. function showAlbumID() {
  6582. if (unsafeWindow.TralbumData && 'id' in unsafeWindow.TralbumData && document.querySelector('#name-section h3')) {
  6583. document.querySelectorAll('#name-section h3').forEach(function (h3) {
  6584. const id = unsafeWindow.TralbumData.id;
  6585. const h4 = h3.parentNode.appendChild(document.createElement('h4'));
  6586. h4.style.fontSize = '13px';
  6587. h4.style.fontWeight = 'normal';
  6588. h4.style.opacity = 0.6;
  6589. h4.style.marginTop = '4px';
  6590. h4.innerHTML = `Album ID: <span style="user-select: all;">${id}</span>`;
  6591. h4.addEventListener('click', function () {
  6592. GM_setClipboard(id.toString());
  6593. const span = h4.appendChild(document.createElement('span'));
  6594. span.innerHTML = ' copied!';
  6595. span.style.marginLeft = '5px';
  6596. span.style.transition = 'opacity 2s';
  6597. span.style.opacity = 1;
  6598. window.setInterval(() => span.style.opacity = 0, 0);
  6599. window.setInterval(() => span.remove(), 1000);
  6600. });
  6601. });
  6602. }
  6603. }
  6604. function formatReleaseDateOnAlbumPage() {
  6605. const textContainers = document.querySelectorAll('.tralbumData');
  6606. if (textContainers.length === 0) {
  6607. return;
  6608. }
  6609. GM.getValue('custom_release_date_format_str').then(function customFormatReleaseDate(format) {
  6610. if (!format || !format.trim()) {
  6611. console.warn('formatReleaseDateOnAlbumPage: No custom release date format string set.');
  6612. return;
  6613. }
  6614. textContainers.forEach(function (textContainer) {
  6615. for (const match of textContainer.innerHTML.matchAll(/(January|February|March|April|May|June|July|August|September|October|November|December)\s+(\d{1,2}),\s+(\d{4})/gim)) {
  6616. const epochMs = Date.parse(match[0]);
  6617. if (Number.isNaN(epochMs)) {
  6618. console.warn(`formatReleaseDateOnAlbumPage: Could not parse date string "${match[0].trim()}"`);
  6619. continue;
  6620. }
  6621. const date = new Date(epochMs);
  6622. textContainer.innerHTML = textContainer.innerHTML.replace(match[0], `${customDateFormatter(format, date)}`);
  6623. }
  6624. });
  6625. });
  6626. }
  6627. function showDownloadLinkOnAlbumPage() {
  6628. if (!document.querySelector('a[href*="purchases?from=menubar"]')) {
  6629. return;
  6630. }
  6631. const purchasesUrl = document.querySelector('a[href*="purchases?from=menubar"]').href;
  6632. const itemUrl = document.location.href.split('#')[0];
  6633. const showDownloadLinkForUrl = function (downloadUrl) {
  6634. const purchasedMsgA = document.querySelector('#purchased-msg a');
  6635. purchasedMsgA.href = downloadUrl;
  6636. purchasedMsgA.textContent = 'Download';
  6637. };
  6638. GM.xmlHttpRequest({
  6639. method: 'GET',
  6640. url: purchasesUrl,
  6641. onload: function loadPurchases(response) {
  6642. const doc = new window.DOMParser().parseFromString(response.responseText, 'text/html').documentElement;
  6643. for (const purchasesItem of Array.from(doc.querySelectorAll('.purchases-item'))) {
  6644. if (!purchasesItem.querySelector('.purchases-item-title[href]')) {
  6645. continue;
  6646. }
  6647. const url = purchasesItem.querySelector('.purchases-item-title[href]').href;
  6648. if (url !== itemUrl) {
  6649. continue;
  6650. }
  6651. const downloadLink = purchasesItem.querySelector('.purchases-item-download a[href]');
  6652. if (!downloadLink && !downloadLink.href) {
  6653. continue;
  6654. }
  6655. return showDownloadLinkForUrl(downloadLink.href);
  6656. }
  6657. if (doc.querySelector('#js-crumbs-data') && doc.querySelector('#pagedata')) {
  6658. try {
  6659. const crumb = JSON.parse(doc.querySelector('#js-crumbs-data').dataset.crumbs)['api/orderhistory/1/get_items'];
  6660. const orderhistory = JSON.parse(doc.querySelector('#pagedata').dataset.blob).orderhistory;
  6661. nextOrderHistoryPage(itemUrl, {
  6662. username: orderhistory.username,
  6663. last_token: orderhistory.last_token,
  6664. platform: orderhistory.platform,
  6665. crumb
  6666. }, showDownloadLinkForUrl);
  6667. } catch (e) {
  6668. console.error('Error in showDownloadLinkOnAlbumPage, failed to launch nextOrderHistoryPage:', e);
  6669. }
  6670. }
  6671. },
  6672. onerror: function loadPurchasesError(response) {
  6673. console.error('showDownloadLinkOnAlbumPage() in onerror() Error: ' + response.status + '\nResponse:\n' + response.responseText + '\n' + ('error' in response ? response.error : ''));
  6674. }
  6675. });
  6676. }
  6677. async function nextOrderHistoryPage(itemUrl, data, cbFoundDownloadLink) {
  6678. // Load download links from api (same as clicking on "more" at the bototm of purchases page)
  6679. const handleResponse = function (result) {
  6680. for (const item of result.items) {
  6681. if (item.item_url === itemUrl) {
  6682. return cbFoundDownloadLink(item.download_url);
  6683. }
  6684. }
  6685. if ('last_token' in result && result.last_token) {
  6686. data.last_token = result.last_token;
  6687. return nextOrderHistoryPage(itemUrl, data, cbFoundDownloadLink);
  6688. }
  6689. };
  6690. const cacheKey = data.last_token;
  6691. const cached = await cacheGet('orderhistory', ONEHOUR, cacheKey, null);
  6692. if (cached) {
  6693. return handleResponse(JSON.parse(cached));
  6694. }
  6695. GM.xmlHttpRequest({
  6696. method: 'POST',
  6697. url: 'https://bandcamp.com/api/orderhistory/1/get_items',
  6698. headers: {
  6699. ' Content-Type': 'application/json'
  6700. },
  6701. data: JSON.stringify(data),
  6702. onload: function loadPurchases(response) {
  6703. try {
  6704. const result = JSON.parse(response.responseText);
  6705. cacheSet('orderhistory', ONEHOUR, cacheKey, response.responseText);
  6706. handleResponse(result);
  6707. } catch (e) {
  6708. console.error('Error in nextOrderHistoryPage:', e);
  6709. }
  6710. },
  6711. onerror: function loadPurchasesError(response) {
  6712. console.error('nextOrderHistoryPage () in onerror() Error: ' + response.status + '\nResponse:\n' + response.responseText + '\n' + ('error' in response ? response.error : ''));
  6713. }
  6714. });
  6715. }
  6716. function feedShowOnlyNewReleases() {
  6717. const stories = document.querySelectorAll('#stories li.story');
  6718. if (stories.length < 0) {
  6719. window.setTimeout(feedShowOnlyNewReleases, 10000);
  6720. return;
  6721. }
  6722. if (Array.from(stories).reduce((accumulator, story) => {
  6723. // Remove stories that are not 'nr' => new releases
  6724. if (!story.classList.contains('nr')) {
  6725. story.remove();
  6726. accumulator++;
  6727. }
  6728. return accumulator;
  6729. }, 0)) {
  6730. // If any were removed, trigger a reload of the feed
  6731. window.scrollBy(0, 1);
  6732. window.scrollBy(0, -1);
  6733. window.setTimeout(feedShowOnlyNewReleases, 500);
  6734. } else {
  6735. window.setTimeout(feedShowOnlyNewReleases, 1500);
  6736. }
  6737. }
  6738. function feedShowAudioControls() {
  6739. const makeAudioVisible = function () {
  6740. this.removeEventListener('timeupdate', makeAudioVisible);
  6741. this.controls = true;
  6742. this.loop = false;
  6743. this.style = `
  6744. width: 20%;
  6745. min-width: 200px;
  6746. height: 40px;
  6747. position: fixed;
  6748. right: 0px;
  6749. bottom: 0px;
  6750. display: block;
  6751. opacity: 1;`;
  6752. };
  6753. const audio = document.querySelector('body>audio');
  6754. if (audio) {
  6755. audio.addEventListener('timeupdate', makeAudioVisible);
  6756. }
  6757. }
  6758. function feedEnablePlayNextItem() {
  6759. // Play next item in feed when current item ends
  6760. let currentItem = null;
  6761. const onItemStart = async function () {
  6762. // Save item that is currently playing (play button is showing Pause-symbol)
  6763. sleep(2000);
  6764. currentItem = currentItem || document.querySelector('.collection-item-container.playing');
  6765. };
  6766. const onItemEnded = function () {
  6767. if (currentItem) {
  6768. // Find next item and click play button
  6769. let isNext = false;
  6770. for (const item of document.querySelectorAll('.collection-item-container')) {
  6771. if (isNext && item.querySelector('.play-button')) {
  6772. item.querySelector('.play-button').click();
  6773. currentItem = null;
  6774. break;
  6775. } else if (item === currentItem) {
  6776. isNext = true;
  6777. }
  6778. }
  6779. }
  6780. };
  6781. const audio = document.querySelector('body>audio');
  6782. if (audio) {
  6783. audio.addEventListener('play', onItemStart);
  6784. audio.addEventListener('ended', onItemEnded);
  6785. }
  6786. }
  6787. function feedAddDiscographyPlayerButtons() {
  6788. const play = function (ev) {
  6789. ev.preventDefault();
  6790. playAlbumFromUrl(this.dataset.url);
  6791. };
  6792. document.querySelectorAll('.collect-item ul').forEach(ul => {
  6793. if (ul.querySelector('li.discographyplayerbutton') || !ul.querySelector('li.buy-now')) {
  6794. return;
  6795. }
  6796. const li = ul.appendChild(ul.querySelector('li.buy-now').cloneNode(true));
  6797. li.classList.remove('buy-now');
  6798. li.classList.add('discographyplayerbutton');
  6799. const a = li.querySelector('a');
  6800. a.dataset.url = a.href;
  6801. a.href = '#';
  6802. a.textContent = 'Play album';
  6803. a.addEventListener('click', play);
  6804. const img = li.insertBefore(document.createElement('img'), li.querySelector('a'));
  6805. img.src = 'https://raw.githubusercontent.com/cvzi/Bandcamp-script-deluxe-edition/master/images/icon.png';
  6806. img.style = 'width: 14px; vertical-align: sub;padding:0px 3px 0px 0px;';
  6807. img.alt = 'Play in discography player';
  6808. });
  6809. window.setTimeout(feedAddDiscographyPlayerButtons, 10000);
  6810. }
  6811. function darkMode() {
  6812. // CSS taken from https://userstyles.org/styles/171538/bandcamp-in-dark by Simonus (Version from January 24, 2020)
  6813. // https://userstyles.org/api/v1/styles/css/171538
  6814.  
  6815. let propOpenWrapperBackgroundColor = '#2626268f';
  6816. try {
  6817. const brightnessStr = window.localStorage.getItem('bcsde_bgimage_brightness');
  6818. if (brightnessStr !== null && brightnessStr !== 'null') {
  6819. const brightness = parseFloat(brightnessStr);
  6820. const alpha = (brightness - 50) / 255;
  6821. propOpenWrapperBackgroundColor = `rgba(0, 0, 0, ${alpha})`;
  6822. }
  6823. } catch (e) {
  6824. console.error('Could not access window.localStorage: ' + e);
  6825. }
  6826. addStyle(`
  6827. :root {
  6828. --pgBdColor: #262626;
  6829. --propOpenWrapperBackgroundColor: ${propOpenWrapperBackgroundColor}
  6830. }`);
  6831. addStyle(darkmodeCSS);
  6832. window.setTimeout(humour, 3000);
  6833. darkModeInjected = true;
  6834. }
  6835. async function darkModeOnLoad() {
  6836. const yes = await darkModeMode();
  6837. if (!yes) {
  6838. return;
  6839. }
  6840.  
  6841. // Load body's background image and detect if it is light or dark and adapt it's transparency
  6842. const backgroudImageCSS = window.getComputedStyle(document.body).backgroundImage;
  6843. let imageURL = backgroudImageCSS.match(/["'](.*)["']/);
  6844. let shouldUpdate = false;
  6845. let hasBackgroundImage = false;
  6846. if (imageURL && imageURL[1]) {
  6847. imageURL = imageURL[1];
  6848. shouldUpdate = true;
  6849. hasBackgroundImage = true;
  6850. try {
  6851. const editTime = parseInt(window.localStorage.getItem('bcsde_bgimage_brightness_time'));
  6852. if (Date.now() - editTime < 604800000) {
  6853. shouldUpdate = false;
  6854. }
  6855. } catch (e) {
  6856. console.error('Could not read from window.localStorage: ' + e);
  6857. }
  6858. }
  6859. if (shouldUpdate) {
  6860. const canvas = await loadCrossSiteImage(imageURL);
  6861. const ctx = canvas.getContext('2d');
  6862. const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
  6863. let sum = 0.0;
  6864. let div = 0;
  6865. const stepSize = canvas.width * canvas.height / 1000;
  6866. const len = data.length - 4;
  6867. for (let i = 0; i < len; i += 4 * parseInt(stepSize * Math.random())) {
  6868. const v = Math.max(Math.max(data[i], data[i + 1]), data[i + 2]);
  6869. sum += v;
  6870. div++;
  6871. }
  6872. const brightness = sum / div;
  6873. const alpha = (brightness - 50) / 255;
  6874. document.querySelector('#propOpenWrapper').style.backgroundColor = `rgba(0, 0, 0, ${alpha})`;
  6875. try {
  6876. window.localStorage.setItem('bcsde_bgimage_brightness', brightness);
  6877. window.localStorage.setItem('bcsde_bgimage_brightness_time', Date.now());
  6878. } catch (e) {
  6879. console.error('Could not write to window.localStorage: ' + e);
  6880. }
  6881. }
  6882. if (!hasBackgroundImage) {
  6883. // No background image, check background color
  6884. const color = window.getComputedStyle(document.body).backgroundColor;
  6885. if (color) {
  6886. const m = color.match(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/);
  6887. if (m) {
  6888. const [, r, g, b] = m;
  6889. if (r < 70 && g < 70 && b < 70) {
  6890. addStyle(`
  6891. :root {
  6892. --propOpenWrapperBackgroundColor: rgb(${r}, ${g}, ${b})
  6893. }
  6894. `);
  6895. }
  6896. }
  6897. }
  6898. }
  6899. // pgBd background color
  6900. if (document.getElementById('custom-design-rules-style')) {
  6901. const customCss = document.getElementById('custom-design-rules-style').textContent;
  6902. if (customCss.indexOf('#pgBd') !== -1) {
  6903. const pgBdStyle = customCss.split('#pgBd')[1].split('}')[0];
  6904. const m = pgBdStyle.match(/background(-color)?\s*:\s*(.+?)[;\s]/m);
  6905. if (m && m.length > 2 && m[2]) {
  6906. const color = css2rgb(m[2]);
  6907. if (color) {
  6908. const [r, g, b] = color;
  6909. if (r < 70 && g < 70 && b < 70) {
  6910. addStyle(`
  6911. :root {
  6912. --pgBdColor: rgb(${r}, ${g}, ${b});
  6913. }
  6914. `);
  6915. }
  6916. }
  6917. }
  6918. }
  6919. }
  6920. }
  6921. async function updateSuntimes() {
  6922. const value = await GM.getValue('darkmode', '1');
  6923. if (value.startsWith('3#')) {
  6924. const data = JSON.parse(value.substring(2));
  6925. const sunData = suntimes(new Date(), data.latitude, data.longitude);
  6926. const newValue = '3#' + JSON.stringify(Object.assign(data, sunData));
  6927. if (newValue !== value) {
  6928. await GM.setValue('darkmode', newValue);
  6929. }
  6930. }
  6931. }
  6932. function confirmDomain() {
  6933. return new Promise(function confirmDomainPromise(resolve) {
  6934. GM.getValue('domains', '{}').then(function (v) {
  6935. const domains = JSON.parse(v);
  6936. if (document.location.hostname in domains) {
  6937. const isBandcamp = domains[document.location.hostname];
  6938. return resolve(isBandcamp);
  6939. } else {
  6940. window.setTimeout(function () {
  6941. const isBandcamp = window.confirm(`${SCRIPT_NAME}
  6942.  
  6943. This page looks like a bandcamp page, but the URL ${document.location.hostname} is not a bandcamp URL.
  6944.  
  6945. Do you want to run the userscript on this page?
  6946.  
  6947. If this is a malicious website, running the userscript may leak personal data (e.g. played albums) to the website`);
  6948. domains[document.location.hostname] = isBandcamp;
  6949. GM.setValue('domains', JSON.stringify(domains)).then(() => resolve(isBandcamp));
  6950. }, 3000);
  6951. }
  6952. });
  6953. });
  6954. }
  6955. async function setDomain(enabled) {
  6956. const domains = JSON.parse(await GM.getValue('domains', '{}'));
  6957. domains[document.location.hostname] = enabled;
  6958. await GM.setValue('domains', JSON.stringify(domains));
  6959. }
  6960. let darkModeModeCurrent = null;
  6961. async function darkModeMode() {
  6962. if (darkModeModeCurrent != null) {
  6963. return darkModeModeCurrent;
  6964. }
  6965. const value = await GM.getValue('darkmode', '1');
  6966. darkModeModeCurrent = false;
  6967. if (value.startsWith('1')) {
  6968. darkModeModeCurrent = true;
  6969. } else if (value.startsWith('2#')) {
  6970. darkModeModeCurrent = nowInTimeRange(value.substring(2));
  6971. } else if (value.startsWith('3#')) {
  6972. const data = JSON.parse(value.substring(2));
  6973. window.setTimeout(updateSuntimes, Math.random() * 10000);
  6974. darkModeModeCurrent = nowInBetween(new Date(data.sunset), new Date(data.sunrise));
  6975. }
  6976. return darkModeModeCurrent;
  6977. }
  6978. function start() {
  6979. // Load settings and enable darkmode
  6980. return new Promise(function startFct(resolve) {
  6981. GM.getValue('enabledFeatures', false).then(value => getEnabledFeatures(value)).then(function () {
  6982. if (BANDCAMP && allFeatures.darkMode.enabled) {
  6983. darkModeMode().then(function (yes) {
  6984. if (yes) {
  6985. darkMode();
  6986. }
  6987. resolve();
  6988. });
  6989. } else {
  6990. resolve();
  6991. }
  6992. });
  6993. });
  6994. }
  6995. function onLoaded() {
  6996. if (!enabledFeaturesLoaded) {
  6997. GM.getValue('enabledFeatures', false).then(value => getEnabledFeatures(value)).then(function () {
  6998. onLoaded();
  6999. });
  7000. return;
  7001. }
  7002. if (!BANDCAMP && document.querySelector('#legal.horizNav li.view-switcher.desktop a,head>meta[name=generator][content=Bandcamp]')) {
  7003. // Page is a bandcamp page but does not have a bandcamp domain
  7004. confirmDomain().then(function (isBandcamp) {
  7005. BANDCAMP = isBandcamp;
  7006. if (isBandcamp) {
  7007. onLoaded();
  7008. GM.registerMenuCommand(SCRIPT_NAME + ' - disable on this page', () => setDomain(false).then(() => document.location.reload()));
  7009. } else {
  7010. GM.registerMenuCommand(SCRIPT_NAME + ' - enable on this page', () => setDomain(true).then(() => document.location.reload()));
  7011. }
  7012. });
  7013. return;
  7014. } else if (!BANDCAMP && !CAMPEXPLORER) {
  7015. // Not a bandcamp page -> quit
  7016. return;
  7017. }
  7018. const IS_PLAYER_URL = document.location.href.startsWith(PLAYER_URL);
  7019. const IS_PLAYER_FRAME = IS_PLAYER_URL && document.location.search.indexOf('iframe');
  7020. if (allFeatures.darkMode.enabled) {
  7021. // Darkmode in start() is only run on bandcamp domains
  7022. if (!darkModeInjected) {
  7023. darkModeMode().then(function (yes) {
  7024. if (yes) {
  7025. darkMode();
  7026. }
  7027. });
  7028. }
  7029. window.setTimeout(darkModeOnLoad, 0);
  7030. }
  7031. storeTralbumDataPermanentlySwitch = allFeatures.keepLibrary.enabled;
  7032. const maintenanceContent = document.querySelector('.content');
  7033. if (maintenanceContent && maintenanceContent.textContent.indexOf('are offline') !== -1) {
  7034. console.log('Maintenance detected');
  7035. } else {
  7036. if (NOEMOJI) {
  7037. addStyle('@font-face{font-family:Symbola;src:local("Symbola Regular"),local("Symbola"),url(https://cdnjs.cloudflare.com/ajax/libs/mathquill/0.10.1/font/Symbola.woff2) format("woff2"),url(https://cdnjs.cloudflare.com/ajax/libs/mathquill/0.10.1/font/Symbola.woff) format("woff"),url(https://cdnjs.cloudflare.com/ajax/libs/mathquill/0.10.1/font/Symbola.ttf) format("truetype"),url(https://cdnjs.cloudflare.com/ajax/libs/mathquill/0.10.1/font/Symbola.otf) format("opentype"),url(https://cdnjs.cloudflare.com/ajax/libs/mathquill/0.10.1/font/Symbola.svg#Symbola) format("svg")}' + '.sharepanelchecksymbol,.bdp_check_onlinkhover_symbol,.bdp_check_onchecked_symbol,.volumeSymbol,.downloaddisk,.downloadlink,#user-nav .menubar-symbol,.listened-symbol,.mark-listened-symbol,.minimizebutton{font-family:Symbola,Quivira,"Segoe UI Symbol","Segoe UI Emoji",Arial,sans-serif}' + '.downloaddisk,.downloadlink{font-weight: bolder}');
  7038. }
  7039. GM.getValue('notification_timeout', NOTIFICATION_TIMEOUT).then(function (ms) {
  7040. NOTIFICATION_TIMEOUT = parseInt(ms);
  7041. });
  7042. if (allFeatures.releaseReminder.enabled && !IS_PLAYER_FRAME) {
  7043. showPastReleases();
  7044. }
  7045. if (document.querySelector('#indexpage .indexpage_list_cell a[href*="/album/"] img')) {
  7046. // Index pages are almost like discography page. To make them compatible, let's add the class names from the discography page
  7047. document.querySelector('#indexpage').classList.add('music-grid');
  7048. document.querySelectorAll('#indexpage .indexpage_list_cell').forEach(cell => cell.classList.add('music-grid-item'));
  7049. addStyle('#indexpage .ipCellImage { position:relative }');
  7050. }
  7051. if (document.querySelector('.search .result-items .searchresult img')) {
  7052. // Search result pages. To make them compatible, let's add the class names from the discography page
  7053. document.querySelector('.search .result-items').classList.add('music-grid');
  7054. // Add class name to albums, tracks, labels and artists
  7055. document.querySelectorAll(`
  7056. .search .result-items .searchresult[data-search*='"type":"a"'],
  7057. .search .result-items .searchresult[data-search*='"type":"t"'],
  7058. .search .result-items .searchresult[data-search*='"type":"b"']
  7059. `).forEach(cell => cell.classList.add('music-grid-item'));
  7060. }
  7061. if (allFeatures.discographyplayer.enabled && document.querySelector('.music-grid .music-grid-item a[href*="/album/"] img,.music-grid .music-grid-item a[href*="/track/"] img')) {
  7062. // Discography page
  7063. makeAlbumCoversGreat();
  7064. }
  7065. if (document.querySelector('.inline_player')) {
  7066. // Album page with player
  7067. if (allFeatures.thetimehascome.enabled) {
  7068. removeTheTimeHasComeToOpenThyHeartWallet();
  7069. }
  7070. if (allFeatures.albumPageVolumeBar.enabled) {
  7071. window.setTimeout(addVolumeBarToAlbumPage, 3000);
  7072. }
  7073. if (allFeatures.albumPageDownloadLinks.enabled) {
  7074. window.setTimeout(addDownloadLinksToAlbumPage, 500);
  7075. }
  7076. if (allFeatures.albumPageLyrics.enabled) {
  7077. window.setTimeout(addLyricsToAlbumPage, 500);
  7078. }
  7079. if (allFeatures.discographyplayer.enabled) {
  7080. addOpenDiscographyPlayerFromAlbumPage();
  7081. }
  7082. }
  7083. if (document.location.pathname.startsWith('/tag/')) {
  7084. // Tag search page
  7085. if (allFeatures.tagSearchPlayer.enabled) {
  7086. makeTagSearchCoversGreat();
  7087. }
  7088. }
  7089. if (document.querySelector('.share-panel-wrapper-desktop')) {
  7090. // Album page with Share,Embed,Wishlist links
  7091.  
  7092. if (allFeatures.markasplayedEverywhere.enabled) {
  7093. addListenedButtonToCollectControls();
  7094. }
  7095. if (document.location.hash === '#collect-wishlist') {
  7096. clickAddToWishlist();
  7097. }
  7098. if (unsafeWindow.TralbumData && unsafeWindow.TralbumData.current && unsafeWindow.TralbumData.current.release_date) {
  7099. addReleaseDateButton();
  7100. }
  7101. }
  7102. if (unsafeWindow.TralbumData && unsafeWindow.TralbumData.tralbum_collect_info && unsafeWindow.TralbumData.tralbum_collect_info.is_purchased) {
  7103. showDownloadLinkOnAlbumPage();
  7104. }
  7105. GM.registerMenuCommand(SCRIPT_NAME + ' - Settings', mainMenu);
  7106. if (document.getElementById('user-nav')) {
  7107. appendMainMenuButtonTo(document.getElementById('user-nav'));
  7108. } else if (document.getElementById('customHeaderWrapper')) {
  7109. appendMainMenuButtonLeftTo(document.getElementById('customHeaderWrapper'));
  7110. } else if (document.querySelector('#corphome-autocomplete-form ul.hd-nav.corp-nav')) {
  7111. // Homepage and not logged in
  7112. appendMainMenuButtonTo(document.querySelector('#corphome-autocomplete-form ul.hd-nav.corp-nav'));
  7113. }
  7114. if (document.querySelector('.hd-banner-2018')) {
  7115. // Move the "we are hiring" banner (not loggin in)
  7116. document.querySelector('.hd-banner-2018').style.left = '-500px';
  7117. }
  7118. if (document.querySelector('.li-banner-2018')) {
  7119. // Remove the "we are hiring" banner (logged in)
  7120. document.querySelector('.li-banner-2018').remove();
  7121. }
  7122. if (document.getElementById('carousel-player') || document.querySelector('.play-carousel')) {
  7123. window.setTimeout(makeCarouselPlayerGreatAgain, 5000);
  7124. }
  7125. if (document.querySelector('ol#grid-tabs li') && document.querySelector('.fan-bio-pic-upload-container')) {
  7126. const listenedTabLink = makeListenedListTabLink();
  7127. if (document.location.hash === '#listened-tab') {
  7128. window.setTimeout(function resetGridTabs() {
  7129. document.querySelector('#grid-tabs .active').classList.remove('active');
  7130. document.querySelector('#grids .grid.active').classList.remove('active');
  7131. listenedTabLink.classList.add('active');
  7132. listenedTabLink.click();
  7133. }, 500);
  7134. }
  7135. }
  7136. if (allFeatures.albumPageVolumeBar.enabled) {
  7137. restoreVolume();
  7138. }
  7139. if (allFeatures.markasplayedEverywhere.enabled) {
  7140. makeAlbumLinksGreat();
  7141. }
  7142. if (allFeatures.backupReminder.enabled && !IS_PLAYER_FRAME) {
  7143. checkBackupStatus();
  7144. }
  7145. if (allFeatures.customReleaseDateFormat.enabled) {
  7146. formatReleaseDateOnAlbumPage();
  7147. }
  7148. if (allFeatures.showAlbumID.enabled) {
  7149. showAlbumID();
  7150. }
  7151. if (allFeatures.feedShowOnlyNewReleases.enabled && document.querySelector('#stories li.story')) {
  7152. feedShowOnlyNewReleases();
  7153. }
  7154. if (allFeatures.feedShowAudioControls.enabled && document.querySelector('#stories li.story')) {
  7155. feedShowAudioControls();
  7156. }
  7157. feedEnablePlayNextItem();
  7158. feedAddDiscographyPlayerButtons();
  7159. if (CAMPEXPLORER) {
  7160. let lastTagsText = document.querySelector('.tags') ? document.querySelector('.tags').textContent : '';
  7161. window.setInterval(function () {
  7162. const tagsText = document.querySelector('.tags') ? document.querySelector('.tags').textContent : '';
  7163. if (lastTagsText !== tagsText) {
  7164. lastTagsText = tagsText;
  7165. if (allFeatures.discographyplayer.enabled) {
  7166. makeAlbumCoversGreat();
  7167. }
  7168. if (allFeatures.markasplayedEverywhere.enabled) {
  7169. makeAlbumLinksGreat();
  7170. }
  7171. }
  7172. }, 3000);
  7173.  
  7174. // Add a little space at the bottom of the page to accommodate the discographyplayer at the bottom
  7175. document.body.style.paddingBottom = '200px';
  7176. // Move the sidebar to the left
  7177. document.querySelectorAll('.sidebar').forEach(function (div) {
  7178. div.style.alignSelf = 'flex-start';
  7179. div.querySelectorAll('.shortcuts').forEach(function (shortcuts) {
  7180. shortcuts.style.borderRadius = '0 1em 1em 0';
  7181. });
  7182. });
  7183. }
  7184. if (IS_PLAYER_URL) {
  7185. showExplorer();
  7186. } else if (document.location.pathname === LYRICS_EMPTY_PATH) {
  7187. initGenius();
  7188. }
  7189. GM.getValue('musicPlayerState', '{}').then(function restoreState(s) {
  7190. if (s !== '{}') {
  7191. GM.setValue('musicPlayerState', '{}');
  7192. musicPlayerRestoreState(JSON.parse(s));
  7193. }
  7194. });
  7195. if (document.querySelector('.inline_player') && unsafeWindow.TralbumData && unsafeWindow.TralbumData.current && unsafeWindow.TralbumData.trackinfo) {
  7196. const TralbumData = correctTralbumData(JSON.parse(JSON.stringify(unsafeWindow.TralbumData)), document.body.innerHTML);
  7197. storeTralbumDataPermanently(TralbumData);
  7198. }
  7199. }
  7200. }
  7201. start().then(function () {
  7202. if (document.readyState === 'loading') {
  7203. document.addEventListener('DOMContentLoaded', onLoaded);
  7204. } else {
  7205. onLoaded();
  7206. }
  7207. });
  7208.  
  7209. })(React, ReactDOM);