HTML5 thingie for Spotify Web Player

Play music in the browser without having to install Flash Player. Yes, I know why SWF bridges exist.

目前為 2016-01-29 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name HTML5 thingie for Spotify Web Player
  3. // @description Play music in the browser without having to install Flash Player. Yes, I know why SWF bridges exist.
  4. // @author Swyter
  5. // @namespace https://greasyfork.org/users/4813-swyter
  6. // @match https://play.spotify.com/*
  7. // @version 2016.01.29
  8. // @noframes
  9. // @icon https://i.imgur.com/LHkCkka.png
  10. // @grant none
  11. // @run-at document-start
  12. // ==/UserScript==
  13.  
  14. /* it's random, trust me, I'm Sony! */
  15. Object.defineProperty(window.Math, 'random',
  16. {
  17. configurable: false,
  18. writable: false,
  19. value: function(a) { return 0.1337; }
  20. });
  21.  
  22. /* SWFobject.js faker, sneaky! */
  23. Object.defineProperty(window, 'swfobject',
  24. {
  25. configurable: false,
  26. writable: false,
  27. value:
  28. {
  29. getFlashPlayerVersion: function(){ console.log("-<-< getFlashPlayerVersion =>", arguments); return { major: 11, minor: 2, release: 202 }; },
  30. hasFlashPlayerVersion: function(){ console.log("-<-< hasFlashPlayerVersion =>", arguments); return true; },
  31. embedSWF: function(swf, parent_id, unk_a, unk_b, req_flash_ver, unk_c, properties)
  32. {
  33. console.log("-<-< embedSWF =>", arguments, arguments[9].toString(), this, properties);
  34.  
  35. /* create our audio player in substitution of the swf abobination */
  36. var dummy = document.createElement("audio");
  37.  
  38. dummy.id = properties.id;
  39. dummy["instanceid"] = properties.instanceId;
  40.  
  41. dummy.loop = false;
  42. dummy.preload = 'auto';
  43. dummy.autoplay = false;
  44. dummy.volume = 1.0;
  45.  
  46. dummy.sp_run = function(proof) { console.log("-<-< sp_run =>", arguments); return unsafeWindow.proof; };
  47. dummy.sp_hasSound = function() { return true };
  48. dummy.sp_load = function(player_id, raw_uri, options)
  49. {
  50. /* for some reason we have to massage the url format to remove the 'mp3:' protocol
  51. prefix from the uri, and the '/cfx/st' from the server string */
  52. // uri : "mp3:/mp3/6b381db769d31beb544ba67eb7cbc3ce4fc8ab4c.mp3?Expires=1450045402&Signature=dgvyYa~K2P-v6ArrdVBmRxAF44JTJhpk6PJqQXzHbMOmtcHw~eY~E1C0GgviL~O63-EhejMzCB~dLjlgaug-TQej8mCjvroY8crd776GRsBx0AJz4pnp3ZH03T3PnUecBHRwMrg28pjAbi1xWmuybyNvwWpitB9Q~hiCKxMzUhnXRjqpWJKZVrLDY7~iXB2GlptZNz8RZoapexeEkNA2kgjnYXk4JTe4CNTdRSmn~Uf9YHvxJdA4ttlRfDt353eSxCDTXKQdA7GkEBTKJfDvN6NgXyw8~Tm8tBHk9VYYn7jZMLYckwqi3OJAonof2SZZlHZoepgympEYxK8BdkvZMg__&Key-Pair-Id=APKAJXKSII4ED2EOGZZA"
  53. // options.server: "http://dsu0uct5x2puz.cloudfront.net/cfx/st"
  54.  
  55. var uri = options.server.match(/(.+\/\/[^\/]+?)\//)[1] + raw_uri.split(":")[1];
  56.  
  57. console.log("sp_load =>", uri, arguments, this);
  58. this.src = uri;
  59.  
  60. if (options.startFrom !== 0)
  61. this.currentTime = Math.floor(0.001 * options.startFrom);
  62.  
  63. if (options.autoplay)
  64. this.play();
  65.  
  66. console.log(this.paused)
  67.  
  68. unsafeWindow.Spotify.Instances.get(this.instanceid).audioManager.getPlayerById(player_id).trigger('LOAD', {}, {id: player_id});
  69. };
  70.  
  71. /* dummy functions after __noSuchMethod__ was deprecated in Firefox 44 */
  72. dummy.sp_initializePlayerById = function(player_id) { console.log("=> sp_initializePlayerById", arguments); };
  73. dummy.sp_stop = function(player_id) { console.log("=> sp_stop", arguments); };
  74.  
  75. /* actual reimplementations of functions that embody the internal SWF interface */
  76. dummy.sp_setVolume = function(player_id, vol) { console.log("=> volume", arguments); if (player_id == "main:A" && vol !== 0) this.volume = vol };
  77. dummy.sp_getVolume = function(player_id, vol) { console.log("=> golume", arguments); if (player_id == "main:A" && vol !== 0) return parseFloat(this.volume); else return 0 };
  78. dummy.sp_seek = function(player_id, pos) { console.log("=> seek", arguments); this.currentTime = Math.floor(0.001 * pos) };
  79. dummy.sp_pause = function(player_id) { console.log("=> pause", arguments); this.pause() };
  80. dummy.sp_resume = function(player_id) { console.log("=> pause", arguments); this.play() };
  81.  
  82. dummy.sp_playerState = function(player_id)
  83. {
  84. return {
  85. volume: this.volume,
  86. position: Math.floor(1000 * this.currentTime),
  87. duration: Math.floor(1000 * this.duration),
  88. isPlaying: !this.paused,
  89. isStopped: false,
  90. isPaused: this.paused
  91. };
  92. };
  93.  
  94. dummy.sp_addPlayer = function(player_index, player_id, player_protocol)
  95. {
  96. if (player_id != "main:A")
  97. return;
  98.  
  99. var sp_html5_event_listeners =
  100. {
  101. canplay: 'LOAD',
  102. playing: 'PLAYING',
  103. pause: 'PAUSED',
  104. ended: 'TRACK_ENDED',
  105. durationchange: 'DURATION',
  106. progress: 'PROGRESS',
  107. error: 'PLAYBACK_FAILED'
  108. };
  109.  
  110. function sp_html5_generic_callback(e)
  111. {
  112. console.log("sp html5 audio «" + e.type + "» event", e, sp_html5_event_listeners[e.type]);
  113.  
  114. var ret;
  115.  
  116. switch(sp_html5_event_listeners[e.type])
  117. {
  118. case 'DURATION':
  119. ret = {duration: Math.floor(1000 * this.duration)};
  120. break;
  121.  
  122. case 'PROGRESS':
  123. ret = {position: Math.floor(1000 * this.currentTime)};
  124. break;
  125.  
  126. default:
  127. ret = {};
  128. }
  129.  
  130. unsafeWindow.Spotify.Instances.get(this.instanceid).audioManager.getPlayerById(player_id).trigger(sp_html5_event_listeners[e.type], ret, {id: player_id});
  131. }
  132.  
  133. for (var i_event in sp_html5_event_listeners)
  134. this.addEventListener(i_event, sp_html5_generic_callback);
  135.  
  136. return true;
  137. };
  138.  
  139. dummy.__noSuchMethod__ = function(name, params) { console.log('==>>== > invalid function call', name, params); };
  140.  
  141. /* necessary for the spotify framework to find it in the right place */
  142. window.document[properties.id] = dummy;
  143.  
  144. /* insert our dummy audio player in the requested element */
  145. document.getElementById(parent_id).appendChild(dummy);
  146.  
  147. /* tell the spotify framework that the swf embed is ready */
  148. arguments[9].apply(this, [{success: true}]);
  149.  
  150. // act as the swf bridge and tell it that the Flash-backend is ready
  151. // JSInterface.notify(ApplicationEvents.READY,null,1);
  152. //Spotify.Instances.get(properties.instanceId).audioManager.getInterface()._triggerDeferred('FLASH_AVAILABLE', null);
  153. Spotify.Instances.get(properties.instanceId).audioManager.getInterface()._triggerDeferred('READY', null);
  154.  
  155. console.log("AUDIOMANAGER-INTERFACE", properties.id, window.document[properties.id], Spotify.Instances.get(properties.instanceId).audioManager.getInterface(),
  156. Spotify.Instances.get(properties.instanceId).audioManager.getInterface().hasSound());
  157. }
  158. }
  159. });
  160.  
  161.  
  162. function when_external_loaded()
  163. {
  164. // ---
  165.  
  166.  
  167. function get_pong(ping)
  168. {
  169. // http://crossorigin.me/http://ping-pong.spotify.nodestuff.net/64-104-120-204-164-75-214-221-224-109-28-127-73-236-239-150-88-238-177-90
  170.  
  171. console.log("ping-pong", ping);
  172.  
  173. var xhr = new XMLHttpRequest();
  174. xhr.open("GET", "https://crossorigin.me/http://ping-pong.spotify.nodestuff.net/" + ping.replace(/ /g,"-"), true);
  175. xhr.responseType = "json";
  176.  
  177. xhr.onloadend = function()
  178. {
  179. if (xhr.readyState != xhr.DONE)
  180. return;
  181.  
  182. console.log("pong", xhr);
  183. window.proof = xhr.response.pong.replace(/-/g," ");
  184.  
  185. if (!sp_ws)
  186. return;
  187.  
  188. sp_ws.send(`{"id":` + (window.proof_id || 2) + `,"name":"sp/pong_flash2","args":["` + window.proof + `"]}`);
  189. //sp_ws.send(`{"id":2,"name":"sp/work_done","args":["undefined"]}`);
  190.  
  191. }
  192.  
  193. xhr.send();
  194. }
  195.  
  196. /* wait until the page is ready for the code snippet to run */
  197. document.addEventListener('DOMContentLoaded', function()
  198. {
  199. console.log("!!! DOMContentLoaded");
  200.  
  201. WebSocket.prototype.sond = WebSocket.prototype.send;
  202. WebSocket.prototype.send = function(msg)
  203. {
  204. window.sp_ws = this;
  205.  
  206. if (this.onmessage && this.sucks !== true)
  207. {
  208. callback = this.onmessage;
  209.  
  210. console.log("orig prev callback:", callback);
  211.  
  212. this.onmessage = function(message)
  213. {
  214. var json_msg = JSON.parse(message.data);
  215.  
  216. if (json_msg && json_msg.message && json_msg.message[0] == 'ping_flash2' && json_msg.message[1])
  217. {
  218. console.log("getting preventive pong", json_msg);
  219. get_pong(json_msg.message[1]);
  220. }
  221.  
  222. //if (json_msg.id === window.last_track_msg)
  223. console.info("<- ws recv: ", window.last_track_msg, message.data);
  224.  
  225. //if (json_msg && json_msg.result && json_msg.result.uri)
  226. //open(json_msg.result.uri);
  227.  
  228. callback(message);
  229. }
  230.  
  231. this.sucks = true;
  232. }
  233.  
  234. var json_msg = JSON.parse(msg);
  235.  
  236. // block the flash pong reply until we have the correct reply for the challenge
  237. if (typeof window.proof !== "string" && json_msg && (json_msg.name == 'sp/pong_flash2')) // || json_msg.name == 'sp/work_done'))
  238. {
  239. console.info("-> blocking sent message until we have challenge: ", json_msg.id, msg);
  240.  
  241. window.proof_id = json_msg.id;
  242.  
  243. return;
  244. }
  245.  
  246. // get the http link instead or rtmp, thankies!
  247. if (json_msg && json_msg.name == 'sp/track_uri')
  248. {
  249. arguments[0] = msg.replace(',"rtmp"', '');
  250. window.last_track_msg = json_msg.id;
  251. console.info("-> ws send: ", json_msg.id, msg);
  252. }
  253. //dec_msg = json_msg.name === 'sp/hm_b64' ? atob(json_msg.args[0]) : null;
  254.  
  255. console.info("-> ws send: ", msg); //json_msg, dec_msg);
  256.  
  257. //if (json_msg.name !== 'sp/log')
  258. return WebSocket.prototype.sond.apply(this, arguments);
  259. }
  260.  
  261. });
  262.  
  263. // ---
  264. }
  265.  
  266. /* inject this cleaning function right in the page to avoid silly sandbox-related greasemonkey limitations */
  267. window.document.head.appendChild(
  268. inject_fn = document.createElement("script")
  269. );
  270.  
  271. inject_fn.innerHTML = '(' + when_external_loaded.toString() + ')()';
  272.