Greasy Fork is available in English.

Netflix - subtitle downloader

Allows you to download subtitles from Netflix

Tính đến 06-02-2020. Xem phiên bản mới nhất.

  1. // ==UserScript==
  2. // @name Netflix - subtitle downloader
  3. // @description Allows you to download subtitles from Netflix
  4. // @license MIT
  5. // @version 3.1.0
  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. class ProgressBar {
  14. constructor(max) {
  15. this.current = 0;
  16. this.max = max;
  17.  
  18. let container = document.querySelector('#userscript_progress_bars');
  19. if(container === null) {
  20. container = document.createElement('div');
  21. container.id = 'userscript_progress_bars'
  22. document.body.appendChild(container)
  23. container.style
  24. container.style.position = 'fixed';
  25. container.style.top = 0;
  26. container.style.left = 0;
  27. container.style.width = '100%';
  28. container.style.background = 'red';
  29. container.style.zIndex = '99999999';
  30. }
  31.  
  32. this.progressElement = document.createElement('div');
  33. this.progressElement.style.width = 0;
  34. this.progressElement.style.height = '10px';
  35. this.progressElement.style.background = 'green';
  36.  
  37. container.appendChild(this.progressElement);
  38. }
  39. increment() {
  40. this.current += 1;
  41. if(this.current <= this.max)
  42. this.progressElement.style.width = this.current / this.max * 100 + '%';
  43. }
  44.  
  45. destroy() {
  46. this.progressElement.remove();
  47. }
  48. }
  49.  
  50. const MAIN_TITLE = '.player-status-main-title, .ellipsize-text>h4, .video-title>h4';
  51. const TRACK_MENU = '#player-menu-track-settings, .audio-subtitle-controller';
  52. const NEXT_EPISODE = '.player-next-episode:not(.player-hidden), .button-nfplayerNextEpisode';
  53.  
  54. const WEBVTT = 'webvtt-lssdh-ios8';
  55.  
  56. const DOWNLOAD_MENU = `<lh class="list-header">Netflix subtitle downloader</lh>
  57. <li class="list-header">Netflix subtitle downloader</li>
  58. <li class="track download">Download subs for this episode</li>
  59. <li class="track download-all">Download subs from this ep till last available</li>`;
  60.  
  61. const SCRIPT_CSS = `.player-timed-text-tracks, .track-list-subtitles{ border-right:1px solid #000 }
  62. .player-timed-text-tracks+.player-timed-text-tracks, .track-list-subtitles+.track-list-subtitles{ border-right:0 }
  63. .subtitle-downloader-menu { list-style:none }
  64. #player-menu-track-settings .subtitle-downloader-menu li.list-header,
  65. .audio-subtitle-controller .subtitle-downloader-menu lh.list-header{ display:none }`;
  66.  
  67. const SUB_TYPES = {
  68. 'subtitles': '',
  69. 'closedcaptions': '[cc]'
  70. };
  71.  
  72. let zip;
  73. let subCache = {};
  74. let batch = false;
  75.  
  76. const popRandomElement = arr => {
  77. return arr.splice(arr.length * Math.random() << 0, 1)[0];
  78. };
  79.  
  80. // get show name or full name with episode number
  81. const __getTitle = full => {
  82. if(typeof full === 'undefined')
  83. full = true;
  84. const titleElement = document.querySelector(MAIN_TITLE);
  85. if(titleElement === null)
  86. return null;
  87. const title = [titleElement.textContent.replace(/[:*?"<>|\\\/]+/g, '_').replace(/ /g, '.')];
  88. if(full) {
  89. const episodeElement = titleElement.nextElementSibling;
  90. if(episodeElement) {
  91. const m = episodeElement.textContent.match(/^[^\d]*(\d+)[^\d]+(\d+)[^\d]*$/);
  92. if(m && m.length == 3) {
  93. title.push(`S${m[1].padStart(2, '0')}E${m[2].padStart(2, '0')}`);
  94. }
  95. else {
  96. title.push(episodeElement.textContent.trim().replace(/[:*?"<>|\\\/]+/g, '_').replace(/ /g, '.'));
  97. }
  98. }
  99. title.push('WEBRip.Netflix');
  100. }
  101. return title.join('.');
  102. };
  103. // helper function, periodically checking for the title and resolving promise if found
  104. const _getTitle = (full, resolve) => {
  105. const title = __getTitle(full);
  106. if(title === null)
  107. window.setTimeout(_getTitle, 200, full, resolve);
  108. else
  109. resolve(title);
  110. };
  111. // promise of a title
  112. const getTitle = full => new Promise(resolve => {
  113. _getTitle(full, resolve);
  114. });
  115.  
  116. const processSubInfo = async result => {
  117. const tracks = result.timedtexttracks;
  118. const titleP = getTitle();
  119. const subs = {};
  120. for(const track of tracks) {
  121. if(track.isNoneTrack)
  122. continue;
  123. if(typeof track.ttDownloadables[WEBVTT] === 'undefined')
  124. continue;
  125.  
  126. let type = SUB_TYPES[track.rawTrackType];
  127. if(typeof type === 'undefined')
  128. type = `[${track.rawTrackType}]`;
  129. const lang = track.language + type + (track.isForcedNarrative ? '-forced' : '');
  130. subs[lang] = Object.values(track.ttDownloadables[WEBVTT].downloadUrls);
  131. }
  132. subCache[result.movieId] = {titleP, subs};
  133.  
  134. if(batch) {
  135. downloadAll();
  136. }
  137. };
  138.  
  139. const getMovieID = () => window.location.pathname.split('/').pop();
  140.  
  141.  
  142. const _save = async (_zip, title) => {
  143. const content = await _zip.generateAsync({type:'blob'});
  144. saveAs(content, title + '.zip');
  145. };
  146.  
  147. const _download = async _zip => {
  148. const showTitle = getTitle(false);
  149. const {titleP, subs} = subCache[getMovieID()];
  150. const downloaded = [];
  151. const progress = new ProgressBar(Object.keys(subs).length);
  152. for(const [lang, urls] of Object.entries(subs)) {
  153. while(urls.length > 0) {
  154. let url = popRandomElement(urls);
  155. const result = await fetch(url, {mode: "cors"});
  156. progress.increment();
  157. const data = await result.text();
  158. if(data.length > 0) {
  159. downloaded.push({lang, data});
  160. break;
  161. }
  162. }
  163. }
  164. progress.destroy();
  165. const title = await titleP;
  166.  
  167. downloaded.forEach(x => {
  168. const {lang, data} = x;
  169. _zip.file(`${title}.${lang}.vtt`, data);
  170. });
  171.  
  172. return await showTitle;
  173. };
  174.  
  175. const downloadThis = async () => {
  176. const _zip = new JSZip();
  177. const showTitle = await _download(_zip);
  178. _save(_zip, showTitle);
  179. };
  180.  
  181. const downloadAll = async () => {
  182. zip = zip || new JSZip();
  183. batch = true;
  184. const showTitle = await _download(zip);
  185. const nextEp = document.querySelector(NEXT_EPISODE);
  186. if(nextEp)
  187. nextEp.click();
  188. else {
  189. await _save(zip, showTitle);
  190. zip = undefined;
  191. batch = false;
  192. }
  193. };
  194.  
  195. const processMessage = e => {
  196. processSubInfo(e.detail);
  197. }
  198.  
  199. const injection = () => {
  200. const WEBVTT = 'webvtt-lssdh-ios8';
  201. const MANIFEST_URL = "/manifest";
  202.  
  203. // hijack JSON.parse and JSON.stringify functions
  204. ((parse, stringify) => {
  205. JSON.parse = function (text) {
  206. const data = parse(text);
  207. if (data && data.result && data.result.timedtexttracks && data.result.movieId) {
  208. window.dispatchEvent(new CustomEvent('netflix_sub_downloader_data', {detail: data.result}));
  209. }
  210. return data;
  211. };
  212. JSON.stringify = function (data) {
  213. if (data && data.url === MANIFEST_URL) {
  214. for (let v of Object.values(data)) {
  215. try {
  216. if (v.profiles)
  217. v.profiles.unshift(WEBVTT);
  218. if (v.showAllSubDubTracks != null)
  219. v.showAllSubDubTracks = true;
  220. }
  221. catch (e) {
  222. if (e instanceof TypeError)
  223. continue;
  224. else
  225. throw e;
  226. }
  227. }
  228. }
  229. return stringify(data);
  230. };
  231. })(JSON.parse, JSON.stringify);
  232. }
  233.  
  234. window.addEventListener('netflix_sub_downloader_data', processMessage, false);
  235.  
  236. // inject script
  237. const sc = document.createElement('script');
  238. sc.innerHTML = '(' + injection.toString() + ')()';
  239. document.head.appendChild(sc);
  240. document.head.removeChild(sc);
  241.  
  242. // add CSS style
  243. const s = document.createElement('style');
  244. s.innerHTML = SCRIPT_CSS;
  245. document.head.appendChild(s);
  246.  
  247. // add menu when it's not there
  248. const observer = new MutationObserver(function(mutations) {
  249. mutations.forEach(function(mutation) {
  250. mutation.addedNodes.forEach(function(node) {
  251. if(node.nodeName.toUpperCase() == 'DIV') {
  252. let trackMenu = (node.parentNode || node).querySelector(TRACK_MENU);
  253. if(trackMenu !== null && trackMenu.querySelector('.subtitle-downloader-menu') === null) {
  254. let ol = document.createElement('ol');
  255. ol.setAttribute('class', 'subtitle-downloader-menu player-timed-text-tracks track-list track-list-subtitles');
  256. ol.innerHTML = DOWNLOAD_MENU;
  257. trackMenu.appendChild(ol);
  258. ol.querySelector('.download').addEventListener('click', downloadThis);
  259. ol.querySelector('.download-all').addEventListener('click', downloadAll);
  260. }
  261. }
  262. });
  263. });
  264. });
  265. observer.observe(document.body, { childList: true, subtree: true });