Greasy Fork is available in English.

Bandcamp script (Deluxe Edition)

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

ของเมื่อวันที่ 30-12-2022 ดู เวอร์ชันล่าสุด

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