AniLINK - Episode Link Extractor

Stream or download your favorite anime series effortlessly with AniLINK! Unlock the power to play any anime series directly in your preferred video player or download entire seasons in a single click using popular download managers like IDM. AniLINK generates direct download links for all episodes, conveniently sorted by quality. Elevate your anime-watching experience now!

  1. // ==UserScript==
  2. // @name AniLINK - Episode Link Extractor
  3. // @namespace https://greasyfork.org/en/users/781076-jery-js
  4. // @version 6.7.1
  5. // @description Stream or download your favorite anime series effortlessly with AniLINK! Unlock the power to play any anime series directly in your preferred video player or download entire seasons in a single click using popular download managers like IDM. AniLINK generates direct download links for all episodes, conveniently sorted by quality. Elevate your anime-watching experience now!
  6. // @icon https://www.google.com/s2/favicons?domain=animepahe.ru
  7. // @author Jery
  8. // @license MIT
  9. // @match https://anitaku.*/*
  10. // @match https://anitaku.bz/*
  11. // @match https://gogoanime.*/*
  12. // @match https://gogoanime3.cc/*
  13. // @match https://gogoanime3.*/*
  14. // @match https://animepahe.*/play/*
  15. // @match https://animepahe.*/anime/*
  16. // @match https://animepahe.ru/play/*
  17. // @match https://animepahe.com/play/*
  18. // @match https://animepahe.org/play/*
  19. // @match https://yugenanime.*/anime/*/*/watch/
  20. // @match https://yugenanime.tv/anime/*/*/watch/
  21. // @match https://yugenanime.sx/anime/*/*/watch/
  22. // @match https://hianime.*/watch/*
  23. // @match https://hianime.to/watch/*
  24. // @match https://hianime.nz/watch/*
  25. // @match https://hianime.sz/watch/*
  26. // @match https://otaku-streamers.com/info/*/*
  27. // @match https://beta.otaku-streamers.com/watch/*/*
  28. // @match https://beta.otaku-streamers.com/title/*/*
  29. // @match https://animeheaven.me/anime.php?*
  30. // @match https://animez.org/*/*
  31. // @match https://*.miruro.to/watch?id=*
  32. // @match https://*.miruro.tv/watch?id=*
  33. // @match https://*.miruro.online/watch?id=*
  34. // @match https://animekai.to/watch/*
  35. // @grant GM_registerMenuCommand
  36. // @grant GM_xmlhttpRequest
  37. // @grant GM.xmlHttpRequest
  38. // @require https://cdn.jsdelivr.net/npm/@trim21/gm-fetch@0.2.1
  39. // @grant GM_addStyle
  40. // @grant GM_getValue
  41. // ==/UserScript==
  42.  
  43. class Episode {
  44. constructor(number, animeTitle, links, thumbnail, epTitle) {
  45. this.number = number; // The episode number
  46. this.animeTitle = animeTitle; // The title of the anime.
  47. this.epTitle = epTitle; // The title of the episode (this can be the specific ep title or blank).
  48. this.links = links; // An object containing streaming links and tracks for each source: {"source1":{stream:"url", type:"m3u8|mp4", tracks:[{file:"url", kind:"caption|audio", label:"name"}]}}}
  49. this.thumbnail = thumbnail; // The URL of the episode's thumbnail image (if unavailable, then just any image is fine. Thumbnail property isnt really used in the script yet).
  50. this.filename = `${this.animeTitle} - ${this.number.padStart(3, '0')}${this.epTitle ? ` - ${this.epTitle}` : ''}.${Object.values(this.links)[0]?.type || 'm3u8'}`; // The formatted name of the episode, combining anime name, number and title and extension.
  51. this.title = this.epTitle ?? this.animeTitle;
  52. }
  53. }
  54.  
  55. /**
  56. * @typedef {Object} Websites[]
  57. * @property {string} name - The name of the website (required).
  58. * @property {string[]} url - An array of URL patterns that identify the website (required).
  59. * @property {string} thumbnail - A CSS selector to identify the episode thumbnail on the website (required).
  60. * @property {Function} addStartButton - A function to add the "Generate Download Links" button to the website (required).
  61. * @property {AsyncGeneratorFunction} extractEpisodes - An async generator function to extract episode information from the website (required).
  62. * @property {string} epLinks - A CSS selector to identify the episode links on the website (optional).
  63. * @property {string} epTitle - A CSS selector to identify the episode title on the website (optional).
  64. * @property {string} linkElems - A CSS selector to identify the download link elements on the website (optional).
  65. * @property {string} [animeTitle] - A CSS selector to identify the anime title on the website (optional).
  66. * @property {string} [epNum] - A CSS selector to identify the episode number on the website (optional).
  67. * @property {Function} [_getVideoLinks] - A function to extract video links from the website (optional).
  68. * @property {string} [styles] - Custom CSS styles to be applied to the website (optional).
  69. *
  70. * @description An array of website configurations for extracting episode links.
  71. *
  72. * @note To add a new website, follow these steps:
  73. * 1. Create a new object with the following properties:
  74. * - `name`: The name of the website.
  75. * - `url`: An array of URL patterns that identify the website.
  76. * - `thumbnail`: A CSS selector to identify the episode thumbnail on the website.
  77. * - `addStartButton`: A function to add the "Generate Download Links" button to the website.
  78. * - `extractEpisodes`: An async generator function to extract episode information from the website.
  79. * 2. Optionally, add the following properties if needed (they arent used by the script, but they will come in handy when the animesite changes its layout):
  80. * - `animeTitle`: A CSS selector to identify the anime title on the website.
  81. * - `epLinks`: A CSS selector to identify the episode links on the website.
  82. * - `epTitle`: A CSS selector to identify the episode title on the website.
  83. * - `linkElems`: A CSS selector to identify the download link elements on the website.
  84. * - `epNum`: A CSS selector to identify the episode number on the website.
  85. * - `_getVideoLinks`: A function to extract video links from the website.
  86. * - `styles`: Custom CSS styles to be applied to the website.
  87. * 3. Implement the `addStartButton` function to add the "Generate Download Links" button to the website.
  88. * - This function should create a element and append it to the appropriate location on the website.
  89. * - The button should have an ID of "AniLINK_startBtn".
  90. * 4. Implement the `extractEpisodes` function to extract episode information from the website.
  91. * - This function should be an async generator function that yields Episode objects (To ensure fast processing, using chunks is recommended).
  92. * - Use the `fetchPage` function to fetch the HTML content of each episode page.
  93. * - Parse the HTML content to extract the episode title, number, links, and thumbnail.
  94. * - Create an `Episode` object for each episode and yield it using the `yieldEpisodesFromPromises` function.
  95. * 5. Optionally, implement the `_getVideoLinks` function to extract video links from the website.
  96. * - This function should return a promise that resolves to an object containing video links.
  97. * - Use this function if the video links require additional processing or API calls.
  98. * - Tip: use GM_xmlhttpRequest to make cross-origin requests if needed (I've used proxy.sh so far which I plan to change in the future since GM_XHR seems more reliable).
  99. */
  100. const websites = [
  101. {
  102. name: 'GoGoAnime',
  103. url: ['anitaku.to/', 'gogoanime3.co/', 'gogoanime3', 'anitaku', 'gogoanime'],
  104. epLinks: '#episode_related > li > a',
  105. epTitle: '.title_name > h2',
  106. linkElems: '.cf-download > a',
  107. thumbnail: '.headnav_left > a > img',
  108. addStartButton: function () {
  109. const button = Object.assign(document.createElement('a'), {
  110. id: "AniLINK_startBtn",
  111. style: "cursor: pointer; background-color: #145132;",
  112. innerHTML: document.querySelector("div.user_auth a[href='/login.html']")
  113. ? `<b style="color:#FFC119;">AniLINK:</b> Please <a href="/login.html"><u>log in</u></a> to download`
  114. : '<i class="icongec-dowload"></i> Generate Download Links'
  115. });
  116. const target = location.href.includes('/category/') ? '#episode_page' : '.cf-download';
  117. document.querySelector(target)?.appendChild(button);
  118. return button;
  119. },
  120. extractEpisodes: async function* (status) {
  121. status.textContent = 'Starting...';
  122. const throttleLimit = 12; // Number of episodes to extract in parallel
  123. const allEpLinks = Array.from(document.querySelectorAll(this.epLinks));
  124. const epLinks = await applyEpisodeRangeFilter(allEpLinks, status);
  125. if (!epLinks) return; // User cancelled
  126. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  127. const chunk = epLinks.slice(i, i + throttleLimit);
  128. const episodePromises = chunk.map(async epLink => {
  129. try {
  130. const page = await fetchPage(epLink.href);
  131.  
  132. const [, epTitle, epNumber] = page.querySelector(this.epTitle).textContent.match(/(.+?) Episode (\d+(?:\.\d+)?)/);
  133. const thumbnail = page.querySelector(this.thumbnail).src;
  134. status.textContent = `Extracting ${epTitle} - ${epNumber.padStart(3, '0')}...`;
  135. const links = [...page.querySelectorAll(this.linkElems)].reduce((obj, elem) => ({ ...obj, [elem.textContent.trim()]: { stream: elem.href, type: 'mp4' } }), {});
  136. status.textContent = `Extracted ${epTitle} - ${epNumber.padStart(3, '0')}`;
  137.  
  138. return new Episode(epNumber, epTitle, links, thumbnail); // Return Episode object
  139. } catch (e) { showToast(e); return null; }
  140. }); // Handle errors and return null
  141.  
  142. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  143. }
  144. }
  145. },
  146. {
  147. name: 'YugenAnime',
  148. url: ['yugenanime.tv', 'yugenanime.sx'],
  149. epLinks: '.ep-card > a.ep-thumbnail',
  150. animeTitle: '.ani-info-ep .link h1',
  151. epTitle: 'div.col.col-w-65 > div.box > h1',
  152. thumbnail: 'a.ep-thumbnail img',
  153. addStartButton: function () {
  154. return document.querySelector(".content .navigation").appendChild(Object.assign(document.createElement('a'), { id: "AniLINK_startBtn", className: "link p-15", textContent: "Generate Download Links" }));
  155. },
  156. extractEpisodes: async function* (status) {
  157. status.textContent = 'Getting list of episodes...';
  158. const allEpLinks = Array.from(document.querySelectorAll(this.epLinks));
  159. const epLinks = await applyEpisodeRangeFilter(allEpLinks, status);
  160. if (!epLinks) return; // User cancelled
  161.  
  162. const throttleLimit = 6; // Number of episodes to extract in parallel
  163.  
  164. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  165. const chunk = epLinks.slice(i, i + throttleLimit);
  166. const episodePromises = chunk.map(async (epLink, index) => {
  167. try {
  168. status.textContent = `Loading ${epLink.pathname}`;
  169. const page = await fetchPage(epLink.href);
  170.  
  171. const animeTitle = page.querySelector(this.animeTitle).textContent;
  172. const epNumber = epLink.href.match(/(\d+)\/?$/)[1];
  173. const epTitle = page.querySelector(this.epTitle).textContent.match(/^${epNumber} : (.+)$/) || animeTitle;
  174. const thumbnail = document.querySelectorAll(this.thumbnail)[index].src;
  175. status.textContent = `Extracting ${`${epNumber.padStart(3, '0')} - ${animeTitle}` + (epTitle != animeTitle ? `- ${epTitle}` : '')}...`;
  176. const rawLinks = await this._getVideoLinks(page, status, epTitle);
  177. const links = Object.entries(rawLinks).reduce((acc, [quality, url]) => ({ ...acc, [quality]: { stream: url, type: 'm3u8' } }), {});
  178.  
  179. return new Episode(epNumber, epTitle, links, thumbnail);
  180. } catch (e) { showToast(e); return null; }
  181. });
  182. yield* yieldEpisodesFromPromises(episodePromises);
  183. }
  184. },
  185. _getVideoLinks: async function (page, status, episodeTitle) {
  186. const embedLinkId = page.body.innerHTML.match(new RegExp(`src="//${page.domain}/e/(.*?)/"`))[1];
  187. const embedApiResponse = await fetch(`https://${page.domain}/api/embed/`, { method: 'POST', headers: { "X-Requested-With": "XMLHttpRequest" }, body: new URLSearchParams({ id: embedLinkId, ac: "0" }) });
  188. const json = await embedApiResponse.json();
  189. const m3u8GeneralLink = json.hls[0];
  190. status.textContent = `Parsing ${episodeTitle}...`;
  191. // Fetch the m3u8 file content
  192. const m3u8Response = await fetch(m3u8GeneralLink);
  193. const m3u8Text = await m3u8Response.text();
  194. // Parse the m3u8 file to extract different qualities
  195. const qualityMatches = m3u8Text.matchAll(/#EXT-X-STREAM-INF:.*RESOLUTION=\d+x\d+.*NAME="(\d+p)"\n(.*\.m3u8)/g);
  196. const links = {};
  197. for (const match of qualityMatches) {
  198. const [_, quality, m3u8File] = match;
  199. links[quality] = `${m3u8GeneralLink.slice(0, m3u8GeneralLink.lastIndexOf('/') + 1)}${m3u8File}`;
  200. }
  201. return links;
  202. }
  203. },
  204. {
  205. name: 'AnimePahe',
  206. url: ['animepahe.ru', 'animepahe.com', 'animepahe.org'],
  207. epLinks: (location.pathname.startsWith('/anime/')) ? '.play' : '.dropup.episode-menu .dropdown-item',
  208. epTitle: '.theatre-info > h1',
  209. linkElems: '#resolutionMenu > button',
  210. thumbnail: '.theatre-info > a > img',
  211. addStartButton: function () {
  212. GM_addStyle(`.theatre-settings .col-sm-3 { max-width: 20%; }`);
  213. (document.location.pathname.startsWith('/anime/'))
  214. ? document.querySelector(".col-6.bar").innerHTML += `
  215. <div class="btn-group btn-group-toggle">
  216. <label id="AniLINK_startBtn" class="btn btn-dark btn-sm">Generate Download Links</label>
  217. </div>`
  218. : document.querySelector("div.theatre-settings > div.row").innerHTML += `
  219. <div class="col-12 col-sm-3">
  220. <div class="dropup">
  221. <a class="btn btn-secondary btn-block" id="AniLINK_startBtn">
  222. Generate Download Links
  223. </a>
  224. </div>
  225. </div>
  226. `;
  227. return document.getElementById("AniLINK_startBtn");
  228. },
  229. extractEpisodes: async function* (status) {
  230. status.textContent = 'Starting...';
  231. const allEpLinks = Array.from(document.querySelectorAll(this.epLinks));
  232. const epLinks = await applyEpisodeRangeFilter(allEpLinks, status);
  233. if (!epLinks) return; // User cancelled
  234. const throttleLimit = 36; // Setting high throttle limit actually improves performance
  235.  
  236. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  237. const chunk = epLinks.slice(i, i + throttleLimit);
  238. const episodePromises = chunk.map(async epLink => {
  239. try {
  240. const page = await fetchPage(epLink.href);
  241.  
  242. if (page.querySelector(this.epTitle) == null) return;
  243. const [, animeTitle, epNumber] = page.querySelector(this.epTitle).outerText.split(/Watch (.+) - (\d+(?:\.\d+)?) Online$/);
  244. const thumbnail = page.querySelector(this.thumbnail).src;
  245. status.textContent = `Extracting ${animeTitle} - ${epNumber.padStart(3, "0")}...`;
  246.  
  247. async function getVideoUrl(kwikUrl) {
  248. const response = await fetch(kwikUrl, { headers: { "Referer": "https://animepahe.com" } });
  249. const data = await response.text();
  250. return eval(/(eval)(\(f.*?)(\n<\/script>)/s.exec(data)[2].replace("eval", "")).match(/https.*?m3u8/)[0];
  251. }
  252. let links = {};
  253. for (const elm of [...page.querySelectorAll(this.linkElems)]) {
  254. links[elm.textContent] = { stream: await getVideoUrl(elm.getAttribute('data-src')), type: 'm3u8' };
  255. status.textContent = `Parsed ${`${epNumber.padStart(3, '0')} - ${animeTitle}`}`;
  256. }
  257. return new Episode(epNumber, animeTitle, links, thumbnail);
  258. } catch (e) { showToast(e); return null; }
  259. });
  260. yield* yieldEpisodesFromPromises(episodePromises);
  261. }
  262. },
  263. styles: `div#AniLINK_LinksContainer { font-size: 10px; } #Quality > b > div > ul {font-size: 16px;}`
  264. },
  265. {
  266. name: 'Beta-Otaku-Streamers',
  267. url: ['beta.otaku-streamers.com'],
  268. epLinks: (document.location.pathname.startsWith('/title/')) ? '.item-title a' : '.video-container .clearfix > a',
  269. epTitle: '.title > a',
  270. epNum: '.watch_curep',
  271. thumbnail: 'video',
  272. addStartButton: function () {
  273. (document.location.pathname.startsWith('/title/')
  274. ? document.querySelector(".album-top-box") : document.querySelector('.video-container .title-box'))
  275. .innerHTML += `<a id="AniLINK_startBtn" class="btn btn-outline rounded-btn">Generate Download Links</a>`;
  276. return document.getElementById("AniLINK_startBtn");
  277. },
  278. extractEpisodes: async function* (status) {
  279. status.textContent = 'Starting...';
  280. const allEpLinks = Array.from(document.querySelectorAll(this.epLinks));
  281. const epLinks = await applyEpisodeRangeFilter(allEpLinks, status);
  282. if (!epLinks) return; // User cancelled
  283. const throttleLimit = 12;
  284.  
  285. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  286. const chunk = epLinks.slice(i, i + throttleLimit);
  287. const episodePromises = chunk.map(async epLink => {
  288. try {
  289. const page = await fetchPage(epLink.href);
  290. const epTitle = page.querySelector(this.epTitle).textContent.trim();
  291. const epNumber = page.querySelector(this.epNum).textContent.replace("Episode ", '');
  292. const thumbnail = page.querySelector(this.thumbnail).poster;
  293.  
  294. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  295. const links = { 'Video Links': { stream: page.querySelector('video > source').src, type: 'mp4' } };
  296.  
  297. return new Episode(epNumber, epTitle, links, thumbnail);
  298. } catch (e) { showToast(e); return null; }
  299. });
  300. yield* yieldEpisodesFromPromises(episodePromises);
  301. }
  302. }
  303. },
  304. {
  305. name: 'Otaku-Streamers',
  306. url: ['otaku-streamers.com'],
  307. epLinks: 'table > tbody > tr > td:nth-child(2) > a',
  308. epTitle: '#strw_player > table > tbody > tr:nth-child(1) > td > span:nth-child(1) > a',
  309. epNum: '#video_episode',
  310. thumbnail: 'otaku-streamers.com/images/os.jpg',
  311. addStartButton: function () {
  312. const button = document.createElement('a');
  313. button.id = "AniLINK_startBtn";
  314. button.style.cssText = `cursor: pointer; background-color: #145132; float: right;`;
  315. button.innerHTML = 'Generate Download Links';
  316. document.querySelector('table > tbody > tr:nth-child(2) > td > div > table > tbody > tr > td > h2').appendChild(button);
  317. return button;
  318. },
  319. extractEpisodes: async function* (status) {
  320. status.textContent = 'Starting...';
  321. const allEpLinks = Array.from(document.querySelectorAll(this.epLinks));
  322. const epLinks = await applyEpisodeRangeFilter(allEpLinks, status);
  323. if (!epLinks) return; // User cancelled
  324. const throttleLimit = 12; // Number of episodes to extract in parallel
  325.  
  326. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  327. const chunk = epLinks.slice(i, i + throttleLimit);
  328. const episodePromises = chunk.map(async epLink => {
  329. try {
  330. const page = await fetchPage(epLink.href);
  331. const epTitle = page.querySelector(this.epTitle).textContent;
  332. const epNumber = page.querySelector(this.epNum).textContent.replace("Episode ", '')
  333.  
  334. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  335. const links = { 'mp4': { stream: page.querySelector('video > source').src, type: 'mp4' } };
  336.  
  337. return new Episode(epNumber, epTitle, links, this.thumbnail); // Return Episode object
  338. } catch (e) { showToast(e); return null; }
  339. }); // Handle errors and return null
  340.  
  341. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  342. }
  343. }
  344. },
  345. {
  346. name: 'AnimeHeaven',
  347. url: ['animeheaven.me'],
  348. epLinks: 'a.ac3',
  349. epTitle: 'a.c2.ac2',
  350. epNumber: '.boxitem.bc2.c1.mar0',
  351. thumbnail: 'img.posterimg',
  352. addStartButton: function () {
  353. const button = document.createElement('a');
  354. button.id = "AniLINK_startBtn";
  355. button.style.cssText = `cursor: pointer; border: 2px solid red; padding: 4px;`;
  356. button.innerHTML = 'Generate Download Links';
  357. document.querySelector("div.linetitle2.c2").parentNode.insertBefore(button, document.querySelector("div.linetitle2.c2"));
  358. return button;
  359. },
  360. extractEpisodes: async function* (status) {
  361. status.textContent = 'Starting...';
  362. const allEpLinks = Array.from(document.querySelectorAll(this.epLinks));
  363. const epLinks = await applyEpisodeRangeFilter(allEpLinks, status);
  364. if (!epLinks) return; // User cancelled
  365. const throttleLimit = 12; // Number of episodes to extract in parallel
  366.  
  367. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  368. const chunk = epLinks.slice(i, i + throttleLimit);
  369. const episodePromises = chunk.map(async epLink => {
  370. try {
  371. const page = await fetchPage(epLink.href);
  372. const epTitle = page.querySelector(this.epTitle).textContent;
  373. const epNumber = page.querySelector(this.epNumber).textContent.replace("Episode ", '');
  374. const thumbnail = document.querySelector(this.thumbnail).src;
  375.  
  376. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  377. const links = [...page.querySelectorAll('#vid > source')].reduce((acc, source) => ({ ...acc, [source.src.match(/\/\/(\w+)\./)[1]]: { stream: source.src, type: 'mp4' } }), {});
  378.  
  379. return new Episode(epNumber, epTitle, links, thumbnail); // Return Episode object
  380. } catch (e) { showToast(e); return null; }
  381. }); // Handle errors and return null
  382.  
  383. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  384. }
  385. }
  386. },
  387. {
  388. name: 'AnimeZ',
  389. url: ['animez.org'],
  390. epLinks: 'li.wp-manga-chapter a',
  391. epTitle: '#title-detail-manga',
  392. epNum: '.wp-manga-chapter.active',
  393. thumbnail: '.Image > figure > img',
  394. addStartButton: function () {
  395. (document.querySelector(".MovieTabNav.ControlPlayer") || document.querySelector(".mb-3:has(#keyword_chapter)"))
  396. .innerHTML += `<div class="Lnk AAIco-link" id="AniLINK_startBtn">Extract Episode Links</div>`;
  397. return document.getElementById("AniLINK_startBtn");
  398. },
  399. extractEpisodes: async function* (status) {
  400. /// work in progress- stopped when animes.org started redirecting to some random manhwa site
  401. status.textContent = 'Fetching Episodes List...';
  402. const mangaId = (window.location.pathname.match(/-(\d+)(?:\/|$)/) || [])[1] || document.querySelector('[data-manga-id]')?.getAttribute('data-manga-id');
  403. if (!mangaId) return showToast('Could not determine manga_id for episode list.');
  404. const nav = document.querySelectorAll('#nav_list_chapter_id_detail li').map(e => e.querySelector('i.icon').parentElement.parentElement)
  405. const maxPage = Math.max(1, ...Array.from(nav).map(a => +(a.getAttribute('onclick')?.match(/load_list_chapter\((\d+)\)/)?.[1] || 0)).filter(Boolean));
  406. // Parse all episode links from all pages in parallel
  407. status.textContent = `Loading all ${maxPage} episode pages...`;
  408. let allEpLinks = [];
  409. try {
  410. await Promise.all(Array.from({ length: maxPage }, (_, i) => fetch(`/?act=ajax&code=load_list_chapter&manga_id=${mangaId}&page_num=${i + 1}&chap_id=0&keyword=`).then(r => r.text()).then(t => {
  411. let html = JSON.parse(t).list_chap;
  412. const doc = document.implementation.createHTMLDocument('eps');
  413. doc.body.innerHTML = html;
  414. allEpLinks.push(...doc.querySelectorAll(this.epLinks));
  415. })));
  416. } catch (e) { showToast('Failed to load Episodes List: ' + e); return null; }
  417. // Remove duplicates
  418. allEpLinks = allEpLinks.filter((el, idx, self) => self.findIndex(e => e.href === el.href && e.textContent.trim() === el.textContent.trim()) === idx);
  419. const epLinks = await applyEpisodeRangeFilter(allEpLinks, status);
  420. if (!epLinks) return; // User cancelled
  421. const throttleLimit = 12;
  422. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  423. const chunk = epLinks.slice(i, i + throttleLimit);
  424. const episodePromises = chunk.map(async epLink => {
  425. try {
  426. const page = await fetchPage(epLink.href);
  427. const epTitle = page.querySelector(this.epTitle).textContent;
  428. const isDub = page.querySelector(this.epNum).textContent.includes('-Dub');
  429. const epNumber = page.querySelector(this.epNum).textContent.replace(/-Dub/, '').trim();
  430. const thumbnail = document.querySelector(this.thumbnail).src;
  431.  
  432. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  433. const links = { [isDub ? "Dub" : "Sub"]: { stream: page.querySelector('iframe').src.replace('/embed/', '/anime/'), type: 'm3u8' } };
  434.  
  435. return new Episode(epNumber, epTitle, links, thumbnail); // Return Episode object
  436. } catch (e) { showToast(e); return null; }
  437. });
  438. yield* yieldEpisodesFromPromises(episodePromises);
  439. }
  440. }
  441. },
  442. {
  443. name: 'Miruro',
  444. url: ['miruro.to', 'miruro.tv', 'miruro.online'],
  445. animeTitle: '.anime-title > a',
  446. thumbnail: 'a[href^="/info?id="] > img',
  447. baseApiUrl: `${location.origin}/api`,
  448. addStartButton: function (id) {
  449. const intervalId = setInterval(() => {
  450. const target = document.querySelector('.title-actions-container');
  451. if (target) {
  452. clearInterval(intervalId);
  453. const btn = document.createElement('button');
  454. btn.id = id;
  455. btn.style.cssText = `${target.lastChild.style.cssText} display: flex; justify-content: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: auto;`;
  456. btn.className = target.lastChild.className;
  457. btn.innerHTML = `
  458. <svg xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="3 3 18 18"><path fill="currentColor" d="M5 21q-.825 0-1.413-.588T3 19V5q0-.825.588-1.413T5 3h14q.825 0 1.413.588T21 5v14q0 .825-.588 1.413T19 21H5Zm0-2h14V5H5v14Zm3-4.5h2.5v-6H8v6Zm5.25 0h2.5v-6h-2.5v6Zm5.25 0h2.5v-6h-2.5v6Z"/></svg>
  459. <div style="display: flex; justify-content: center; align-items: center;">Extract Episode Links</div>
  460. `;
  461. btn.addEventListener('click', extractEpisodes);
  462. target.appendChild(btn);
  463. }
  464. }, 200);
  465. },
  466. extractEpisodes: async function* (status) {
  467. status.textContent = 'Fetching episode list...';
  468. const animeTitle = document.querySelector(this.animeTitle).textContent;
  469. const malId = document.querySelector(`a[href*="/myanimelist.net/anime/"]`)?.href.split('/').pop();
  470. if (!malId) return showToast('MAL ID not found.');
  471.  
  472. const res = await fetch(`${this.baseApiUrl}/episodes?malId=${malId}`).then(r => r.json());
  473. const providers = Object.entries(res).flatMap(([p, s]) => {
  474. if (p === "ANIMEZ") {
  475. // AnimeZ: treat sub and dub as separate providers
  476. const v = Object.values(s)[0], animeId = Object.keys(s)[0], eps = v?.episodeList?.episodes;
  477. if (!eps) return [];
  478. return ["sub", "dub"].map(type =>
  479. eps[type]?.length
  480. ? { source: `animez-${type}`, animeId, useEpId: true, epList: eps[type] }
  481. : null
  482. )
  483. } else {
  484. // Default: original logic
  485. const v = Object.values(s)[0], ep = v?.episodeList?.episodes || v?.episodeList;
  486. return ep && { source: p.toLowerCase(), animeId: Object.keys(s)[0], useEpId: !!v?.episodeList?.episodes, epList: ep };
  487. }
  488. }).filter(Boolean);
  489.  
  490. // Get the provider with most episodes to use as base for thumbnails, epTitle, epNumber, etc.
  491. // Preferred provider is Zoro, if available, since it has the best title format
  492. let baseProvider = providers.find(p => p.source === 'zoro') || providers.find(p => p.epList.length == Math.max(...providers.map(p => p.epList.length)));
  493. baseProvider = { ...baseProvider, epList: await applyEpisodeRangeFilter(baseProvider.epList, status) };
  494.  
  495. if (!baseProvider) return showToast('No episodes found.');
  496.  
  497. for (const baseEp of baseProvider.epList) {
  498. const num = String(baseEp.number).padStart(3, '0');
  499. let epTitle = baseEp.title, thumbnail = baseEp.snapshot; // will try to update with other providers if this is blank
  500.  
  501. status.textContent = `Fetching Ep ${num}...`;
  502. let links = {};
  503. await Promise.all(providers.map(async ({ source, animeId, useEpId, epList }) => {
  504. const ep = epList.find(ep => ep.number == baseEp.number);
  505. epTitle = epTitle || ep.title; // update title if blank
  506. const epId = !useEpId ? `${animeId}/ep-${ep.number}` : ep.id;
  507. try {
  508. const apiProvider = source.startsWith('animez-') ? 'animez' : source;
  509. const sres = await fetchWithRetry(`${this.baseApiUrl}/sources?episodeId=${epId}&provider=${apiProvider}`);
  510. const sresJson = await sres.json();
  511. links[this._getLocalSourceName(source)] = { stream: sresJson.streams[0].url, type: "m3u8", tracks: sresJson.tracks || [] };
  512. } catch (e) { showToast(`Failed to fetch ep-${ep.number} from ${source}: ${e}`); return null; }
  513. }));
  514.  
  515. if (!epTitle || /^Episode \d+/.test(epTitle)) epTitle = undefined; // remove epTitle if episode title is blank or just "Episode X"
  516. yield new Episode(num, animeTitle, links, thumbnail || document.querySelector(this.thumbnail).src, epTitle);
  517. }
  518. },
  519. _getLocalSourceName: function (source) {
  520. const sourceNames = { 'animepahe': 'kiwi', 'animekai': 'arc', 'animez-sub': 'jet-sub', 'animez-dub': 'jet-dub', 'zoro': 'zoro' };
  521. return sourceNames[source] || source.charAt(0).toUpperCase() + source.slice(1);
  522. },
  523. },
  524.  
  525. // AnimeKai is not fully implemented yet... its a work in progress...
  526. {
  527. name: 'AnimeKai',
  528. url: ['animekai.to/watch/'],
  529. animeTitle: '.title',
  530. thumbnail: 'img',
  531. addStartButton: function () {
  532. const button = Object.assign(document.createElement('button'), {
  533. id: "AniLINK_startBtn",
  534. className: "btn btn-primary", // Use existing site styles
  535. textContent: "Generate Download Links",
  536. style: "margin-left: 10px;"
  537. });
  538. // Add button next to the episode list controls or similar area
  539. const target = document.querySelector('.episode-section');
  540. if (target) {
  541. target.appendChild(button);
  542. } else {
  543. // Fallback location if the primary target isn't found
  544. document.querySelector('.eplist-nav')?.appendChild(button);
  545. }
  546. return button;
  547. },
  548. // --- Helper functions adapted from provided code ---
  549. _reverseIt: (n) => n.split('').reverse().join(''),
  550. _base64UrlEncode: (str) => btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''),
  551. _base64UrlDecode: (n) => { n = n.padEnd(n.length + ((4 - (n.length % 4)) % 4), '=').replace(/-/g, '+').replace(/_/g, '/'); return atob(n); },
  552. _substitute: (input, keys, values) => { const map = Object.fromEntries(keys.split('').map((key, i) => [key, values[i] || ''])); return input.split('').map(char => map[char] || char).join(''); },
  553. _transform: (n, t) => { const v = Array.from({ length: 256 }, (_, i) => i); let c = 0, f = ''; for (let w = 0; w < 256; w++) { c = (c + v[w] + n.charCodeAt(w % n.length)) % 256;[v[w], v[c]] = [v[c], v[w]]; } for (let a = (c = 0), w = 0; a < t.length; a++) { w = (w + 1) % 256; c = (c + v[w]) % 256;[v[w], v[c]] = [v[c], v[w]]; f += String.fromCharCode(t.charCodeAt(a) ^ v[(v[w] + v[c]) % 256]); } return f; },
  554. _GenerateToken: function (n) { n = encodeURIComponent(n); return this._base64UrlEncode(this._substitute(this._base64UrlEncode(this._transform('sXmH96C4vhRrgi8', this._reverseIt(this._reverseIt(this._base64UrlEncode(this._transform('kOCJnByYmfI', this._substitute(this._substitute(this._reverseIt(this._base64UrlEncode(this._transform('0DU8ksIVlFcia2', n))), '1wctXeHqb2', '1tecHq2Xbw'), '48KbrZx1ml', 'Km8Zb4lxr1'))))))), 'hTn79AMjduR5', 'djn5uT7AMR9h')); },
  555. _DecodeIframeData: function (n) { n = `${n}`; n = this._transform('0DU8ksIVlFcia2', this._base64UrlDecode(this._reverseIt(this._substitute(this._substitute(this._transform('kOCJnByYmfI', this._base64UrlDecode(this._reverseIt(this._reverseIt(this._transform('sXmH96C4vhRrgi8', this._base64UrlDecode(this._substitute(this._base64UrlDecode(n), 'djn5uT7AMR9h', 'hTn79AMjduR5'))))))), 'Km8Zb4lxr1', '48KbrZx1ml'), '1tecHq2Xbw', '1wctXeHqb2')))); return decodeURIComponent(n); },
  556. _Decode: function (n) { n = this._substitute(this._reverseIt(this._transform('3U8XtHJfgam02k', this._base64UrlDecode(this._transform('PgiY5eIZWn', this._base64UrlDecode(this._substitute(this._reverseIt(this._substitute(this._transform('QKbVomcBHysCW9', this._base64UrlDecode(this._reverseIt(this._base64UrlDecode(n)))), '0GsO8otUi21aY', 'Go1UiY82st0Oa')), 'rXjnhU3SsbEd', 'rXEsS3nbjhUd')))))), '7DtY4mHcMA2yIL', 'IM7Am4D2yYHctL'); return decodeURIComponent(n); },
  557. // --- Main extraction logic ---
  558. extractEpisodes: async function* (status) {
  559. status.textContent = 'Starting AnimeKai extraction...';
  560. const animeTitle = document.querySelector(this.animeTitle)?.textContent || 'Unknown Anime';
  561. const thumbnail = document.querySelector(this.thumbnail)?.src || '';
  562. const ani_id = document.querySelector('.rate-box#anime-rating')?.getAttribute('data-id');
  563.  
  564. if (!ani_id) {
  565. showToast("Could not find anime ID.");
  566. return;
  567. }
  568.  
  569. const headers = {
  570. 'X-Requested-With': 'XMLHttpRequest',
  571. 'Referer': window.location.href,
  572. 'Accept': 'application/json, text/javascript, */*; q=0.01', // Ensure correct accept header
  573. };
  574.  
  575. try {
  576. status.textContent = 'Fetching episode list...';
  577. const episodeListUrl = `${location.origin}/ajax/episodes/list?ani_id=${ani_id}&_=${this._GenerateToken(ani_id)}`;
  578. console.log(`Fetching episode list from: ${episodeListUrl}`);
  579. const epListResponse = await fetch(episodeListUrl, { headers });
  580. if (!epListResponse.ok) throw new Error(`Failed to fetch episode list: ${epListResponse.status}`);
  581. const epListJson = await epListResponse.json();
  582. console.log(`Episode list response:`, epListJson);
  583. const epListDoc = (new DOMParser()).parseFromString(epListJson.result, 'text/html');
  584. const episodeElements = Array.from(epListDoc.querySelectorAll('div.eplist > ul > li > a'));
  585.  
  586. const throttleLimit = 5; // Limit concurrent requests to avoid rate limiting
  587.  
  588. for (let i = 0; i < episodeElements.length; i += throttleLimit) {
  589. const chunk = episodeElements.slice(i, i + throttleLimit);
  590. const episodePromises = chunk.map(async epElement => {
  591. const epNumber = epElement.getAttribute('num');
  592. const epToken = epElement.getAttribute('token');
  593. const epTitleText = epElement.querySelector('span')?.textContent || `Episode ${epNumber}`;
  594.  
  595. if (!epNumber || !epToken) {
  596. showToast(`Skipping episode: Missing number or token.`);
  597. return null;
  598. }
  599.  
  600. try {
  601. status.textContent = `Fetching servers for Ep ${epNumber}...`;
  602. const serversUrl = `${location.origin}/ajax/links/list?token=${epToken}&_=${this._GenerateToken(epToken)}`;
  603. const serversResponse = await fetch(serversUrl, { headers });
  604. if (!serversResponse.ok) throw new Error(`Failed to fetch servers for Ep ${epNumber}: ${serversResponse.status}`);
  605. const serversJson = await serversResponse.json();
  606. const serversDoc = (new DOMParser()).parseFromString(serversJson.result, 'text/html');
  607. console.log(JSON.stringify(serversDoc));
  608.  
  609. const serverElements = serversDoc.querySelectorAll('.server-items .server');
  610.  
  611. console.log(JSON.stringify(serverElements));
  612. if (serverElements.length === 0) {
  613. showToast(`No servers found for Ep ${epNumber}.`);
  614. return null;
  615. }
  616.  
  617. status.textContent = `Processing ${serverElements.length} servers for Ep ${epNumber}...`;
  618.  
  619. for (const serverElement of serverElements) {
  620. const serverId = serverElement.getAttribute('data-lid');
  621. const serverName = serverElement.textContent || `Server_${serverId?.slice(0, 4)}`; // Fallback name
  622.  
  623. if (!serverId) {
  624. console.warn(`Skipping server: Missing ID.`);
  625. continue;
  626. }
  627.  
  628. try {
  629. // Fetch view link
  630. status.textContent = `Fetching video link for Ep ${epNumber}...`;
  631. const viewUrl = `${location.origin}/ajax/links/view?id=${serverId}&_=${this._GenerateToken(serverId)}`;
  632. const viewResponse = await fetch(viewUrl, { headers });
  633. if (!viewResponse.ok) throw new Error(`Failed to fetch view link for Ep ${epNumber}: ${viewResponse.status}`);
  634. const viewJson = await viewResponse.json();
  635. console.log(`View link response:`, viewJson);
  636.  
  637.  
  638. const decodedIframeData = JSON.parse(this._DecodeIframeData(viewJson.result));
  639. console.log(`Decoded iframe data:`, decodedIframeData);
  640.  
  641. const megaUpEmbedUrl = decodedIframeData.url;
  642.  
  643. if (!megaUpEmbedUrl) {
  644. showToast(`Could not decode embed URL for Ep ${epNumber}.`);
  645. return null;
  646. }
  647.  
  648. // Fetch MegaUp media page to get encrypted sources
  649. const mediaUrl = megaUpEmbedUrl.replace(/\/(e|e2)\//, '/media/');
  650. status.textContent = `Fetching media data for Ep ${epNumber}...`;
  651. const mediaResponse = await GM_fetch(mediaUrl, { headers: { 'Referer': location.origin } });
  652. if (!mediaResponse.ok) throw new Error(`Failed to fetch media data for Ep ${epNumber}: ${mediaResponse.status}`);
  653. const mediaJson = await mediaResponse.json();
  654. console.log(`Media data response:`, mediaJson);
  655.  
  656.  
  657. if (!mediaJson.result) {
  658. showToast(`No result found in media data for Ep ${epNumber}.`);
  659. return null;
  660. }
  661.  
  662. status.textContent = `Decoding sources for Ep ${epNumber}...`;
  663. const decryptedSources = JSON.parse(this._Decode(mediaJson.result).replace(/\\/g, ''));
  664.  
  665. const links = {};
  666. decryptedSources.sources.forEach(source => {
  667. // Try to determine quality from URL or label if available
  668. const qualityMatch = source.file.match(/(\d{3,4})[pP]/);
  669. const quality = qualityMatch ? qualityMatch[1] + 'p' : 'Default';
  670. links[quality] = { stream: source.file, type: 'm3u8' };
  671. });
  672.  
  673. status.textContent = `Extracted Ep ${epNumber}`;
  674. return new Episode(epNumber, animeTitle, links, thumbnail);
  675.  
  676. } catch (epError) {
  677. showToast(`Error processing Ep ${epNumber}: ${epError.message}`);
  678. console.error(`Error processing Ep ${epNumber}:`, epError);
  679. return null;
  680. }
  681.  
  682. }
  683. } catch (serverError) {
  684. showToast(`Error fetching servers for Ep ${epNumber}: ${serverError.message}`);
  685. console.error(`Error fetching servers for Ep ${epNumber}:`, serverError);
  686. return null;
  687. }
  688. });
  689.  
  690. yield* yieldEpisodesFromPromises(episodePromises);
  691. }
  692. } catch (error) {
  693. showToast(`Failed AnimeKai extraction: ${error.message}`);
  694. console.error("AnimeKai extraction error:", error);
  695. status.textContent = `Error: ${error.message}`;
  696. }
  697. }
  698. }
  699. ];
  700.  
  701. /**
  702. * Fetches the HTML content of a given URL and parses it into a DOM object.
  703. *
  704. * @param {string} url - The URL of the page to fetch.
  705. * @returns {Promise<Document>} A promise that resolves to a DOM Document object.
  706. * @throws {Error} If the fetch operation fails.
  707. */
  708. async function fetchPage(url) {
  709. const response = await fetch(url);
  710. if (response.ok) {
  711. const page = (new DOMParser()).parseFromString(await response.text(), 'text/html');
  712. return page;
  713. } else {
  714. showToast(`Failed to fetch HTML for ${url} : ${response.status}`);
  715. throw new Error(`Failed to fetch HTML for ${url} : ${response.status}`);
  716. }
  717. }
  718.  
  719. /**
  720. * Fetches a URL with retry logic for handling rate limits or temporary errors.
  721. *
  722. * @returns {Promise<Response>} A promise that resolves to the response object.
  723. */
  724. async function fetchWithRetry(url, options = {}, retries = 3, sleep = 1000) {
  725. const response = await fetch(url, options);
  726. if (!response.ok) {
  727. if (response.status === 503 && retries > 0) { // 503 is a common status when rate limited
  728. console.log(`Retrying ${url}, ${retries} retries remaining`);
  729. await new Promise(resolve => setTimeout(resolve, sleep)); // Wait 1 second before retrying
  730. return fetchWithRetry(url, options, retries - 1, sleep); // Pass options and sleep to the next call
  731. }
  732. throw new Error(`${response.status} - ${response.statusText}`);
  733. }
  734. return response;
  735. }
  736.  
  737. /**
  738. * Asynchronously processes an array of episode promises and yields each resolved episode.
  739. *
  740. * @param {Array<Promise>} episodePromises - An array of promises, each resolving to an episode.
  741. * @returns {AsyncGenerator} An async generator yielding each resolved episode.
  742. */
  743. async function* yieldEpisodesFromPromises(episodePromises) {
  744. for (const episodePromise of episodePromises) {
  745. const episode = await episodePromise;
  746. if (episode) {
  747. yield episode;
  748. }
  749. }
  750. }
  751.  
  752. /**
  753. * encodes a string to base64url format thats safe for URLs
  754. */
  755. const safeBtoa = str => btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  756.  
  757. /**
  758. * Analyzes the given media url to return duration, size, and resolution of the media.
  759. * @param {string} mediaUrl - The URL of the media to analyze.
  760. * @return {Promise<{duration: string, size: string, resolution: string}>} A promise that resolves to an object
  761. * containing duration (in hh:mm:ss), size of the media (in MB), and resolution (e.g., 1920x1080).
  762. * @TODO: Not Yet Implemented
  763. */
  764. async function analyzeMedia(mediaUrl) {
  765. if (_analyzedMediaCache.has(mediaUrl)) return _analyzedMediaCache.get(mediaUrl);
  766.  
  767. let metadata = { duration: 'N/A', resolution: 'N/A', size: 'N/A' };
  768. try {
  769. if (mediaUrl.endsWith('.mp4')) {
  770. const r = await GM_fetch(mediaUrl, { method: 'HEAD' });
  771. if (r.ok) {
  772. const sz = parseFloat(r.headers.get('Content-Length')) || 0;
  773. metadata.size = `${(sz / 1048576).toFixed(2)} MB`;
  774. }
  775. } else if (mediaUrl.endsWith('.m3u8')) {
  776. const r = await GM_fetch(mediaUrl);
  777. if (r.ok) {
  778. const t = await r.text();
  779. const res = t.match(/RESOLUTION=(\d+x\d+)/i);
  780. if (res) metadata.resolution = res[1];
  781. let d = 0;
  782. for (const m of t.matchAll(/#EXTINF:([\d.]+)/g)) d += parseFloat(m[1]);
  783. if (d > 0) {
  784. const h = Math.floor(d / 3600), m = Math.floor((d % 3600) / 60), s = Math.floor(d % 60);
  785. metadata.duration = [h, m, s].map(v => String(v).padStart(2, '0')).join(':');
  786. }
  787. }
  788. }
  789. if (metadata.duration === 'N/A' || metadata.resolution === 'N/A') {
  790. await new Promise(res => {
  791. const v = document.createElement('video');
  792. v.src = mediaUrl; v.preload = 'metadata'; v.muted = true;
  793. v.onloadedmetadata = () => {
  794. if (v.duration && metadata.duration === 'N/A') {
  795. const h = Math.floor(v.duration / 3600), m = Math.floor((v.duration % 3600) / 60), s = Math.floor(v.duration % 60);
  796. metadata.duration = [h, m, s].map(x => String(x).padStart(2, '0')).join(':');
  797. }
  798. if (v.videoWidth && v.videoHeight && metadata.resolution === 'N/A')
  799. metadata.resolution = `${v.videoWidth}x${v.videoHeight}`;
  800. res();
  801. };
  802. v.onerror = () => res();
  803. setTimeout(res, 2000);
  804. });
  805. }
  806. } catch (e) { }
  807. _analyzedMediaCache.set(mediaUrl, metadata);
  808. return metadata;
  809. }
  810. const _analyzedMediaCache = new Map(); // Cache to store analyzed media results for the above function
  811.  
  812.  
  813. // initialize
  814. console.log('Initializing AniLINK...');
  815. const site = websites.find(site => site.url.some(url => window.location.href.includes(url)));
  816.  
  817. // register menu command to start script
  818. GM_registerMenuCommand('Extract Episodes', extractEpisodes);
  819.  
  820. // attach start button to page
  821. try {
  822. const startBtnId = "AniLINK_startBtn";
  823. (site.addStartButton(startBtnId) || document.getElementById(startBtnId)).addEventListener('click', extractEpisodes);
  824. } catch (e) {
  825. console.error('Error adding start button:', e);
  826. }
  827.  
  828. // append site specific css styles
  829. document.body.style.cssText += (site.styles || '');
  830.  
  831. /***************************************************************
  832. * This function creates an overlay on the page and displays a list of episodes extracted from a website
  833. * The function is triggered by a user command registered with `GM_registerMenuCommand`.
  834. * The episode list is generated by calling the `extractEpisodes` method of a website object that matches the current URL.
  835. ***************************************************************/
  836. async function extractEpisodes() {
  837. // Restore last overlay if it exists
  838. if (document.getElementById("AniLINK_Overlay")) {
  839. document.getElementById("AniLINK_Overlay").style.display = "flex";
  840. return;
  841. }
  842. // Flag to control extraction process
  843. let isExtracting = true;
  844.  
  845. // --- Materialize CSS Initialization ---
  846. GM_addStyle(`
  847. @import url('https://fonts.googleapis.com/icon?family=Material+Icons');
  848.  
  849. #AniLINK_Overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.8); z-index: 1000; display: flex; align-items: center; justify-content: center; }
  850. #AniLINK_LinksContainer { width: 80%; max-height: 85%; background-color: #222; color: #eee; padding: 20px; border-radius: 8px; overflow-y: auto; display: flex; flex-direction: column;} /* Flex container for status and qualities */
  851. .anlink-status-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; } /* Header for status bar and stop button */
  852. .anlink-status-bar { color: #eee; flex-grow: 1; margin-right: 10px; display: block; } /* Status bar takes space */
  853. .anlink-status-icon { background: transparent; border: none; color: #eee; cursor: pointer; padding-right: 10px; } /* status icon style */
  854. .anlink-status-icon i { font-size: 24px; transition: transform 0.3s ease-in-out; } /* Icon size and transition */
  855. .anlink-status-icon i::before { content: 'check_circle'; } /* Show check icon when not extracting */
  856. .anlink-status-icon i.extracting::before { content: 'auto_mode'; animation: spinning 2s linear infinite; } /* Spinner animation class */
  857. .anlink-status-icon:hover i.extracting::before { content: 'stop_circle'; animation: stop; } /* Show stop icon on hover when extracting */
  858. .anlink-quality-section { margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #444; padding-bottom: 5px; }
  859. .anlink-quality-header { display: flex; justify-content: space-between; align-items: center; cursor: pointer; } /* Added cursor pointer */
  860. .anlink-quality-header > span { color: #26a69a; font-size: 1.5em; display: flex; align-items: center; flex-grow: 1; } /* Flex and align items for icon and text */
  861. .anlink-quality-header i { margin-right: 8px; transition: transform 0.3s ease-in-out; } /* Transition for icon rotation */
  862. .anlink-quality-header i.rotate { transform: rotate(90deg); } /* Rotate class */
  863. .anlink-episode-list { list-style: none; padding-left: 0; margin-top: 0; overflow: hidden; transition: max-height 0.5s ease-in-out; } /* Transition for max-height */
  864. .anlink-episode-item { margin-bottom: 5px; padding: 8px; border-bottom: 1px solid #333; display: flex; align-items: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* Single line and ellipsis for item */
  865. .anlink-episode-item:last-child { border-bottom: none; }
  866. .anlink-episode-item > label > span { user-select: none; cursor: pointer; color: #26a69a; } /* Disable selecting the 'Ep: 1' prefix */
  867. .anlink-episode-checkbox { appearance: none; width: 20px; height: 20px; margin-right: 10px; margin-bottom: -5px; border: 1px solid #26a69a; border-radius: 4px; outline: none; cursor: pointer; transition: background-color 0.3s, border-color 0.3s; }
  868. .anlink-episode-checkbox:checked { background-color: #26a69a; border-color: #26a69a; }
  869. .anlink-episode-checkbox:checked::after { content: '✔'; display: block; color: white; font-size: 14px; text-align: center; line-height: 20px; animation: checkTilt 0.3s; }
  870. .anlink-episode-link { color: #ffca28; text-decoration: none; word-break: break-all; overflow: hidden; text-overflow: ellipsis; display: inline; } /* Single line & Ellipsis for long links */
  871. .anlink-episode-link:hover { color: #fff; }
  872. .anlink-header-buttons { display: flex; gap: 10px; }
  873. .anlink-header-buttons button { background-color: #26a69a; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; }
  874. .anlink-header-buttons button:hover { background-color: #2bbbad; }
  875.  
  876. @keyframes spinning { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } /* Spinning animation */
  877. @keyframes checkTilt { from { transform: rotate(-20deg); } to { transform: rotate(0deg); } } /* Checkmark tilt animation */
  878. `);
  879.  
  880. // Create an overlay to cover the page
  881. const overlayDiv = document.createElement("div");
  882. overlayDiv.id = "AniLINK_Overlay";
  883. document.body.appendChild(overlayDiv);
  884. overlayDiv.onclick = event => linksContainer.contains(event.target) ? null : overlayDiv.style.display = "none";
  885.  
  886. // Create a container for links
  887. const linksContainer = document.createElement('div');
  888. linksContainer.id = "AniLINK_LinksContainer";
  889. overlayDiv.appendChild(linksContainer);
  890.  
  891. // Status bar header - container for status bar and status icon
  892. const statusBarHeader = document.createElement('div');
  893. statusBarHeader.className = 'anlink-status-header';
  894. linksContainer.appendChild(statusBarHeader);
  895.  
  896. // Create dynamic status icon
  897. const statusIconElement = document.createElement('a');
  898. statusIconElement.className = 'anlink-status-icon';
  899. statusIconElement.innerHTML = '<i class="material-icons extracting"></i>';
  900. statusIconElement.title = 'Stop Extracting';
  901. statusBarHeader.appendChild(statusIconElement);
  902.  
  903. statusIconElement.addEventListener('click', () => {
  904. isExtracting = false; // Set flag to stop extraction
  905. statusBar.textContent = "Extraction Stopped.";
  906. });
  907.  
  908. // Create a status bar
  909. const statusBar = document.createElement('span');
  910. statusBar.className = "anlink-status-bar";
  911. statusBar.textContent = "Extracting Links..."
  912. statusBarHeader.appendChild(statusBar);
  913.  
  914. // Create a container for qualities and episodes
  915. const qualitiesContainer = document.createElement('div');
  916. qualitiesContainer.id = "AniLINK_QualitiesContainer";
  917. linksContainer.appendChild(qualitiesContainer);
  918.  
  919.  
  920. // --- Process Episodes using Generator ---
  921. const episodeGenerator = site.extractEpisodes(statusBar);
  922. const qualityLinkLists = {}; // Stores lists of links for each quality
  923.  
  924. for await (const episode of episodeGenerator) {
  925. if (!isExtracting) { // Check if extraction is stopped
  926. statusIconElement.querySelector('i').classList.remove('extracting'); // Stop spinner animation
  927. statusBar.textContent = "Extraction Stopped By User.";
  928. return; // Exit if extraction is stopped
  929. }
  930. if (!episode) continue; // Skip if episode is null (error during extraction)
  931.  
  932. // Get all links into format - {[qual1]:[ep1,2,3,4], [qual2]:[ep1,2,3,4], ...}
  933. for (const quality in episode.links) {
  934. qualityLinkLists[quality] = qualityLinkLists[quality] || [];
  935. qualityLinkLists[quality].push(episode);
  936. }
  937.  
  938. // Update UI in real-time - RENDER UI HERE BASED ON qualityLinkLists
  939. renderQualityLinkLists(qualityLinkLists, qualitiesContainer);
  940. }
  941. isExtracting = false; // Extraction completed
  942. statusIconElement.querySelector('i').classList.remove('extracting');
  943. statusBar.textContent = "Extraction Complete!";
  944.  
  945.  
  946. // Renders quality link lists inside a given container element
  947. function renderQualityLinkLists(sortedLinks, container) {
  948. // Track expanded state for each quality section
  949. const expandedState = {};
  950. container.querySelectorAll('.anlink-quality-section').forEach(section => {
  951. const quality = section.dataset.quality;
  952. const episodeList = section.querySelector('.anlink-episode-list');
  953. expandedState[quality] = episodeList && episodeList.style.maxHeight !== '0px';
  954. });
  955.  
  956. for (const quality in sortedLinks) {
  957. let qualitySection = container.querySelector(`.anlink-quality-section[data-quality="${quality}"]`);
  958. let episodeListElem;
  959.  
  960. const episodes = sortedLinks[quality].sort((a, b) => a.number - b.number);
  961.  
  962. if (!qualitySection) {
  963. // Create new section if it doesn't exist
  964. qualitySection = document.createElement('div');
  965. qualitySection.className = 'anlink-quality-section';
  966. qualitySection.dataset.quality = quality;
  967.  
  968. const headerDiv = document.createElement('div'); // Header div for quality-string and buttons - ROW
  969. headerDiv.className = 'anlink-quality-header';
  970.  
  971. // Create a span for the clickable header text and icon
  972. const qualitySpan = document.createElement('span');
  973. qualitySpan.innerHTML = `<i style="opacity: 0.5">(${sortedLinks[quality].length})</i> <i class="material-icons">chevron_right</i> ${quality}`;
  974. qualitySpan.addEventListener('click', toggleQualitySection);
  975. headerDiv.appendChild(qualitySpan);
  976.  
  977.  
  978. // --- Create Speed Dial Button in the Quality Section ---
  979. const headerButtons = document.createElement('div');
  980. headerButtons.className = 'anlink-header-buttons';
  981. headerButtons.innerHTML = `
  982. <button type="button" class="anlink-select-links">Select</button>
  983. <button type="button" class="anlink-copy-links">Copy</button>
  984. <button type="button" class="anlink-export-links">Export</button>
  985. <button type="button" class="anlink-play-links">Play with MPV</button>
  986. `;
  987. headerDiv.appendChild(headerButtons);
  988. qualitySection.appendChild(headerDiv);
  989.  
  990. // --- Add Empty episodes list elm to the quality section ---
  991. episodeListElem = document.createElement('ul');
  992. episodeListElem.className = 'anlink-episode-list';
  993. episodeListElem.style.maxHeight = '0px';
  994. qualitySection.appendChild(episodeListElem);
  995.  
  996. container.appendChild(qualitySection);
  997.  
  998. // Attach handlers
  999. attachBtnClickListeners(episodes, qualitySection);
  1000. } else {
  1001. // Update header count
  1002. const qualitySpan = qualitySection.querySelector('.anlink-quality-header > span');
  1003. if (qualitySpan) {
  1004. qualitySpan.innerHTML = `<i style="opacity: 0.5">(${sortedLinks[quality].length})</i> <i class="material-icons">chevron_right</i> ${quality}`;
  1005. }
  1006. episodeListElem = qualitySection.querySelector('.anlink-episode-list');
  1007. }
  1008.  
  1009. // Update episode list items
  1010. episodeListElem.innerHTML = '';
  1011. episodes.forEach(ep => {
  1012. const listItem = document.createElement('li');
  1013. listItem.className = 'anlink-episode-item';
  1014. listItem.innerHTML = `
  1015. <label>
  1016. <input type="checkbox" class="anlink-episode-checkbox" />
  1017. <span id="mpv-epnum" title="Play in MPV">Ep ${ep.number.replace(/^0+/, '')}: </span>
  1018. <a href="${ep.links[quality].stream}" class="anlink-episode-link" download="${encodeURI(ep.filename)}" data-epnum="${ep.number}" data-ep=${encodeURI(JSON.stringify({ ...ep, links: undefined }))} >${ep.links[quality].stream}</a>
  1019. </label>
  1020. `;
  1021. const episodeLinkElement = listItem.querySelector('.anlink-episode-link');
  1022. const epnumSpan = listItem.querySelector('#mpv-epnum');
  1023. const link = episodeLinkElement.href;
  1024. const name = decodeURIComponent(episodeLinkElement.download);
  1025.  
  1026. // On hover, show MPV icon & file name
  1027. listItem.addEventListener('mouseenter', () => {
  1028. window.getSelection().isCollapsed && (episodeLinkElement.textContent = name);
  1029. epnumSpan.innerHTML = `<img width="20" height="20" fill="#26a69a" style="vertical-align:middle;" src="https://a.fsdn.com/allura/p/mpv-player-windows/icon?1517058933"> ${ep.number.replace(/^0+/, '')}: `;
  1030. });
  1031. listItem.addEventListener('mouseleave', () => {
  1032. episodeLinkElement.textContent = decodeURIComponent(link);
  1033. epnumSpan.textContent = `Ep ${ep.number.replace(/^0+/, '')}: `;
  1034. });
  1035. epnumSpan.addEventListener('click', e => {
  1036. e.preventDefault();
  1037. location.replace('mpv://play/' + safeBtoa(link) + `/?v_title=${safeBtoa(name)}` + `&cookies=${location.hostname}.txt`);
  1038. showToast('Sent to MPV. If nothing happened, install <a href="https://github.com/akiirui/mpv-handler" target="_blank" style="color:#1976d2;">mpv-handler</a>.');
  1039. });
  1040.  
  1041. episodeListElem.appendChild(listItem);
  1042. });
  1043.  
  1044. // Restore expand state only if section was previously expanded
  1045. if (expandedState[quality]) {
  1046. const icon = qualitySection.querySelector('.material-icons');
  1047. episodeListElem.style.maxHeight = `${episodeListElem.scrollHeight}px`;
  1048. icon.classList.add('rotate');
  1049. }
  1050. }
  1051. }
  1052.  
  1053. function toggleQualitySection(event) {
  1054. // Target the closest anlink-quality-header span to ensure only clicks on the text/icon trigger toggle
  1055. const qualitySpan = event.currentTarget;
  1056. const headerDiv = qualitySpan.parentElement;
  1057. const qualitySection = headerDiv.closest('.anlink-quality-section');
  1058. const episodeList = qualitySection.querySelector('.anlink-episode-list');
  1059. const icon = qualitySpan.querySelector('.material-icons'); // Query icon within the span
  1060. const isCollapsed = episodeList.style.maxHeight === '0px';
  1061.  
  1062. if (isCollapsed) {
  1063. episodeList.style.maxHeight = `${episodeList.scrollHeight}px`; // Expand to content height
  1064. icon.classList.add('rotate'); // Rotate icon on expand
  1065. } else {
  1066. episodeList.style.maxHeight = '0px'; // Collapse
  1067. icon.classList.remove('rotate'); // Reset icon rotation
  1068. }
  1069. }
  1070.  
  1071. // Attach click listeners to the speed dial buttons for each quality section
  1072. function attachBtnClickListeners(episodeList, qualitySection) {
  1073. const buttonActions = [
  1074. { selector: '.anlink-select-links', handler: onSelectBtnPressed },
  1075. { selector: '.anlink-copy-links', handler: onCopyBtnClicked },
  1076. { selector: '.anlink-export-links', handler: onExportBtnClicked },
  1077. { selector: '.anlink-play-links', handler: onPlayBtnClicked }
  1078. ];
  1079.  
  1080. buttonActions.forEach(({ selector, handler }) => {
  1081. const button = qualitySection.querySelector(selector);
  1082. button.addEventListener('click', () => handler(button, episodeList, qualitySection));
  1083. });
  1084.  
  1085. // Helper function to get checked episode items within a quality section
  1086. function _getSelectedEpisodeItems(qualitySection) {
  1087. return Array.from(qualitySection.querySelectorAll('.anlink-episode-item input[type="checkbox"]:checked'))
  1088. .map(checkbox => checkbox.closest('.anlink-episode-item'));
  1089. }
  1090.  
  1091. // Helper function to prepare m3u8 playlist string from given episodes
  1092. function _preparePlaylist(episodes, quality) {
  1093. let playlistContent = '#EXTM3U\n';
  1094. episodes.forEach(episode => {
  1095. const linkObj = episode.links[quality];;
  1096. if (!linkObj) {
  1097. showToast(`No link found for source ${quality} in episode ${episode.number}`);
  1098. return;
  1099. }
  1100. // Add tracks if present (subtitles, audio, etc.)
  1101. if (linkObj.tracks && Array.isArray(linkObj.tracks) && linkObj.tracks.length > 0) {
  1102. linkObj.tracks.forEach((track, idx) => {
  1103. // EXT-X-MEDIA for subtitles or alternate audio
  1104. if (track.kind && track.kind.startsWith('audio')) {
  1105. playlistContent += `#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"audio${idx}\",NAME=\"${track.label || 'Audio'}\",DEFAULT=${track.default ? 'YES' : 'NO'},URI=\"${track.file}\"\n`;
  1106. } else if ((track.kind && track.kind.startsWith('caption')) || track.kind === 'subtitles' || track.kind === 'captions') {
  1107. playlistContent += `#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs${idx}\",NAME=\"${track.label || 'Subtitle'}\",DEFAULT=${track.default ? 'YES' : 'NO'},URI=\"${track.file}\"\n`;
  1108. }
  1109. });
  1110. }
  1111. playlistContent += `#EXTINF:-1,${episode.filename}\n`;
  1112. playlistContent += `${linkObj.stream}\n`;
  1113. });
  1114. return playlistContent;
  1115. }
  1116.  
  1117. // Select Button click event handler
  1118. function onSelectBtnPressed(button, episodes, qualitySection) {
  1119. const episodeItems = qualitySection.querySelector('.anlink-episode-list').querySelectorAll('.anlink-episode-item');
  1120. const checkboxes = Array.from(qualitySection.querySelectorAll('.anlink-episode-item input[type="checkbox"]'));
  1121. const allChecked = checkboxes.every(cb => cb.checked);
  1122. const anyUnchecked = checkboxes.some(cb => !cb.checked);
  1123.  
  1124. if (anyUnchecked || allChecked === false) { // If any unchecked OR not all are checked (for the first click when none are checked)
  1125. checkboxes.forEach(checkbox => { checkbox.checked = true; }); // Check all
  1126. // Select all link texts
  1127. const range = new Range();
  1128. range.selectNodeContents(episodeItems[0]);
  1129. range.setEndAfter(episodeItems[episodeItems.length - 1]);
  1130. window.getSelection().removeAllRanges();
  1131. window.getSelection().addRange(range);
  1132. button.textContent = 'Deselect All'; // Change button text to indicate deselect
  1133. } else { // If all are already checked
  1134. checkboxes.forEach(checkbox => { checkbox.checked = false; }); // Uncheck all
  1135. window.getSelection().removeAllRanges(); // Clear selection
  1136. button.textContent = 'Select All'; // Revert button text
  1137. }
  1138. setTimeout(() => { button.textContent = checkboxes.some(cb => !cb.checked) ? 'Select All' : 'Deselect All'; }, 1500); // slight delay revert text
  1139. }
  1140.  
  1141. // copySelectedLinks click event handler
  1142. function onCopyBtnClicked(button, episodes, qualitySection) {
  1143. const selectedItems = _getSelectedEpisodeItems(qualitySection);
  1144. const linksToCopy = selectedItems.length ? selectedItems.map(item => item.querySelector('.anlink-episode-link').href) : Array.from(qualitySection.querySelectorAll('.anlink-episode-item')).map(item => item.querySelector('.anlink-episode-link').href);
  1145.  
  1146. const string = linksToCopy.join('\n');
  1147. navigator.clipboard.writeText(string);
  1148. button.textContent = 'Copied Selected';
  1149. setTimeout(() => { button.textContent = 'Copy'; }, 1000);
  1150. }
  1151.  
  1152. // exportToPlaylist click event handler
  1153. function onExportBtnClicked(button, episodes, qualitySection) {
  1154. const quality = qualitySection.dataset.quality;
  1155. const selectedItems = _getSelectedEpisodeItems(qualitySection);
  1156.  
  1157. const items = selectedItems.length ? selectedItems : Array.from(qualitySection.querySelectorAll('.anlink-episode-item'));
  1158. const playlist = _preparePlaylist(episodes.filter(ep => items.find(i => i.querySelector(`[data-epnum="${ep.number}"]`))), quality);
  1159. const fileName = JSON.parse(decodeURI(items[0]?.querySelector('.anlink-episode-link')?.dataset.ep)).animeTitle + `${GM_getValue('include_source_in_filename', true) ? ` [${quality}]` : ''}.m3u8`;
  1160. const file = new Blob([playlist], { type: 'application/vnd.apple.mpegurl' });
  1161. const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(file), download: fileName });
  1162. a.click();
  1163.  
  1164. button.textContent = 'Exported Selected';
  1165. setTimeout(() => { button.textContent = 'Export'; }, 1000);
  1166. }
  1167.  
  1168. // Play click event handler
  1169. async function onPlayBtnClicked(button, episodes, qualitySection) {
  1170. const quality = qualitySection.dataset.quality;
  1171. const selectedEpisodeItems = _getSelectedEpisodeItems(qualitySection);
  1172. const items = selectedEpisodeItems.length ? selectedEpisodeItems : Array.from(qualitySection.querySelectorAll('.anlink-episode-item'));
  1173. const epList = episodes.filter(ep => items.find(i => i.querySelector(`[data-epnum="${ep.number}"]`))).filter(Boolean);
  1174.  
  1175. button.textContent = 'Processing...';
  1176. const playlistContent = _preparePlaylist(epList, quality);
  1177. const uploadUrl = await GM_fetch("https://paste.rs/", {
  1178. method: "POST",
  1179. body: playlistContent
  1180. }).then(r => r.text()).then(t => t + '.m3u8');
  1181. console.log(`Playlist URL:`, uploadUrl);
  1182.  
  1183. // Use mpv:// protocol to pass the paste.rs link to mpv (requires mpv-handler installed)
  1184. const mpvUrl = 'mpv://play/' + safeBtoa(uploadUrl.trim()) + '/?v_title=' + safeBtoa(epList[0].animeTitle);
  1185. location.replace(mpvUrl);
  1186.  
  1187. button.textContent = 'Sent to MPV';
  1188. setTimeout(() => { button.textContent = 'Play with MPV'; }, 2000);
  1189. setTimeout(() => {
  1190. showToast('If nothing happened, you need to install <a href="https://github.com/akiirui/mpv-handler" target="_blank" style="color:#1976d2;">mpv-handler</a> to enable this feature.');
  1191. }, 1000);
  1192. }
  1193. }
  1194. }
  1195.  
  1196. /***************************************************************
  1197. * Modern Episode Range Selector with Keyboard Navigation
  1198. ***************************************************************/
  1199. async function showEpisodeRangeSelector(total) {
  1200. return new Promise(resolve => {
  1201. const modal = Object.assign(document.createElement('div'), {
  1202. innerHTML: `
  1203. <div class="anlink-modal-backdrop">
  1204. <div class="anlink-modal">
  1205. <div class="anlink-modal-header">
  1206. <div class="anlink-modal-icon">📺</div>
  1207. <h2>Episode Range</h2>
  1208. <div class="anlink-episode-count">${total} episodes found</div>
  1209. <small style="display:block;color:#ccc;font-size:11px;margin-top:2px;">
  1210. Note: Range is by episode count, not episode number<br>(e.g., 1-6 means the first 6 episodes listed).
  1211. </small>
  1212. </div>
  1213. <div class="anlink-modal-body">
  1214. <div class="anlink-range-inputs">
  1215. <div class="anlink-input-group">
  1216. <label>From</label>
  1217. <input type="number" id="start" min="1" max="${total}" value="1" tabindex="1">
  1218. </div>
  1219. <div class="anlink-range-divider">—</div>
  1220. <div class="anlink-input-group">
  1221. <label>To</label>
  1222. <input type="number" id="end" min="1" max="${total}" value="${Math.min(24, total)}" tabindex="2">
  1223. </div>
  1224. </div>
  1225. <div class="anlink-quick-select">
  1226. <button class="anlink-quick-btn" data-range="1,24" tabindex="3">First 24</button>
  1227. <button class="anlink-quick-btn" data-range="${Math.max(1, total - 23)},${total}" tabindex="4">Last 24</button>
  1228. <button class="anlink-quick-btn" data-range="1,${total}" tabindex="5">All ${total}</button>
  1229. </div>
  1230. <div class="anlink-help-text">
  1231. Use <kbd>Tab</kbd> to navigate • <kbd>↑↓</kbd> to adjust values <kbd>Enter</kbd> to extract • <kbd>Esc</kbd> to cancel
  1232. </div>
  1233. </div>
  1234. <div class="anlink-modal-footer">
  1235. <button class="anlink-btn anlink-btn-cancel" data-key="Escape" tabindex="6"><kbd>Esc</kbd> Cancel</button>
  1236. <button class="anlink-btn anlink-btn-primary" data-key="Enter" tabindex="7"><kbd>Enter</kbd> Extract</button>
  1237. </div>
  1238. </div>
  1239. </div>
  1240. `,
  1241. style: 'position:fixed;top:0;left:0;width:100%;height:100%;z-index:1001;'
  1242. });
  1243.  
  1244. // Enhanced styling with keyboard indicators
  1245. GM_addStyle(`
  1246. .anlink-modal-backdrop { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; background: rgba(0,0,0,0.8); backdrop-filter: blur(4px); }
  1247. .anlink-modal { background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%); border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.4); width: 420px; max-width: 90vw; color: #fff; overflow: hidden; }
  1248. .anlink-modal-header { text-align: center; padding: 24px 24px 16px; background: linear-gradient(135deg, #26a69a 0%, #20847a 100%); }
  1249. .anlink-modal-icon { font-size: 48px; margin-bottom: 8px; }
  1250. .anlink-modal h2 { margin: 0 0 8px; font-size: 24px; font-weight: 600; }
  1251. .anlink-episode-count { opacity: 0.9; font-size: 14px; }
  1252. .anlink-modal-body { padding: 24px; }
  1253. .anlink-range-inputs { display: flex; align-items: center; gap: 16px; margin-bottom: 20px; }
  1254. .anlink-input-group { flex: 1; }
  1255. .anlink-input-group label { display: block; margin-bottom: 8px; font-size: 14px; color: #26a69a; font-weight: 500; }
  1256. .anlink-input-group input { width: 100%; padding: 12px; border: 2px solid #444; border-radius: 8px; background: #1a1a1a; color: #fff; font-size: 16px; text-align: center; transition: all 0.2s; }
  1257. .anlink-input-group input:focus { outline: none; border-color: #26a69a; box-shadow: 0 0 0 3px rgba(38,166,154,0.1); }
  1258. .anlink-range-divider { color: #26a69a; font-weight: bold; font-size: 18px; margin-top: 24px; }
  1259. .anlink-quick-select { display: flex; gap: 8px; margin-bottom: 16px; }
  1260. .anlink-quick-btn { flex: 1; padding: 8px 12px; border: 1px solid #444; border-radius: 6px; background: transparent; color: #ccc; cursor: pointer; font-size: 12px; transition: all 0.2s; position: relative; }
  1261. .anlink-quick-btn:hover, .anlink-quick-btn:focus { border-color: #26a69a; color: #26a69a; background: rgba(38,166,154,0.1); outline: none; } .anlink-help-text { font-size: 11px; color: #888; text-align: center; margin-top: 12px; }
  1262. .anlink-modal-footer { display: flex; gap: 12px; padding: 0 24px 24px; }
  1263. .anlink-btn { flex: 1; padding: 12px 24px; border: none; border-radius: 8px; font-size: 14px; font-weight: 500; cursor: pointer; transition: all 0.2s; position: relative; }
  1264. .anlink-btn:focus { outline: 2px solid #26a69a; outline-offset: 2px; }
  1265. .anlink-btn-cancel { background: #444; color: #ccc; }
  1266. .anlink-btn-cancel:hover, .anlink-btn-cancel:focus { background: #555; }
  1267. .anlink-btn-primary { background: linear-gradient(135deg, #26a69a 0%, #20847a 100%); color: #fff; }
  1268. .anlink-btn-primary:hover, .anlink-btn-primary:focus { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(38,166,154,0.3); }
  1269. kbd { background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); border-radius: 3px; padding: 1px 4px; font-size: 10px; margin-right: 4px; }
  1270. `);
  1271.  
  1272. document.body.appendChild(modal);
  1273.  
  1274. const [startInput, endInput] = modal.querySelectorAll('input');
  1275. const buttons = modal.querySelectorAll('button');
  1276. const primaryBtn = modal.querySelector('.anlink-btn-primary');
  1277. const cancelBtn = modal.querySelector('.anlink-btn-cancel');
  1278.  
  1279. const validate = () => {
  1280. const s = Math.max(1, Math.min(total, +startInput.value));
  1281. const e = Math.max(s, Math.min(total, +endInput.value));
  1282. startInput.value = s; endInput.value = e;
  1283. };
  1284.  
  1285. const cleanup = () => modal.remove();
  1286. const accept = () => { validate(); cleanup(); resolve({ start: +startInput.value, end: +endInput.value }); };
  1287. const cancel = () => { cleanup(); resolve(null); };
  1288.  
  1289. // Keyboard navigation with arrow keys for number inputs
  1290. modal.addEventListener('keydown', e => {
  1291. switch (e.key) {
  1292. case 'Escape': e.preventDefault(); cancel(); break;
  1293. case 'Enter': e.preventDefault(); accept(); break;
  1294. case 'f': case 'F':
  1295. if (!e.target.matches('input') && !e.ctrlKey && !e.altKey) {
  1296. e.preventDefault();
  1297. startInput.focus();
  1298. startInput.select();
  1299. }
  1300. break;
  1301. }
  1302. });
  1303.  
  1304. // Input validation and arrow key navigation for number inputs
  1305. [startInput, endInput].forEach(input => {
  1306. input.addEventListener('input', validate);
  1307. input.addEventListener('keydown', e => {
  1308. if (e.key === 'ArrowUp') {
  1309. e.preventDefault();
  1310. input.value = Math.min(total, (+input.value || 0) + 1);
  1311. validate();
  1312. } else if (e.key === 'ArrowDown') {
  1313. e.preventDefault();
  1314. input.value = Math.max(1, (+input.value || 2) - 1);
  1315. validate();
  1316. } else if (e.key === 'Tab' && !e.shiftKey && input === endInput) {
  1317. e.preventDefault();
  1318. modal.querySelector('.anlink-quick-btn').focus();
  1319. }
  1320. });
  1321. });
  1322. // Quick select buttons
  1323. modal.querySelectorAll('.anlink-quick-btn').forEach((btn, index) => {
  1324. btn.addEventListener('click', () => {
  1325. const [s, e] = btn.dataset.range.split(',').map(Number);
  1326. startInput.value = s;
  1327. endInput.value = e;
  1328. validate();
  1329. // Focus extract button after quick select
  1330. setTimeout(() => primaryBtn.focus(), 100);
  1331. });
  1332.  
  1333. // Arrow key navigation between quick select buttons
  1334. btn.addEventListener('keydown', e => {
  1335. if (e.key === 'ArrowLeft' && index > 0) {
  1336. e.preventDefault();
  1337. modal.querySelectorAll('.anlink-quick-btn')[index - 1].focus();
  1338. } else if (e.key === 'ArrowRight' && index < 2) {
  1339. e.preventDefault();
  1340. modal.querySelectorAll('.anlink-quick-btn')[index + 1].focus();
  1341. } else if (e.key === 'Tab' && !e.shiftKey && index === 2) {
  1342. e.preventDefault();
  1343. cancelBtn.focus();
  1344. }
  1345. });
  1346. });
  1347. // Button handlers with enhanced keyboard navigation
  1348. cancelBtn.addEventListener('click', cancel);
  1349. cancelBtn.addEventListener('keydown', e => {
  1350. if (e.key === 'ArrowRight') {
  1351. e.preventDefault();
  1352. primaryBtn.focus();
  1353. }
  1354. });
  1355.  
  1356. primaryBtn.addEventListener('click', accept);
  1357. primaryBtn.addEventListener('keydown', e => {
  1358. if (e.key === 'ArrowLeft') {
  1359. e.preventDefault();
  1360. cancelBtn.focus();
  1361. }
  1362. });
  1363.  
  1364. // Focus management - start with first input and select all text
  1365. setTimeout(() => {
  1366. startInput.focus();
  1367. startInput.select();
  1368. }, 100);
  1369. });
  1370. }
  1371.  
  1372. /***************************************************************
  1373. * Apply episode range filtering with modern UI
  1374. ***************************************************************/
  1375. async function applyEpisodeRangeFilter(allEpLinks, status) {
  1376. const epRangeThreshold = GM_getValue('ep_range_threshold', 12)
  1377. if (allEpLinks.length <= epRangeThreshold) return allEpLinks;
  1378.  
  1379. status.textContent = `Found ${allEpLinks.length} episodes. Waiting for selection...`;
  1380. const selection = await showEpisodeRangeSelector(allEpLinks.length);
  1381.  
  1382. if (!selection) {
  1383. status.textContent = 'Cancelled by user.';
  1384. return null;
  1385. }
  1386.  
  1387. const filtered = allEpLinks.slice(selection.start - 1, selection.end);
  1388. status.textContent = `Extracting episodes ${selection.start}-${selection.end} of ${allEpLinks.length}...`;
  1389. return filtered;
  1390. }
  1391.  
  1392. /***************************************************************
  1393. * Display a simple toast message on the top right of the screen
  1394. ***************************************************************/
  1395. let toasts = [];
  1396.  
  1397. function showToast(message) {
  1398. const maxToastHeight = window.innerHeight * 0.5;
  1399. const toastHeight = 50; // Approximate height of each toast
  1400. const maxToasts = Math.floor(maxToastHeight / toastHeight);
  1401.  
  1402. console.log(message);
  1403.  
  1404. // Create the new toast element
  1405. const x = document.createElement("div");
  1406. x.innerHTML = message;
  1407. x.style.color = "#000";
  1408. x.style.backgroundColor = "#fdba2f";
  1409. x.style.borderRadius = "10px";
  1410. x.style.padding = "10px";
  1411. x.style.position = "fixed";
  1412. x.style.top = `${toasts.length * toastHeight}px`;
  1413. x.style.right = "5px";
  1414. x.style.fontSize = "large";
  1415. x.style.fontWeight = "bold";
  1416. x.style.zIndex = "10000";
  1417. x.style.display = "block";
  1418. x.style.borderColor = "#565e64";
  1419. x.style.transition = "right 2s ease-in-out, top 0.5s ease-in-out";
  1420. document.body.appendChild(x);
  1421.  
  1422. // Add the new toast to the list
  1423. toasts.push(x);
  1424.  
  1425. // Remove the toast after it slides out
  1426. setTimeout(() => {
  1427. x.style.right = "-1000px";
  1428. }, 3000);
  1429.  
  1430. setTimeout(() => {
  1431. x.style.display = "none";
  1432. if (document.body.contains(x)) document.body.removeChild(x);
  1433. toasts = toasts.filter(toast => toast !== x);
  1434. // Move remaining toasts up
  1435. toasts.forEach((toast, index) => {
  1436. toast.style.top = `${index * toastHeight}px`;
  1437. });
  1438. }, 4000);
  1439.  
  1440. // Limit the number of toasts to maxToasts
  1441. if (toasts.length > maxToasts) {
  1442. const oldestToast = toasts.shift();
  1443. document.body.removeChild(oldestToast);
  1444. toasts.forEach((toast, index) => {
  1445. toast.style.top = `${index * toastHeight}px`;
  1446. });
  1447. }
  1448. }
  1449.  
  1450. // On overlay open, show a help link for mpv-handler if not detected
  1451. function showMPVHandlerHelp() {
  1452. showToast('To play directly in MPV, install <a href="https://github.com/akiirui/mpv-handler" target="_blank" style="color:#1976d2;">mpv-handler</a> and reload this page.');
  1453. }