Bandcamp script (bandcamp.com only)

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

当前为 2021-03-17 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址