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-09 提交的版本,查看 最新版本

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