Greasy Fork 还支持 简体中文。

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