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

  1. // ==UserScript==
  2. // @name AniLINK - Episode Link Extractor
  3. // @namespace https://greasyfork.org/en/users/781076-jery-js
  4. // @version 6.1.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. // @grant GM_registerMenuCommand
  31. // @grant GM_addStyle
  32. // ==/UserScript==
  33.  
  34. class Episode {
  35. constructor(number, title, links, type, thumbnail) {
  36. this.number = number; // The episode number
  37. this.title = title; // The title of the episode (this can be the specific ep title or just the anime name).
  38. this.links = links; // An object containing the download links for the episode, keyed by quality (eg: {"source1":"http://linktovideo.mp4", "source2":"vid2.mp4"}).
  39. this.type = type; // The file type of the video links (eg: "mp4", "m3u8").
  40. 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).
  41. this.name = `${this.title} - ${this.number.padStart(3, '0')}.${this.type}`; // The formatted name of the episode, combining title and number.
  42. }
  43. }
  44.  
  45. /**
  46. * @typedef {Object} Websites[]
  47. * @property {string} name - The name of the website (required).
  48. * @property {string[]} url - An array of URL patterns that identify the website (required).
  49. * @property {string} thumbnail - A CSS selector to identify the episode thumbnail on the website (required).
  50. * @property {Function} addStartButton - A function to add the "Generate Download Links" button to the website (required).
  51. * @property {AsyncGeneratorFunction} extractEpisodes - An async generator function to extract episode information from the website (required).
  52. * @property {string} epLinks - A CSS selector to identify the episode links on the website (optional).
  53. * @property {string} epTitle - A CSS selector to identify the episode title on the website (optional).
  54. * @property {string} linkElems - A CSS selector to identify the download link elements on the website (optional).
  55. * @property {string} [animeTitle] - A CSS selector to identify the anime title on the website (optional).
  56. * @property {string} [epNum] - A CSS selector to identify the episode number on the website (optional).
  57. * @property {Function} [_getVideoLinks] - A function to extract video links from the website (optional).
  58. * @property {string} [styles] - Custom CSS styles to be applied to the website (optional).
  59. *
  60. * @description An array of website configurations for extracting episode links.
  61. *
  62. * @note To add a new website, follow these steps:
  63. * 1. Create a new object with the following properties:
  64. * - `name`: The name of the website.
  65. * - `url`: An array of URL patterns that identify the website.
  66. * - `thumbnail`: A CSS selector to identify the episode thumbnail on the website.
  67. * - `addStartButton`: A function to add the "Generate Download Links" button to the website.
  68. * - `extractEpisodes`: An async generator function to extract episode information from the website.
  69. * 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):
  70. * - `animeTitle`: A CSS selector to identify the anime title on the website.
  71. * - `epLinks`: A CSS selector to identify the episode links on the website.
  72. * - `epTitle`: A CSS selector to identify the episode title on the website.
  73. * - `linkElems`: A CSS selector to identify the download link elements on the website.
  74. * - `epNum`: A CSS selector to identify the episode number on the website.
  75. * - `_getVideoLinks`: A function to extract video links from the website.
  76. * - `styles`: Custom CSS styles to be applied to the website.
  77. * 3. Implement the `addStartButton` function to add the "Generate Download Links" button to the website.
  78. * - This function should create a element and append it to the appropriate location on the website.
  79. * - The button should have an ID of "AniLINK_startBtn".
  80. * 4. Implement the `extractEpisodes` function to extract episode information from the website.
  81. * - This function should be an async generator function that yields Episode objects (To ensure fast processing, using chunks is recommended).
  82. * - Use the `fetchPage` function to fetch the HTML content of each episode page.
  83. * - Parse the HTML content to extract the episode title, number, links, and thumbnail.
  84. * - Create an `Episode` object for each episode and yield it using the `yieldEpisodesFromPromises` function.
  85. * 5. Optionally, implement the `_getVideoLinks` function to extract video links from the website.
  86. * - This function should return a promise that resolves to an object containing video links.
  87. * - Use this function if the video links require additional processing or API calls.
  88. * - 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).
  89. */
  90. const websites = [
  91. {
  92. name: 'GoGoAnime',
  93. url: ['anitaku.to/', 'gogoanime3.co/', 'gogoanime3', 'anitaku', 'gogoanime'],
  94. epLinks: '#episode_related > li > a',
  95. epTitle: '.title_name > h2',
  96. linkElems: '.cf-download > a',
  97. thumbnail: '.headnav_left > a > img',
  98. addStartButton: function() {
  99. const button = Object.assign(document.createElement('a'), {
  100. id: "AniLINK_startBtn",
  101. style: "cursor: pointer; background-color: #145132;",
  102. innerHTML: document.querySelector("div.user_auth a[href='/login.html']")
  103. ? `<b style="color:#FFC119;">AniLINK:</b> Please <a href="/login.html"><u>log in</u></a> to download`
  104. : '<i class="icongec-dowload"></i> Generate Download Links'
  105. });
  106. const target = location.href.includes('/category/') ? '#episode_page' : '.cf-download';
  107. document.querySelector(target)?.appendChild(button);
  108. return button;
  109. },
  110. extractEpisodes: async function* (status) {
  111. status.textContent = 'Starting...';
  112. const throttleLimit = 12; // Number of episodes to extract in parallel
  113. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  114. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  115. const chunk = epLinks.slice(i, i + throttleLimit);
  116. const episodePromises = chunk.map(async epLink => { try {
  117. const page = await fetchPage(epLink.href);
  118.  
  119. const [, epTitle, epNumber] = page.querySelector(this.epTitle).textContent.match(/(.+?) Episode (\d+(?:\.\d+)?)/);
  120. const thumbnail = page.querySelector(this.thumbnail).src;
  121. status.textContent = `Extracting ${epTitle} - ${epNumber.padStart(3, '0')}...`;
  122. const links = [...page.querySelectorAll(this.linkElems)].reduce((obj, elem) => ({ ...obj, [elem.textContent.trim()]: elem.href }), {});
  123. status.textContent = `Extracted ${epTitle} - ${epNumber.padStart(3, '0')}`;
  124.  
  125. return new Episode(epNumber, epTitle, links, 'mp4', thumbnail); // Return Episode object
  126. } catch (e) { showToast(e); return null; } }); // Handle errors and return null
  127.  
  128. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  129. }
  130. }
  131. },
  132. {
  133. name: 'YugenAnime',
  134. url: ['yugenanime.tv', 'yugenanime.sx'],
  135. epLinks: '.ep-card > a.ep-thumbnail',
  136. animeTitle: '.ani-info-ep .link h1',
  137. epTitle: 'div.col.col-w-65 > div.box > h1',
  138. thumbnail: 'a.ep-thumbnail img',
  139. addStartButton: function() {
  140. return document.querySelector(".content .navigation").appendChild(Object.assign(document.createElement('a'), { id: "AniLINK_startBtn", className: "link p-15", textContent: "Generate Download Links" }));
  141. },
  142. extractEpisodes: async function* (status) {
  143. status.textContent = 'Getting list of episodes...';
  144. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  145. const throttleLimit = 6; // Number of episodes to extract in parallel
  146.  
  147. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  148. const chunk = epLinks.slice(i, i + throttleLimit);
  149. const episodePromises = chunk.map(async (epLink, index) => { try {
  150. status.textContent = `Loading ${epLink.pathname}`
  151. const page = await fetchPage(epLink.href);
  152.  
  153. const animeTitle = page.querySelector(this.animeTitle).textContent;
  154. const epNumber = epLink.href.match(/(\d+)\/?$/)[1];
  155. const epTitle = page.querySelector(this.epTitle).textContent.match(/^${epNumber} : (.+)$/) || animeTitle;
  156. const thumbnail = document.querySelectorAll(this.thumbnail)[index].src;
  157. status.textContent = `Extracting ${`${epNumber.padStart(3, '0')} - ${animeTitle}` + (epTitle != animeTitle ? `- ${epTitle}` : '')}...`;
  158. const links = await this._getVideoLinks(page, status, (`${epNumber.padStart(3, '0')} - ${animeTitle}` + (epTitle != animeTitle ? `- ${epTitle}` : '')));
  159.  
  160. return new Episode(epNumber, epTitle, links, 'm3u8', thumbnail); // Return Episode object
  161. } catch (e) { showToast(e); return null; } }); // Handle errors and return null
  162.  
  163. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  164. }
  165. },
  166. _getVideoLinks: async function (page, status, episodeTitle) {
  167. const embedLinkId = page.body.innerHTML.match(new RegExp(`src="//${page.domain}/e/(.*?)/"`))[1];
  168. const embedApiResponse = await fetch(`https://${page.domain}/api/embed/`, { method: 'POST', headers: {"X-Requested-With": "XMLHttpRequest"}, body: new URLSearchParams({ id: embedLinkId, ac: "0" }) });
  169. const json = await embedApiResponse.json();
  170. const m3u8GeneralLink = json.hls[0];
  171. status.textContent = `Parsing ${episodeTitle}...`;
  172. // Fetch the m3u8 file content
  173. const m3u8Response = await fetch(m3u8GeneralLink);
  174. const m3u8Text = await m3u8Response.text();
  175. // Parse the m3u8 file to extract different qualities
  176. const qualityMatches = m3u8Text.matchAll(/#EXT-X-STREAM-INF:.*RESOLUTION=\d+x\d+.*NAME="(\d+p)"\n(.*\.m3u8)/g);
  177. const links = {};
  178. for (const match of qualityMatches) {
  179. const [_, quality, m3u8File] = match;
  180. links[quality] = `${m3u8GeneralLink.slice(0, m3u8GeneralLink.lastIndexOf('/') + 1)}${m3u8File}`;
  181. }
  182. return links;
  183. }
  184. },
  185. {
  186. name: 'AnimePahe',
  187. url: ['animepahe.ru', 'animepahe.com', 'animepahe.org', 'animepahe'],
  188. epLinks: (document.location.pathname.startsWith('/anime/'))? '.play': '.dropup.episode-menu .dropdown-item',
  189. epTitle: '.theatre-info > h1',
  190. linkElems: '#resolutionMenu > button',
  191. thumbnail: '.theatre-info > a > img',
  192. addStartButton: function() {
  193. GM_addStyle(`.theatre-settings .col-sm-3 { max-width: 20%; }`);
  194. (document.location.pathname.startsWith('/anime/'))
  195. ? document.querySelector(".col-6.bar").innerHTML += `
  196. <div class="btn-group btn-group-toggle">
  197. <label id="AniLINK_startBtn" class="btn btn-dark btn-sm">Generate Download Links</label>
  198. </div>`
  199. : document.querySelector("div.theatre-settings > div.row").innerHTML += `
  200. <div class="col-12 col-sm-3">
  201. <div class="dropup">
  202. <a class="btn btn-secondary btn-block" id="AniLINK_startBtn">
  203. Generate Download Links
  204. </a>
  205. </div>
  206. </div>
  207. `;
  208. return document.getElementById("AniLINK_startBtn");
  209. },
  210. extractEpisodes: async function* (status) {
  211. status.textContent = 'Starting...';
  212. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  213. const throttleLimit = 200; // Setting high throttle limit actually improves performance
  214.  
  215. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  216. const chunk = epLinks.slice(i, i + throttleLimit);
  217. const episodePromises = chunk.map(async epLink => { try {
  218. const page = await fetchPage(epLink.href);
  219.  
  220. if (page.querySelector(this.epTitle) == null) return;
  221. const [, epTitle, epNumber] = page.querySelector(this.epTitle).outerText.split(/Watch (.+) - (\d+(?:\.\d+)?) Online$/);
  222. const thumbnail = page.querySelector(this.thumbnail).src;
  223. status.textContent = `Extracting ${epTitle} - ${epNumber.padStart(3, "0")}...`;
  224.  
  225. async function getVideoUrl(kwikUrl) {
  226. const response = await fetch(kwikUrl, { headers: { "Referer": "https://animepahe.com" } });
  227. const data = await response.text();
  228. return eval(/(eval)(\(f.*?)(\n<\/script>)/s.exec(data)[2].replace("eval", "")).match(/https.*?m3u8/)[0];
  229. }
  230. let links = {};
  231. for (const elm of [...page.querySelectorAll(this.linkElems)]) {
  232. links[elm.textContent] = await getVideoUrl(elm.getAttribute('data-src'));
  233. status.textContent = `Parsed ${`${epNumber.padStart(3, '0')} - ${epTitle}`}`;
  234. }
  235.  
  236. return new Episode(epNumber, epTitle, links, 'm3u8', thumbnail);
  237. } catch (e) { showToast(e); return null; } });
  238.  
  239. yield* yieldEpisodesFromPromises(episodePromises);
  240. }
  241. },
  242. styles: `div#AniLINK_LinksContainer { font-size: 10px; } #Quality > b > div > ul {font-size: 16px;}`
  243. },
  244. {
  245. name: 'Beta-Otaku-Streamers',
  246. url: ['beta.otaku-streamers.com'],
  247. epLinks: (document.location.pathname.startsWith('/title/')) ? '.item-title a' : '.video-container .clearfix > a',
  248. epTitle: '.title > a',
  249. epNum: '.watch_curep',
  250. thumbnail: 'video',
  251. addStartButton: function() {
  252. (document.location.pathname.startsWith('/title/')
  253. ? document.querySelector(".album-top-box"): document.querySelector('.video-container .title-box'))
  254. .innerHTML += `<a id="AniLINK_startBtn" class="btn btn-outline rounded-btn">Generate Download Links</a>`;
  255. return document.getElementById("AniLINK_startBtn");
  256. },
  257. extractEpisodes: async function* (status) {
  258. status.textContent = 'Starting...';
  259. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  260. const throttleLimit = 12;
  261.  
  262. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  263. const chunk = epLinks.slice(i, i + throttleLimit);
  264. const episodePromises = chunk.map(async epLink => { try {
  265. const page = await fetchPage(epLink.href);
  266. const epTitle = page.querySelector(this.epTitle).textContent.trim();
  267. const epNumber = page.querySelector(this.epNum).textContent.replace("Episode ", '')
  268. const thumbnail = page.querySelector(this.thumbnail).poster;
  269.  
  270. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  271. const links = { 'Video Links': page.querySelector('video > source').src };
  272.  
  273. return new Episode(epNumber, epTitle, links, 'mp4', thumbnail);
  274. } catch (e) { showToast(e); return null; } });
  275.  
  276. yield* yieldEpisodesFromPromises(episodePromises);
  277. }
  278. }
  279. },
  280. {
  281. name: 'Otaku-Streamers',
  282. url: ['otaku-streamers.com'],
  283. epLinks: 'table > tbody > tr > td:nth-child(2) > a',
  284. epTitle: '#strw_player > table > tbody > tr:nth-child(1) > td > span:nth-child(1) > a',
  285. epNum: '#video_episode',
  286. thumbnail: 'otaku-streamers.com/images/os.jpg',
  287. addStartButton: function() {
  288. const button = document.createElement('a');
  289. button.id = "AniLINK_startBtn";
  290. button.style.cssText = `cursor: pointer; background-color: #145132; float: right;`;
  291. button.innerHTML = 'Generate Download Links';
  292. document.querySelector('table > tbody > tr:nth-child(2) > td > div > table > tbody > tr > td > h2').appendChild(button);
  293. return button;
  294. },
  295. extractEpisodes: async function* (status) {
  296. status.textContent = 'Starting...';
  297. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  298. const throttleLimit = 12; // Number of episodes to extract in parallel
  299.  
  300. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  301. const chunk = epLinks.slice(i, i + throttleLimit);
  302. const episodePromises = chunk.map(async epLink => { try {
  303. const page = await fetchPage(epLink.href);
  304. const epTitle = page.querySelector(this.epTitle).textContent;
  305. const epNumber = page.querySelector(this.epNum).textContent.replace("Episode ", '')
  306.  
  307. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  308. const links = { 'mp4': page.querySelector('video > source').src };
  309.  
  310. return new Episode(epNumber, epTitle, links, 'mp4', this.thumbnail); // Return Episode object
  311. } catch (e) { showToast(e); return null; } }); // Handle errors and return null
  312.  
  313. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  314. }
  315. }
  316. },
  317. {
  318. name: 'AnimeHeaven',
  319. url: ['animeheaven.me'],
  320. epLinks: 'a.ac3',
  321. epTitle: 'a.c2.ac2',
  322. epNumber: '.boxitem.bc2.c1.mar0',
  323. thumbnail: 'img.posterimg',
  324. addStartButton: function() {
  325. const button = document.createElement('a');
  326. button.id = "AniLINK_startBtn";
  327. button.style.cssText = `cursor: pointer; border: 2px solid red; padding: 4px;`;
  328. button.innerHTML = 'Generate Download Links';
  329. document.querySelector("div.linetitle2.c2").parentNode.insertBefore(button, document.querySelector("div.linetitle2.c2"));
  330. return button;
  331. },
  332. extractEpisodes: async function* (status) {
  333. status.textContent = 'Starting...';
  334. const epLinks = Array.from(document.querySelectorAll(this.epLinks));
  335. const throttleLimit = 12; // Number of episodes to extract in parallel
  336.  
  337. for (let i = 0; i < epLinks.length; i += throttleLimit) {
  338. const chunk = epLinks.slice(i, i + throttleLimit);
  339. const episodePromises = chunk.map(async epLink => { try {
  340. const page = await fetchPage(epLink.href);
  341. const epTitle = page.querySelector(this.epTitle).textContent;
  342. const epNumber = page.querySelector(this.epNum).textContent.replace("Episode ", '');
  343. const thumbnail = document.querySelector(this.thumbnail).src;
  344.  
  345. status.textContent = `Extracting ${epTitle} - ${epNumber}...`;
  346. const links = [...page.querySelectorAll('#vid > source')].reduce((acc, source) => ({ ...acc, [source.src.match(/\/\/(\w+)\./)[1]]: source.src }), {});
  347.  
  348. return new Episode(epNumber, epTitle, links, 'mp4', thumbnail); // Return Episode object
  349. } catch (e) { showToast(e); return null; } }); // Handle errors and return null
  350.  
  351. yield* yieldEpisodesFromPromises(episodePromises); // Use helper function
  352. }
  353. }
  354. }
  355.  
  356. ];
  357.  
  358. /**
  359. * Fetches the HTML content of a given URL and parses it into a DOM object.
  360. *
  361. * @param {string} url - The URL of the page to fetch.
  362. * @returns {Promise<Document>} A promise that resolves to a DOM Document object.
  363. * @throws {Error} If the fetch operation fails.
  364. */
  365. async function fetchPage(url) {
  366. const response = await fetch(url);
  367. if (response.ok) {
  368. const page = (new DOMParser()).parseFromString(await response.text(), 'text/html');
  369. return page;
  370. } else {
  371. showToast(`Failed to fetch HTML for ${url} : ${response.status}`);
  372. throw new Error(`Failed to fetch HTML for ${url} : ${response.status}`);
  373. }
  374. }
  375.  
  376. /**
  377. * Asynchronously processes an array of episode promises and yields each resolved episode.
  378. *
  379. * @param {Array<Promise>} episodePromises - An array of promises, each resolving to an episode.
  380. * @returns {AsyncGenerator} An async generator yielding each resolved episode.
  381. */
  382. async function* yieldEpisodesFromPromises(episodePromises) {
  383. for (const episodePromise of episodePromises) {
  384. const episode = await episodePromise;
  385. if (episode) {
  386. yield episode;
  387. }
  388. }
  389. }
  390.  
  391.  
  392.  
  393. // initialize
  394. console.log('Initializing AniLINK...');
  395. const site = websites.find(site => site.url.some(url => window.location.href.includes(url)));
  396.  
  397. // register menu command to start script
  398. GM_registerMenuCommand('Extract Episodes', extractEpisodes);
  399.  
  400. // attach start button to page
  401. site.addStartButton().addEventListener('click', extractEpisodes);
  402.  
  403. // append site specific css styles
  404. document.body.style.cssText += (site.styles || '');
  405.  
  406. // This function creates an overlay on the page and displays a list of episodes extracted from a website.
  407. // The function is triggered by a user command registered with `GM_registerMenuCommand`.
  408. // The episode list is generated by calling the `extractEpisodes` method of a website object that matches the current URL.
  409. async function extractEpisodes() {
  410. // Restore last overlay if it exists
  411. if (document.getElementById("AniLINK_Overlay")) {
  412. document.getElementById("AniLINK_Overlay").style.display = "flex";
  413. return;
  414. }
  415. // Flag to control extraction process
  416. let isExtracting = true;
  417.  
  418. // --- Materialize CSS Initialization ---
  419. GM_addStyle(`
  420. @import url('https://fonts.googleapis.com/icon?family=Material+Icons');
  421. @import url('https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css');
  422.  
  423. #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; }
  424. #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 */
  425. .anlink-status-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; } /* Header for status bar and stop button */
  426. .anlink-status-bar { color: #eee; flex-grow: 1; margin-right: 10px; display: block; } /* Status bar takes space */
  427. .anlink-status-icon { background: transparent; border: none; color: #eee; cursor: pointer; padding-right: 10px; } /* status icon style */
  428. .anlink-status-icon i { font-size: 24px; transition: transform 0.3s ease-in-out; } /* Icon size and transition */
  429. .anlink-status-icon i::before { content: 'check_circle'; } /* Show check icon when not extracting */
  430. .anlink-status-icon i.extracting::before { content: 'auto_mode'; animation: spinning 2s linear infinite; } /* Spinner animation class */
  431. .anlink-status-icon:hover i.extracting::before { content: 'stop_circle'; animation: stop; } /* Show stop icon on hover when extracting */
  432. .anlink-quality-section { margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #444; padding-bottom: 5px; }
  433. .anlink-quality-header { display: flex; justify-content: space-between; align-items: center; cursor: pointer; } /* Added cursor pointer */
  434. .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 */
  435. .anlink-quality-header i { margin-right: 8px; transition: transform 0.3s ease-in-out; } /* Transition for icon rotation */
  436. .anlink-quality-header i.rotate { transform: rotate(90deg); } /* Rotate class */
  437. .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 */
  438. .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 */
  439. .anlink-episode-item:last-child { border-bottom: none; }
  440. .anlink-episode-checkbox { margin-right: 10px; }
  441. .anlink-episode-checkbox span { overflow: hidden; text-overflow: ellipsis; display: inline-block; max-width: 100px; } /* Ellipsis for episode number/title */
  442. .anlink-episode-link { color: #ffca28; text-decoration: none; word-break: break-all; overflow: hidden; text-overflow: ellipsis; display: inline; } /* Single line and ellipsis for link */
  443. .anlink-episode-link:hover { color: #fff; }
  444. .anlink-header-buttons { display: flex; gap: 10px; }
  445. .anlink-header-buttons button { background-color: #26a69a; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; }
  446. .anlink-header-buttons button:hover { background-color: #2bbbad; }
  447.  
  448. @keyframes spinning { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } /* Spinning animation */
  449. `);
  450.  
  451. // Create an overlay to cover the page
  452. const overlayDiv = document.createElement("div");
  453. overlayDiv.id = "AniLINK_Overlay";
  454. document.body.appendChild(overlayDiv);
  455. overlayDiv.onclick = event => linksContainer.contains(event.target) ? null : overlayDiv.style.display = "none";
  456.  
  457. // Create a container for links
  458. const linksContainer = document.createElement('div');
  459. linksContainer.id = "AniLINK_LinksContainer";
  460. overlayDiv.appendChild(linksContainer);
  461.  
  462. // Status bar header - container for status bar and status icon
  463. const statusBarHeader = document.createElement('div');
  464. statusBarHeader.className = 'anlink-status-header';
  465. linksContainer.appendChild(statusBarHeader);
  466.  
  467. // Create dynamic status icon
  468. const statusIconElement = document.createElement('a');
  469. statusIconElement.className = 'anlink-status-icon';
  470. statusIconElement.innerHTML = '<i class="material-icons extracting"></i>';
  471. statusIconElement.title = 'Stop Extracting';
  472. statusBarHeader.appendChild(statusIconElement);
  473.  
  474. statusIconElement.addEventListener('click', () => {
  475. isExtracting = false; // Set flag to stop extraction
  476. statusBar.textContent = "Extraction Stopped.";
  477. });
  478.  
  479. // Create a status bar
  480. const statusBar = document.createElement('span');
  481. statusBar.className = "anlink-status-bar";
  482. statusBar.textContent = "Extracting Links..."
  483. statusBarHeader.appendChild(statusBar);
  484.  
  485. // Create a container for qualities and episodes
  486. const qualitiesContainer = document.createElement('div');
  487. qualitiesContainer.id = "AniLINK_QualitiesContainer";
  488. linksContainer.appendChild(qualitiesContainer);
  489.  
  490.  
  491. // --- Process Episodes using Generator ---
  492. const episodeGenerator = site.extractEpisodes(statusBar);
  493. const qualityLinkLists = {}; // Stores lists of links for each quality
  494.  
  495. for await (const episode of episodeGenerator) {
  496. if (!isExtracting) { // Check if extraction is stopped
  497. statusIconElement.querySelector('i').classList.remove('extracting'); // Stop spinner animation
  498. statusBar.textContent = "Extraction Stopped By User.";
  499. return; // Exit if extraction is stopped
  500. }
  501. if (!episode) continue; // Skip if episode is null (error during extraction)
  502.  
  503. // Get all links into format - {[qual1]:[ep1,2,3,4], [qual2]:[ep1,2,3,4], ...}
  504. for (const quality in episode.links) {
  505. qualityLinkLists[quality] = qualityLinkLists[quality] || [];
  506. qualityLinkLists[quality].push(episode);
  507. }
  508.  
  509. // Update UI in real-time - RENDER UI HERE BASED ON qualityLinkLists
  510. renderQualityLinkLists(qualityLinkLists, qualitiesContainer);
  511. }
  512. isExtracting = false; // Extraction completed
  513. statusIconElement.querySelector('i').classList.remove('extracting');
  514. statusBar.textContent = "Extraction Complete!";
  515.  
  516. // Renders quality link lists inside a given container element
  517. function renderQualityLinkLists(sortedLinks, container) {
  518. const previousExpandedState = {};
  519. container.querySelectorAll('.anlink-quality-section').forEach(section => {
  520. const quality = section.dataset.quality;
  521. const episodeList = section.querySelector('.anlink-episode-list');
  522. previousExpandedState[quality] = episodeList.style.maxHeight !== '0px';
  523. });
  524.  
  525. container.innerHTML = ''; // Clear existing content
  526. for (const quality in sortedLinks) {
  527. const episodes = sortedLinks[quality].sort((a, b) => a.number - b.number); // Ensure episodes are sorted
  528.  
  529. const qualitySection = document.createElement('div');
  530. qualitySection.className = 'anlink-quality-section';
  531. qualitySection.dataset.quality = quality; // Store quality-string in data attribute
  532.  
  533. const headerDiv = document.createElement('div'); // Header div for quality-string and buttons - ROW
  534. headerDiv.className = 'anlink-quality-header';
  535.  
  536. // Create a span for the clickable header text and icon
  537. const qualitySpan = document.createElement('span');
  538. qualitySpan.innerHTML = `<i class="material-icons">chevron_right</i> ${quality}`; // Expand icon and quality text
  539. qualitySpan.addEventListener('click', toggleQualitySection); // Add click listener to the span
  540. headerDiv.appendChild(qualitySpan);
  541.  
  542.  
  543. // --- Create Speed Dial Button in the Quality Section ---
  544. const headerButtons = document.createElement('div');
  545. headerButtons.className = 'anlink-header-buttons';
  546. headerButtons.innerHTML = `
  547. <button type="button" class="anlink-select-links">Select</button>
  548. <button type="button" class="anlink-copy-links">Copy</button>
  549. <button type="button" class="anlink-export-links">Export</button>
  550. <button type="button" class="anlink-play-links">Play</button>
  551. `;
  552. headerDiv.appendChild(headerButtons);
  553. qualitySection.appendChild(headerDiv);
  554.  
  555.  
  556. // --- Populate the quality section with episodes ---
  557. const episodeListElem = document.createElement('ul');
  558. episodeListElem.className = 'anlink-episode-list';
  559. episodeListElem.style.maxHeight = '0px'; // Default to collapsed
  560.  
  561. episodes.forEach(ep => {
  562. const listItem = document.createElement('li');
  563. listItem.className = 'anlink-episode-item';
  564. listItem.innerHTML = `
  565. <label>
  566. <input type="checkbox" class="anlink-episode-checkbox" />
  567. <span>Ep ${ep.number.replace(/^0+/, '')}: </span>
  568. <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>
  569. </label>
  570. `;
  571. const episodeLinkElement = listItem.querySelector('.anlink-episode-link');
  572. const link = episodeLinkElement.href;
  573. const name = decodeURIComponent(episodeLinkElement.download);
  574. listItem.addEventListener('mouseenter', () => window.getSelection().isCollapsed && (episodeLinkElement.textContent = name));
  575. listItem.addEventListener('mouseleave', () => episodeLinkElement.textContent = decodeURIComponent(link));
  576.  
  577. episodeListElem.appendChild(listItem);
  578. });
  579. qualitySection.appendChild(episodeListElem); // Append ul inside section
  580. container.appendChild(qualitySection);
  581.  
  582. // Attach handlers to the quality sections
  583. attachBtnClickListeners(episodes, qualitySection);
  584.  
  585. // Restore expand state
  586. if (previousExpandedState[quality]) {
  587. const icon = qualitySpan.querySelector('.material-icons');
  588. episodeListElem.style.maxHeight = `${episodeListElem.scrollHeight}px`;
  589. icon.classList.add('rotate');
  590. }
  591. }
  592. }
  593.  
  594. function toggleQualitySection(event) {
  595. // Target the closest anlink-quality-header span to ensure only clicks on the text/icon trigger toggle
  596. const qualitySpan = event.currentTarget;
  597. const headerDiv = qualitySpan.parentElement;
  598. const qualitySection = headerDiv.closest('.anlink-quality-section');
  599. const episodeList = qualitySection.querySelector('.anlink-episode-list');
  600. const icon = qualitySpan.querySelector('.material-icons'); // Query icon within the span
  601. const isCollapsed = episodeList.style.maxHeight === '0px';
  602.  
  603. if (isCollapsed) {
  604. episodeList.style.maxHeight = `${episodeList.scrollHeight}px`; // Expand to content height
  605. icon.classList.add('rotate'); // Rotate icon on expand
  606. } else {
  607. episodeList.style.maxHeight = '0px'; // Collapse
  608. icon.classList.remove('rotate'); // Reset icon rotation
  609. }
  610. }
  611.  
  612. // Attach click listeners to the speed dial buttons for each quality section
  613. function attachBtnClickListeners(episodeList, qualitySection) {
  614. const buttonActions = [
  615. { selector: '.anlink-select-links', handler: onSelectBtnPressed },
  616. { selector: '.anlink-copy-links', handler: onCopyBtnClicked },
  617. { selector: '.anlink-export-links', handler: onExportBtnClicked },
  618. { selector: '.anlink-play-links', handler: onPlayBtnClicked }
  619. ];
  620. buttonActions.forEach(({ selector, handler }) => {
  621. const button = qualitySection.querySelector(selector);
  622. button.addEventListener('click', () => handler(button, episodeList, qualitySection));
  623. });
  624. // Helper function to get checked episode items within a quality section
  625. function _getSelectedEpisodeItems(qualitySection) {
  626. return Array.from(qualitySection.querySelectorAll('.anlink-episode-item input[type="checkbox"]:checked'))
  627. .map(checkbox => checkbox.closest('.anlink-episode-item'));
  628. }
  629.  
  630. // Helper function to prepare m3u8 playlist string from given episodes
  631. function _preparePlaylist(episodes, quality) {
  632. let playlistContent = '#EXTM3U\n';
  633. episodes.forEach(episode => {
  634. playlistContent += `#EXTINF:-1,${episode.name}\n`;
  635. playlistContent += `${episode.links[quality]}\n`;
  636. });
  637. return playlistContent;
  638. }
  639. // Select Button click event handler
  640. function onSelectBtnPressed(button, episodes, qualitySection) {
  641. const episodeItems = qualitySection.querySelector('.anlink-episode-list').querySelectorAll('.anlink-episode-item');
  642. const checkboxes = Array.from(qualitySection.querySelectorAll('.anlink-episode-item input[type="checkbox"]'));
  643. const allChecked = checkboxes.every(cb => cb.checked);
  644. const anyUnchecked = checkboxes.some(cb => !cb.checked);
  645. if (anyUnchecked || allChecked === false) { // If any unchecked OR not all are checked (for the first click when none are checked)
  646. checkboxes.forEach(checkbox => { checkbox.checked = true; }); // Check all
  647. // Select all link texts
  648. const range = new Range();
  649. range.selectNodeContents(episodeItems[0]);
  650. range.setEndAfter(episodeItems[episodeItems.length - 1]);
  651. window.getSelection().removeAllRanges();
  652. window.getSelection().addRange(range);
  653. button.textContent = 'Deselect All'; // Change button text to indicate deselect
  654. } else { // If all are already checked
  655. checkboxes.forEach(checkbox => { checkbox.checked = false; }); // Uncheck all
  656. window.getSelection().removeAllRanges(); // Clear selection
  657. button.textContent = 'Select All'; // Revert button text
  658. }
  659. setTimeout(() => { button.textContent = checkboxes.some(cb => !cb.checked) ? 'Select All' : 'Deselect All'; }, 1500); // slight delay revert text
  660. }
  661. // copySelectedLinks click event handler
  662. function onCopyBtnClicked(button, episodes, qualitySection) {
  663. const selectedItems = _getSelectedEpisodeItems(qualitySection);
  664. 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);
  665. const string = linksToCopy.join('\n');
  666. navigator.clipboard.writeText(string);
  667. button.textContent = 'Copied Selected';
  668. setTimeout(() => { button.textContent = 'Copy'; }, 1000);
  669. }
  670. // exportToPlaylist click event handler
  671. function onExportBtnClicked(button, episodes, qualitySection) {
  672. const quality = qualitySection.dataset.quality;
  673. const selectedItems = _getSelectedEpisodeItems(qualitySection);
  674. const items = selectedItems.length ? selectedItems : Array.from(qualitySection.querySelectorAll('.anlink-episode-item'));
  675. const playlist = _preparePlaylist(episodes.filter(ep => items.find(i => i.querySelector(`[data-epnum="${ep.number}"]`))), quality);
  676. const fileName = items[0]?.querySelector('.anlink-episode-link')?.title + `_${quality}.m3u`;
  677. const file = new Blob([playlist], { type: 'application/vnd.apple.mpegurl' });
  678. const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(file), download: fileName });
  679. a.click();
  680.  
  681. button.textContent = 'Exported Selected';
  682. setTimeout(() => { button.textContent = 'Export'; }, 1000);
  683. }
  684. // PlayWithVLC click event handler
  685. function onPlayBtnClicked(button, episodes, qualitySection) {
  686. const quality = qualitySection.dataset.quality;
  687. const selectedEpisodeItems = _getSelectedEpisodeItems(qualitySection);
  688. const items = selectedEpisodeItems.length ? selectedEpisodeItems : Array.from(qualitySection.querySelectorAll('.anlink-episode-item'));
  689. const playlist = _preparePlaylist(episodes.filter(ep => items.find(i => i.querySelector(`[data-epnum="${ep.number}"]`))), quality);
  690. const file = new Blob([playlist], {type:'application/vnd.apple.mpegurl', });
  691. const fileUrl = URL.createObjectURL(file);
  692. window.open(fileUrl);
  693. button.textContent = 'Playing Selected';
  694. setTimeout(() => { button.textContent = 'Play'; }, 2000);
  695. 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.");
  696. }
  697. }
  698. }
  699.  
  700. /***************************************************************
  701. * Display a simple toast message on the top right of the screen
  702. ***************************************************************/
  703. let toasts = [];
  704.  
  705. function showToast(message) {
  706. const maxToastHeight = window.innerHeight * 0.5;
  707. const toastHeight = 50; // Approximate height of each toast
  708. const maxToasts = Math.floor(maxToastHeight / toastHeight);
  709.  
  710. console.log(message);
  711.  
  712. // Create the new toast element
  713. const x = document.createElement("div");
  714. x.innerHTML = message;
  715. x.style.color = "#000";
  716. x.style.backgroundColor = "#fdba2f";
  717. x.style.borderRadius = "10px";
  718. x.style.padding = "10px";
  719. x.style.position = "fixed";
  720. x.style.top = `${toasts.length * toastHeight}px`;
  721. x.style.right = "5px";
  722. x.style.fontSize = "large";
  723. x.style.fontWeight = "bold";
  724. x.style.zIndex = "10000";
  725. x.style.display = "block";
  726. x.style.borderColor = "#565e64";
  727. x.style.transition = "right 2s ease-in-out, top 0.5s ease-in-out";
  728. document.body.appendChild(x);
  729.  
  730. // Add the new toast to the list
  731. toasts.push(x);
  732.  
  733. // Remove the toast after it slides out
  734. setTimeout(() => {
  735. x.style.right = "-1000px";
  736. }, 3000);
  737.  
  738. setTimeout(() => {
  739. x.style.display = "none";
  740. if (document.body.contains(x)) document.body.removeChild(x);
  741. toasts = toasts.filter(toast => toast !== x);
  742. // Move remaining toasts up
  743. toasts.forEach((toast, index) => {
  744. toast.style.top = `${index * toastHeight}px`;
  745. });
  746. }, 4000);
  747.  
  748. // Limit the number of toasts to maxToasts
  749. if (toasts.length > maxToasts) {
  750. const oldestToast = toasts.shift();
  751. document.body.removeChild(oldestToast);
  752. toasts.forEach((toast, index) => {
  753. toast.style.top = `${index * toastHeight}px`;
  754. });
  755. }
  756. }