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!

当前为 2024-04-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name AniLINK - Episode Link Extractor
  3. // @namespace https://greasyfork.org/en/users/781076-jery-js
  4. // @version 4.0.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.to/*
  11. // @match https://gogoanime.*/*
  12. // @match https://gogoanime3.co/*
  13. // @match https://gogoanime3.*/*
  14. // @match https://animepahe.*/play/*
  15. // @match https://animepahe.ru/play/*
  16. // @match https://animepahe.com/play/*
  17. // @match https://animepahe.org/play/*
  18. // @grant GM_registerMenuCommand
  19. // ==/UserScript==
  20.  
  21. class Episode {
  22. constructor(number, title, links, thumbnail) {
  23. this.number = number;
  24. this.title = title;
  25. this.links = links;
  26. this.thumbnail = thumbnail;
  27. this.name = `${this.title} - ${this.number}`;
  28. }
  29. }
  30.  
  31. const websites = [
  32. {
  33. name: 'GoGoAnime',
  34. url: ['anitaku.to/', 'gogoanime3.co/', 'gogoanime3', 'anitaku', 'gogoanime'],
  35. epLinks: '#episode_related > li > a',
  36. epTitle: '.title_name > h2',
  37. linkElems: '.cf-download > a',
  38. thumbnail: '.headnav_left > a > img',
  39. addStartButton: function() {
  40. const button = document.createElement('a');
  41. button.id = "AniLINK_startBtn";
  42. button.style.cssText = `cursor: pointer; background-color: #145132;`;
  43. button.innerHTML = '<i class="icongec-dowload"></i> Generate Download Links';
  44. button.addEventListener('click', extractEpisodes);
  45.  
  46. // Add the button to the page if user is logged in otherwise show placeholder
  47. if (document.querySelector('.cf-download')) {
  48. document.querySelector('.cf-download').appendChild(button);
  49. } else {
  50. const loginMessage = document.querySelector('.list_dowload > div > span');
  51. loginMessage.innerHTML = `<b style="color:#FFC119;">AniLINK:</b> Please <a href="/login.html" title="login"><u>log in</u></a> to be able to batch download animes.`;
  52. }
  53. },
  54. extractEpisodes: async function (status) {
  55. status.textContent = 'Starting...';
  56. let episodes = {};
  57. const episodePromises = Array.from(document.querySelectorAll(this.epLinks)).map(async epLink => {
  58. const response = await fetchHtml(epLink.href);
  59. const page = (new DOMParser()).parseFromString(response, 'text/html');
  60. const [, epTitle, epNumber] = page.querySelector(this.epTitle).textContent.match(/(.+?) Episode (\d+)(?:.+)$/);
  61. const episodeTitle = `${epNumber.padStart(3, '0')} - ${epTitle}`;
  62. const thumbnail = page.querySelector(this.thumbnail).src;
  63. const links = [...page.querySelectorAll(this.linkElems)].reduce((obj, elem) => ({ ...obj, [elem.textContent.trim()]: elem.href }), {});
  64. status.textContent = `Extracting ${epTitle} - ${epNumber.padStart(3, '0')}...`;
  65.  
  66. episodes[episodeTitle] = new Episode(epNumber.padStart(3, '0'), epTitle, links, thumbnail);
  67. });
  68. await Promise.all(episodePromises);
  69. return episodes;
  70. }
  71. },
  72. {
  73. name: 'AnimePahe',
  74. url: ['animepahe.ru', 'animepahe.com', 'animepahe.org', 'animepahe'],
  75. epLinks: '.dropup.episode-menu .dropdown-item',
  76. epTitle: '.theatre-info > h1',
  77. linkElems: '#resolutionMenu > button',
  78. thumbnail: '.theatre-info > a > img',
  79. addStartButton: null,
  80. extractEpisodes: async function (status) {
  81. status.textContent = 'Starting...';
  82. let episodes = {};
  83. const episodePromises = Array.from(document.querySelectorAll(this.epLinks)).map(async epLink => {
  84. const response = await fetchHtml(epLink.href);
  85. const page = (new DOMParser()).parseFromString(response, 'text/html');
  86. const [, epTitle, epNumber] = page.querySelector(this.epTitle).outerText.split(/Watch (.+) - (\d+) Online$/);
  87. const episodeTitle = `${epNumber.padStart(3, '0')} - ${epTitle}`;
  88. const thumbnail = page.querySelector(this.thumbnail).src;
  89. status.textContent = `Extracting ${epTitle} - ${epNumber.padStart(3, "0")}...`;
  90.  
  91. async function getVideoUrl(kwikUrl) {
  92. const response = await fetch(kwikUrl, { headers: { "Referer": "https://animepahe.com" } });
  93. const data = await response.text();
  94. return eval(/(eval)(\(f.*?)(\n<\/script>)/s.exec(data)[2].replace("eval", "")).match(/https.*?m3u8/)[0];
  95. }
  96. let links = {};
  97. for (const elm of [...page.querySelectorAll(this.linkElems)]) {
  98. links[elm.textContent] = await getVideoUrl(elm.getAttribute('data-src'));
  99. }
  100.  
  101. episodes[episodeTitle] = new Episode(epNumber.padStart(3, '0'), epTitle, links, thumbnail);
  102. });
  103. await Promise.all(episodePromises);
  104. console.log(episodes);
  105. return episodes;
  106. },
  107. styles: `div#AniLINK_LinksContainer { font-size: 10px; } #Quality > b > div > ul {font-size: 16px;}`
  108. }
  109. ];
  110.  
  111. async function fetchHtml(url) {
  112. const response = await fetch(url);
  113. if (response.ok) {
  114. return response.text();
  115. } else {
  116. alert(`Failed to fetch HTML for ${url}`);
  117. throw new Error(`Failed to fetch HTML for ${url}`);
  118. }
  119. }
  120.  
  121. GM_registerMenuCommand('Extract Episodes', extractEpisodes);
  122.  
  123. // initialize
  124. console.log('Initializing AniLINK...');
  125. const site = websites.find(site => site.url.some(url => window.location.href.includes(url)));
  126.  
  127. // attach button to page
  128. site.addStartButton();
  129.  
  130. // append site specific css styles
  131. document.body.style.cssText += (site.styles || '');
  132.  
  133. // This function creates an overlay on the page and displays a list of episodes extracted from a website.
  134. // The function is triggered by a user command registered with `GM_registerMenuCommand`.
  135. // The episode list is generated by calling the `extractEpisodes` method of a website object that matches the current URL.
  136. async function extractEpisodes() {
  137. // Restore last overlay if it exists
  138. if (document.getElementById("AniLINK_Overlay")) {
  139. document.getElementById("AniLINK_Overlay").style.display = "flex";
  140. return;
  141. }
  142.  
  143. // Create an overlay to cover the page
  144. const overlayDiv = document.createElement("div");
  145. overlayDiv.id = "AniLINK_Overlay";
  146. overlayDiv.style.cssText = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.6); z-index: 999; display: flex; align-items: center; justify-content: center;";
  147. document.body.appendChild(overlayDiv);
  148. overlayDiv.onclick = event => linksContainer.contains(event.target) ? null : overlayDiv.style.display = "none";
  149.  
  150. // Create a form to display the Episodes list
  151. const linksContainer = document.createElement('div');
  152. linksContainer.id = "AniLINK_LinksContainer";
  153. linksContainer.style.cssText = "position:relative; height:70%; width:60%; color:cyan; background-color:#0b0b0b; overflow:auto; border: groove rgb(75, 81, 84); border-radius: 10px; padding: 10px 5px; resize: both; scrollbar-width: thin; scrollbar-color: cyan transparent; display: flex; justify-content: center; align-items: center;";
  154. overlayDiv.appendChild(linksContainer);
  155.  
  156. // Create a progress bar to display the progress of the episode extraction process
  157. const statusBar = document.createElement('span');
  158. statusBar.id = "AniLINK_StatusBar";
  159. statusBar.textContent = "Extracting Links..."
  160. statusBar.style.cssText = "background-color: #0b0b0b; color: cyan;";
  161. linksContainer.appendChild(statusBar);
  162.  
  163. // Extract episodes
  164. const episodes = await site.extractEpisodes(statusBar);
  165.  
  166. console.log(episodes);
  167.  
  168. // Get all links into format - {[qual1]:[ep1,2,3,4], [qual2]:[ep1,2,3,4], ...}
  169. const sortedEpisodes = Object.values(episodes).sort((a, b) => a.number - b.number);
  170. const sortedLinks = sortedEpisodes.reduce((acc, episode) => {
  171. for (let quality in episode.links) (acc[quality] ??= []).push(episode);
  172. return acc;
  173. }, {});
  174. console.log('sorted', sortedLinks);
  175.  
  176.  
  177. const qualityLinkLists = Object.entries(sortedLinks).map(([quality, episode]) => {
  178. const listOfLinks = episode.map(ep => {
  179. return `<li id="EpisodeLink" style="list-style-type: none;">
  180. <span style="user-select:none; color:cyan;">
  181. Ep ${ep.number.replace(/^0+/, '')}: </span>
  182. <a title="${ep.title.replace(/[<>:"/\\|?*]/g, '')}" download="${encodeURI(ep.name)}.mp4" href="${ep.links[quality]}" style="color:#FFC119;">
  183. ${ep.links[quality]}</a>
  184. </li>`;
  185. }).join("");
  186.  
  187. return `<ol style="white-space: nowrap;">
  188. <span id="Quality" style="display:flex; justify-content:center; align-items:center;">
  189. <b style="color:#58FFA9; font-size:25px; cursor:pointer; user-select:none;">
  190. -------------------${quality}-------------------\n
  191. </b>
  192. </span>
  193. ${listOfLinks}
  194. </ol><br><br>`;
  195. });
  196.  
  197. // Update the linksContainer with the finally generated links under each quality option header
  198. linksContainer.style.cssText = "position:relative; height:70%; width:60%; color:cyan; background-color:#0b0b0b; overflow:auto; border: groove rgb(75, 81, 84); border-radius: 10px; padding: 10px 5px; resize: both; scrollbar-width: thin; scrollbar-color: cyan transparent;";
  199. linksContainer.innerHTML = qualityLinkLists.join("");
  200.  
  201. // Add hover event listeners to update link text on hover
  202. linksContainer.querySelectorAll('#EpisodeLink').forEach(element => {
  203. const episode = element.querySelector('a');
  204. const link = episode.href;
  205. const name = decodeURIComponent(episode.download);
  206. element.addEventListener('mouseenter', () => window.getSelection().isCollapsed && (episode.textContent = name));
  207. element.addEventListener('mouseleave', () => episode.textContent = decodeURIComponent(link));
  208. });
  209.  
  210. // Add hover event listeners to quality headers to transform them into speed dials
  211. document.querySelectorAll('#Quality b').forEach(header => {
  212. const style = `style="background-color: #00A651; padding: 5px 10px; border: none; border-radius: 5px; cursor: pointer; user-select: none;"`
  213. const sdHTML = `
  214. <div style="display: flex; justify-content: center; padding: 10px;">
  215. <ul style="list-style: none; display: flex; gap: 10px;">
  216. <button type="button" ${style} id="AniLINK_selectLinks">Select</button>
  217. <button type="button" ${style} id="AniLINK_copyLinks">Copy</button>
  218. <button type="button" ${style} id="AniLINK_exportLinks">Export</button>
  219. <button type="button" ${style} id="AniLINK_playLinks">Play with VLC</button>
  220. </ul>
  221. </div>`
  222.  
  223. let headerHTML = header.innerHTML;
  224. header.parentElement.addEventListener('mouseenter', () => (header.innerHTML = sdHTML, attachBtnClickListeners()));
  225. header.parentElement.addEventListener('mouseleave', () => (header.innerHTML = headerHTML));
  226. });
  227.  
  228. // Attach click listeners to the speed dial buttons
  229. function attachBtnClickListeners() {
  230. const buttonIds = [
  231. { id: 'AniLINK_selectLinks', handler: onSelectBtnPressed },
  232. { id: 'AniLINK_copyLinks', handler: onCopyBtnClicked },
  233. { id: 'AniLINK_exportLinks', handler: onExportBtnClicked },
  234. { id: 'AniLINK_playLinks', handler: onPlayBtnClicked }
  235. ];
  236.  
  237. buttonIds.forEach(({ id, handler }) => {
  238. const button = document.querySelector(`#${id}`);
  239. button.addEventListener('click', () => handler(button));
  240. });
  241.  
  242. // Select Button click event handler
  243. function onSelectBtnPressed(it) {
  244. const links = it.closest('ol').querySelectorAll('li');
  245. const range = new Range();
  246. range.selectNodeContents(links[0]);
  247. range.setEndAfter(links[links.length - 1]);
  248. window.getSelection().removeAllRanges();
  249. window.getSelection().addRange(range);
  250. it.textContent = 'Selected!!';
  251. setTimeout(() => { it.textContent = 'Select'; }, 1000);
  252. }
  253.  
  254. // copySelectedLinks click event handler
  255. function onCopyBtnClicked(it) {
  256. const links = it.closest('ol').querySelectorAll('li');
  257. const string = [...links].map(link => link.children[1].href).join('\n');
  258. navigator.clipboard.writeText(string);
  259. it.textContent = 'Copied!!';
  260. setTimeout(() => { it.textContent = 'Copy'; }, 1000);
  261. }
  262.  
  263. // exportToPlaylist click event handler
  264. function onExportBtnClicked(it) {
  265. // Export all links under the quality header into a playlist file
  266. const links = it.closest('ol').querySelectorAll('li');
  267. let string = '#EXTM3U\n';
  268. links.forEach(link => {
  269. const episode = decodeURIComponent(link.children[1].download);
  270. string += `#EXTINF:-1,${episode}\n` + link.children[1].href + '\n';
  271. });
  272. const fileName = links[0].querySelector('a').title + '.m3u';
  273. const file = new Blob([string], { type: 'application/vnd.apple.mpegurl' });
  274. const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(file), download: fileName });
  275. a.click();
  276. it.textContent = 'Exported!!';
  277. setTimeout(() => { it.textContent = 'Export'; }, 1000);
  278. }
  279.  
  280. // PlayWithVLC click event handler
  281. function onPlayBtnClicked(it) {
  282. // Export all links under the quality header into a playlist file
  283. const links = it.closest('ol').querySelectorAll('li');
  284. let string = '#EXTM3U\n';
  285. links.forEach(link => {
  286. const episode = decodeURIComponent(link.children[1].download);
  287. string += `#EXTINF:-1,${episode}\n` + link.children[1].href + '\n';
  288. });
  289. const file = new Blob([string], { type: 'application/vnd.apple.mpegurl' });
  290. const fileUrl = URL.createObjectURL(file);
  291. window.open(fileUrl);
  292. it.textContent = 'Launching VLC!!';
  293. setTimeout(() => { it.textContent = 'Play with VLC'; }, 2000);
  294. 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.");
  295. }
  296.  
  297. return {
  298. onSelectBtnPressed,
  299. onCopyBtnClicked,
  300. onExportBtnClicked,
  301. onPlayBtnClicked
  302. };
  303. }
  304. }