IMDb - List Helper

Makes creating IMDb lists more efficient and convenient

当前为 2018-02-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name IMDb - List Helper
  3. // @description Makes creating IMDb lists more efficient and convenient
  4. // @namespace imdb
  5. // @author themagician, monk-time
  6. // @include http://*imdb.com/list/*/edit
  7. // @include http://*imdb.com/list/*/edit?*
  8. // @require https://cdnjs.cloudflare.com/ajax/libs/d3-dsv/1.0.8/d3-dsv.min.js
  9. // @icon http://www.imdb.com/favicon.ico
  10. // @version 3.1
  11. // ==/UserScript==
  12.  
  13. //
  14. // CHANGELOG
  15. //
  16. // 3.1
  17. // fixed: 'Skip/retry' buttons failed to keep search results visible
  18. // changed: The script searches for both IDs or titles by default again
  19. // added: A more granular control for what is used for search
  20. //
  21. // 3.0.1
  22. // fixed: New IMDb search results layout
  23. // changed: Search only for regex matches by default
  24. // added: A checkbox to toggle search mode (matches only vs. matches or full string)
  25. //
  26. // 3.0
  27. // fixed: Search by movie title
  28. // fixed: No longer requires jQuery; jquery-csv is replaced with d3-dsv
  29. // fixed: Remove delay before auto-clicking on a search result
  30. // changed: Criticker score conversion: 0..10 -> 1, 11..20 -> 2, 91..100 -> 10
  31. // changed: Criticker importer requires .csv
  32. // changed: If the regex fails, try searching for the whole string
  33. //
  34. // 2.4.1
  35. // fixed: In some instances the script wasn't loaded (bad @include)
  36. // changed: Limit number of setTimeOut calls
  37. //
  38. // 2.4.0
  39. // fixed: IMDb changed layout
  40. //
  41. // 2.3.0
  42. // fixed: importing ratings works again
  43. //
  44. // 2.2.0
  45. // added: support for people
  46. //
  47. // 2.1.1
  48. // added: only show import form if ratings is selected
  49. //
  50. // 2.1
  51. // added: importers for imdb, rateyourmusic, criticker
  52. //
  53. // 2.0
  54. // added: import ratings
  55. // added: if regex doesn't match, skip entry
  56. //
  57. // 1.6.1.2
  58. // added: input text suggestion as a placeholder
  59. //
  60. // 1.6.1.1
  61. // fixed: some entries are skipped when adding imdb ids/urls
  62. //
  63.  
  64. /* global d3 */
  65.  
  66. 'use strict';
  67.  
  68. // milliseconds between each request
  69. const REQUEST_DELAY = 1000;
  70.  
  71. // ----- DOM ELEMENTS: STYLING, CREATION AND TRACKING -----
  72.  
  73. document.head.insertAdjacentHTML('beforeend', `<style>
  74. #ilh-ui {
  75. margin: 0 5% 5% 5%;
  76. padding: 10px;
  77. border: 1px solid #e8e8e8;
  78. }
  79.  
  80. #ilh-ui div {
  81. margin: 0.5em 0 0.75em
  82. }
  83.  
  84. #ilh-ui label {
  85. font-weight: normal;
  86. margin-right: 6px;
  87. }
  88.  
  89. #ilh-ui span,
  90. #ilh-ui label:first-child {
  91. font-weight: bold;
  92. }
  93.  
  94. #ilh-ui textarea {
  95. width: 100%;
  96. background-color: lightyellow;
  97. overflow: auto;
  98. }
  99.  
  100. #ilh-ui .ilh-block {
  101. display: flex;
  102. }
  103.  
  104. #ilh-ui .ilh-block input[type=text] {
  105. font-family: monospace;
  106. flex-grow: 1;
  107. }
  108. </style>`);
  109.  
  110. const searchModeHints = {
  111. auto: 'Input titles, IMDb URLs or IDs here and click Start. ' +
  112. 'If a line has an IMDb ID, it\'ll be auto-added to the list. ' +
  113. 'Otherwise the whole line will be searched for, ' +
  114. 'and you\'ll have to select the correct title manually.',
  115. imdbid: 'Input text containing IMDb IDs here and click Start. ' +
  116. 'IMDb IDs are extracted from lines (only one per line) and ' +
  117. 'auto-added to the list, skipping the rest.',
  118. line: 'Input titles or IMDb IDs here and click Start. ' +
  119. 'Whole lines are used for search, nothing is skipped.',
  120. regexp: 'Input text here and click Start. Only captured groups of regex matches ' +
  121. 'are used for search.',
  122. rating: 'Use the controls below to load data from a file or input text here and click Start. ' +
  123. 'Your rating and IMDb ID/title is extracted from each line with regex.',
  124. };
  125.  
  126. const uiHTML = `
  127. <div id="ilh-ui">
  128. <div class="ilh-block">
  129. <label>Import mode:</label>
  130. <input type="radio" id="ilh-mode-list" name="mode" value="list" checked>
  131. <label for="ilh-mode-list">List</label>
  132. <input type="radio" id="ilh-mode-ratings" name="mode" value="ratings">
  133. <label for="ilh-mode-ratings">Ratings</label>
  134. </div>
  135. <textarea id="ilh-film-list" rows="7" placeholder="${searchModeHints.auto}"></textarea>
  136. <div>
  137. <input type="button" value="Start" id="ilh-start">
  138. <input type="button" value="Skip" id="ilh-skip">
  139. <input type="button" value="Retry" id="ilh-retry">
  140. <span>Remaining: <span id="ilh-films-remaining">0</span></span>
  141. </div>
  142. <div class="ilh-block">
  143. <label for="ilh-current-film">Current:</label>
  144. <input type="text" id="ilh-current-film">
  145. </div>
  146. <div class="ilh-block" id="ilh-regexp-box" style="display: none">
  147. <label for="ilh-regexp">Regexp:</label>
  148. <input type="text" id="ilh-regexp">
  149. </div>
  150. <div id="ilh-search-mode-box">
  151. <label for="ilh-search-mode">Search mode:</label>
  152. <select name="searchmode" id="ilh-search-mode">
  153. <option value="auto" selected>Auto</option>
  154. <option value="imdbid">IMDb IDs</option>
  155. <option value="line">Line</option>
  156. <option value="regexp">Regexp</option>
  157. </select>
  158. </div>
  159. <div id="ilh-import" style="display: none">
  160. <label for="ilh-import-sel">Import .csv from:</label>
  161. <select name="import" id="ilh-import-sel">
  162. <option value="" selected disabled hidden>Select</option>
  163. <option value="imdb">IMDb</option>
  164. <option value="rym">RateYourMusic</option>
  165. <option value="criticker">Criticker</option>
  166. </select>
  167. <span>File:</span>
  168. <input type="file" id="ilh-file-import" disabled>
  169. </div>
  170. </div>`;
  171.  
  172. document.querySelector('div.lister-search').insertAdjacentHTML('afterend', uiHTML);
  173.  
  174. const innerIDs = [
  175. 'mode-list',
  176. 'mode-ratings',
  177. 'film-list',
  178. 'start',
  179. 'skip',
  180. 'retry',
  181. 'films-remaining',
  182. 'current-film',
  183. 'search-mode-box',
  184. 'search-mode',
  185. 'regexp-box',
  186. 'regexp',
  187. 'import',
  188. 'import-sel',
  189. 'file-import',
  190. ];
  191.  
  192. const camelCase = s => s.replace(/-[a-z]/g, m => m[1].toUpperCase());
  193.  
  194. // Main object for interacting with the script's UI; keys match element ids
  195. const ui = Object.assign(...innerIDs.map(id => ({
  196. [camelCase(id)]: document.getElementById(`ilh-${id}`),
  197. })));
  198.  
  199. ui.freezables = [ui.modeList, ui.modeRatings, ui.filmList, ui.start, ui.regexp, ui.searchMode];
  200. const elIMDbSearch = document.getElementById('add-to-list-search');
  201. const elIMDbResults = document.getElementById('add-to-list-search-results');
  202.  
  203. // ----- HANDLERS AND ACTIONS -----
  204.  
  205. const convertRating = n => Math.ceil(n / 10) || 1; // 0..100 -> 1..10
  206. // d3 skips a row if a row conversion function returns null
  207. const joinOrSkip = (...fields) => (fields.includes(undefined) ? null : fields.join(','));
  208. const rowConverters = {
  209. imdb: row => joinOrSkip(row['Your Rating'], row.Const),
  210. rym: row => joinOrSkip(row.Rating, row.Title),
  211. // .csv exported from Criticker have spaces between column names
  212. criticker: row => joinOrSkip(convertRating(+row.Score), row[' IMDB ID']),
  213. };
  214.  
  215. const prepareImport = e => {
  216. const isLegalParser = Boolean(rowConverters[e.target.value]); // in case of html-js mismatch
  217. ui.fileImport.disabled = !isLegalParser;
  218. };
  219.  
  220. const handleImport = e => {
  221. const format = ui.importSel.value;
  222. const reader = new FileReader();
  223. reader.onload = event => {
  224. const fileStr = event.target.result;
  225. ui.filmList.value = d3.csvParse(fileStr, rowConverters[format]).join('\n');
  226. };
  227.  
  228. const [file] = e.target.files;
  229. reader.readAsText(file);
  230. };
  231.  
  232. const RatingManager = {
  233. rating: 0,
  234. regex: /^([1-9]|10),(.*)$/i,
  235. match: (line, mode, regex) => regex.exec(line),
  236. processMatch: ([, rating, filmTitle], callback) => {
  237. RatingManager.rating = rating;
  238. callback(filmTitle);
  239. },
  240. afterClick: async (imdbID, callback) => {
  241. console.log(`RatingManager::afterClick: Rating ${imdbID}`);
  242. const moviePage = await fetch(
  243. `http://www.imdb.com/title/${imdbID}/`,
  244. { credentials: 'same-origin' },
  245. );
  246. const authHash = new DOMParser()
  247. .parseFromString(await moviePage.text(), 'text/html')
  248. .getElementById('star-rating-widget')
  249. .dataset.auth;
  250.  
  251. const params = {
  252. tconst: imdbID,
  253. rating: RatingManager.rating,
  254. auth: authHash,
  255. tracking_tag: 'list',
  256. };
  257.  
  258. const postResp = await fetch('http://www.imdb.com/ratings/_ajax/title', {
  259. method: 'POST',
  260. body: new URLSearchParams(params),
  261. credentials: 'same-origin',
  262. });
  263.  
  264. if (postResp.ok) {
  265. callback();
  266. } else {
  267. alert(`Rating failed. Status code ${postResp.status}`);
  268. }
  269. },
  270. };
  271.  
  272. const ListManager = {
  273. regex: /((?:tt|nm)\d+)/i, // IMDb IDs
  274. match: (line, mode, regex) => ({
  275. /* eslint-disable no-sparse-arrays */
  276. // 'auto' - search for an id (if a string has one) or for a full non-empty string
  277. auto: s => ListManager.regex.exec(s) || s && [, s],
  278. imdbid: s => ListManager.regex.exec(s),
  279. line: s => s && [, s],
  280. regexp: s => regex.exec(s),
  281. /* eslint-enable no-sparse-arrays */
  282. })[mode](line),
  283. processMatch: ([, filmTitle], callback) => callback(filmTitle),
  284. afterClick: (imdbID, callback) => callback(),
  285. };
  286.  
  287. const App = {
  288. manager: ListManager,
  289. films: [],
  290. regexObj: null,
  291. run: () => {
  292. // Set the default value for the 'Regexp' mode
  293. ui.regexp.value = App.manager.regex.source;
  294.  
  295. ui.importSel.addEventListener('change', prepareImport);
  296. ui.fileImport.addEventListener('change', handleImport);
  297.  
  298. ui.searchMode.addEventListener('change', () => {
  299. ui.regexpBox.style.display = ui.searchMode.value === 'regexp' ? '' : 'none';
  300. ui.filmList.placeholder = searchModeHints[ui.searchMode.value];
  301. });
  302.  
  303. ui.modeList.addEventListener('change', () => {
  304. App.manager = ListManager;
  305. ui.import.style.display = 'none';
  306. ui.regexp.value = App.manager.regex.source;
  307. ui.regexpBox.style.display = ui.searchMode.value === 'regexp' ? '' : 'none';
  308. ui.searchModeBox.style.display = '';
  309. ui.filmList.placeholder = searchModeHints[ui.searchMode.value];
  310. });
  311.  
  312. ui.modeRatings.addEventListener('change', () => {
  313. App.manager = RatingManager;
  314. ui.import.style.display = '';
  315. ui.regexp.value = App.manager.regex.source;
  316. ui.regexpBox.style.display = '';
  317. ui.searchModeBox.style.display = 'none';
  318. ui.filmList.placeholder = searchModeHints.rating;
  319. });
  320.  
  321. ui.start.addEventListener('click', () => {
  322. // This will be used only for ListManager's 'regexp' mode or RatingManager
  323. App.regexObj = new RegExp(ui.regexp.value, 'i');
  324.  
  325. // Disable relevant UI elements
  326. ui.freezables.forEach(el => {
  327. el.disabled = true;
  328. });
  329.  
  330. App.films = ui.filmList.value.trim().split('\n');
  331. App.handleNext();
  332. });
  333.  
  334. // When the search popup loses focus, IMDb will hide it after 300 ms,
  335. // so all button clicks that want to keep it visible need to be delayed
  336. ui.skip.addEventListener('click', () =>
  337. setTimeout(() => App.handleNext(), 350));
  338.  
  339. ui.retry.addEventListener('click', () =>
  340. setTimeout(() => elIMDbSearch.dispatchEvent(new Event('keydown')), 350));
  341. },
  342. handleNext: () => {
  343. if (App.films.length) {
  344. App.search(App.films.shift());
  345. } else { // if last film
  346. App.reset();
  347. }
  348. },
  349. reset: () => {
  350. App.films = [];
  351. App.regexObj = null;
  352.  
  353. ui.freezables.forEach(el => {
  354. el.disabled = false;
  355. });
  356.  
  357. ui.currentFilm.value = '';
  358. elIMDbSearch.value = '';
  359. },
  360. search: line => {
  361. line = line.trim();
  362. ui.currentFilm.value = line;
  363. ui.filmsRemaining.textContent = App.films.length;
  364. ui.filmList.value = App.films.join('\n');
  365.  
  366. const result = App.manager.match(line, ui.searchMode.value, App.regexObj);
  367. if (result) {
  368. App.manager.processMatch(result, filmTitle => {
  369. // Set imdb search input field to film title and trigger search
  370. elIMDbSearch.value = filmTitle;
  371. elIMDbSearch.dispatchEvent(new Event('keydown'));
  372. });
  373. } else {
  374. App.handleNext();
  375. }
  376. },
  377. };
  378.  
  379. // Handle clicks on search results by a user or the script
  380. elIMDbResults.addEventListener('click', e => {
  381. const imdbID = e.target.closest('a').dataset.const;
  382. if (!imdbID || !imdbID.startsWith('tt')) return;
  383. App.manager.afterClick(imdbID, () => {
  384. setTimeout(() => App.handleNext(), REQUEST_DELAY);
  385. });
  386. });
  387.  
  388. // Monitor for changes to the search result box.
  389. // If the search was for IMDb URL/ID, the only result is clicked automatically
  390. const mut = new MutationObserver(mutList => mutList.forEach(({ addedNodes }) => {
  391. if (!addedNodes.length || !/(nm|tt)\d{7}/i.test(ui.currentFilm.value)) return;
  392. addedNodes[0].click();
  393. }));
  394. mut.observe(elIMDbResults, { childList: true });
  395.  
  396. App.run();