Netflix - subtitle downloader

Allows you to download subtitles from Netflix

目前为 2019-01-07 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Netflix - subtitle downloader
  3. // @description Allows you to download subtitles from Netflix
  4. // @license MIT
  5. // @version 3.0.4
  6. // @namespace tithen-firion.github.io
  7. // @include https://www.netflix.com/*
  8. // @grant unsafeWindow
  9. // @require https://cdn.jsdelivr.net/gh/Stuk/jszip@579beb1d45c8d586d8be4411d5b2e48dea018c06/dist/jszip.min.js?version=3.1.5
  10. // @require https://cdn.jsdelivr.net/gh/eligrey/FileSaver.js@283f438c31776b622670be002caf1986c40ce90c/dist/FileSaver.min.js?version=2018-12-29
  11. // ==/UserScript==
  12.  
  13. const MAIN_TITLE = '.player-status-main-title, .ellipsize-text>h4, .video-title>h4';
  14. const TRACK_MENU = '#player-menu-track-settings, .audio-subtitle-controller';
  15. const NEXT_EPISODE = '.player-next-episode:not(.player-hidden), .button-nfplayerNextEpisode';
  16.  
  17. const WEBVTT = 'webvtt-lssdh-ios8';
  18.  
  19. const DOWNLOAD_MENU = `<lh class="list-header">Netflix subtitle downloader</lh>
  20. <li class="list-header">Netflix subtitle downloader</li>
  21. <li class="track download">Download subs for this episode</li>
  22. <li class="track download-all">Download subs from this ep till last available</li>`;
  23.  
  24. const SCRIPT_CSS = `.player-timed-text-tracks, .track-list-subtitles{ border-right:1px solid #000 }
  25. .player-timed-text-tracks+.player-timed-text-tracks, .track-list-subtitles+.track-list-subtitles{ border-right:0 }
  26. #player-menu-track-settings .subtitle-downloader-menu li.list-header,
  27. .audio-subtitle-controller .subtitle-downloader-menu lh.list-header{ display:none }`;
  28.  
  29. const SUB_TYPES = {
  30. 'subtitles': '',
  31. 'closedcaptions': '[cc]'
  32. };
  33.  
  34. let zip;
  35. let subCache = {};
  36. let batch = false;
  37.  
  38. const randomProperty = obj => {
  39. const keys = Object.keys(obj);
  40. return obj[keys[keys.length * Math.random() << 0]];
  41. };
  42.  
  43. // get show name or full name with episode number
  44. const __getTitle = full => {
  45. if(typeof full === 'undefined')
  46. full = true;
  47. const titleElement = document.querySelector(MAIN_TITLE);
  48. if(titleElement === null)
  49. return null;
  50. const title = [titleElement.textContent.replace(/[:*?"<>|\\\/]+/g, '_').replace(/ /g, '.')];
  51. if(full) {
  52. const episodeElement = titleElement.nextElementSibling;
  53. if(episodeElement) {
  54. const m = episodeElement.textContent.match(/^[^\d]*?(\d+)[^\d]*?(\d+)?[^\d]*?$/);
  55. if(m && m.length == 3) {
  56. if(typeof m[2] == 'undefined') // example: Stranger Things season 1
  57. title.push(`S01E${m[1].padStart(2, '0')}`);
  58. else
  59. title.push(`S${m[1].padStart(2, '0')}E${m[2].padStart(2, '0')}`);
  60. }
  61. }
  62. title.push('WEBRip.Netflix');
  63. }
  64. return title.join('.');
  65. };
  66. // helper function, periodically checking for the title and resolving promise if found
  67. const _getTitle = (full, resolve) => {
  68. const title = __getTitle(full);
  69. if(title === null)
  70. window.setTimeout(_getTitle, 200, full, resolve);
  71. else
  72. resolve(title);
  73. };
  74. // promise of a title
  75. const getTitle = full => new Promise(resolve => {
  76. _getTitle(full, resolve);
  77. });
  78.  
  79. const processSubInfo = async result => {
  80. if(result.isSupplemental)
  81. return;
  82. const tracks = result.timedtexttracks;
  83. const titleP = getTitle();
  84. const subs = {};
  85. for(const track of tracks) {
  86. if(track.isNoneTrack)
  87. continue;
  88.  
  89. let type = SUB_TYPES[track.rawTrackType];
  90. if(typeof type === 'undefined')
  91. type = `[${track.rawTrackType}]`;
  92. const lang = track.language + type + (track.isForcedNarrative ? '-forced' : '');
  93. subs[lang] = randomProperty(track.ttDownloadables[WEBVTT].downloadUrls);
  94. }
  95. subCache[result.movieId] = {titleP, subs};
  96.  
  97. if(batch) {
  98. downloadAll();
  99. }
  100. };
  101.  
  102. const getMovieID = () => window.location.pathname.split('/').pop();
  103.  
  104.  
  105. const _save = async (_zip, title) => {
  106. const content = await _zip.generateAsync({type:'blob'});
  107. saveAs(content, title + '.zip');
  108. };
  109.  
  110. const _download = async _zip => {
  111. const showTitle = getTitle(false);
  112. const {titleP, subs} = subCache[getMovieID()];
  113. const downloaded = [];
  114. for(const [lang, url] of Object.entries(subs)) {
  115. const result = await fetch(url, {mode: "cors"});
  116. const data = await result.text();
  117. downloaded.push({lang, data});
  118. }
  119. const title = await titleP;
  120.  
  121. downloaded.forEach(x => {
  122. const {lang, data} = x;
  123. _zip.file(`${title}.${lang}.vtt`, data);
  124. });
  125.  
  126. return await showTitle;
  127. };
  128.  
  129. const downloadThis = async () => {
  130. const _zip = new JSZip();
  131. const showTitle = await _download(_zip);
  132. _save(_zip, showTitle);
  133. };
  134.  
  135. const downloadAll = async () => {
  136. zip = zip || new JSZip();
  137. batch = true;
  138. const showTitle = await _download(zip);
  139. const nextEp = document.querySelector(NEXT_EPISODE);
  140. if(nextEp)
  141. nextEp.click();
  142. else {
  143. await _save(zip, showTitle);
  144. zip = undefined;
  145. batch = false;
  146. }
  147. };
  148.  
  149. const processMessage = e => {
  150. processSubInfo(e.detail);
  151. }
  152.  
  153. const injection = () => {
  154. const WEBVTT = 'webvtt-lssdh-ios8';
  155.  
  156. // hijack JSON.parse and JSON.stringify functions
  157. ((parse, stringify) => {
  158. JSON.parse = function (text) {
  159. const data = parse(text);
  160. if (data && data.result && data.result.timedtexttracks && data.result.movieId) {
  161. window.dispatchEvent(new CustomEvent('netflix_sub_downloader_data', {detail: data.result}));
  162. }
  163. return data;
  164. };
  165. JSON.stringify = function (data) {
  166. if (data && data.params && data.params.profiles) {
  167. data.params.profiles.unshift(WEBVTT);
  168. }
  169. return stringify(data);
  170. };
  171. })(JSON.parse, JSON.stringify);
  172. }
  173.  
  174. window.addEventListener('netflix_sub_downloader_data', processMessage, false);
  175.  
  176. // inject script
  177. const sc = document.createElement('script');
  178. sc.innerHTML = '(' + injection.toString() + ')()';
  179. document.head.appendChild(sc);
  180. document.head.removeChild(sc);
  181.  
  182. // add CSS style
  183. const s = document.createElement('style');
  184. s.innerHTML = SCRIPT_CSS;
  185. document.head.appendChild(s);
  186.  
  187. // add menu when it's not there
  188. const observer = new MutationObserver(function(mutations) {
  189. mutations.forEach(function(mutation) {
  190. mutation.addedNodes.forEach(function(node) {
  191. if(node.nodeName.toUpperCase() == 'DIV') {
  192. let trackMenu = (node.parentNode || node).querySelector(TRACK_MENU);
  193. if(trackMenu !== null && trackMenu.querySelector('.subtitle-downloader-menu') === null) {
  194. let ol = document.createElement('ol');
  195. ol.setAttribute('class', 'subtitle-downloader-menu player-timed-text-tracks track-list track-list-subtitles');
  196. ol.innerHTML = DOWNLOAD_MENU;
  197. trackMenu.appendChild(ol);
  198. ol.querySelector('.download').addEventListener('click', downloadThis);
  199. ol.querySelector('.download-all').addEventListener('click', downloadAll);
  200. }
  201. }
  202. });
  203. });
  204. });
  205. observer.observe(document.body, { childList: true, subtree: true });

QingJ © 2025

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