Bandcamp script (bandcamp.com only)

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

当前为 2023-01-06 提交的版本,查看 最新版本

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

QingJ © 2025

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