useSoundcloudPlayer.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import { ref, watch } from "vue";
  2. import { generateUuid } from "@common/utils/generateUuid";
  3. const soundcloudDomain = "https://w.soundcloud.com";
  4. export const useSoundcloudPlayer = () => {
  5. const uuid = generateUuid();
  6. const soundcloudIframeElement = ref();
  7. const widgetId = ref();
  8. const volume = ref();
  9. const readyCallback = ref();
  10. const attemptsToPlay = ref(0);
  11. const debouncePause = ref(null);
  12. const iframeUrl = ref("");
  13. const playAttemptTimeout = ref();
  14. const paused = ref(true);
  15. const currentTrackId = ref(null);
  16. const methodCallbacks = {};
  17. const eventListenerCallbacks = {};
  18. const stateChangeCallbacks = [];
  19. const debug = (...args) =>
  20. process.env.NODE_ENV === "development" &&
  21. console.debug("[USP]", uuid, widgetId.value, ...args);
  22. debug("Init start");
  23. if (!window.soundcloudIframeLockUuids)
  24. window.soundcloudIframeLockUuids = new Set();
  25. /*
  26. EVENTS:
  27. LOAD_PROGRESS: "loadProgress",
  28. PLAY_PROGRESS: "playProgress",
  29. PLAY: "play",
  30. PAUSE: "pause",
  31. FINISH: "finish",
  32. SEEK: "seek",
  33. READY: "ready",
  34. OPEN_SHARE_PANEL: "sharePanelOpened",
  35. CLICK_DOWNLOAD: "downloadClicked",
  36. CLICK_BUY: "buyClicked",
  37. ERROR: "error"
  38. METHODS:
  39. GET_VOLUME: "getVolume",
  40. GET_DURATION: "getDuration",
  41. GET_POSITION: "getPosition",
  42. GET_SOUNDS: "getSounds",
  43. GET_CURRENT_SOUND: "getCurrentSound",
  44. GET_CURRENT_SOUND_INDEX: "getCurrentSoundIndex",
  45. IS_PAUSED: "isPaused"
  46. PLAY: "play",
  47. PAUSE: "pause",
  48. TOGGLE: "toggle",
  49. SEEK_TO: "seekTo",
  50. SET_VOLUME: "setVolume",
  51. NEXT: "next",
  52. PREV: "prev",
  53. SKIP: "skip"
  54. REMOVE_LISTENER: "removeEventListener",
  55. ADD_LISTENER: "addEventListener"
  56. */
  57. const trackState = ref("NOT_PLAYING");
  58. const dispatchMessage = (method, value = null) => {
  59. const payload = {
  60. method,
  61. value
  62. };
  63. if (!soundcloudIframeElement.value) return;
  64. if (
  65. !soundcloudIframeElement.value.src ||
  66. !soundcloudIframeElement.value.src.startsWith(soundcloudDomain)
  67. )
  68. return;
  69. if (method !== "getPosition" && method !== "getDuration")
  70. debug("Dispatch message", method, value);
  71. soundcloudIframeElement.value.contentWindow.postMessage(
  72. JSON.stringify(payload),
  73. `${soundcloudDomain}/player`
  74. );
  75. };
  76. const onLoadListener = () => {};
  77. const onMessageListener = event => {
  78. if (event.origin !== soundcloudDomain) return;
  79. const data = JSON.parse(event.data);
  80. if (
  81. data.method !== "getPosition" &&
  82. data.method !== "getDuration" &&
  83. (data.method === "ready" || data.widgetId === widgetId.value)
  84. )
  85. debug("MESSAGE DATA", data);
  86. if (data.method === "ready") {
  87. if (window.soundcloudIframeLockUuid !== uuid) return;
  88. widgetId.value = data.widgetId;
  89. if (readyCallback.value) readyCallback.value();
  90. if (eventListenerCallbacks[data.method])
  91. eventListenerCallbacks[data.method].forEach(callback => {
  92. callback(data.value);
  93. });
  94. window.soundcloudIframeLockUuid = null;
  95. document.dispatchEvent(new Event("soundcloudUnlock"));
  96. return;
  97. }
  98. if (data.widgetId !== widgetId.value) return;
  99. if (methodCallbacks[data.method]) {
  100. methodCallbacks[data.method].forEach(callback => {
  101. callback(data.value);
  102. });
  103. methodCallbacks[data.method] = [];
  104. }
  105. if (eventListenerCallbacks[data.method]) {
  106. eventListenerCallbacks[data.method].forEach(callback => {
  107. callback(data.value);
  108. });
  109. }
  110. };
  111. const addMethodCallback = (type, cb) => {
  112. if (!methodCallbacks[type]) methodCallbacks[type] = [];
  113. methodCallbacks[type].push(cb);
  114. };
  115. const changeTrackState = newTrackState => {
  116. clearTimeout(debouncePause.value);
  117. const oldTrackState = trackState.value;
  118. trackState.value = newTrackState;
  119. if (newTrackState !== oldTrackState) {
  120. stateChangeCallbacks.forEach(cb => {
  121. cb(newTrackState);
  122. });
  123. }
  124. };
  125. const soundcloudGetIsPaused = callback => {
  126. let called = false;
  127. const _callback = value => {
  128. if (called) return;
  129. called = true;
  130. callback(value);
  131. };
  132. addMethodCallback("isPaused", _callback);
  133. dispatchMessage("isPaused");
  134. };
  135. const soundcloudGetCurrentSound = callback => {
  136. let called = false;
  137. const _callback = value => {
  138. if (called) return;
  139. called = true;
  140. callback(value);
  141. };
  142. addMethodCallback("getCurrentSound", _callback);
  143. dispatchMessage("getCurrentSound");
  144. };
  145. const attemptToPlay = () => {
  146. if (trackState.value === "playing") return;
  147. if (trackState.value !== "attempting_to_play") {
  148. attemptsToPlay.value = 0;
  149. changeTrackState("attempting_to_play");
  150. }
  151. attemptsToPlay.value += 1;
  152. dispatchMessage("play");
  153. setTimeout(() => {
  154. soundcloudGetIsPaused(value => {
  155. if (trackState.value !== "attempting_to_play") return;
  156. // Success
  157. if (!value) {
  158. changeTrackState("playing");
  159. return;
  160. }
  161. soundcloudGetCurrentSound(sound => {
  162. // Sound is not available to play
  163. if (
  164. value &&
  165. !paused.value &&
  166. typeof sound === "object" &&
  167. (!sound.playable ||
  168. !sound.public ||
  169. sound.policy === "BLOCK")
  170. ) {
  171. changeTrackState("sound_unavailable");
  172. attemptsToPlay.value = 0;
  173. return;
  174. }
  175. // Too many attempts, failed
  176. if (attemptsToPlay.value >= 10 && value && !paused.value) {
  177. changeTrackState("failed_to_play");
  178. attemptsToPlay.value = 0;
  179. return;
  180. }
  181. if (playAttemptTimeout.value)
  182. clearTimeout(playAttemptTimeout.value);
  183. playAttemptTimeout.value = setTimeout(() => {
  184. if (trackState.value === "attempting_to_play")
  185. attemptToPlay();
  186. }, 500);
  187. });
  188. });
  189. }, 500);
  190. };
  191. const changeIframeUrl = url => {
  192. iframeUrl.value = url;
  193. if (url && window.soundcloudIframeLockUuid !== uuid) {
  194. // Don't change the iframe src if the player hasn't initialized and isn't allowed to initialize yet
  195. if (url) window.soundcloudIframeLockUuids.add(uuid);
  196. if (!window.soundcloudIframeLockUuid)
  197. document.dispatchEvent(new Event("soundcloudUnlock"));
  198. return;
  199. }
  200. if (!url) widgetId.value = null;
  201. soundcloudIframeElement.value.setAttribute(
  202. "src",
  203. url ?? `${soundcloudDomain}/player`
  204. );
  205. };
  206. const documentUnlockEventListener = () => {
  207. if (
  208. !window.soundcloudIframeLockUuid &&
  209. window.soundcloudIframeLockUuids.size > 0 &&
  210. window.soundcloudIframeLockUuids.keys().next().value === uuid
  211. ) {
  212. window.soundcloudIframeLockUuid = uuid;
  213. window.soundcloudIframeLockUuids.delete(uuid);
  214. changeIframeUrl(iframeUrl.value);
  215. }
  216. };
  217. watch(soundcloudIframeElement, (newElement, oldElement) => {
  218. if (oldElement) {
  219. oldElement.removeEventListener("load", onLoadListener);
  220. window.removeEventListener("message", onMessageListener);
  221. if (window.soundcloudIframeLockUuid === uuid)
  222. window.soundcloudIframeLockUuid = null;
  223. window.soundcloudIframeLockUuids.delete(uuid);
  224. document.removeEventListener(
  225. "soundcloudUnlock",
  226. documentUnlockEventListener
  227. );
  228. }
  229. if (newElement) {
  230. newElement.addEventListener("load", onLoadListener);
  231. window.addEventListener("message", onMessageListener);
  232. document.removeEventListener(
  233. "soundcloudUnlock",
  234. documentUnlockEventListener
  235. );
  236. document.addEventListener(
  237. "soundcloudUnlock",
  238. documentUnlockEventListener
  239. );
  240. }
  241. if (!window.soundcloudIframeLockUuid)
  242. document.dispatchEvent(new Event("soundcloudUnlock"));
  243. });
  244. /* Exported functions */
  245. const soundcloudPlay = () => {
  246. paused.value = false;
  247. debug("Soundcloud play");
  248. if (trackState.value !== "attempting_to_play") attemptToPlay();
  249. };
  250. const soundcloudPause = () => {
  251. paused.value = true;
  252. debug("Soundcloud pause");
  253. if (playAttemptTimeout.value) clearTimeout(playAttemptTimeout.value);
  254. dispatchMessage("pause");
  255. };
  256. const soundcloudSetVolume = _volume => {
  257. volume.value = _volume;
  258. debug("Soundcloud set volume");
  259. dispatchMessage("setVolume", _volume);
  260. };
  261. const soundcloudSeekTo = time => {
  262. debug("SC SEEK TO", time);
  263. debug("Soundcloud seek to");
  264. dispatchMessage("seekTo", time);
  265. };
  266. const soundcloudGetPosition = callback => {
  267. let called = false;
  268. const _callback = value => {
  269. if (called) return;
  270. called = true;
  271. callback(value);
  272. };
  273. addMethodCallback("getPosition", _callback);
  274. dispatchMessage("getPosition");
  275. };
  276. const soundcloudGetDuration = callback => {
  277. let called = false;
  278. const _callback = value => {
  279. if (called) return;
  280. called = true;
  281. callback(value);
  282. };
  283. addMethodCallback("getDuration", _callback);
  284. dispatchMessage("getDuration");
  285. };
  286. const soundcloudGetState = () => trackState.value;
  287. const soundcloudGetTrackId = () => currentTrackId.value;
  288. const soundcloudGetTrackState = () => trackState.value;
  289. const soundcloudLoadTrack = (trackId, startTime, _paused) => {
  290. if (!soundcloudIframeElement.value) return;
  291. debug("Soundcloud load track");
  292. const url = `${soundcloudDomain}/player?autoplay=false&buying=false&sharing=false&download=false&show_artwork=false&show_playcount=false&show_user=false&url=${`https://api.soundcloud.com/tracks/${trackId}`}`;
  293. changeIframeUrl(url);
  294. paused.value = _paused;
  295. currentTrackId.value = trackId;
  296. if (playAttemptTimeout.value) clearTimeout(playAttemptTimeout.value);
  297. changeTrackState("not_started");
  298. readyCallback.value = () => {
  299. Object.keys(eventListenerCallbacks).forEach(event => {
  300. dispatchMessage("addEventListener", event);
  301. });
  302. dispatchMessage("setVolume", volume.value ?? 20);
  303. dispatchMessage("seekTo", (startTime ?? 0) * 1000);
  304. if (!_paused) attemptToPlay();
  305. };
  306. };
  307. const soundcloudBindListener = (name, callback) => {
  308. if (!eventListenerCallbacks[name]) {
  309. eventListenerCallbacks[name] = [];
  310. dispatchMessage("addEventListener", name);
  311. }
  312. eventListenerCallbacks[name].push(callback);
  313. };
  314. const soundcloudOnTrackStateChange = callback => {
  315. debug("On track state change listener added");
  316. stateChangeCallbacks.push(callback);
  317. };
  318. const soundcloudDestroy = () => {
  319. if (!soundcloudIframeElement.value) return;
  320. changeIframeUrl(null);
  321. currentTrackId.value = null;
  322. changeTrackState("none");
  323. };
  324. const soundcloudUnload = () => {
  325. window.removeEventListener("message", onMessageListener);
  326. };
  327. soundcloudBindListener("play", () => {
  328. debug("On play");
  329. if (trackState.value !== "attempting_to_play")
  330. changeTrackState("playing");
  331. });
  332. soundcloudBindListener("pause", eventValue => {
  333. debug("On pause", eventValue);
  334. const finishedPlaying = eventValue.relativePosition === 1;
  335. if (finishedPlaying) return;
  336. clearTimeout(debouncePause.value);
  337. debouncePause.value = setTimeout(() => {
  338. if (trackState.value !== "attempting_to_play")
  339. changeTrackState("paused");
  340. }, 500);
  341. });
  342. soundcloudBindListener("finish", () => {
  343. debug("On finish");
  344. changeTrackState("finished");
  345. });
  346. soundcloudBindListener("error", () => {
  347. debug("On error");
  348. changeTrackState("error");
  349. });
  350. debug("Init end");
  351. return {
  352. soundcloudIframeElement,
  353. soundcloudPlay,
  354. soundcloudPause,
  355. soundcloudSeekTo,
  356. soundcloudSetVolume,
  357. soundcloudLoadTrack,
  358. soundcloudGetPosition,
  359. soundcloudGetDuration,
  360. soundcloudGetIsPaused,
  361. soundcloudGetState,
  362. soundcloudGetTrackId,
  363. soundcloudGetCurrentSound,
  364. soundcloudGetTrackState,
  365. soundcloudBindListener,
  366. soundcloudOnTrackStateChange,
  367. soundcloudDestroy,
  368. soundcloudUnload
  369. };
  370. };