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!

当前为 2025-04-22 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name AniLINK - Episode Link Extractor
  3. // @namespace https://greasyfork.org/en/users/781076-jery-js
  4. // @version 6.5.0
  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. // ==/UserScript==
  41.  
  42. class Episode {
  43. constructor(number, animeTitle, links, thumbnail, epTitle) {
  44. this.number = number; // The episode number
  45. this.animeTitle = animeTitle; // The title of the anime.
  46. this.epTitle = epTitle; // The title of the episode (this can be the specific ep title or blank).
  47. 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"}]}}}
  48. 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).
  49. this.name = `${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.
  50. this.title = this.epTitle ?? this.animeTitle;
  51. }
  52. }
  53.  
  54. /**
  55. * @typedef {Object} Websites[]
  56. * @property {string} name - The name of the website (required).
  57. * @property {string[]} url - An array of URL patterns that identify the website (required).
  58. * @property {string} thumbnail - A CSS selector to identify the episode thumbnail on the website (required).
  59. * @property {Function} addStartButton - A function to add the "Generate Download Links" button to the website (required).
  60. * @property {AsyncGeneratorFunction} extractEpisodes - An async generator function to extract episode information from the website (required).
  61. * @property {string} epLinks - A CSS selector to identify the episode links on the website (optional).
  62. * @property {string} epTitle - A CSS selector to identify the episode title on the website (optional).
  63. * @property {string} linkElems - A CSS selector to identify the download link elements on the website (optional).
  64. * @property {string} [animeTitle] - A CSS selector to identify the anime title on the website (optional).
  65. * @property {string} [epNum] - A CSS selector to identify the episode number on the website (optional).
  66. * @property {Function} [_getVideoLinks] - A function to extract video links from the website (optional).
  67. * @property {string} [styles] - Custom CSS styles to be applied to the website (optional).
  68. *
  69. * @description An array of website configurations for extracting episode links.
  70. *
  71. * @note To add a new website, follow these steps:
  72. * 1. Create a new object with the following properties:
  73. * - `name`: The name of the website.
  74. * - `url`: An array of URL patterns that identify the website.
  75. * - `thumbnail`: A CSS selector to identify the episode thumbnail on the website.
  76. * - `addStartButton`: A function to add the "Generate Download Links" button to the website.
  77. * - `extractEpisodes`: An async generator function to extract episode information from the website.
  78. * 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):
  79. * - `animeTitle`: A CSS selector to identify the anime title on the website.
  80. * - `epLinks`: A CSS selector to identify the episode links on the website.
  81. * - `epTitle`: A CSS selector to identify the episode title on the website.
  82. * - `linkElems`: A CSS selector to identify the download link elements on the website.
  83. * - `epNum`: A CSS selector to identify the episode number on the website.
  84. * - `_getVideoLinks`: A function to extract video links from the website.
  85. * - `styles`: Custom CSS styles to be applied to the website.
  86. * 3. Implement the `addStartButton` function to add the "Generate Download Links" button to the website.
  87. * - This function should create a element and append it to the appropriate location on the website.
  88. * - The button should have an ID of "AniLINK_startBtn".
  89. * 4. Implement the `extractEpisodes` function to extract episode information from the website.
  90. * - This function should be an async generator function that yields Episode objects (To ensure fast processing, using chunks is recommended).
  91. * - Use the `fetchPage` function to fetch the HTML content of each episode page.
  92. * - Parse the HTML content to extract the episode title, number, links, and thumbnail.
  93. * - Create an `Episode` object for each episode and yield it using the `yieldEpisodesFromPromises` function.
  94. * 5. Optionally, implement the `_getVideoLinks` function to extract video links from the website.
  95. * - This function should return a promise that resolves to an object containing video links.
  96. * - Use this function if the video links require additional processing or API calls.
  97. * - 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).
  98. */
  99. const websites = [
  100. {
  101. name: 'GoGoAnime',
  102. url: ['anitaku.to/', 'gogoanime3.co/', 'gogoanime3', 'anitaku', 'gogoanime'],
  103. epLinks: '#episode_related > li > a',
  104. epTitle: '.title_name > h2',
  105. linkElems: '.cf-download > a',
  106. thumbnail: '.headnav_left > a > img',
  107. addStartButton: function() {
  108. const button = Object.assign(document.createElement('a'), {
  109. id: "AniLINK_startBtn",
  110. style: "cursor: pointer; background-color: #145132;",
  111. innerHTML: document.querySelector("div.user_auth a[href='/login.html']")
  112. ? `<b style="color:#FFC119;">AniLINK:</b> Please <a href="/login.html"><u>log in</u></a> to download`
  113. : '<i class="icongec-dowload"></i> Generate Download Links'
  114. });
  115. const target = location.href.includes('/category/') ? '#episode_page' : '.cf-download';
  116. document.querySelector(target)?.appendChild(button);
  117. return button;
  118. },
  119. extractEpisodes: async function* (status) {
  120. status.textContent = 'Starting...';
  121. const throttleLimit = 12; // Number of episodes to extract in parallel
  122. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  123. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  124. const chunk = epLinks.slice(i, i + throttleLimit);
  125. const episodePromises = chunk.map(async epLink => { try {
  126. const page = await fetchPage(epLink.href);
  127.  
  128. const [, epTitle, epNumber] = page.querySelector(this.epTitle).textContent.match(/(.+?) Episode (\d+(?:\.\d+)?)/);
  129. const thumbnail = page.querySelector(this.thumbnail).src;
  130. status.textContent = `Extracting ${epTitle} - ${epNumber.padStart(3, '0')}...`;
  131. const links = [...page.querySelectorAll(this.linkElems)].reduce((obj, elem) => ({ ...obj, [elem.textContent.trim()]: { stream: elem.href, type: 'mp4' } }), {});
  132. status.textContent = `Extracted ${epTitle} - ${epNumber.padStart(3, '0')}`;
  133.  
  134. return new Episode(epNumber, epTitle, links, thumbnail); // Return Episode object
  135. } catch (e) { showToast(e); return null; } }); // Handle errors and return null
  136.  
  137. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  138. }
  139. }
  140. },
  141. {
  142. name: 'YugenAnime',
  143. url: ['yugenanime.tv', 'yugenanime.sx'],
  144. epLinks: '.ep-card > a.ep-thumbnail',
  145. animeTitle: '.ani-info-ep .link h1',
  146. epTitle: 'div.col.col-w-65 > div.box > h1',
  147. thumbnail: 'a.ep-thumbnail img',
  148. addStartButton: function() {
  149. return document.querySelector(".content .navigation").appendChild(Object.assign(document.createElement('a'), { id: "AniLINK_startBtn", className: "link p-15", textContent: "Generate Download Links" }));
  150. },
  151. extractEpisodes: async function* (status) {
  152. status.textContent = 'Getting list of episodes...';
  153. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  154. const throttleLimit = 6; // Number of episodes to extract in parallel
  155.  
  156. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  157. const chunk = epLinks.slice(i, i + throttleLimit);
  158. const episodePromises = chunk.map(async (epLink, index) => { try {
  159. status.textContent = `Loading ${epLink.pathname}`;
  160. const page = await fetchPage(epLink.href);
  161.  
  162. const animeTitle = page.querySelector(this.animeTitle).textContent;
  163. const epNumber = epLink.href.match(/(\d+)\/?$/)[1];
  164. const epTitle = page.querySelector(this.epTitle).textContent.match(/^${epNumber} : (.+)$/) || animeTitle;
  165. const thumbnail = document.querySelectorAll(this.thumbnail)[index].src;
  166. status.textContent = `Extracting ${`${epNumber.padStart(3, '0')} - ${animeTitle}` + (epTitle != animeTitle ? `- ${epTitle}` : '')}...`;
  167. const rawLinks = await this._getVideoLinks(page, status, epTitle);
  168. const links = Object.entries(rawLinks).reduce((acc, [quality, url]) => ({...acc, [quality]: { stream: url, type: 'm3u8' }}), {});
  169.  
  170. return new Episode(epNumber, epTitle, links, thumbnail);
  171. } catch (e) { showToast(e); return null; } });
  172. yield* yieldEpisodesFromPromises(episodePromises);
  173. }
  174. },
  175. _getVideoLinks: async function (page, status, episodeTitle) {
  176. const embedLinkId = page.body.innerHTML.match(new RegExp(`src="//${page.domain}/e/(.*?)/"`))[1];
  177. const embedApiResponse = await fetch(`https://${page.domain}/api/embed/`, { method: 'POST', headers: {"X-Requested-With": "XMLHttpRequest"}, body: new URLSearchParams({ id: embedLinkId, ac: "0" }) });
  178. const json = await embedApiResponse.json();
  179. const m3u8GeneralLink = json.hls[0];
  180. status.textContent = `Parsing ${episodeTitle}...`;
  181. // Fetch the m3u8 file content
  182. const m3u8Response = await fetch(m3u8GeneralLink);
  183. const m3u8Text = await m3u8Response.text();
  184. // Parse the m3u8 file to extract different qualities
  185. const qualityMatches = m3u8Text.matchAll(/#EXT-X-STREAM-INF:.*RESOLUTION=\d+x\d+.*NAME="(\d+p)"\n(.*\.m3u8)/g);
  186. const links = {};
  187. for (const match of qualityMatches) {
  188. const [_, quality, m3u8File] = match;
  189. links[quality] = `${m3u8GeneralLink.slice(0, m3u8GeneralLink.lastIndexOf('/') + 1)}${m3u8File}`;
  190. }
  191. return links;
  192. }
  193. },
  194. {
  195. name: 'AnimePahe',
  196. url: ['animepahe.ru', 'animepahe.com', 'animepahe.org'],
  197. epLinks: (location.pathname.startsWith('/anime/'))? '.play': '.dropup.episode-menu .dropdown-item',
  198. epTitle: '.theatre-info > h1',
  199. linkElems: '#resolutionMenu > button',
  200. thumbnail: '.theatre-info > a > img',
  201. addStartButton: function() {
  202. GM_addStyle(`.theatre-settings .col-sm-3 { max-width: 20%; }`);
  203. (document.location.pathname.startsWith('/anime/'))
  204. ? document.querySelector(".col-6.bar").innerHTML += `
  205. <div class="btn-group btn-group-toggle">
  206. <label id="AniLINK_startBtn" class="btn btn-dark btn-sm">Generate Download Links</label>
  207. </div>`
  208. : document.querySelector("div.theatre-settings > div.row").innerHTML += `
  209. <div class="col-12 col-sm-3">
  210. <div class="dropup">
  211. <a class="btn btn-secondary btn-block" id="AniLINK_startBtn">
  212. Generate Download Links
  213. </a>
  214. </div>
  215. </div>
  216. `;
  217. return document.getElementById("AniLINK_startBtn");
  218. },
  219. extractEpisodes: async function* (status) {
  220. status.textContent = 'Starting...';
  221. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  222. const throttleLimit = 36; // Setting high throttle limit actually improves performance
  223.  
  224. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  225. const chunk = epLinks.slice(i, i + throttleLimit);
  226. const episodePromises = chunk.map(async epLink => { try {
  227. const page = await fetchPage(epLink.href);
  228.  
  229. if (page.querySelector(this.epTitle) == null) return;
  230. const [, animeTitle, epNumber] = page.querySelector(this.epTitle).outerText.split(/Watch (.+) - (\d+(?:\.\d+)?) Online$/);
  231. const thumbnail = page.querySelector(this.thumbnail).src;
  232. status.textContent = `Extracting ${animeTitle} - ${epNumber.padStart(3, "0")}...`;
  233.  
  234. async function getVideoUrl(kwikUrl) {
  235. const response = await fetch(kwikUrl, { headers: { "Referer": "https://animepahe.com" } });
  236. const data = await response.text();
  237. return eval(/(eval)(\(f.*?)(\n<\/script>)/s.exec(data)[2].replace("eval", "")).match(/https.*?m3u8/)[0];
  238. }
  239. let links = {};
  240. for (const elm of [...page.querySelectorAll(this.linkElems)]) {
  241. links[elm.textContent] = { stream: await getVideoUrl(elm.getAttribute('data-src')), type: 'm3u8' };
  242. status.textContent = `Parsed ${`${epNumber.padStart(3, '0')} - ${animeTitle}`}`;
  243. }
  244. return new Episode(epNumber, animeTitle, links, thumbnail);
  245. } catch (e) { showToast(e); return null; } });
  246. yield* yieldEpisodesFromPromises(episodePromises);
  247. }
  248. },
  249. styles: `div#AniLINK_LinksContainer { font-size: 10px; } #Quality > b > div > ul {font-size: 16px;}`
  250. },
  251. {
  252. name: 'Beta-Otaku-Streamers',
  253. url: ['beta.otaku-streamers.com'],
  254. epLinks: (document.location.pathname.startsWith('/title/')) ? '.item-title a' : '.video-container .clearfix > a',
  255. epTitle: '.title > a',
  256. epNum: '.watch_curep',
  257. thumbnail: 'video',
  258. addStartButton: function() {
  259. (document.location.pathname.startsWith('/title/')
  260. ? document.querySelector(".album-top-box"): document.querySelector('.video-container .title-box'))
  261. .innerHTML += `<a id="AniLINK_startBtn" class="btn btn-outline rounded-btn">Generate Download Links</a>`;
  262. return document.getElementById("AniLINK_startBtn");
  263. },
  264. extractEpisodes: async function* (status) {
  265. status.textContent = 'Starting...';
  266. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  267. const throttleLimit = 12;
  268.  
  269. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  270. const chunk = epLinks.slice(i, i + throttleLimit);
  271. const episodePromises = chunk.map(async epLink => { try {
  272. const page = await fetchPage(epLink.href);
  273. const epTitle = page.querySelector(this.epTitle).textContent.trim();
  274. const epNumber = page.querySelector(this.epNum).textContent.replace("Episode ", '');
  275. const thumbnail = page.querySelector(this.thumbnail).poster;
  276.  
  277. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  278. const links = { 'Video Links': { stream: page.querySelector('video > source').src, type: 'mp4' }};
  279.  
  280. return new Episode(epNumber, epTitle, links, thumbnail);
  281. } catch (e) { showToast(e); return null; } });
  282. yield* yieldEpisodesFromPromises(episodePromises);
  283. }
  284. }
  285. },
  286. {
  287. name: 'Otaku-Streamers',
  288. url: ['otaku-streamers.com'],
  289. epLinks: 'table > tbody > tr > td:nth-child(2) > a',
  290. epTitle: '#strw_player > table > tbody > tr:nth-child(1) > td > span:nth-child(1) > a',
  291. epNum: '#video_episode',
  292. thumbnail: 'otaku-streamers.com/images/os.jpg',
  293. addStartButton: function() {
  294. const button = document.createElement('a');
  295. button.id = "AniLINK_startBtn";
  296. button.style.cssText = `cursor: pointer; background-color: #145132; float: right;`;
  297. button.innerHTML = 'Generate Download Links';
  298. document.querySelector('table > tbody > tr:nth-child(2) > td > div > table > tbody > tr > td > h2').appendChild(button);
  299. return button;
  300. },
  301. extractEpisodes: async function* (status) {
  302. status.textContent = 'Starting...';
  303. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  304. const throttleLimit = 12; // Number of episodes to extract in parallel
  305.  
  306. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  307. const chunk = epLinks.slice(i, i + throttleLimit);
  308. const episodePromises = chunk.map(async epLink => { try {
  309. const page = await fetchPage(epLink.href);
  310. const epTitle = page.querySelector(this.epTitle).textContent;
  311. const epNumber = page.querySelector(this.epNum).textContent.replace("Episode ", '')
  312.  
  313. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  314. const links = {'mp4': { stream: page.querySelector('video > source').src, type: 'mp4' }};
  315.  
  316. return new Episode(epNumber, epTitle, links, this.thumbnail); // Return Episode object
  317. } catch (e) { showToast(e); return null; } }); // Handle errors and return null
  318.  
  319. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  320. }
  321. }
  322. },
  323. {
  324. name: 'AnimeHeaven',
  325. url: ['animeheaven.me'],
  326. epLinks: 'a.ac3',
  327. epTitle: 'a.c2.ac2',
  328. epNumber: '.boxitem.bc2.c1.mar0',
  329. thumbnail: 'img.posterimg',
  330. addStartButton: function() {
  331. const button = document.createElement('a');
  332. button.id = "AniLINK_startBtn";
  333. button.style.cssText = `cursor: pointer; border: 2px solid red; padding: 4px;`;
  334. button.innerHTML = 'Generate Download Links';
  335. document.querySelector("div.linetitle2.c2").parentNode.insertBefore(button, document.querySelector("div.linetitle2.c2"));
  336. return button;
  337. },
  338. extractEpisodes: async function* (status) {
  339. status.textContent = 'Starting...';
  340. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  341. const throttleLimit = 12; // Number of episodes to extract in parallel
  342.  
  343. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  344. const chunk = epLinks.slice(i, i + throttleLimit);
  345. const episodePromises = chunk.map(async epLink => { try {
  346. const page = await fetchPage(epLink.href);
  347. const epTitle = page.querySelector(this.epTitle).textContent;
  348. const epNumber = page.querySelector(this.epNumber).textContent.replace("Episode ", '');
  349. const thumbnail = document.querySelector(this.thumbnail).src;
  350.  
  351. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  352. const links = [...page.querySelectorAll('#vid > source')].reduce((acc, source) => ({...acc, [source.src.match(/\/\/(\w+)\./)[1]]: { stream: source.src, type: 'mp4' }}), {});
  353.  
  354. return new Episode(epNumber, epTitle, links, thumbnail); // Return Episode object
  355. } catch (e) { showToast(e); return null; } }); // Handle errors and return null
  356.  
  357. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  358. }
  359. }
  360. },
  361. {
  362. name: 'AnimeZ',
  363. url: ['animez.org'],
  364. epLinks: '.list-chapter .wp-manga-chapter a',
  365. epTitle: '#title-detail-manga',
  366. epNum: '.wp-manga-chapter.active',
  367. thumbnail: '.Image > figure > img',
  368. addStartButton: function() {
  369. (document.querySelector(".MovieTabNav.ControlPlayer") || document.querySelector(".mb-3:has(#keyword_chapter)"))
  370. .innerHTML += `<div class="Lnk AAIco-link" id="AniLINK_startBtn">Extract Episode Links</div>`;
  371. return document.getElementById("AniLINK_startBtn");
  372. },
  373. extractEpisodes: async function* (status) {
  374. status.textContent = 'Starting...';
  375. const epLinks = Array.from(document.querySelectorAll(this.epLinks))
  376. .filter((el, index, self) => self.findIndex(e => e.href === el.href && e.textContent.trim() === el.textContent.trim()) === index);;
  377. const throttleLimit = 12; // Number of episodes to extract in parallel
  378.  
  379. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  380. const chunk = epLinks.slice(i, i + throttleLimit);
  381. const episodePromises = chunk.map(async epLink => { try {
  382. const page = await fetchPage(epLink.href);
  383. const epTitle = page.querySelector(this.epTitle).textContent;
  384. const isDub = page.querySelector(this.epNum).textContent.includes('-Dub');
  385. const epNumber = page.querySelector(this.epNum).textContent.replace(/-Dub/, '').trim();
  386. const thumbnail = document.querySelector(this.thumbnail).src;
  387.  
  388. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  389. const links = {[isDub ? "Dub" : "Sub"]: { stream: page.querySelector('iframe').src.replace('/embed/', '/anime/'), type: 'm3u8' }};
  390.  
  391. return new Episode(epNumber, epTitle, links, thumbnail); // Return Episode object
  392. } catch (e) { showToast(e); return null; } }); // Handle errors and return null
  393.  
  394. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  395. }
  396. }
  397. },
  398. {
  399. name: 'Miruro',
  400. url: ['miruro.to', 'miruro.tv', 'miruro.online'],
  401. animeTitle: '.anime-title > a',
  402. thumbnail: 'a[href^="/info?id="] > img',
  403. baseApiUrl: `${location.origin}/api`,
  404. addStartButton: function(id) {
  405. const intervalId = setInterval(() => {
  406. const target = document.querySelector('.title-actions-container');
  407. if (target) {
  408. clearInterval(intervalId);
  409. const btn = document.createElement('button');
  410. btn.id = id;
  411. btn.style.cssText = "display: flex; justifyContent: center;";
  412. btn.className = "sc-dpGNEc eZVSAR";
  413. btn.innerHTML = `
  414. <i style="font-size: 18px" class="material-icons">download</i>
  415. <div style="display: flex; justify-content: center; align-items: center;">Extract Episode Links</div>
  416. `;
  417. btn.addEventListener('click', extractEpisodes);
  418. target.appendChild(btn);
  419. }
  420. }, 200);
  421. },
  422. extractEpisodes: async function* (status) {
  423. status.textContent = 'Fetching episode list...';
  424. const animeTitle = document.querySelector(this.animeTitle).textContent;
  425. const malId = document.querySelector(`a[href*="/myanimelist.net/anime/"]`)?.href.split('/').pop();
  426. if (!malId) return showToast('MAL ID not found.');
  427.  
  428. const res = await fetch(`${this.baseApiUrl}/episodes?malId=${malId}`).then(r => r.json());
  429. const providers = Object.entries(res).map(([p, s]) => {
  430. const v = Object.values(s)[0], ep = v?.episodeList?.episodes || v?.episodeList;
  431. return ep && { source: p.toLowerCase(), animeId: Object.keys(s)[0], useEpId: !!v?.episodeList?.episodes, epList: ep };
  432. }).filter(Boolean);
  433.  
  434. // Get the provider with most episodes to use as base for thumbnails, epTitle, epNumber, etc.
  435. const baseProvider = providers.find(p=> p.epList.length == Math.max(...providers.map(p => p.epList.length)));
  436.  
  437. if (!baseProvider) return showToast('No episodes found.');
  438.  
  439. for (const baseEp of baseProvider.epList) {
  440. const num = String(baseEp.number).padStart(3, '0');
  441. let epTitle = baseEp.title, thumbnail = baseEp.snapshot; // will try to update with other providers if this is blank
  442.  
  443. status.textContent = `Fetching Ep ${num}...`;
  444. let links = {};
  445. await Promise.all(providers.map(async ({ source, animeId, useEpId, epList }) => {
  446. const ep = epList.find(ep => ep.number == baseEp.number);
  447. epTitle = epTitle || ep.title; // update title if blank
  448. const epId = !useEpId ? `${animeId}/ep-${ep.number}` : ep.id;
  449. try {
  450. const sres = await fetchWithRetry(`${this.baseApiUrl}/sources?episodeId=${epId}&provider=${source}`);
  451. const sresJson = await sres.json();
  452. links[this._getLocalSourceName(source)] = { stream: sresJson.streams[0].url, type: "m3u8", tracks: sresJson.tracks || [] };
  453. } catch (e) { showToast(`Failed to fetch ep-${ep.number} from ${source}: ${e}`); return null; }
  454. }));
  455.  
  456. if (!epTitle || /^Episode \d+/.test(epTitle)) epTitle = undefined; // remove epTitle if episode title is blank or just "Episode X"
  457. yield new Episode(num, animeTitle, links, thumbnail || document.querySelector(this.thumbnail).src, epTitle);
  458. }
  459. },
  460. _getLocalSourceName: function (source) {
  461. const sourceNames = {'animepahe': 'kiwi', 'animekai': 'arc', 'animez': 'jet', 'zoro': 'zoro'};
  462. return sourceNames[source] || source.charAt(0).toUpperCase() + source.slice(1);
  463. },
  464. },
  465. // AnimeKai is not fully implemented yet... its a work in progress...
  466. {
  467. name: 'AnimeKai',
  468. url: ['animekai.to/watch/'],
  469. animeTitle: '.title',
  470. thumbnail: 'img',
  471. addStartButton: function() {
  472. const button = Object.assign(document.createElement('button'), {
  473. id: "AniLINK_startBtn",
  474. className: "btn btn-primary", // Use existing site styles
  475. textContent: "Generate Download Links",
  476. style: "margin-left: 10px;"
  477. });
  478. // Add button next to the episode list controls or similar area
  479. const target = document.querySelector('.episode-section');
  480. if (target) {
  481. target.appendChild(button);
  482. } else {
  483. // Fallback location if the primary target isn't found
  484. document.querySelector('.eplist-nav')?.appendChild(button);
  485. }
  486. return button;
  487. },
  488. // --- Helper functions adapted from provided code ---
  489. _reverseIt: (n) => n.split('').reverse().join(''),
  490. _base64UrlEncode: (str) => btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''),
  491. _base64UrlDecode: (n) => { n = n.padEnd(n.length + ((4 - (n.length % 4)) % 4), '=').replace(/-/g, '+').replace(/_/g, '/'); return atob(n); },
  492. _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(''); },
  493. _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; },
  494. _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' ) ); },
  495. _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); },
  496. _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); },
  497. // --- Main extraction logic ---
  498. extractEpisodes: async function* (status) {
  499. status.textContent = 'Starting AnimeKai extraction...';
  500. const animeTitle = document.querySelector(this.animeTitle)?.textContent || 'Unknown Anime';
  501. const thumbnail = document.querySelector(this.thumbnail)?.src || '';
  502. const ani_id = document.querySelector('.rate-box#anime-rating')?.getAttribute('data-id');
  503.  
  504. if (!ani_id) {
  505. showToast("Could not find anime ID.");
  506. return;
  507. }
  508.  
  509. const headers = {
  510. 'X-Requested-With': 'XMLHttpRequest',
  511. 'Referer': window.location.href,
  512. 'Accept': 'application/json, text/javascript, */*; q=0.01', // Ensure correct accept header
  513. };
  514.  
  515. try {
  516. status.textContent = 'Fetching episode list...';
  517. const episodeListUrl = `${location.origin}/ajax/episodes/list?ani_id=${ani_id}&_=${this._GenerateToken(ani_id)}`;
  518. console.log(`Fetching episode list from: ${episodeListUrl}`);
  519. const epListResponse = await fetch(episodeListUrl, { headers });
  520. if (!epListResponse.ok) throw new Error(`Failed to fetch episode list: ${epListResponse.status}`);
  521. const epListJson = await epListResponse.json();
  522. console.log(`Episode list response:`, epListJson);
  523. const epListDoc = (new DOMParser()).parseFromString(epListJson.result, 'text/html');
  524. const episodeElements = Array.from(epListDoc.querySelectorAll('div.eplist > ul > li > a'));
  525.  
  526. const throttleLimit = 5; // Limit concurrent requests to avoid rate limiting
  527.  
  528. for (let i = 0; i < episodeElements.length; i += throttleLimit) {
  529. const chunk = episodeElements.slice(i, i + throttleLimit);
  530. const episodePromises = chunk.map(async epElement => {
  531. const epNumber = epElement.getAttribute('num');
  532. const epToken = epElement.getAttribute('token');
  533. const epTitleText = epElement.querySelector('span')?.textContent || `Episode ${epNumber}`;
  534.  
  535. if (!epNumber || !epToken) {
  536. showToast(`Skipping episode: Missing number or token.`);
  537. return null;
  538. }
  539.  
  540. try {
  541. status.textContent = `Fetching servers for Ep ${epNumber}...`;
  542. const serversUrl = `${location.origin}/ajax/links/list?token=${epToken}&_=${this._GenerateToken(epToken)}`;
  543. const serversResponse = await fetch(serversUrl, { headers });
  544. if (!serversResponse.ok) throw new Error(`Failed to fetch servers for Ep ${epNumber}: ${serversResponse.status}`);
  545. const serversJson = await serversResponse.json();
  546. const serversDoc = (new DOMParser()).parseFromString(serversJson.result, 'text/html');
  547. console.log(JSON.stringify(serversDoc));
  548.  
  549. const serverElements = serversDoc.querySelectorAll('.server-items .server');
  550. console.log(JSON.stringify(serverElements));
  551. if (serverElements.length === 0) {
  552. showToast(`No servers found for Ep ${epNumber}.`);
  553. return null;
  554. }
  555.  
  556. status.textContent = `Processing ${serverElements.length} servers for Ep ${epNumber}...`;
  557.  
  558. for (const serverElement of serverElements) {
  559. const serverId = serverElement.getAttribute('data-lid');
  560. const serverName = serverElement.textContent || `Server_${serverId?.slice(0, 4)}`; // Fallback name
  561.  
  562. if (!serverId) {
  563. console.warn(`Skipping server: Missing ID.`);
  564. continue;
  565. }
  566.  
  567. try {
  568. // Fetch view link
  569. status.textContent = `Fetching video link for Ep ${epNumber}...`;
  570. const viewUrl = `${location.origin}/ajax/links/view?id=${serverId}&_=${this._GenerateToken(serverId)}`;
  571. const viewResponse = await fetch(viewUrl, { headers });
  572. if (!viewResponse.ok) throw new Error(`Failed to fetch view link for Ep ${epNumber}: ${viewResponse.status}`);
  573. const viewJson = await viewResponse.json();
  574. console.log(`View link response:`, viewJson);
  575.  
  576. const decodedIframeData = JSON.parse(this._DecodeIframeData(viewJson.result));
  577. console.log(`Decoded iframe data:`, decodedIframeData);
  578. const megaUpEmbedUrl = decodedIframeData.url;
  579.  
  580. if (!megaUpEmbedUrl) {
  581. showToast(`Could not decode embed URL for Ep ${epNumber}.`);
  582. return null;
  583. }
  584.  
  585. // Fetch MegaUp media page to get encrypted sources
  586. const mediaUrl = megaUpEmbedUrl.replace(/\/(e|e2)\//, '/media/');
  587. status.textContent = `Fetching media data for Ep ${epNumber}...`;
  588. const mediaResponse = await GM_fetch(mediaUrl, { headers: { 'Referer': location.origin } });
  589. if (!mediaResponse.ok) throw new Error(`Failed to fetch media data for Ep ${epNumber}: ${mediaResponse.status}`);
  590. const mediaJson = await mediaResponse.json();
  591. console.log(`Media data response:`, mediaJson);
  592.  
  593. if (!mediaJson.result) {
  594. showToast(`No result found in media data for Ep ${epNumber}.`);
  595. return null;
  596. }
  597.  
  598. status.textContent = `Decoding sources for Ep ${epNumber}...`;
  599. const decryptedSources = JSON.parse(this._Decode(mediaJson.result).replace(/\\/g, ''));
  600.  
  601. const links = {};
  602. decryptedSources.sources.forEach(source => {
  603. // Try to determine quality from URL or label if available
  604. const qualityMatch = source.file.match(/(\d{3,4})[pP]/);
  605. const quality = qualityMatch ? qualityMatch[1] + 'p' : 'Default';
  606. links[quality] = { stream: source.file, type: 'm3u8' };
  607. });
  608.  
  609. status.textContent = `Extracted Ep ${epNumber}`;
  610. return new Episode(epNumber, animeTitle, links, thumbnail);
  611.  
  612. } catch (epError) {
  613. showToast(`Error processing Ep ${epNumber}: ${epError.message}`);
  614. console.error(`Error processing Ep ${epNumber}:`, epError);
  615. return null;
  616. }
  617. }
  618. } catch (serverError) {
  619. showToast(`Error fetching servers for Ep ${epNumber}: ${serverError.message}`);
  620. console.error(`Error fetching servers for Ep ${epNumber}:`, serverError);
  621. return null;
  622. }
  623. });
  624.  
  625. yield* yieldEpisodesFromPromises(episodePromises);
  626. }
  627. } catch (error) {
  628. showToast(`Failed AnimeKai extraction: ${error.message}`);
  629. console.error("AnimeKai extraction error:", error);
  630. status.textContent = `Error: ${error.message}`;
  631. }
  632. }
  633. }
  634. ];
  635.  
  636. /**
  637. * Fetches the HTML content of a given URL and parses it into a DOM object.
  638. *
  639. * @param {string} url - The URL of the page to fetch.
  640. * @returns {Promise<Document>} A promise that resolves to a DOM Document object.
  641. * @throws {Error} If the fetch operation fails.
  642. */
  643. async function fetchPage(url) {
  644. const response = await fetch(url);
  645. if (response.ok) {
  646. const page = (new DOMParser()).parseFromString(await response.text(), 'text/html');
  647. return page;
  648. } else {
  649. showToast(`Failed to fetch HTML for ${url} : ${response.status}`);
  650. throw new Error(`Failed to fetch HTML for ${url} : ${response.status}`);
  651. }
  652. }
  653.  
  654. /**
  655. * Fetches a URL with retry logic for handling rate limits or temporary errors.
  656. *
  657. * @returns {Promise<Response>} A promise that resolves to the response object.
  658. */
  659. async function fetchWithRetry(url, options = {}, retries = 3, sleep = 1000) {
  660. const response = await fetch(url, options);
  661. if (!response.ok) {
  662. if (response.status === 503 && retries > 0) { // 503 is a common status when rate limited
  663. console.log(`Retrying ${url}, ${retries} retries remaining`);
  664. await new Promise(resolve => setTimeout(resolve, sleep)); // Wait 1 second before retrying
  665. return fetchWithRetry(url, options, retries - 1, sleep); // Pass options and sleep to the next call
  666. }
  667. throw new Error(`${response.status} - ${response.statusText}`);
  668. }
  669. return response;
  670. }
  671.  
  672. /**
  673. * Asynchronously processes an array of episode promises and yields each resolved episode.
  674. *
  675. * @param {Array<Promise>} episodePromises - An array of promises, each resolving to an episode.
  676. * @returns {AsyncGenerator} An async generator yielding each resolved episode.
  677. */
  678. async function* yieldEpisodesFromPromises(episodePromises) {
  679. for (const episodePromise of episodePromises) {
  680. const episode = await episodePromise;
  681. if (episode) {
  682. yield episode;
  683. }
  684. }
  685. }
  686.  
  687. /**
  688. * encodes a string to base64url format thats safe for URLs
  689. */
  690. const safeBtoa = str => btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  691.  
  692.  
  693.  
  694. // initialize
  695. console.log('Initializing AniLINK...');
  696. const site = websites.find(site => site.url.some(url => window.location.href.includes(url)));
  697.  
  698. // register menu command to start script
  699. GM_registerMenuCommand('Extract Episodes', extractEpisodes);
  700.  
  701. // attach start button to page
  702. try {
  703. const startBtnId = "AniLINK_startBtn";
  704. (site.addStartButton(startBtnId) || document.getElementById(startBtnId)).addEventListener('click', extractEpisodes);
  705. } catch (e) {
  706. console.error('Error adding start button:', e);
  707. }
  708.  
  709. // append site specific css styles
  710. document.body.style.cssText += (site.styles || '');
  711.  
  712. /***************************************************************
  713. * This function creates an overlay on the page and displays a list of episodes extracted from a website
  714. * The function is triggered by a user command registered with `GM_registerMenuCommand`.
  715. * The episode list is generated by calling the `extractEpisodes` method of a website object that matches the current URL.
  716. ***************************************************************/
  717. async function extractEpisodes() {
  718. // Restore last overlay if it exists
  719. if (document.getElementById("AniLINK_Overlay")) {
  720. document.getElementById("AniLINK_Overlay").style.display = "flex";
  721. return;
  722. }
  723. // Flag to control extraction process
  724. let isExtracting = true;
  725.  
  726. // --- Materialize CSS Initialization ---
  727. GM_addStyle(`
  728. @import url('https://fonts.googleapis.com/icon?family=Material+Icons');
  729.  
  730. #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; }
  731. #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 */
  732. .anlink-status-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; } /* Header for status bar and stop button */
  733. .anlink-status-bar { color: #eee; flex-grow: 1; margin-right: 10px; display: block; } /* Status bar takes space */
  734. .anlink-status-icon { background: transparent; border: none; color: #eee; cursor: pointer; padding-right: 10px; } /* status icon style */
  735. .anlink-status-icon i { font-size: 24px; transition: transform 0.3s ease-in-out; } /* Icon size and transition */
  736. .anlink-status-icon i::before { content: 'check_circle'; } /* Show check icon when not extracting */
  737. .anlink-status-icon i.extracting::before { content: 'auto_mode'; animation: spinning 2s linear infinite; } /* Spinner animation class */
  738. .anlink-status-icon:hover i.extracting::before { content: 'stop_circle'; animation: stop; } /* Show stop icon on hover when extracting */
  739. .anlink-quality-section { margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #444; padding-bottom: 5px; }
  740. .anlink-quality-header { display: flex; justify-content: space-between; align-items: center; cursor: pointer; } /* Added cursor pointer */
  741. .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 */
  742. .anlink-quality-header i { margin-right: 8px; transition: transform 0.3s ease-in-out; } /* Transition for icon rotation */
  743. .anlink-quality-header i.rotate { transform: rotate(90deg); } /* Rotate class */
  744. .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 */
  745. .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 */
  746. .anlink-episode-item:last-child { border-bottom: none; }
  747. .anlink-episode-item > label > span { user-select: none; cursor: pointer; color: #26a69a; } /* Disable selecting the 'Ep: 1' prefix */
  748. .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; }
  749. .anlink-episode-checkbox:checked { background-color: #26a69a; border-color: #26a69a; }
  750. .anlink-episode-checkbox:checked::after { content: '✔'; display: block; color: white; font-size: 14px; text-align: center; line-height: 20px; animation: checkTilt 0.3s; }
  751. .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 */
  752. .anlink-episode-link:hover { color: #fff; }
  753. .anlink-header-buttons { display: flex; gap: 10px; }
  754. .anlink-header-buttons button { background-color: #26a69a; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; }
  755. .anlink-header-buttons button:hover { background-color: #2bbbad; }
  756.  
  757. @keyframes spinning { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } /* Spinning animation */
  758. @keyframes checkTilt { from { transform: rotate(-20deg); } to { transform: rotate(0deg); } } /* Checkmark tilt animation */
  759. `);
  760.  
  761. // Create an overlay to cover the page
  762. const overlayDiv = document.createElement("div");
  763. overlayDiv.id = "AniLINK_Overlay";
  764. document.body.appendChild(overlayDiv);
  765. overlayDiv.onclick = event => linksContainer.contains(event.target) ? null : overlayDiv.style.display = "none";
  766.  
  767. // Create a container for links
  768. const linksContainer = document.createElement('div');
  769. linksContainer.id = "AniLINK_LinksContainer";
  770. overlayDiv.appendChild(linksContainer);
  771.  
  772. // Status bar header - container for status bar and status icon
  773. const statusBarHeader = document.createElement('div');
  774. statusBarHeader.className = 'anlink-status-header';
  775. linksContainer.appendChild(statusBarHeader);
  776.  
  777. // Create dynamic status icon
  778. const statusIconElement = document.createElement('a');
  779. statusIconElement.className = 'anlink-status-icon';
  780. statusIconElement.innerHTML = '<i class="material-icons extracting"></i>';
  781. statusIconElement.title = 'Stop Extracting';
  782. statusBarHeader.appendChild(statusIconElement);
  783.  
  784. statusIconElement.addEventListener('click', () => {
  785. isExtracting = false; // Set flag to stop extraction
  786. statusBar.textContent = "Extraction Stopped.";
  787. });
  788.  
  789. // Create a status bar
  790. const statusBar = document.createElement('span');
  791. statusBar.className = "anlink-status-bar";
  792. statusBar.textContent = "Extracting Links..."
  793. statusBarHeader.appendChild(statusBar);
  794.  
  795. // Create a container for qualities and episodes
  796. const qualitiesContainer = document.createElement('div');
  797. qualitiesContainer.id = "AniLINK_QualitiesContainer";
  798. linksContainer.appendChild(qualitiesContainer);
  799.  
  800.  
  801. // --- Process Episodes using Generator ---
  802. const episodeGenerator = site.extractEpisodes(statusBar);
  803. const qualityLinkLists = {}; // Stores lists of links for each quality
  804.  
  805. for await (const episode of episodeGenerator) {
  806. if (!isExtracting) { // Check if extraction is stopped
  807. statusIconElement.querySelector('i').classList.remove('extracting'); // Stop spinner animation
  808. statusBar.textContent = "Extraction Stopped By User.";
  809. return; // Exit if extraction is stopped
  810. }
  811. if (!episode) continue; // Skip if episode is null (error during extraction)
  812.  
  813. // Get all links into format - {[qual1]:[ep1,2,3,4], [qual2]:[ep1,2,3,4], ...}
  814. for (const quality in episode.links) {
  815. qualityLinkLists[quality] = qualityLinkLists[quality] || [];
  816. qualityLinkLists[quality].push(episode);
  817. }
  818.  
  819. // Update UI in real-time - RENDER UI HERE BASED ON qualityLinkLists
  820. renderQualityLinkLists(qualityLinkLists, qualitiesContainer);
  821. }
  822. isExtracting = false; // Extraction completed
  823. statusIconElement.querySelector('i').classList.remove('extracting');
  824. statusBar.textContent = "Extraction Complete!";
  825.  
  826.  
  827. // Renders quality link lists inside a given container element
  828. function renderQualityLinkLists(sortedLinks, container) {
  829. // Track expanded state for each quality section
  830. const expandedState = {};
  831. container.querySelectorAll('.anlink-quality-section').forEach(section => {
  832. const quality = section.dataset.quality;
  833. const episodeList = section.querySelector('.anlink-episode-list');
  834. expandedState[quality] = episodeList && episodeList.style.maxHeight !== '0px';
  835. });
  836.  
  837. for (const quality in sortedLinks) {
  838. let qualitySection = container.querySelector(`.anlink-quality-section[data-quality="${quality}"]`);
  839. let episodeListElem;
  840.  
  841. const episodes = sortedLinks[quality].sort((a, b) => a.number - b.number);
  842.  
  843. if (!qualitySection) {
  844. // Create new section if it doesn't exist
  845. qualitySection = document.createElement('div');
  846. qualitySection.className = 'anlink-quality-section';
  847. qualitySection.dataset.quality = quality;
  848.  
  849. const headerDiv = document.createElement('div'); // Header div for quality-string and buttons - ROW
  850. headerDiv.className = 'anlink-quality-header';
  851.  
  852. // Create a span for the clickable header text and icon
  853. const qualitySpan = document.createElement('span');
  854. qualitySpan.innerHTML = `<i style="opacity: 0.5">(${sortedLinks[quality].length})</i> <i class="material-icons">chevron_right</i> ${quality}`;
  855. qualitySpan.addEventListener('click', toggleQualitySection);
  856. headerDiv.appendChild(qualitySpan);
  857.  
  858.  
  859. // --- Create Speed Dial Button in the Quality Section ---
  860. const headerButtons = document.createElement('div');
  861. headerButtons.className = 'anlink-header-buttons';
  862. headerButtons.innerHTML = `
  863. <button type="button" class="anlink-select-links">Select</button>
  864. <button type="button" class="anlink-copy-links">Copy</button>
  865. <button type="button" class="anlink-export-links">Export</button>
  866. <button type="button" class="anlink-play-links">Play with MPV</button>
  867. `;
  868. headerDiv.appendChild(headerButtons);
  869. qualitySection.appendChild(headerDiv);
  870.  
  871. // --- Add Empty episodes list elm to the quality section ---
  872. episodeListElem = document.createElement('ul');
  873. episodeListElem.className = 'anlink-episode-list';
  874. episodeListElem.style.maxHeight = '0px';
  875. qualitySection.appendChild(episodeListElem);
  876.  
  877. container.appendChild(qualitySection);
  878.  
  879. // Attach handlers
  880. attachBtnClickListeners(episodes, qualitySection);
  881. } else {
  882. // Update header count
  883. const qualitySpan = qualitySection.querySelector('.anlink-quality-header > span');
  884. if (qualitySpan) {
  885. qualitySpan.innerHTML = `<i style="opacity: 0.5">(${sortedLinks[quality].length})</i> <i class="material-icons">chevron_right</i> ${quality}`;
  886. }
  887. episodeListElem = qualitySection.querySelector('.anlink-episode-list');
  888. }
  889.  
  890. // Update episode list items
  891. episodeListElem.innerHTML = '';
  892. episodes.forEach(ep => {
  893. const listItem = document.createElement('li');
  894. listItem.className = 'anlink-episode-item';
  895. listItem.innerHTML = `
  896. <label>
  897. <input type="checkbox" class="anlink-episode-checkbox" />
  898. <span id="mpv-epnum" title="Play in MPV">Ep ${ep.number.replace(/^0+/, '')}: </span>
  899. <a href="${ep.links[quality].stream}" class="anlink-episode-link" download="${encodeURI(ep.name)}" data-epnum="${ep.number}" title="${ep.title.replace(/[<>:"/\\|?*]/g, '')}" ep-title="${ep.title.replace(/[<>:"/\\|?*]/g, '')}">${ep.links[quality].stream}</a>
  900. </label>
  901. `;
  902. const episodeLinkElement = listItem.querySelector('.anlink-episode-link');
  903. const epnumSpan = listItem.querySelector('#mpv-epnum');
  904. const link = episodeLinkElement.href;
  905. const name = decodeURIComponent(episodeLinkElement.download);
  906. // On hover, show MPV icon & file name
  907. listItem.addEventListener('mouseenter', () => {
  908. window.getSelection().isCollapsed && (episodeLinkElement.textContent = name);
  909. 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+/, '')}: `;
  910. });
  911. listItem.addEventListener('mouseleave', () => {
  912. episodeLinkElement.textContent = decodeURIComponent(link);
  913. epnumSpan.textContent = `Ep ${ep.number.replace(/^0+/, '')}: `;
  914. });
  915. epnumSpan.addEventListener('click', e => {
  916. e.preventDefault();
  917. location.replace('mpv://play/' + safeBtoa(link) + `/?v_title=${safeBtoa(name)}` + `&cookies=${location.hostname}.txt`);
  918. showToast('Sent to MPV. If nothing happened, install <a href="https://github.com/akiirui/mpv-handler" target="_blank" style="color:#1976d2;">mpv-handler</a>.');
  919. });
  920. episodeListElem.appendChild(listItem);
  921. });
  922.  
  923. // Restore expand state only if section was previously expanded
  924. if (expandedState[quality]) {
  925. const icon = qualitySection.querySelector('.material-icons');
  926. episodeListElem.style.maxHeight = `${episodeListElem.scrollHeight}px`;
  927. icon.classList.add('rotate');
  928. }
  929. }
  930. }
  931.  
  932. function toggleQualitySection(event) {
  933. // Target the closest anlink-quality-header span to ensure only clicks on the text/icon trigger toggle
  934. const qualitySpan = event.currentTarget;
  935. const headerDiv = qualitySpan.parentElement;
  936. const qualitySection = headerDiv.closest('.anlink-quality-section');
  937. const episodeList = qualitySection.querySelector('.anlink-episode-list');
  938. const icon = qualitySpan.querySelector('.material-icons'); // Query icon within the span
  939. const isCollapsed = episodeList.style.maxHeight === '0px';
  940.  
  941. if (isCollapsed) {
  942. episodeList.style.maxHeight = `${episodeList.scrollHeight}px`; // Expand to content height
  943. icon.classList.add('rotate'); // Rotate icon on expand
  944. } else {
  945. episodeList.style.maxHeight = '0px'; // Collapse
  946. icon.classList.remove('rotate'); // Reset icon rotation
  947. }
  948. }
  949.  
  950. // Attach click listeners to the speed dial buttons for each quality section
  951. function attachBtnClickListeners(episodeList, qualitySection) {
  952. const buttonActions = [
  953. { selector: '.anlink-select-links', handler: onSelectBtnPressed },
  954. { selector: '.anlink-copy-links', handler: onCopyBtnClicked },
  955. { selector: '.anlink-export-links', handler: onExportBtnClicked },
  956. { selector: '.anlink-play-links', handler: onPlayBtnClicked }
  957. ];
  958.  
  959. buttonActions.forEach(({ selector, handler }) => {
  960. const button = qualitySection.querySelector(selector);
  961. button.addEventListener('click', () => handler(button, episodeList, qualitySection));
  962. });
  963.  
  964. // Helper function to get checked episode items within a quality section
  965. function _getSelectedEpisodeItems(qualitySection) {
  966. return Array.from(qualitySection.querySelectorAll('.anlink-episode-item input[type="checkbox"]:checked'))
  967. .map(checkbox => checkbox.closest('.anlink-episode-item'));
  968. }
  969.  
  970. // Helper function to prepare m3u8 playlist string from given episodes
  971. function _preparePlaylist(episodes, quality) {
  972. let playlistContent = '#EXTM3U\n';
  973. episodes.forEach(episode => {
  974. const linkObj = episode.links[quality];;
  975. if (!linkObj) {
  976. showToast(`No link found for source ${quality} in episode ${episode.number}`);
  977. return;
  978. }
  979. // Add tracks if present (subtitles, audio, etc.)
  980. if (linkObj.tracks && Array.isArray(linkObj.tracks) && linkObj.tracks.length > 0) {
  981. linkObj.tracks.forEach((track, idx) => {
  982. // EXT-X-MEDIA for subtitles or alternate audio
  983. if (track.kind && track.kind.startsWith('audio')) {
  984. playlistContent += `#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"audio${idx}\",NAME=\"${track.label || 'Audio'}\",DEFAULT=${track.default?'YES':'NO'},URI=\"${track.file}\"\n`;
  985. } else if ((track.kind && track.kind.startsWith('caption')) || track.kind === 'subtitles' || track.kind === 'captions') {
  986. playlistContent += `#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs${idx}\",NAME=\"${track.label || 'Subtitle'}\",DEFAULT=${track.default?'YES':'NO'},URI=\"${track.file}\"\n`;
  987. }
  988. });
  989. }
  990. playlistContent += `#EXTINF:-1,${episode.name}\n`;
  991. playlistContent += `${linkObj.stream}\n`;
  992. });
  993. return playlistContent;
  994. }
  995.  
  996. // Select Button click event handler
  997. function onSelectBtnPressed(button, episodes, qualitySection) {
  998. const episodeItems = qualitySection.querySelector('.anlink-episode-list').querySelectorAll('.anlink-episode-item');
  999. const checkboxes = Array.from(qualitySection.querySelectorAll('.anlink-episode-item input[type="checkbox"]'));
  1000. const allChecked = checkboxes.every(cb => cb.checked);
  1001. const anyUnchecked = checkboxes.some(cb => !cb.checked);
  1002.  
  1003. if (anyUnchecked || allChecked === false) { // If any unchecked OR not all are checked (for the first click when none are checked)
  1004. checkboxes.forEach(checkbox => { checkbox.checked = true; }); // Check all
  1005. // Select all link texts
  1006. const range = new Range();
  1007. range.selectNodeContents(episodeItems[0]);
  1008. range.setEndAfter(episodeItems[episodeItems.length - 1]);
  1009. window.getSelection().removeAllRanges();
  1010. window.getSelection().addRange(range);
  1011. button.textContent = 'Deselect All'; // Change button text to indicate deselect
  1012. } else { // If all are already checked
  1013. checkboxes.forEach(checkbox => { checkbox.checked = false; }); // Uncheck all
  1014. window.getSelection().removeAllRanges(); // Clear selection
  1015. button.textContent = 'Select All'; // Revert button text
  1016. }
  1017. setTimeout(() => { button.textContent = checkboxes.some(cb => !cb.checked) ? 'Select All' : 'Deselect All'; }, 1500); // slight delay revert text
  1018. }
  1019.  
  1020. // copySelectedLinks click event handler
  1021. function onCopyBtnClicked(button, episodes, qualitySection) {
  1022. const selectedItems = _getSelectedEpisodeItems(qualitySection);
  1023. 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);
  1024.  
  1025. const string = linksToCopy.join('\n');
  1026. navigator.clipboard.writeText(string);
  1027. button.textContent = 'Copied Selected';
  1028. setTimeout(() => { button.textContent = 'Copy'; }, 1000);
  1029. }
  1030.  
  1031. // exportToPlaylist click event handler
  1032. function onExportBtnClicked(button, episodes, qualitySection) {
  1033. const quality = qualitySection.dataset.quality;
  1034. const selectedItems = _getSelectedEpisodeItems(qualitySection);
  1035.  
  1036. const items = selectedItems.length ? selectedItems : Array.from(qualitySection.querySelectorAll('.anlink-episode-item'));
  1037. const playlist = _preparePlaylist(episodes.filter(ep => items.find(i => i.querySelector(`[data-epnum="${ep.number}"]`))), quality);
  1038. const fileName = items[0]?.querySelector('.anlink-episode-link')?.title + ` [${quality}].m3u8`;
  1039. const file = new Blob([playlist], { type: 'application/vnd.apple.mpegurl' });
  1040. const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(file), download: fileName });
  1041. a.click();
  1042.  
  1043. button.textContent = 'Exported Selected';
  1044. setTimeout(() => { button.textContent = 'Export'; }, 1000);
  1045. }
  1046.  
  1047. // Play click event handler
  1048. function onPlayBtnClicked(button, episodes, qualitySection) {
  1049. const quality = qualitySection.dataset.quality;
  1050. const selectedEpisodeItems = _getSelectedEpisodeItems(qualitySection);
  1051. const items = selectedEpisodeItems.length ? selectedEpisodeItems : Array.from(qualitySection.querySelectorAll('.anlink-episode-item'));
  1052. const urls = episodes
  1053. .filter(ep => items.find(i => i.querySelector(`[data-epnum="${ep.number}"]`)))
  1054. .map(ep => ep.links[quality]?.stream)
  1055. .filter(Boolean);
  1056. if (!urls.length) return showToast('No links found for selected episodes.');
  1057.  
  1058. // Use mpv:// protocol (requires mpv-handler installed)
  1059. const mpvUrl = 'mpv://play/' + safeBtoa(urls.join("|")) + `/?v_title=${safeBtoa(episodes.map(it=>it.name).join('|'))}` + `&cookies=${location.hostname}.txt`;
  1060. location.replace(mpvUrl);
  1061. button.textContent = 'Sent to MPV';
  1062. setTimeout(() => { button.textContent = 'Play with MPV'; }, 2000);
  1063. // Show install instructions if handler is not installed
  1064. setTimeout(() => {
  1065. 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.');
  1066. }, 1000);
  1067. }
  1068. }
  1069. }
  1070.  
  1071. /***************************************************************
  1072. * Display a simple toast message on the top right of the screen
  1073. ***************************************************************/
  1074. let toasts = [];
  1075.  
  1076. function showToast(message) {
  1077. const maxToastHeight = window.innerHeight * 0.5;
  1078. const toastHeight = 50; // Approximate height of each toast
  1079. const maxToasts = Math.floor(maxToastHeight / toastHeight);
  1080.  
  1081. console.log(message);
  1082.  
  1083. // Create the new toast element
  1084. const x = document.createElement("div");
  1085. x.innerHTML = message;
  1086. x.style.color = "#000";
  1087. x.style.backgroundColor = "#fdba2f";
  1088. x.style.borderRadius = "10px";
  1089. x.style.padding = "10px";
  1090. x.style.position = "fixed";
  1091. x.style.top = `${toasts.length * toastHeight}px`;
  1092. x.style.right = "5px";
  1093. x.style.fontSize = "large";
  1094. x.style.fontWeight = "bold";
  1095. x.style.zIndex = "10000";
  1096. x.style.display = "block";
  1097. x.style.borderColor = "#565e64";
  1098. x.style.transition = "right 2s ease-in-out, top 0.5s ease-in-out";
  1099. document.body.appendChild(x);
  1100.  
  1101. // Add the new toast to the list
  1102. toasts.push(x);
  1103.  
  1104. // Remove the toast after it slides out
  1105. setTimeout(() => {
  1106. x.style.right = "-1000px";
  1107. }, 3000);
  1108.  
  1109. setTimeout(() => {
  1110. x.style.display = "none";
  1111. if (document.body.contains(x)) document.body.removeChild(x);
  1112. toasts = toasts.filter(toast => toast !== x);
  1113. // Move remaining toasts up
  1114. toasts.forEach((toast, index) => {
  1115. toast.style.top = `${index * toastHeight}px`;
  1116. });
  1117. }, 4000);
  1118.  
  1119. // Limit the number of toasts to maxToasts
  1120. if (toasts.length > maxToasts) {
  1121. const oldestToast = toasts.shift();
  1122. document.body.removeChild(oldestToast);
  1123. toasts.forEach((toast, index) => {
  1124. toast.style.top = `${index * toastHeight}px`;
  1125. });
  1126. }
  1127. }
  1128.  
  1129. // On overlay open, show a help link for mpv-handler if not detected
  1130. function showMPVHandlerHelp() {
  1131. 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.');
  1132. }