embyToLocalPlayer

需要 Python。Emby/Jellyfin 调用外部本地播放器,并回传播放记录。适配 Plex。

目前为 2024-01-04 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name embyToLocalPlayer
  3. // @name:zh-CN embyToLocalPlayer
  4. // @name:en embyToLocalPlayer
  5. // @namespace https://github.com/kjtsune/embyToLocalPlayer
  6. // @version 1.1.13.1
  7. // @description 需要 Python。Emby/Jellyfin 调用外部本地播放器,并回传播放记录。适配 Plex。
  8. // @description:zh-CN 需要 Python。Emby/Jellyfin 调用外部本地播放器,并回传播放记录。适配 Plex。
  9. // @description:en Require Python. Play in an external player. Update watch history to Emby/Jellyfin server. Support Plex.
  10. // @author Kjtsune
  11. // @match *://*/web/index.html*
  12. // @match *://*/*/web/index.html*
  13. // @icon https://www.google.com/s2/favicons?sz=64&domain=emby.media
  14. // @grant unsafeWindow
  15. // @grant GM_xmlhttpRequest
  16. // @grant GM_registerMenuCommand
  17. // @grant GM_unregisterMenuCommand
  18. // @run-at document-start
  19. // @connect 127.0.0.1
  20. // @license MIT
  21. // ==/UserScript==
  22. 'use strict';
  23. /*
  24. 2024-1-2:
  25. 1. 适配 Emby 跳过简介/片头。(限 mpv,且视频本身无章节,通过添加章节实现。)
  26. * 版本间累积更新:
  27. * mpv script-opts 被覆盖。@verygoodlee
  28. * mpv 切回第一集时网络外挂字幕丢失。@verygoodlee
  29. 2023-12-11:
  30. 1. 美化 mpv pot 标题。
  31. 2. 改善版本筛选逻辑。
  32. 2023-12-07:
  33. 1. mpv 播放列表避免与官方 autoload.lua 冲突。
  34. 2. pot 修复读盘模式播放列表漏播第零季选集。(详见 FAQ 隐藏功能)
  35. * 版本间累积更新:
  36. * 追更 TG 通知。(详见 FAQ 隐藏功能)
  37. * 适配 Emby beta 版本 api 变动。
  38. * bgm.tv: 适配上游搜索结果变动。
  39. * bgm.tv: 增加旧版搜索 api 备选。
  40. * trakt: 适配上游新剧缺失单集 imdb/tvdb。
  41. * .bat 强制使用 utf-8 编码。
  42. * 默认启用日志文件。
  43. * pot 播放列表 未加载完成时可退出。
  44. * 网络流:外挂 sup 支持(限 Emby v4.8.0.55 | mpv)。升级 Emby 记得备份,无法回退。
  45. */
  46. (function () {
  47. 'use strict';
  48.  
  49. let fistTime = true;
  50. let config = {
  51. logLevel: 2,
  52. disableOpenFolder: false, // false 改为 true 则禁用打开文件夹的按钮。
  53. };
  54.  
  55. let logger = {
  56. error: function (...args) {
  57. if (config.logLevel >= 1) {
  58. console.log('%cerror', 'color: yellow; font-style: italic; background-color: blue;', ...args);
  59. }
  60. },
  61. info: function (...args) {
  62. if (config.logLevel >= 2) {
  63. console.log('%cinfo', 'color: yellow; font-style: italic; background-color: blue;', ...args);
  64. }
  65. },
  66. debug: function (...args) {
  67. if (config.logLevel >= 3) {
  68. console.log('%cdebug', 'color: yellow; font-style: italic; background-color: blue;', ...args);
  69. }
  70. },
  71. }
  72.  
  73. async function sleep(ms) {
  74. return new Promise(resolve => setTimeout(resolve, ms));
  75. }
  76.  
  77. function removeErrorWindows() {
  78. let okButtonList = document.querySelectorAll('button[data-id="ok"]');
  79. let state = false;
  80. for (let index = 0; index < okButtonList.length; index++) {
  81. const element = okButtonList[index];
  82. if (element.textContent.search(/(了解|好的|知道|Got It)/) != -1) {
  83. element.click();
  84. state = true;
  85. }
  86. }
  87.  
  88. let jellyfinSpinner = document.querySelector('div.docspinner');
  89. if (jellyfinSpinner) {
  90. jellyfinSpinner.remove();
  91. state = true;
  92. };
  93.  
  94. return state;
  95. }
  96.  
  97. function switchLocalStorage(key, defaultValue = 'true', trueValue = 'true', falseValue = 'false') {
  98. if (key in localStorage) {
  99. let value = (localStorage.getItem(key) === trueValue) ? falseValue : trueValue;
  100. localStorage.setItem(key, value);
  101. } else {
  102. localStorage.setItem(key, defaultValue)
  103. }
  104. logger.info('switchLocalStorage ', key, ' to ', localStorage.getItem(key));
  105. }
  106.  
  107. function setModeSwitchMenu(storageKey, menuStart = '', menuEnd = '', defaultValue = '关闭', trueValue = '开启', falseValue = '关闭') {
  108. let switchNameMap = { 'true': trueValue, 'false': falseValue, null: defaultValue };
  109. let menuId = GM_registerMenuCommand(menuStart + switchNameMap[localStorage.getItem(storageKey)] + menuEnd, clickMenu);
  110.  
  111. function clickMenu() {
  112. GM_unregisterMenuCommand(menuId);
  113. switchLocalStorage(storageKey)
  114. menuId = GM_registerMenuCommand(menuStart + switchNameMap[localStorage.getItem(storageKey)] + menuEnd, clickMenu);
  115. }
  116.  
  117. }
  118.  
  119. function sendDataToLocalServer(data, path) {
  120. let url = `http://127.0.0.1:58000/${path}/`;
  121. GM_xmlhttpRequest({
  122. method: 'POST',
  123. url: url,
  124. data: JSON.stringify(data),
  125. headers: {
  126. 'Content-Type': 'application/json'
  127. },
  128. });
  129. }
  130.  
  131. async function removeErrorWindowsMultiTimes() {
  132. for (const times of Array(15).keys()) {
  133. await sleep(200);
  134. if (removeErrorWindows()) {
  135. logger.info(`remove error window used time: ${(times + 1) * 0.2}`);
  136. break;
  137. };
  138. }
  139. }
  140.  
  141. async function embyToLocalPlayer(playbackUrl, request, playbackData, extraData) {
  142. let data = {
  143. ApiClient: ApiClient,
  144. playbackData: playbackData,
  145. playbackUrl: playbackUrl,
  146. request: request,
  147. mountDiskEnable: localStorage.getItem('mountDiskEnable'),
  148. extraData: extraData,
  149. fistTime: fistTime,
  150. };
  151. sendDataToLocalServer(data, 'embyToLocalPlayer');
  152. removeErrorWindowsMultiTimes();
  153. fistTime = false;
  154. }
  155.  
  156. function isHidden(el) {
  157. return (el.offsetParent === null);
  158. }
  159.  
  160. function getVisibleElement(elList) {
  161. if (!elList) return;
  162. if (NodeList.prototype.isPrototypeOf(elList)) {
  163. for (let i = 0; i < elList.length; i++) {
  164. if (!isHidden(elList[i])) {
  165. return elList[i];
  166. }
  167. }
  168. } else {
  169. return elList;
  170. }
  171. }
  172.  
  173. async function addOpenFolderElement() {
  174. if (config.disableOpenFolder) return;
  175. let mediaSources = null;
  176. for (const _ of Array(5).keys()) {
  177. await sleep(500);
  178. mediaSources = getVisibleElement(document.querySelectorAll('div.mediaSources'));
  179. if (mediaSources) break;
  180. }
  181. if (!mediaSources) return;
  182. let pathDiv = mediaSources.querySelector('div[class^="sectionTitle sectionTitle-cards"] > div');
  183. if (!pathDiv || pathDiv.className == 'mediaInfoItems' || pathDiv.id == 'addFileNameElement') return;
  184. let full_path = pathDiv.textContent;
  185. if (!full_path.match(/[/:]/)) return;
  186. if (full_path.match(/\d{1,3}\.?\d{0,2} (MB|GB)/)) return;
  187.  
  188. let openButtonHtml = `<a id="openFolderButton" is="emby-linkbutton" class="raised item-tag-button
  189. nobackdropfilter emby-button" ><i class="md-icon button-icon button-icon-left">link</i>Open Folder</a>`
  190. pathDiv.insertAdjacentHTML('beforebegin', openButtonHtml);
  191. let btn = mediaSources.querySelector('a#openFolderButton');
  192. btn.addEventListener("click", () => {
  193. logger.info(full_path);
  194. sendDataToLocalServer({ full_path: full_path }, 'openFolder');
  195. });
  196. }
  197.  
  198. async function addFileNameElement(url, request) {
  199. let mediaSources = null;
  200. for (const _ of Array(5).keys()) {
  201. await sleep(500);
  202. mediaSources = getVisibleElement(document.querySelectorAll('div.mediaSources'));
  203. if (mediaSources) break;
  204. }
  205. if (!mediaSources) return;
  206. let pathDivs = mediaSources.querySelectorAll('div[class^="sectionTitle sectionTitle-cards"] > div');
  207. if (!pathDivs) return;
  208. pathDivs = Array.from(pathDivs);
  209. let _pathDiv = pathDivs[0];
  210. if (!/\d{4}\/\d+\/\d+/.test(_pathDiv.textContent)) return;
  211. if (_pathDiv.id == 'addFileNameElement') return;
  212.  
  213. let response = await originFetch(url, request);
  214. let data = await response.json();
  215. data = data.MediaSources;
  216.  
  217. for (let index = 0; index < pathDivs.length; index++) {
  218. const pathDiv = pathDivs[index];
  219. let filePath = data[index].Path;
  220. let fileName = filePath.split('\\').pop().split('/').pop();
  221. let fileDiv = `<div id="addFileNameElement">${fileName}</div> `
  222. pathDiv.insertAdjacentHTML('beforebegin', fileDiv);
  223. }
  224. }
  225.  
  226.  
  227. let serverName = null;
  228. let episodesInfoCache = []; // ['type:[Episodes|NextUp|Items]', resp]
  229. let episodesInfoRe = /\/Episodes\?IsVirtual|\/NextUp\?Series|\/Items\?ParentId=\w+&Filters=IsNotFolder&Recursive=true/; // Items已排除播放列表
  230. // 点击位置:Episodes 继续观看,如果是即将观看,可能只有一集的信息 | NextUp 新播放或媒体库播放 | Items 季播放。 只有 Episodes 返回所有集的数据。
  231. let playlistInfoCache = null;
  232.  
  233. const originFetch = fetch;
  234. unsafeWindow.fetch = async (url, request) => {
  235. if (serverName === null) {
  236. serverName = typeof ApiClient === 'undefined' ? null : ApiClient._appName.split(' ')[0].toLowerCase();
  237. }
  238. // 获取各集标题等
  239. let _epMatch = url.match(episodesInfoRe);
  240. if (_epMatch) {
  241. _epMatch = _epMatch[0].split(['?'])[0].substring(1); // Episodes|NextUp|Items
  242. let _resp = await originFetch(url, request);
  243. episodesInfoCache = [_epMatch, _resp.clone()]
  244. logger
  245. logger.info(episodesInfoCache)
  246. return _resp
  247. }
  248. // 适配播放列表及媒体库的全部播放、随机播放。限电影及音乐视频。
  249. if (url.includes('Items?') && (url.includes('Limit=300') || url.includes('Limit=1000'))) {
  250. playlistInfoCache = null;
  251. let _resp = await originFetch(url, request);
  252. let _resd = await _resp.clone().json();
  253. if (['Movie', 'MusicVideo'].includes(_resd.Items[0].Type)) {
  254. playlistInfoCache = _resd
  255. }
  256. return _resp
  257.  
  258. }
  259. try {
  260. if (url.indexOf('/PlaybackInfo?UserId') != -1) {
  261. if (url.indexOf('IsPlayback=true') != -1 && localStorage.getItem('webPlayerEnable') != 'true') {
  262. let match = url.match(/\/Items\/(\w+)\/PlaybackInfo/);
  263. let itemId = match ? match[1] : null;
  264. let userId = ApiClient._serverInfo.UserId;
  265. let [playbackResp, mainEpInfo] = await Promise.all([
  266. originFetch(url, request),
  267. ApiClient.getItem(userId, itemId),
  268. ]);
  269. let playbackData = await playbackResp.clone().json();
  270. let episodesInfoData = episodesInfoCache[0] ? await episodesInfoCache[1].clone().json() : null;
  271. episodesInfoData = episodesInfoData ? episodesInfoData.Items : null;
  272. let playlistData = playlistInfoCache ? playlistInfoCache.Items : null;
  273. episodesInfoCache = []
  274. let extraData = {
  275. mainEpInfo: mainEpInfo,
  276. episodesInfo: episodesInfoData,
  277. playlistInfo: playlistData,
  278. }
  279. playlistInfoCache = null;
  280. logger.info(extraData);
  281. if (playbackData.MediaSources[0].Path.search(/\Wbackdrop/i) == -1) {
  282. embyToLocalPlayer(url, request, playbackData, extraData);
  283. return
  284. }
  285. } else {
  286. addOpenFolderElement();
  287. addFileNameElement(url, request);
  288. }
  289. } else if (url.indexOf('/Playing/Stopped') != -1 && localStorage.getItem('webPlayerEnable') != 'true') {
  290. return
  291. }
  292. } catch (error) {
  293. logger.error(error);
  294. removeErrorWindowsMultiTimes();
  295. return
  296. }
  297. return originFetch(url, request);
  298. }
  299.  
  300. function initXMLHttpRequest() {
  301. const open = XMLHttpRequest.prototype.open;
  302. XMLHttpRequest.prototype.open = function (...args) {
  303. let url = args[1]
  304. if (serverName === null && url.indexOf('X-Plex-Product') != -1) { serverName = 'plex' };
  305. // 正常请求不匹配的网址
  306. if (url.indexOf('playQueues?type=video') == -1) {
  307. return open.apply(this, args);
  308. }
  309. // 请求前拦截
  310. if (url.indexOf('playQueues?type=video') != -1
  311. && localStorage.getItem('webPlayerEnable') != 'true') {
  312. fetch(url, {
  313. method: args[0],
  314. headers: {
  315. 'Accept': 'application/json',
  316. }
  317. })
  318. .then(response => response.json())
  319. .then((res) => {
  320. let data = {
  321. playbackData: res,
  322. playbackUrl: url,
  323. mountDiskEnable: localStorage.getItem('mountDiskEnable'),
  324.  
  325. };
  326. sendDataToLocalServer(data, 'plexToLocalPlayer');
  327. });
  328. return;
  329. }
  330. return open.apply(this, args);
  331. }
  332. }
  333.  
  334. // 初始化请求并拦截 plex
  335. initXMLHttpRequest()
  336.  
  337. setModeSwitchMenu('webPlayerEnable', '脚本在当前服务器 已', '', '启用', '禁用', '启用')
  338. setModeSwitchMenu('mountDiskEnable', '读取硬盘模式已经 ')
  339. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址