Plex External Player

Play plex videos in an external player

目前為 2016-04-09 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Plex External Player
  3. // @namespace https://github.com/Kayomani/PlexExternalPlayer
  4. // @version 1.6
  5. // @description Play plex videos in an external player
  6. // @author Kayomani
  7. // @include /^https?://.*:32400/web.*
  8. // @include http://*:32400/web/index.html*
  9. // @require http://code.jquery.com/jquery-1.11.3.min.js
  10. // @connect *
  11. // @require https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js
  12. // @grant GM_xmlhttpRequest
  13. // ==/UserScript==
  14.  
  15. $("head").append (
  16. '<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet" type="text/css">'
  17. );
  18.  
  19.  
  20. toastr.options = {
  21. "closeButton": true,
  22. "debug": false,
  23. "newestOnTop": true,
  24. "progressBar": true,
  25. "positionClass": "toast-bottom-right",
  26. "preventDuplicates": false,
  27. "onclick": null,
  28. "showDuration": "300",
  29. "hideDuration": "1000",
  30. "timeOut": "5000",
  31. "extendedTimeOut": "1000",
  32. "showEasing": "swing",
  33. "hideEasing": "linear",
  34. "showMethod": "fadeIn",
  35. "hideMethod": "fadeOut"
  36. };
  37.  
  38. var showToast = function(msg, error){
  39. var title = 'Plex External Player';
  40. if(error){
  41. toastr.error(msg, title, {timeOut: 10000});
  42. logMessage(msg);
  43. }
  44. else
  45. {
  46. toastr.success(msg, title);
  47. }
  48. };
  49.  
  50. var logMessage = function(msg){
  51. console.log('Plex External: ' + msg);
  52. };
  53.  
  54. var makeRequest = function(url){
  55. return new Promise( function (resolve, reject) {
  56. GM_xmlhttpRequest({
  57. method: "GET",
  58. headers: {
  59. "X-Plex-Token":localStorage["myPlexAccessToken"]
  60. },
  61. url: url,
  62. onload: resolve,
  63. onreadystatechange: function(state) {
  64. if (state.readyState === 4) {
  65. if (state.status !== 200) {
  66. showToast('Error calling: ' + url + '. Response: ' + error.responseText + ' Code:' + error.status + ' Message: ' + error.statusText, 1);
  67. }
  68. }
  69. },
  70. onerror: reject
  71. });
  72. });
  73. };
  74.  
  75.  
  76.  
  77. var markAsPlayedInPlex = function(id) {
  78. logMessage('Marking ' + id + ' as played');
  79. return makeRequest(window.location.origin + '/:/scrobble?key='+ id +'&identifier=com.plexapp.plugins.library').catch(function(){
  80. showToast('Failed to mark item ' + id + ' as played');
  81. });
  82. };
  83.  
  84. var openItemOnAgent = function(path, id, openFolder) {
  85. if(openFolder){
  86. var fwd = path.lastIndexOf('/');
  87. var bck = path.lastIndexOf('\\');
  88. var best = fwd>bck?fwd:bck;
  89. if(best>-1){
  90. path = path.substr(0, best);
  91. }
  92. }
  93. showToast('Playing ' + path, 0);
  94. logMessage('Playing ' + path);
  95. // umicrosharp doesn't handle plus properly
  96. path = path.replace(/\+/g, '[PLEXEXTPLUS]');
  97. var url = 'http://localhost:7251/?protocol=2&item=' + encodeURIComponent(path);
  98. return new Promise(function (resolve, reject) {
  99. makeRequest(url).then(function(){
  100. markAsPlayedInPlex(id).then(resolve, reject);
  101. },reject);
  102. });
  103. };
  104.  
  105. var clickListener = function(e) {
  106. e.preventDefault();
  107. e.stopPropagation();
  108. var a = jQuery(e.target).closest('a');
  109. var link = a.attr('href');
  110. var openFolder = a.attr('data-type') === 'folder';
  111. var url = link;
  112. if (link === '#' || link === undefined) {
  113. url = window.location.hash;
  114. }
  115.  
  116. if (url.indexOf('%2Fmetadata%2F') > -1) {
  117. var idx = url.indexOf('%2Fmetadata%2F');
  118. var id = url.substr(idx + 14);
  119.  
  120. // Get metadata
  121. var metaDataPath = window.location.origin + '/library/metadata/' + id + '?checkFiles=1&includeExtras=1';
  122. makeRequest(metaDataPath)
  123. .then(function(response){
  124. // Play the first availible part
  125. var parts = response.responseXML.getElementsByTagName('Part');
  126. for (var i = 0; i < parts.length; i++) {
  127. if (parts[i].attributes['file'] !== undefined) {
  128. openItemOnAgent(parts[i].attributes['file'].value, id, openFolder).catch(function(){
  129. showToast('Failed to connect to agent, is it running or firewalled?',1);
  130. });
  131. return;
  132. }
  133. }
  134.  
  135. if (parts.length === 0) {
  136. // If we got a directory/Season back then get the files in it
  137. var dirs = response.responseXML.getElementsByTagName('Directory');
  138. if (dirs.length > 0) {
  139. makeRequest(window.location.origin + dirs[0].attributes['key'].value)
  140. .then(function(response){
  141. var videos = response.responseXML.getElementsByTagName('Video');
  142. var file = null;
  143. var id = null;
  144. if(videos.length === 0)
  145. {
  146. showToast('Could not determine which video to play as there are multiple seasons.',true);
  147. return;
  148. }
  149. for (var i = 0; i < videos.length; i++) {
  150. var vparts = videos[i].getElementsByTagName('Part');
  151. if (vparts.length > 0) {
  152. file = vparts[0].attributes['file'].value;
  153. id = vparts[0].attributes['id'].value;
  154. if (videos[i].attributes['lastViewedAt'] === null || videos[i].attributes['lastViewedAt'] === undefined) {
  155. break;
  156. }
  157. }
  158. }
  159.  
  160. if (file !== null)
  161. {
  162. openItemOnAgent(file, id, openFolder).catch(function(){
  163. showToast('Failed to connect to agent, is it running or firewalled?',1);
  164. });
  165. }
  166. }).catch(function(){
  167. showToast('Failed to get information for directory',1);
  168. });
  169. }
  170. }
  171. }, function(error){
  172. showToast('Error getting metadata from' + metaDataPath, 1);
  173. });
  174. }
  175. };
  176.  
  177. var bindClicks = function() {
  178. jQuery(".glyphicon.play").each(function(i, e) {
  179. e = jQuery(e);
  180. if (!e.hasClass('plexextplayer')) {
  181. if (!e.parent().hasClass('hidden')) {
  182. e.addClass('plexextplayer');
  183. var parent = e.parent().parent();
  184. if (parent.is('li')) {
  185. var template = jQuery('<li><a class="btn-gray" href="javascript:void(0)" title="Play Externally" data-toggle="Play Externally" data-original-title="Play Externally"><i class="glyphicon play plexextplayer plexextplayerico"></i></a></li><li><a class="btn-gray" href="#" title="Open containing folder" data-type="folder" data-toggle="Play Externally" data-original-title="Open containing folder"><i class="glyphicon play plexextplayer plexfolderextplayerico"></i></a></li>');
  186. parent.after(template);
  187. template.click(clickListener);
  188. } else if (parent.is('div') && parent.hasClass('media-poster-actions')) {
  189. var template = jQuery('<button class="play-btn media-poster-btn btn-link" tabindex="-1"><i class="glyphicon play plexextplayer plexextplayerico"></i></button>');
  190. parent.prepend(template);
  191. template.click(clickListener);
  192. }
  193. }
  194. }
  195. });
  196. // React cover page
  197. jQuery(".plex-icon-more-560").each(function(i, e) {
  198. e = jQuery(e);
  199. var poster = e.parent().parent();
  200. if(poster.length === 1 && poster[0].className.startsWith('MetadataPosterCardOverlay'))
  201. {
  202. var existingButton = poster.find('.plexextplayerico');
  203. if(existingButton.length === 0)
  204. {
  205. var url = poster.find('a').attr('href');
  206. var template = jQuery('<a href="'+ url +'" aria-haspopup="false" aria-role="button" class="" type="button"><i class="glyphicon play plexextplayer plexextplayerico plexextplayericocover"></i></button>');
  207. var newButton = template.appendTo(poster);
  208. newButton.click(clickListener);
  209. poster.mouseenter(function(){
  210. newButton.find('i').css('display','block');
  211. });
  212. poster.mouseleave(function(){
  213. newButton.find('i').css('display','none');
  214. });
  215. }
  216. }
  217. });
  218. };
  219.  
  220. // Make buttons smaller
  221. jQuery('body').append('<style>.plexextplayericocover {right: 10px; top: 10px; position:absolute; display:none;font-size:15px;} .glyphicon.plexfolderextplayerico:before { content: "\\e343"; } .glyphicon.plexextplayerico:before { content: "\\e161"; }</style>');
  222.  
  223. // Bind buttons and check for new ones every 100ms
  224. setInterval(bindClicks, 100);
  225. bindClicks();