HTML5 thingie for Spotify Web Player

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

目前为 2015-12-18 提交的版本。查看 最新版本

  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 2015.12.17
  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. dummy.id = properties.id;
  38. dummy["instanceid"] = properties.instanceId;
  39. dummy.loop = false;
  40. dummy.preload = 'auto';
  41. dummy.autoplay = false;
  42. dummy.volume = 1.0;
  43. dummy.sp_run = function(proof) { console.log("-<-< sp_run =>", arguments); return unsafeWindow.proof; };
  44. dummy.sp_hasSound = function() { return true };
  45. dummy.sp_load = function(player_id, raw_uri, options)
  46. {
  47. /* for some reason we have to massage the url format to remove the 'mp3:' protocol
  48. prefix from the uri, and the '/cfx/st' from the server string */
  49. // 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"
  50. // options.server: "http://dsu0uct5x2puz.cloudfront.net/cfx/st"
  51.  
  52. var uri = options.server.match(/(.+\/\/[^\/]+?)\//)[1] + raw_uri.split(":")[1];
  53. console.log("sp_load =>", uri, arguments, this);
  54. this.src = uri;
  55.  
  56. if (options.startFrom !== 0)
  57. this.currentTime = Math.floor(0.001 * options.startFrom);
  58.  
  59. if (options.autoplay)
  60. this.play();
  61. console.log(this.paused)
  62.  
  63. unsafeWindow.Spotify.Instances.get(this.instanceid).audioManager.getPlayerById(player_id).trigger('LOAD', {}, {id: player_id});
  64. };
  65. dummy.sp_setVolume = function(player_id, vol) { console.log("=> volume", arguments); if (player_id == "main:A" && vol !== 0) this.volume = vol };
  66. 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 };
  67. dummy.sp_seek = function(player_id, pos) { console.log("=> seek", arguments); this.currentTime = Math.floor(0.001 * pos) };
  68. dummy.sp_pause = function(player_id) { console.log("=> pause", arguments); this.pause() };
  69. dummy.sp_resume = function(player_id) { console.log("=> pause", arguments); this.play() };
  70. dummy.sp_playerState = function(player_id)
  71. {
  72. return {
  73. volume: this.volume,
  74. position: Math.floor(1000 * this.currentTime),
  75. duration: Math.floor(1000 * this.duration),
  76. isPlaying: !this.paused,
  77. isStopped: false,
  78. isPaused: this.paused
  79. };
  80. };
  81. dummy.sp_addPlayer = function(player_index, player_id, player_protocol)
  82. {
  83. if (player_id != "main:A")
  84. return;
  85. var sp_html5_event_listeners =
  86. {
  87. canplay: 'LOAD',
  88. playing: 'PLAYING',
  89. pause: 'PAUSED',
  90. ended: 'TRACK_ENDED',
  91. durationchange: 'DURATION',
  92. progress: 'PROGRESS',
  93. error: 'PLAYBACK_FAILED'
  94. };
  95.  
  96. function sp_html5_generic_callback(e)
  97. {
  98. console.log("sp html5 audio «" + e.type + "» event", e, sp_html5_event_listeners[e.type]);
  99. var ret;
  100. switch(sp_html5_event_listeners[e.type])
  101. {
  102. case 'DURATION':
  103. ret = {duration: Math.floor(1000 * this.duration)};
  104. break;
  105. case 'PROGRESS':
  106. ret = {position: Math.floor(1000 * this.currentTime)};
  107. break;
  108.  
  109. default:
  110. ret = {};
  111. }
  112.  
  113. unsafeWindow.Spotify.Instances.get(this.instanceid).audioManager.getPlayerById(player_id).trigger(sp_html5_event_listeners[e.type], ret, {id: player_id});
  114. }
  115.  
  116. for (var i_event in sp_html5_event_listeners)
  117. this.addEventListener(i_event, sp_html5_generic_callback);
  118.  
  119. return true;
  120. };
  121. dummy.__noSuchMethod__ = function(name, params) { console.log('==>>== > invalid function call', name, params); };
  122.  
  123. /* necessary for the spotify framework to find it in the right place */
  124. window.document[properties.id] = dummy;
  125.  
  126. /* insert our dummy audio player in the requested element */
  127. document.getElementById(parent_id).appendChild(dummy);
  128.  
  129. /* tell the spotify framework that the swf embed is ready */
  130. arguments[9].apply(this, [{success: true}]);
  131. // act as the swf bridge and tell it that the Flash-backend is ready
  132. // JSInterface.notify(ApplicationEvents.READY,null,1);
  133. //Spotify.Instances.get(properties.instanceId).audioManager.getInterface()._triggerDeferred('FLASH_AVAILABLE', null);
  134. Spotify.Instances.get(properties.instanceId).audioManager.getInterface()._triggerDeferred('READY', null);
  135. console.log("AUDIOMANAGER-INTERFACE", properties.id, window.document[properties.id], Spotify.Instances.get(properties.instanceId).audioManager.getInterface(),
  136. Spotify.Instances.get(properties.instanceId).audioManager.getInterface().hasSound());
  137. }
  138. }
  139. });
  140.  
  141.  
  142. function when_external_loaded()
  143. {
  144. // ---
  145.  
  146. function get_pong(ping)
  147. {
  148. // 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
  149.  
  150. console.log("ping-pong", ping);
  151.  
  152. var xhr = new XMLHttpRequest();
  153. xhr.open("GET", "https://crossorigin.me/http://ping-pong.spotify.nodestuff.net/" + ping.replace(/ /g,"-"), true);
  154. xhr.responseType = "json";
  155.  
  156. xhr.onloadend = function()
  157. {
  158. if (xhr.readyState != xhr.DONE)
  159. return;
  160.  
  161. console.log("pong", xhr);
  162. window.proof = xhr.response.pong.replace(/-/g," ");
  163. if (!sp_ws)
  164. return;
  165. sp_ws.send(`{"id":1,"name":"sp/pong_flash2","args":["` + window.proof + `"]}`);
  166. sp_ws.send(`{"id":2,"name":"sp/work_done","args":["undefined"]}`);
  167. }
  168.  
  169. xhr.send();
  170. }
  171. /* wait until the page is ready for the code snippet to run */
  172. document.addEventListener('DOMContentLoaded', function()
  173. {
  174. console.log("!!! DOMContentLoaded");
  175.  
  176. WebSocket.prototype.sond = WebSocket.prototype.send;
  177. WebSocket.prototype.send = function(msg)
  178. {
  179. window.sp_ws = this;
  180.  
  181. if (this.onmessage && this.sucks !== true)
  182. {
  183. callback = this.onmessage;
  184. console.log("orig prev callback:", callback);
  185.  
  186. this.onmessage = function(message)
  187. {
  188. var json_msg = JSON.parse(message.data);
  189.  
  190. if (json_msg && json_msg.message && json_msg.message[0] == 'ping_flash2' && json_msg.message[1])
  191. {
  192. console.log("getting preventive pong", json_msg);
  193. get_pong(json_msg.message[1]);
  194. }
  195.  
  196. if (json_msg.id === window.last_track_msg)
  197. console.info("<- ws recv: ", window.last_track_msg, message.data);
  198. //if (json_msg && json_msg.result && json_msg.result.uri)
  199. //open(json_msg.result.uri);
  200. callback(message);
  201. }
  202. this.sucks = true;
  203. }
  204.  
  205. var json_msg = JSON.parse(msg);
  206. // block the flash pong reply until we have the correct reply for the challenge
  207. if (typeof window.proof !== "string" && json_msg && (json_msg.name == 'sp/pong_flash2' || json_msg.name == 'sp/work_done'))
  208. {
  209. console.info("-> blocking sent message until we have challenge: ", json_msg.id, msg);
  210. return;
  211. }
  212.  
  213. // get the http link instead or rtmp, thankies!
  214. if (json_msg && json_msg.name == 'sp/track_uri')
  215. {
  216. arguments[0] = msg.replace(',"rtmp"', '');
  217. window.last_track_msg = json_msg.id;
  218. console.info("-> ws send: ", json_msg.id, msg);
  219. }
  220. //dec_msg = json_msg.name === 'sp/hm_b64' ? atob(json_msg.args[0]) : null;
  221. console.info("-> ws send: ", msg); //json_msg, dec_msg);
  222. //if (json_msg.name !== 'sp/log')
  223. return WebSocket.prototype.sond.apply(this, arguments);
  224. }
  225. });
  226. // ---
  227. }
  228.  
  229. /* inject this cleaning function right in the page to avoid silly sandbox-related greasemonkey limitations */
  230. window.document.head.appendChild(
  231. inject_fn = document.createElement("script")
  232. );
  233.  
  234. inject_fn.innerHTML = '(' + when_external_loaded.toString() + ')()';