AniLINK - Episode Link Extractor

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

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