// ==UserScript== // @name AnimePahe Improvements // @namespace https://gist.github.com/Ellivers/f7716b6b6895802058c367963f3a2c51 // @homepageURL https://github.com/Ellivers/ap-improvements // @downloadURL https://raw.githubusercontent.com/Ellivers/ap-improvements/refs/heads/master/ap-improvements.user.js // @updateURL https://raw.githubusercontent.com/Ellivers/ap-improvements/refs/heads/master/ap-improvements.user.js // @match https://animepahe.pw/* // @match https://animepahe.com/* // @match https://animepahe.org/* // @match https://kwik.cx/e/* // @match https://kwik.cx/f/* // @grant GM_getValue // @grant GM_setValue // @grant GM_xmlhttpRequest // @grant GM_info // @version 4.13.2 // @author Ellivers // @license MIT // @description Improvements and additions for the AnimePahe site // ==/UserScript== /* How to install: * Get the Violentmonkey browser extension (Tampermonkey is mostly untested, but seems to work as well). * For the GitHub Gist page, click the "Raw" button above this file. * For Greasy Fork, click "Install this script". * I highly suggest using an ad blocker (uBlock Origin is recommended). Feature list: * Automatically redirects to the correct session when a tab with an old session is loaded. * Saves your watch progress of each video, so you can resume right where you left off. * Bookmark anime and view it in a bookmark menu. * You can change watching status for each bookmarked anime to keep track of what you're watching. * Add ongoing anime to an episode feed to easily check when new episodes are out. * Quickly visit the download page for a video, instead of having to wait 5 seconds when clicking the download link. * Find collections of anime series in the search results, with the series listed in release order. * Jump directly to the next anime's first episode from the previous anime's last episode, and the other way around. * Keeps track of episodes that have been watched. * Adds a section on the main page where you can view episodes that you have started watching. * Adds a menu to episodes in the Latest Releases feed and on anime pages where you can copy a link to them, mark/unmark them as watched, or download them. * Reworked anime index page. You can now: * Find anime with your desired genre, theme, type, demographic, status and season. * Search among these filter results. * Open a random anime within the specified filters. * Adds an option to hide all episode thumbnails on the site. * Adds an option to have the header always stay at the top of the screen. * Saved data can be viewed and deleted in the "Manage Data" menu. * You can enable data syncing to sync your data between multiple devices. * Choose what data to sync, per device. * Create a sync code and enter it on the devices you want to sync with. * Automatically finds a relevant cover for the top of anime pages. * Allows you to go to specific pages of an anime's episode list. * Adds points in the video player progress bar for opening, ending, and other highlights (only available for some anime). * Adds a button to skip openings and endings when they start (only available for some anime). * Allows you to copy screenshots to the clipboard instead of downloading them. * Frame-by-frame controls on videos, using ',' and '.' * Skip 10 seconds on videos at a time, using 'J' and 'L' * Adds a keybind for taking a video screenshot (P) * Adds keybinds for going to the start and end of a video (Home & End) * Changes the video 'loop' keybind to Shift + L (by default) * Allows you to press Shift + N to go to the next episode, or Shift + P to go to the previous one. * Speed up or slow down a video by holding Ctrl and: * Scrolling up/down * Pressing the up/down keys * You can also hold shift to make the speed change more gradual. * Remembers the selected speed for each anime. * Allows you to see images from the video while hovering over the progress bar. * Allows you to also use numpad number keys to seek through videos. * Theatre mode for a better non-fullscreen video experience on larger screens. * Instantly loads the video instead of having to click a button to load it. * Sets the default video time to show time elapsed instead of time remaining. * Adds buttons to copy shortcut links to anime and episode pages. * Adds site-wide keyboard shortcuts: * B (default) to open the bookmark menu * N (default) to open the episode feed * S (default) to open the main search bar, as an alternative to F2 * All added keyboard shortcuts can be rebound or disabled. * Adds a more noticeable spinning loading indicator on videos. * Adds an "Auto-Play Video" option to automatically play the video (on some browsers, you may need to allow auto-playing for this to work). * Adds an "Auto-Play Next" option to automatically go to the next episode when the current one is finished. * Focuses on the video player when loading the page, so you don't have to click on it to use keyboard controls. * Adds an option to automatically choose the highest quality available when loading the video. * Adds a button (in the options menu) to reset the video player. * Shows the dates of when episodes were added. * And more! */ /*global $,GM_getValue,GM_setValue,sendMessage,Hls,hls,jQuery,Fuse,GM_xmlhttpRequest,GM_info,html2canvas,Cookies*/ // MARKER:START const baseUrl = window.location.toString(); const initialStorage = getStorage(); function getDefaultData() { return { version: 5, linkList:[], videoTimes:[], bookmarks:[], notifications: { lastUpdated: Date.now(), anime: [], episodes: [] }, badCovers: [], settings: { autoDelete:true, hideThumbnails:false, theatreMode:false, bestQuality:true, autoDownload:true, autoPlayNext:false, autoPlayVideo:false, seekThumbnails:true, seekPoints:true, skipButton:true, reduceMotion:false, copyScreenshots:true, stickyHeader:false, relativeEpNums:false, bookmarkLayout: "grid", bookmarkSort: "recent", notifScheduleStart: 0, numpadSeeking: true, dlPreferRes: 1080, dlPreferLang: '', showContinueWatching: true, changeSpeedScroll: true, changeSpeedArrows: true, keybindBookmarks: "b", keybindNotifications: "n", keybindSearch: "s", keybindModalBack: "Backspace", keybindTheatreMode: "t", keybindNextEpisode: "Shift+N", keybindPrevEpisode: "Shift+P", keybind10sBackward: "j", keybind10sForward: "l", keybind1fBackward: ",", keybind1fForward: ".", keybindPlayerStart: "Home", keybindPlayerEnd: "End", keybindScreenshot: "p", keybindToggleLoop: "Shift+L", keybindResetPlayer: "", }, videoSpeed: [], watched: "", sync: { syncCode: "", lastSynced: 0, currentMessage: null, temp: { addedData: [], removedData: [], requiredHash: '', inProgress: false }, previousSettings: [], settings: { linkList: false, videoTimes: true, bookmarks: true, notifications: true, watched: true, interval: 300 } }, cached: { firstEpisode: [], poster: [], } }; } function upgradeData(data, fromver) { if (fromver === undefined) { fromver = 0; } const defaultVer = getDefaultData().version; if (fromver >= defaultVer) return; console.log(`[AnimePahe Improvements] Upgrading data from version ${fromver}`); /* Changes: * V1: * autoPlay -> autoPlayNext * V2: * autoDelete -> settings.autoDelete * hideThumbnails -> settings.hideThumbnails * theatreMode -> settings.theatreMode * bestQuality -> settings.bestQuality * autoDownload -> settings.autoDownload * autoPlayNext -> settings.autoPlayNext * autoPlayVideo -> settings.autoPlayVideo * V3: * linkList[].subInfo {name,quality,other} -> [name,quality,other] * V4: * Fix incorrect anime ID formats caused by 4.9.0 */ const upgradeFunctions = [ () => { // upgrading from V0 data.autoPlayNext = data.autoPlay; delete data.autoPlay; }, () => { // upgrading from V1 const settings = {}; settings.autoDelete = data.autoDelete; settings.hideThumbnails = data.hideThumbnails; settings.theatreMode = data.theatreMode; settings.bestQuality = data.bestQuality; settings.autoDownload = data.autoDownload; settings.autoPlayNext = data.autoPlayNext; settings.autoPlayVideo = data.autoPlayVideo; data.settings = settings; delete data.autoDelete; delete data.hideThumbnails; delete data.theatreMode; delete data.bestQuality; delete data.autoDownload; delete data.autoPlayNext; delete data.autoPlayVideo; }, () => { // upgrading from V2 if (!data.linkList) return; data.linkList.forEach(g => { if (!g.subInfo || Array.isArray(g.subInfo)) return; g.subInfo = [g.subInfo.name, g.subInfo.quality, g.subInfo.other]; }); }, () => { // upgrading from V3 if (data.linkList?.length) data.linkList.forEach(g => { if (g.animeId) g.animeId = +g.animeId; }); if (data.videoTimes?.length) data.videoTimes.forEach(g => { if (g.animeId) g.animeId = +g.animeId; }); if (data.bookmarks?.length) data.bookmarks.forEach(g => { if (g.id) g.id = +g.id; }); if (data.notifications?.anime?.length) data.notifications.anime.forEach(g => { if (g.id) g.id = +g.id; }); if (data.notifications?.episodes?.length) data.notifications.episodes.forEach(g => { if (g.animeId) g.animeId = +g.animeId; }); }, () => { // upgrading from V4 if (data.videoTimes?.length) data.videoTimes.forEach(g => { if (!g.videoUrls?.length) return; g.videoPaths = g.videoUrls.map(h => getVideoPath(h)); delete g.videoUrls; }); }, ]; for (let i = fromver; i < defaultVer; i++) { const fn = upgradeFunctions[i]; if (fn !== undefined) fn(); } data.version = defaultVer; } function getStorage() { const defa = getDefaultData(); const res = GM_getValue('anime-link-tracker', defa); const oldVersion = res.version; for (const key of Object.keys(defa)) { if (res[key] !== undefined) continue; res[key] = defa[key]; } for (const key of Object.keys(defa.settings)) { if (res.settings[key] !== undefined) continue; res.settings[key] = defa.settings[key]; } for (const key of Object.keys(defa.cached)) { if (res.cached[key] !== undefined) continue; res.cached[key] = defa.cached[key]; } if (oldVersion !== defa.version) { upgradeData(res, oldVersion); saveData(res); } return res; } function saveData(data) { GM_setValue('anime-link-tracker', data); } function getStorageLimits() { return { linkList: 1000, videoTimes: 1000, bookmarks: 300, notifications: { anime: 100, episodes: 150 }, videoSpeed: 1000, cached: { firstEpisode: 200, poster: 100, }, } } // Turns seconds into "hrs:minutes:seconds" or "minutes:seconds" function secondsToHMS(secs) { const mins = Math.floor(secs/60); const hrs = Math.floor(mins/60); const newSecs = Math.floor(secs % 60); return `${hrs > 0 ? hrs + ':' : ''}${hrs > 0 && (mins%60).toString().length <= 1 ? '0' : ''}${mins % 60}:${newSecs.toString().length > 1 ? '' : '0'}${newSecs % 60}`; } function HMStoSeconds(hms) { const durParts = hms.split(':'); if (durParts.length === 3) return (+durParts[0] * 3600) + (+durParts[1] * 60) + (+durParts[2]); else if (durParts.length === 2) return (+durParts[0] * 60) + (+durParts[1]); } // MARKER:WATCHED ENCODING /* Watched episode format: * anime_id:episode_num1-episode_num2,episode_num3; */ function decodeWatched(watched) { const decoded = []; if (watched?.split === undefined) { console.error('[AnimePahe Improvements] Attempted to decode watched episode list with incorrect type ' + typeof(watched)); return []; } for (const anime of watched.split(';')) { const parts = anime.split(':'); if (parts.length <= 1) continue; const animeId = parseInt(parts[0], 36); if (isNaN(animeId)) continue; const episodes = []; for (const ep of parts[1].split(',')) { if (ep.includes('-')) { const epParts = ep.split('-').map(e => parseEpNum(e)); for (let i = epParts[0]; i <= epParts[1]; i++) { // If start or end of range is NaN, the for loop will not run episodes.push(i); } } else { const episode = parseEpNum(ep); if (!isNaN(episode)) episodes.push(episode); } } decoded.push({ animeId: animeId, episodes: episodes }); } return decoded; function parseEpNum(str) { const parts = str.split('.'); if (parts.length === 1) return parseInt(parts[0], 36); else if (parts.length === 2) return parseInt(parts[0], 36) + (parseInt(parts[1], 36) / 10); else return NaN; } } function encodeWatched(watched) { return watched.map(a => { return a.animeId.toString(36) + ':' + (() => { const episodeRanges = []; const sorted = a.episodes.sort((a,b) => a > b ? 1 : -1); for (const episode of sorted) { const lastRange = episodeRanges[episodeRanges.length - 1]; if (lastRange && episode - 1 === lastRange[1]) { lastRange[1] = episode; } else { episodeRanges.push([episode, episode]); } } return episodeRanges.map(e => { if (e[0] === e[1]) return encodeEpNum(e[0]); else return encodeEpNum(e[0]) + '-' + encodeEpNum(e[1]); }).join(','); })(); }).join(';'); function encodeEpNum(ep) { const parts = ep.toString().split('.'); if (parts.length === 1) return ep.toString(36); else if (parts.length === 2) return parseInt(parts[0]).toString(36) + '.' + parseInt(parts[1][0]/*Limits the decimal value to one digit*/).toString(36); else return '0'; } } function isWatched(animeId, episode, watched = decodeWatched(getStorage().watched)) { const found = watched.find(a => a.animeId === animeId); if (found === undefined) return false; return found.episodes.includes(episode); } function addWatched(animeId, episode, storage = getStorage()) { const watched = decodeWatched(storage.watched); const found = watched.find(a => a.animeId === animeId); if (found === undefined) { watched.push({ animeId: animeId, episodes: [episode] }); } else { if (found.episodes.find(e => e === episode) !== undefined) return; found.episodes.push(episode); } if (isSyncEnabled(storage)) { const foundAdded = storage.sync.temp.addedData.find(g => g.type === 'watched' && g.animeId === animeId); if (foundAdded) foundAdded.episodes.push(episode); else storage.sync.temp.addedData.push({type: 'watched', animeId: animeId, episodes: [episode]}); } storage.watched = encodeWatched(watched); saveData(storage); } function removeWatched(animeId, episode, storage = getStorage()) { const watched = decodeWatched(storage.watched); const found = watched.find(a => a.animeId === animeId); if (found === undefined) return; found.episodes = found.episodes.filter(e => e !== episode); if (found.episodes.length === 0) { const index = watched.indexOf(found); watched.splice(index, 1); } if (isSyncEnabled(storage)) { storage.sync.temp.removedData.push({type: 'watched', animeId: animeId, episodes: [episode]}); } storage.watched = encodeWatched(watched); saveData(storage); } function removeWatchedAnime(animeId, storage = getStorage()) { const decoded = decodeWatched(storage.watched); if (isSyncEnabled(storage)) { const found = decoded.filter(a => a.animeId === animeId); if (found.length) storage.sync.temp.removedData.push(found.map(a => {return {type: 'watched', animeId: animeId, episodes: a.episodes}})[0]); } storage.watched = encodeWatched(decoded.filter(a => a.animeId !== animeId)); saveData(storage); } function getRelativeEpisodeNum(episode, firstEpisode) { return episode - Math.max(firstEpisode - 1, 0); } function getEpisodeValue(ep, ep2 = undefined, firstEp = undefined) { return firstEp !== undefined ? `${getRelativeEpisodeNum(ep, firstEp)}${ep2 ? '-' + getRelativeEpisodeNum(ep2, firstEp) : ''}` : `${ep}${ep2 ? '-' + ep2 : ''}`; } function getStoredTime(name, ep, storage = getStorage(), id = undefined) { if (id) { return storage.videoTimes.find(a => a.episodeNum === ep && a.animeId === id); } else return storage.videoTimes.find(a => a.animeName === name && a.episodeNum === ep); } function pressedKeybind(event, keybind) { if (!keybind) return false; const parts = keybind.split('+'); const shift = parts.find(g => g === 'Shift'); const ctrl = parts.find(g => g === 'Control'); const key = parts.filter(g => !['Shift','Control'].includes(g))[0] || '+'; return (key.toLowerCase() === event.key.toLowerCase() && event.shiftKey === Boolean(shift) && event.ctrlKey === Boolean(ctrl)); } // Only works for full URLs function getPathname(url) { return new URL(url).pathname; } function getVideoPath(url) { const parts = /(\w+)$/.exec(url); if (!parts) return undefined; return parts[1]; } function copyObj(obj) { return JSON.parse(JSON.stringify(obj)); } function isSyncEnabled(storage) { return storage.sync.syncCode !== ''; } function bumpSyncDiff(storage, bumpReason) { if (isSyncEnabled(storage) && !storage.sync.temp.addedData.length) storage.sync.temp.addedData.push({bump:bumpReason}); // Mark that changes have been made } function applyCssSheet(cssString) { $("head").append(''); const sheet = $("#anitracker-style")[0].sheet; const rules = cssString.split(/^\}/mg).map(a => a.replace(/\n/gm,'') + '}'); for (let i = 0; i < rules.length - 1; i++) { sheet.insertRule(rules[i], i); } } const kwikDLPageRegex = /^https:\/\/kwik\.\w+\/f\//; // MARKER:VIDEO IFRAME // Video player improvements function anitrackerKwikLoad() { if (typeof $ !== "undefined" && $() !== null) anitrackerPlayerLoad(window.location.origin + window.location.pathname); else { let scriptElem; for (const elem of document.querySelectorAll('head > link')) { if (!elem.href.includes('jquery')) continue; scriptElem = elem; break; } if (!scriptElem) { const h1 = document.querySelector('h1'); // Some bug that the kwik DL page had before // (You're not actually blocked when this happens) if (!kwikDLPageRegex.test(baseUrl) && h1.textContent == "Sorry, you have been blocked") { h1.textContent = "Oops, page failed to load."; document.querySelector('h2').textContent = "This doesn't mean you're blocked. Try playing from another page instead."; } return; } scriptElem.addEventListener('load', () => {anitrackerPlayerLoad(window.location.origin + window.location.pathname)}); } function anitrackerPlayerLoad(url) { // "url" does not include search params if (kwikDLPageRegex.test(url)) { if (initialStorage.settings.autoDownload === false) return; $(`
[AnimePahe Improvements] Downloading...
`).prependTo(document.body); if ($('form').length) { $('form').submit(); setTimeout(() => {$('#anitrackerKwikDL').remove()}, 1500); } else new MutationObserver(function(mutationList, observer) { if ($('form').length) { observer.disconnect(); $('form').submit(); setTimeout(() => {$('#anitrackerKwikDL').remove()}, 1500); } }).observe(document.body, { childList: true, subtree: true }); return; } // Needs to have this indentation const _css = ` .anitracker-loading { background: none!important; border: 12px solid rgba(130,130,130,0.7); border-top-color: #00d1b2; border-radius: 50%; animation: spin 1.2s linear infinite; translate: -50% -50%; width: 80px; height: 80px; } .anitracker-message { width:50rem; max-width: 100%; height:6rem; position:absolute; background-color:rgba(0,0,0,0.5); justify-content:center; align-items:center; margin-top:1.5%; border-radius:20px; padding: 16px; } .anitracker-message>span { color: white; font-size: 2.5em; line-height: 1em; } .anitracker-progress-tooltip { width: 219px; padding: 5px; opacity:0; position: absolute; left:0%; bottom: 100%; background-color: rgba(255,255,255,0.88); border-radius: 8px; transition: translate .2s ease .1s,scale .2s ease .1s,opacity .1s ease .05s; transform: translate(-50%,0); user-select: none; pointer-events: none; z-index: 2; } .anitracker-progress-image { height: 100%; width: 100%; background-color: gray; display:flex; flex-direction: column; align-items: center; overflow: hidden; border-radius: 5px; } .anitracker-progress-image>img { width: 100%; } .anitracker-progress-image>span { font-size: .9em; bottom: 5px; position: fixed; background-color: rgba(0,0,0,0.7); border-radius: 3px; padding: 0 4px 0 4px; } .anitracker-skip-button { position: absolute; left: 5%; bottom: 10%; color: white; background-color: rgba(100,100,100,0.6); z-index: 1; border: 3px solid white; border-radius: 8px; padding: 10px 24px; transition: .3s; } .anitracker-skip-button:hover, .anitracker-skip-button:focus-visible { background-color: rgba(0,0,0,0.75); } .anitracker-skip-button:focus-visible { outline: 3px dotted #00b3ff; } .anitracker-seek-points { width: 100%; bottom: 0; height: 100%; position: absolute; display: flex; align-items: center; } .anitracker-seek-points>i { position: absolute; width: 5px; height: 5px; border-radius: 2px; background-color: #1a9166; pointer-events: none; z-index: 2; translate: -50% 0; } .plyr--hide-controls>.anitracker-hide-control { opacity: 0!important; pointer-events: none!important; } .plyr.plyr--hide-controls { cursor: none; } @media screen and (max-width: 700px) { .anitracker-message>span { font-size: 1.5em; } } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`; applyCssSheet(_css); if ($('.anitracker-message').length) { console.log("[AnimePahe Improvements (Player)] Script was reloaded."); return; } $('button.plyr__controls__item:nth-child(1)').hide(); $('.plyr__progress__container').hide(); $('.plyr__control--overlaid').hide(); $(`
Loading...
`).appendTo('.plyr--video'); const player = $('#kwikPlayer')[0]; function getVideoInfo() { const fileName = document.getElementsByClassName('ss-label')[0].textContent; const nameParts = fileName.split('_'); let name = ''; for (let i = 0; i < nameParts.length; i++) { const part = nameParts[i]; if (part.trim() === 'AnimePahe') { i++; continue; } if (part === 'Dub' && i >= 1 && [2,3,4,5].includes(nameParts[i-1].length)) break; if (/\d{2}/.test(part) && i >= 1 && nameParts[i-1] === '-') break; name += nameParts[i-1] + ' '; } return { animeName: name.slice(0, -1), episodeNum: +/^AnimePahe_.+_-_([\d.]{2,})/.exec(fileName)[1] }; } $(`
`).appendTo('.plyr__progress'); function setSeekPoints(timestampData) { $('.anitracker-seek-points>i').remove(); for (const t of timestampData) { const percentage = Math.min((t.start / player.duration) * 100, 100); $(``).appendTo('.anitracker-seek-points'); } } var timestamps = []; const anitrackerSettings = initialStorage.settings; async function getAnidbId() { const byRequest = await getValueByRequest('anidb_id'); if (byRequest) return byRequest; const name = await getValueByRequest('name'); const byName1 = name && await getAnidbIdFromTitle(name); if (byName1) return byName1; return await getAnidbIdFromTitle(getVideoInfo().animeName); } function saveTimestampData(timestampData, storage) { const vidInfo = getVideoInfo(); const storedVideoTime = getStoredTime(vidInfo.animeName, vidInfo.episodeNum, storage); if (!storedVideoTime) return; if (!timestampData) { storedVideoTime.hasTimestamps = false; delete storedVideoTime.timestampData; } else { storedVideoTime.hasTimestamps = true; storedVideoTime.timestampData = timestampData; } saveData(storage); } function applyTimestampData(timestampData) { setSeekPoints(anitrackerSettings.seekPoints ? timestampData : []); timestamps = anitrackerSettings.skipButton ? timestampData : []; } async function setupTimestamps() { const anidbId = await getAnidbId(); if (!anidbId) return; const firstEp = await getValueByRequest('first_episode'); const timestampData = await getTimestampData(anidbId, getVideoInfo().episodeNum, firstEp); saveTimestampData(timestampData, getStorage()); if (timestampData) applyTimestampData(timestampData); } async function getAnidbIdFromTitle(title) { return new Promise((resolve) => { const req = new XMLHttpRequest(); req.open('GET', 'https://raw.githubusercontent.com/NOBLES5E/anidb-titles/refs/heads/main/animes-titles.json', true); req.onload = () => { if (req.status !== 200) { resolve(false); return; } const data = JSON.parse(req.response); let anidbId = undefined; for (const anime of data) { if (!anime.titles.find(a => a.text === title)) continue; anidbId = +anime.aid; break; } resolve(anidbId); }; req.send(); }); } async function getTimestampData(anidbId, episode, firstEpisode = undefined) { return new Promise((resolve) => { const req = new XMLHttpRequest(); req.open('GET', 'https://raw.githubusercontent.com/Ellivers/open-anime-timestamps/refs/heads/master/timestamps.json', true); // Timestamp data req.onload = () => { if (req.status !== 200) return resolve(undefined); const data = JSON.parse(req.response)[anidbId]; if (!data) { console.log(`[AnimePahe Improvements] No timestamp data found for this anime.`); return resolve(undefined); } if (firstEpisode !== undefined) { episode = getRelativeEpisodeNum(episode, firstEpisode); } const episodeData = data.find(e => e.episode_number === episode); if (episodeData) { console.log(`[AnimePahe Improvements] Found timestamp data for episode ${episode}.`); } else { console.log(`[AnimePahe Improvements] No timestamp data found for episode ${episode}.`); return resolve(undefined); } const timestampData = [ { type: "recap", start: episodeData.recap.start, end: episodeData.recap.end }, { type: "opening", start: episodeData.opening.start, end: episodeData.opening.end }, { type: "ending", start: episodeData.ending.start, end: episodeData.ending.end }, { type: "preview", start: episodeData.preview_start } ]; // Filter off unusable timestamps resolve(timestampData.filter(t => ![-1,-2].includes(t.start))); }; req.send(); }); } function updateStoredPlaybackSpeed(speed) { const storage = getStorage(); const vidInfo = getVideoInfo(); const storedVideoTime = getStoredTime(vidInfo.animeName, vidInfo.episodeNum, storage); if (!storedVideoTime) return; const id = storedVideoTime.animeId; const name = vidInfo.animeName; const storedPlaybackSpeed = (() => { if (id) return storage.videoSpeed.find(a => a.animeId === id); else return storage.videoSpeed.find(a => a.animeName === name); })(); if (speed === 1) { if (!storedPlaybackSpeed) return; if (id) storage.videoSpeed = storage.videoSpeed.filter(a => a.animeId !== id); else storage.videoSpeed = storage.videoSpeed.filter(a => a.animeName !== name); saveData(storage); return; } if (!storedPlaybackSpeed) { storage.videoSpeed.push({ animeId: id, animeName: name, speed: speed }); if (storage.videoSpeed.length > 256) storage.videoSpeed.splice(0,1); } else storedPlaybackSpeed.speed = speed; saveData(storage); } let reachedWatchedStatus = false; function updateStoredTime() { const currentTime = player.currentTime; const storage = getStorage(); const vidInfo = getVideoInfo(); const storedVideoTime = getStoredTime(vidInfo.animeName, vidInfo.episodeNum, storage); if (!storedVideoTime) { getValueByRequest('id').then(id => { pushDataEntry(makeDataEntry(id), getStorage()); setupTimestamps(); }); return; } if ((currentTime / player.duration) > 0.9) { // Mark as watched if (!reachedWatchedStatus && storedVideoTime.animeId) { reachedWatchedStatus = true; addWatched(storedVideoTime.animeId, vidInfo.episodeNum, storage); } // Delete the storage entry if (player.duration - currentTime <= 20) return deleteDataEntry(storedVideoTime, storage); } bumpSyncDiff(storage, 'videoTimeUpdate'); storedVideoTime.time = Math.floor(currentTime); saveData(storage); } function setSeekThumbnailsState(on) { const elem = $('.anitracker-progress-tooltip'); if (elem.length) { elem.trigger(on ? 'anitracker:enabled' : 'anitracker:disabled'); return; } if (on) requestSeekThumbnails(); } function updateSetting(id, value) { anitrackerSettings[id] = value; if (player.readyState < 2) return; const vidInfo = getVideoInfo(); const storedVideoTime = getStoredTime(vidInfo.animeName, vidInfo.episodeNum); if (id === 'seekPoints' && storedVideoTime.hasTimestamps) { setSeekPoints(value ? storedVideoTime.timestampData : []); } else if (id === 'seekThumbnails') setSeekThumbnailsState(value); else if (id === 'skipButton') { if (value) { timestamps = storedVideoTime.timestampData; checkActiveTimestamps(); } else { setSkipBtnVisibility(false); timestamps = []; } } } let timestampEditModeEnabled = false; // MARKER:MESSAGES FROM MAIN PAGE const requests = {}; // Messages received from main page window.onmessage = async function(e) { const data = e.data; if (initialStorage.debug?.msg) console.log('Received from main page: ' + (typeof(e.data) === 'object' ? JSON.stringify(e.data) : e.data)); const action = data.action; if (action === 'response') { requests[data.type]?.onsuccess(data.value); } else if (action === 'newer_time') { if (player.paused && data.time !== undefined && data.time > player.currentTime) player.currentTime = data.time; } else if (action === 'key') { if (!data.event.shiftKey && !data.event.ctrlKey) { if (data.key === 'f') return showMessage('Press again for full screen'); if (anitrackerSettings.copyScreenshots && pressedKeybind(data.event, anitrackerSettings.keybindScreenshot)) return showMessage('Press again to copy screenshot'); else if ([' ','k'].includes(data.key)) { if (player.paused) player.play(); else player.pause(); return; } else if (data.key === 'ArrowLeft') { player.currentTime = Math.max(0, player.currentTime - 5); return; } else if (data.key === 'ArrowRight') { player.currentTime = Math.min(player.duration, player.currentTime + 5); return; } else if (/^\d$/.test(data.key) && data.event.code.startsWith('Digit')) { player.currentTime = (player.duration/10)*(+data.key); return; } else if (data.key === 'm') { player.muted = !player.muted; return; } } $(player).trigger('keydown', {event: data.event}); } else if (action === 'setting_changed') { updateSetting(data.id, data.value); } else if (action === 'timestamp_edit_mode') { timestampEditMode(); } }; function timestampEditMode() { if (timestampEditModeEnabled) return; timestampEditModeEnabled = true; sendMessage({action:'timestamp_edit_mode_toggle',value:true}); const vidInfo = getVideoInfo(); const storage = getStorage(); const storedVideoTime = getStoredTime(vidInfo.animeName, vidInfo.episodeNum, storage); if (!storedVideoTime) { showMessage('Error: no data object'); return; } let newTimestamps = copyObj(storedVideoTime.timestampData || []); const types = ['recap','opening','ending','preview']; let currentType = 'opening'; $('.anitracker-message').on('anitracker:message_close', () => { showMessage(`
W - Set start  E - Set end
R - Remove all  D - Done 
`, 0, true); setType(currentType); }).trigger('anitracker:message_close'); const keydownFn = (e) => { if (!e.key) return; if (['ArrowUp','ArrowDown'].includes(e.key) && !e.ctrlKey) { let index = types.indexOf(currentType); if (e.key === 'ArrowUp') index--; if (e.key === 'ArrowDown') index++; if (index < 0) index = types.length - 1; if (index >= types.length) index = 0; setType(types[index]); e.preventDefault(); e.stopPropagation(); } const key = e.key.toLowerCase(); if (['d','q'].includes(key)) exit(key === 'd'); else if (key === 'r') { $('.anitracker-seek-points>i').remove(); newTimestamps = newTimestamps.filter(a => a.type !== currentType); } else if (key === 'w') setTimestamp(Math.floor(player.currentTime), 'start'); else if (key === 'e') { if (currentType === 'preview') return showMessage("Preview only has a start"); setTimestamp(Math.floor(player.currentTime), 'end'); } }; function exit(save) { $(document).off('keydown', keydownFn); $('#anitracker-timestamp-edit-cancel').off('click', exit); $('.anitracker-message').off('anitracker:message_close').hide(); $('.anitracker-seek-points>i').remove(); timestampEditModeEnabled = false; sendMessage({action:'timestamp_edit_mode_toggle',value:false}); if (save === true) { newTimestamps = newTimestamps.filter(a => a.start !== undefined || a.end !== undefined); sendMessage({action:'timestamp_edit_mode_done', timestamps:newTimestamps}); const storage = getStorage(); if (storage.settings.skipButton) timestamps = newTimestamps; if (storage.settings.seekPoints) setSeekPoints(newTimestamps); const storedVideoTime = getStoredTime(vidInfo.animeName, vidInfo.episodeNum, storage); if (!storedVideoTime) return; const hasTimestamps = Boolean(newTimestamps.find(a => a.start >= 0)); storedVideoTime.hasTimestamps = hasTimestamps; if (!hasTimestamps) { saveData(storage); return; } storedVideoTime.timestampData = newTimestamps; saveData(storage); } else { if (storage.settings.seekPoints) setSeekPoints(storedVideoTime.timestampData || []); } } $(document).on('keydown', keydownFn); $('#anitracker-timestamp-edit-cancel').on('click', exit); function setType(type) { currentType = type; $('#anitracker-timestamp-edit-current').text(`Currently editing: ↕️ ${type[0].toUpperCase()}${type.slice(1)}`); $('.anitracker-seek-points>i').remove(); const obj = getTypeObj(); if (obj.start !== undefined) setTimestamp(obj.start, 'start'); if (obj.end !== undefined) setTimestamp(obj.end, 'end'); } function setTimestamp(time, type) { // type parameter here is 'start' or 'end' $(`#anitracker-timestamp-edit-${type}-point`).remove(); getTypeObj()[type] = time; if (time < 0) return; const percentage = Math.min((time / player.duration) * 100, 100); $(``).appendTo('.anitracker-seek-points'); } function getTypeObj() { const found = newTimestamps.find(a => a.type === currentType); if (found) return found; newTimestamps.push({type: currentType}); return newTimestamps[newTimestamps.length - 1]; } } $('.plyr--full-ui').attr('tabindex','1'); let skipBtnVisible = false; function setSkipBtnVisibility(on) { const elem = $('.anitracker-skip-button'); if (on && !skipBtnVisible) { elem.css('opacity','1').css('pointer-events','').css('translate',''); elem.attr('tabindex','2'); skipBtnVisible = true; } else if (!on && skipBtnVisible) { elem.css('opacity','0').css('pointer-events','none').css('translate','-50%'); elem.removeClass('anitracker-hide-control'); elem.attr('tabindex','-1'); elem.off('click'); skipBtnVisible = false; } } const skipTexts = { 'recap': 'Skip Recap', 'opening': 'Skip Opening', 'ending': 'Skip Ending', 'preview': 'Skip to End' }; function checkActiveTimestamps(time = player.currentTime) { if (!timestamps.length) return; let activeTimestamp; for (const t of timestamps) { if (time > t.start && (time < (t.end - 2) || t.end === undefined)) { activeTimestamp = t; break; } } if (activeTimestamp === undefined) { setSkipBtnVisibility(false); return; } const elem = $('.anitracker-skip-button'); const text = skipTexts[activeTimestamp.type] || 'Skip Section'; if (text === elem.text() && skipBtnVisible) { if (time - activeTimestamp.start > 4) { elem.addClass('anitracker-hide-control'); } return; } setSkipBtnVisibility(true); elem.text(text).off('click').on('click', () => { player.focus(); player.currentTime = activeTimestamp.end !== undefined ? activeTimestamp.end - 2 : player.duration; setSkipBtnVisibility(false); }); } // Return values: // -1 - request has failed // 0 - request has not been sent yet // 1 - request is underway // 2 - request succeeded function getRequestStatus(type) { const entry = requests[type]; if (!entry) return 0; return entry.status; } function requestIsInProgress(type) { return getRequestStatus(type) === 1; } function requestHasFailed(type) { return getRequestStatus(type) === -1; } function requestHasSucceeded(type) { return getRequestStatus(type) === 2; } function getRequestWaitTime(type) { return ({ 'id': 1000, 'anidb_id': 1000, 'video_source': 8000, 'first_episode': 8000, 'name': 1000 })[type] || 100; } function sendRequest(type) { requests[type] = {}; const req = requests[type]; req.status = 1; req.promise = new Promise((resolve, reject) => { const rejTimeout = setTimeout(() => { requests[type].status = -1; reject(`Couldn't get requested ${type}`); }, getRequestWaitTime(type)); req.onsuccess = (value) => { requests[type].status = 2; requests[type].value = value; clearTimeout(rejTimeout); resolve(value); }; }); sendMessage({action:'request',type:type}); return req.promise; } function sendOrGetRequest(type) { if (requestIsInProgress(type)) return requests[type].promise; return sendRequest(type); } function getValueByRequest(type) { return new Promise(resolve => { if (requestHasFailed()) return resolve(undefined); if (requestHasSucceeded()) return resolve(requests[type].value); sendOrGetRequest(type) .then(value => {resolve(value)}) .catch(() => {resolve(undefined)}); }); } function makeDataEntry(id = undefined) { const vidInfo = getVideoInfo(); const obj = { videoPaths: [getVideoPath(url)], time: Math.floor(player.currentTime), animeName: vidInfo.animeName, episodeNum: vidInfo.episodeNum, duration: Math.floor(player.duration) }; if (id) obj.animeId = id; return obj; } function pushDataEntry(obj, storage) { if (getStoredTime(obj.animeName, obj.episodeNum, storage)) return; if (isSyncEnabled(storage)) { storage.sync.temp.addedData.push({type: 'videoTimes', animeName: obj.animeName, episodeNum: obj.episodeNum}); } storage.videoTimes.push(obj); if (storage.videoTimes.length > getStorageLimits().videoTimes) { storage.videoTimes.splice(0,1); } saveData(storage); } function deleteDataEntry(entry, storage) { if (isSyncEnabled(storage)) { storage.sync.temp.removedData.push(...storage.videoTimes.filter(g => g.animeName === entry.animeName && g.episodeNum === entry.episodeNum).map(() => {return {type: 'videoTimes', animeName: entry.animeName, episodeNum: entry.episodeNum}})); } storage.videoTimes = storage.videoTimes.filter(a => !(a.animeName === entry.animeName && a.episodeNum === entry.episodeNum)); saveData(storage); } function initialSeek(time) { if (time === 0) return finishedLoading(); $(player).on('seeked', function fn() { finishedLoading(); $(player).off('seeked', fn); }); player.currentTime = time; } function applyPlaybackSpeedFromEntry(id, storage = getStorage()) { const storedPlaybackSpeed = storage.videoSpeed.find(a => a.animeId === id); if (storedPlaybackSpeed) setSpeed(storedPlaybackSpeed.speed); } function setupVars(storedVideoTime) { if (storedVideoTime.animeId) applyPlaybackSpeedFromEntry(storedVideoTime.animeId); if (!storedVideoTime.hasTimestamps) return; if (storedVideoTime.timestampData?.timestamps) setupTimestamps(); // Handle previous format else applyTimestampData(storedVideoTime.timestampData); } function upgradeVideoTimeData(storedVideoTime, storage) { const videoPath = getVideoPath(url); if (!storedVideoTime.videoPaths.includes(videoPath)) { bumpSyncDiff(storage, 'videoTimeEntryUpdate'); storedVideoTime.videoPaths.push(videoPath); saveData(storage); } if (storedVideoTime.duration === undefined) { bumpSyncDiff(storage, 'videoTimeEntryUpdate'); storedVideoTime.duration = Math.floor(player.duration); saveData(storage); } if (!storedVideoTime.animeId) getValueByRequest('id').then(id => { if (!id) return; const storage = getStorage(); const storedVideoTime2 = getStoredTime(storedVideoTime.animeName, storedVideoTime.episodeNum, storage); storedVideoTime2.animeId = id; saveData(storage); applyPlaybackSpeedFromEntry(id, storage); }); } // MARKER:VIDEO LOADED EVENT $(player).on('progress', function loadVideoData() { if (player.readyState < 2) return; $(player).off('progress', loadVideoData); // Set up video events let lastTimeUpdate = 0; player.addEventListener('timeupdate', function() { const currentTime = player.currentTime; checkActiveTimestamps(currentTime); if (Math.trunc(currentTime) % 10 === 0 && player.currentTime - lastTimeUpdate > 9) { updateStoredTime(); lastTimeUpdate = player.currentTime; } }); $(player).on('timeupdate', function fn() { if (player.currentTime === 0) return; $('.plyr__time').click(); // Toggle to show time elapsed instead of time remaining $(player).off('timeupdate', fn); }); player.addEventListener('pause', updateStoredTime); player.addEventListener('ended', updateStoredTime); player.addEventListener('seeked', () => { updateStoredTime(); checkActiveTimestamps(); }); player.addEventListener('ratechange', () => { if (player.readyState > 2) updateStoredPlaybackSpeed(player.playbackRate); }); // Events end player.playbackRate = 1; // Get stored video time const storage = getStorage(); const vidInfo = getVideoInfo(); const storedVideoTime = getStoredTime(vidInfo.animeName, vidInfo.episodeNum, storage); // // If time exists: if (storedVideoTime) { setupVars(storedVideoTime); upgradeVideoTimeData(storedVideoTime, storage); initialSeek(Math.max(0, Math.min(storedVideoTime.time, player.duration))); } else { getValueByRequest('id').then(id => { pushDataEntry(makeDataEntry(id), getStorage()); setupTimestamps(); if (id) applyPlaybackSpeedFromEntry(id); }); finishedLoading(); } // Handle the time argument const timeArg = Array.from(new URLSearchParams(window.location.search)).find(a => a[0] === 'time'); if (timeArg) { const newTime = +timeArg[1]; if (!storedVideoTime || (storedVideoTime && Math.floor(storedVideoTime.time) === Math.floor(newTime)) || (storedVideoTime && confirm(`[AnimePahe Improvements]\n\nYou already have saved progress on this video (${secondsToHMS(storedVideoTime.time)}). Do you want to overwrite it and go to ${secondsToHMS(newTime)}?`))) { initialSeek(Math.max(0, Math.min(newTime, player.duration))); } window.history.replaceState({}, document.title, url); } // // Replace the capture button and assign events $('button[data-plyr="capture"]').replaceWith($('button[data-plyr="capture"]').clone()); // Just to remove existing event listeners $('button[data-plyr="capture"]').on('click', takeScreenshot); // }); if (player.readyState > 2) $(player).trigger('progress'); function takeScreenshot() { const canvas = document.createElement('canvas'); canvas.height = player.videoHeight; canvas.width = player.videoWidth; const ctx = canvas.getContext('2d'); ctx.drawImage(player, 0, 0, canvas.width, canvas.height); if (anitrackerSettings.copyScreenshots) { canvas.toBlob(async (blob) => { try { await navigator.clipboard.write([ new ClipboardItem({[blob.type]: blob}) ]); showMessage('Copied screenshot!'); } catch (e) { console.error(e); showMessage("Couldn't copy screenshot!"); alert("[AnimePahe Improvements]\n\nCouldn't copy screenshot. Try disabling the Copy Screenshots option."); return; } }); } else { // Otherwise, download const element = document.createElement('a'); element.setAttribute('href', canvas.toDataURL('image/png')); element.setAttribute('download', $('.ss-label').text()); element.click(); element.remove(); } } function getFrame(video, time, dimensions) { return new Promise((resolve) => { video.onseeked = () => { const canvas = document.createElement('canvas'); canvas.height = dimensions.y; canvas.width = dimensions.x; const ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, canvas.width, canvas.height); canvas.toBlob(blob => { resolve(URL.createObjectURL(blob)); }, 'image/png'); }; try { video.currentTime = time; } catch (e) { console.error(time, e); } }); } const settingsContainerId = (() => { for (const elem of $('.plyr__menu__container')) { const regex = /plyr-settings-(\d+)/.exec(elem.id); if (regex === null) continue; return regex[1]; } return undefined; })(); function getThumbnailTime(time, timeBetweenThumbnails, fullDuration) { // Make thumbnails in the middle of the "time between thumbnails" slots by adding half the interval time to them const thumbnailTime = Math.trunc(time/timeBetweenThumbnails)*timeBetweenThumbnails + Math.trunc(timeBetweenThumbnails / 2); return Math.min(thumbnailTime, fullDuration); } function setupSeekThumbnails(videoSource) { const resolution = 167; const bgVid = document.createElement('video'); bgVid.height = resolution; bgVid.onloadeddata = () => { let enabled = true; const fullDuration = bgVid.duration; const timeBetweenThumbnails = fullDuration/(24*6); // Just something arbitrary that seems good const thumbnails = []; const aspectRatio = bgVid.videoWidth / bgVid.videoHeight; const aspectRatioCss = `${bgVid.videoWidth} / ${bgVid.videoHeight}`; $('.plyr__progress .plyr__tooltip').hide(); $(`
0:00
`).insertAfter(`progress`); $('.anitracker-progress-tooltip img').on('load', () => { $('.anitracker-progress-tooltip img').css('display', 'block'); }); const toggleVisibility = (on) => { if (on) $('.anitracker-progress-tooltip').css('opacity', '1').css('scale','1').css('translate',''); else $('.anitracker-progress-tooltip').css('opacity', '0').css('scale','0.75').css('translate','-12.5% 20px'); }; const elem = $('.anitracker-progress-tooltip'); const seekElem = $(`#plyr-seek-${settingsContainerId}`); let currentTime = 0; let seekTimeout; new MutationObserver(function() { if (!enabled) return; if ($('.plyr--full-ui').hasClass('plyr--hide-controls') || !seekElem[0].matches(`#plyr-seek-${settingsContainerId}:hover,#plyr-seek-${settingsContainerId}:focus`)) { toggleVisibility(false); return; } toggleVisibility(true); const seekValue = seekElem.attr('seek-value') || ((+seekElem.attr('aria-valuenow') / fullDuration) * 100); const time = seekValue !== undefined ? Math.min(Math.max(Math.trunc(fullDuration*(+seekValue/100)), 0), fullDuration) : Math.trunc(player.currentTime); const timeSlot = Math.trunc(time/timeBetweenThumbnails); const roundedTime = getThumbnailTime(time, timeBetweenThumbnails, fullDuration); elem.find('span').text(secondsToHMS(time)); elem.css('left', seekValue + '%'); if (roundedTime === getThumbnailTime(currentTime, timeBetweenThumbnails, fullDuration)) return; currentTime = time; const cached = thumbnails.find(a => a.time === timeSlot); if (cached) return elem.find('img').attr('src', cached.data); elem.find('img').css('display', 'none'); clearTimeout(seekTimeout); seekTimeout = setTimeout(() => { getFrame(bgVid, roundedTime, {y: resolution, x: resolution*aspectRatio}).then((response) => { thumbnails.push({ time: timeSlot, data: response }); if (roundedTime !== getThumbnailTime(currentTime, timeBetweenThumbnails, fullDuration)) return; if (initialStorage.debug?.seekThumbnails) console.log('thumb:',timeSlot,response); elem.find('img').attr('src', response); }); }, 50); }).observe(seekElem[0], { attributes: true }); seekElem.on('mouseleave blur', (e) => { if (e.type === 'mouseleave') seekElem.blur(); toggleVisibility(false); }); $('.anitracker-progress-tooltip').on('anitracker:disabled', () => { $('.anitracker-progress-tooltip').hide(); $('.plyr__progress .plyr__tooltip').show(); enabled = false; }); $('.anitracker-progress-tooltip').on('anitracker:enabled', () => { $('.anitracker-progress-tooltip').show(); $('.plyr__progress .plyr__tooltip').hide(); enabled = true; }); }; if (initialStorage.debug?.seekThumbnails) { $(``).appendTo($(player).parents().eq(1)) .on('click', () => { console.log('started'); const canvas = document.createElement('canvas'); canvas.height = resolution; canvas.width = resolution * 1.77777778; const ctx = canvas.getContext('2d'); ctx.drawImage(bgVid, 0, 0, canvas.width, canvas.height); canvas.toBlob(blob => { const src = URL.createObjectURL(blob); console.log('showing image!', src); $(`
`).appendTo($(player).parents().eq(1)); }, 'image/png'); }); } const hls2 = new Hls({ maxBufferLength: 0.1, backBufferLength: 0, capLevelToPlayerSize: true, maxAudioFramesDrift: Infinity }); hls2.loadSource(videoSource); hls2.attachMedia(bgVid); } // Thumbnails when seeking async function requestSeekThumbnails() { if (!Hls.isSupported()) return; const videoSource = await getValueByRequest('video_source'); if (!videoSource) { if (typeof hls !== "undefined") setupSeekThumbnails(hls.url); return; } setupSeekThumbnails(videoSource); } if (initialStorage.settings.seekThumbnails) requestSeekThumbnails(); function finishedLoading() { if (!$('.anitracker-loading').length) return; $('.anitracker-loading').remove(); $('button.plyr__controls__item:nth-child(1)').show(); $('.plyr__progress__container').show(); $('.plyr__control--overlaid').show(); const storage = getStorage(); if (storage.settings.autoPlayVideo === true) player.play().catch(() => { showMessage('Auto-play failed! Try enabling autoplay/sound for this site.', 6000, true); }); } let messageTimeout; function showMessage(text, time = 1000, html = false) { $('.anitracker-message span').empty(); if (html) $('.anitracker-message span').html(text); else $('.anitracker-message span').text(text); $('.anitracker-message').css('display', 'flex'); clearTimeout(messageTimeout); if (time === 0) return; messageTimeout = setTimeout(() => { $('.anitracker-message').hide().trigger('anitracker:message_close'); }, time); } const frametime = 1 / 24; let funPitch = ""; let loop = player.loop; // MARKER:VIDEO KEYBOARD SHORTCUTS $(document).on('keydown', function(e, other = undefined) { if (!e.key) e = other.event; const key = e.key; if (pressedKeybind(e, anitrackerSettings.keybindToggleLoop)) { showMessage('Loop: ' + (loop ? 'Off' : 'On')); loop = !loop; player.loop = loop; return; } if (['l','L'].includes(e.key)) setTimeout(() => {player.loop = loop}, 5); if (anitrackerSettings.changeSpeedArrows) { if (key === 'ArrowUp') { changeSpeed(e, -1); // The changeSpeed function only works if ctrl is being held return; } if (key === 'ArrowDown') { changeSpeed(e, 1); return; } } if (pressedKeybind(e, anitrackerSettings.keybind10sBackward)) { player.currentTime = Math.max(0, player.currentTime - 10); return; } else if (pressedKeybind(e, anitrackerSettings.keybind10sForward)) { player.currentTime = Math.min(player.duration, player.currentTime + 10); return; } if (!(player.currentTime > 0 && !player.paused && !player.ended && player.readyState > 2)) { if (pressedKeybind(e, anitrackerSettings.keybind1fBackward)) { player.currentTime = Math.max(0, player.currentTime - frametime); return; } else if (pressedKeybind(e, anitrackerSettings.keybind1fForward)) { player.currentTime = Math.min(player.duration, player.currentTime + frametime); return; } } if (player.readyState > 2) { if (pressedKeybind(e, anitrackerSettings.keybindScreenshot)) return takeScreenshot(); if (pressedKeybind(e, anitrackerSettings.keybindPlayerStart)) { return player.currentTime = 0; } if (pressedKeybind(e, anitrackerSettings.keybindPlayerEnd)) { return player.currentTime = player.duration; } } if (!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) { if (/^Numpad\d$/.test(e.code) && anitrackerSettings.numpadSeeking) { player.currentTime = (player.duration/10)*(+e.code.replace('Numpad', '')); return; } funPitch += key; if (funPitch === 'crazy') { player.preservesPitch = !player.preservesPitch; showMessage(player.preservesPitch ? 'Off' : 'Change speed ;D'); funPitch = ""; return; } if (!"crazy".startsWith(funPitch)) { funPitch = ""; } } if (e.msg) return; // If this was a message from main page, don't do recursive stuff sendMessage({action:"key",key:e.key,event:{key:e.key, ctrlKey:e.ctrlKey, shiftKey:e.shiftKey, altKey:e.altKey, metaKey:e.metaKey, msg:true}}); }); // Ctrl+scrolling to change speed $(` `).appendTo($(player).parents().eq(1)); jQuery.event.special.wheel = { setup: function( _, ns, handle ){ this.addEventListener("wheel", handle, { passive: false }); } }; const defaultSpeeds = player.plyr.options.speed; function changeSpeed(e, delta) { if (!e.ctrlKey) return; if (e.preventDefault) e.preventDefault(); if (delta == 0) return; const speedChange = e.shiftKey ? 0.05 : 0.1; setSpeed(player.playbackRate + speedChange * (delta > 0 ? -1 : 1)); } function setSpeed(speed) { if (speed > 0) player.playbackRate = Math.round(speed * 100) / 100; showMessage(player.playbackRate + "x"); if (defaultSpeeds.includes(player.playbackRate)) { $('.anitracker-custom-speed-btn').remove(); } else if (!$('.anitracker-custom-speed-btn').length) { $(`#plyr-settings-${settingsContainerId}-speed>div>button`).attr('aria-checked','false'); $(` `).prependTo(`#plyr-settings-${settingsContainerId}-speed>div`); for (const elem of $(`#plyr-settings-${settingsContainerId}-home>div>`)) { if (!/^Speed/.test($(elem).children('span')[0].textContent)) continue; $(elem).find('span')[1].textContent = "Custom"; } } } $(`#plyr-settings-${settingsContainerId}-speed>div>button`).on('click', () => { $('.anitracker-custom-speed-btn').remove(); }); $(document).on('wheel', function(e) { if (anitrackerSettings.changeSpeedScroll) changeSpeed(e, e.originalEvent.deltaY); }); } } if (/^https:\/\/kwik\.\w+/.test(baseUrl)) { anitrackerKwikLoad(); return; } if (typeof $ !== 'undefined' && $() !== null) anitrackerLoad(); else { for (const elem of document.querySelectorAll('head > link')) { if (!elem.href.includes('jquery')) continue; elem.addEventListener('load', anitrackerLoad); break; } } function anitrackerLoad() { if ($('#anitracker-modal').length) { console.log("[AnimePahe Improvements] Script was reloaded."); return; } if (initialStorage.settings.hideThumbnails === true) { hideThumbnails(); } if (initialStorage.settings.stickyHeader === true) { stickyHeader(true); } function windowOpen(url, target = '_blank') { $(``)[0].click(); } (function($) { $.fn.changeElementType = function(newType) { let attrs = {}; $.each(this[0].attributes, function(idx, attr) { attrs[attr.nodeName] = attr.nodeValue; }); this.replaceWith(function() { return $("<" + newType + "/>", attrs).append($(this).contents()); }); }; $.fn.replaceClass = function(oldClass, newClass) { this.removeClass(oldClass).addClass(newClass); return this; }; })(jQuery); jQuery.anitrackerCachedScript = function(surl, success) { return $.ajax({ url: surl, dataType: 'script', cache: true, success: success }); } // -------- AnimePahe Improvements CSS --------- const animationTimes = { modalOpen: 0.2, fadeIn: 0.2, flash: 0.2, }; // MARKER:MAIN PAGE CSS const _css = ` :root { --anitracker-dark: rgb(20, 26, 31); --anitracker-darker: rgb(14, 20, 23); --pahe-pink: #d5015b; } #anitracker, .anitracker-button-row { display: flex; gap: 7px 7px; align-items: center; flex-wrap: wrap; } .anitracker-index { display: flex; flex-wrap: wrap; align-items: end; gap: 15px 7px; margin-bottom: 10px; } #anitracker>span {align-self: center;\n} #anitracker-modal { position: fixed; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); z-index: 20; display: flex; visibility: hidden; will-change: opacity; } #anitracker-modal-content { max-height: 90%; max-width: 100%; background-color: var(--dark); margin: auto auto auto auto; border-radius: 20px; display: flex; padding: 20px; z-index:50; box-shadow: rgba(0, 0, 0, 0.49) 0px 0px 10px 2px; } #anitracker-modal-content>div { display:flex; flex-direction:column; max-width: 100%; } #anitracker-modal-close { font-size: 2.5em; margin-right: 5px; cursor: pointer; height: 1em; aspect-ratio: 1; border-radius: 5px; text-align: center; position: absolute; margin-top: -5px; } #anitracker-modal-close:hover,#anitracker-modal-close:focus-visible { color: rgb(255, 0, 108); background-color: rgb(28, 28, 34); } #anitracker-modal-close:active { translate: 0px 7%; } #anitracker-modal-content.shift #anitracker-modal-close { position: relative; } #anitracker-modal-title, #anitracker-modal-subtitle { margin: 0px auto; width: fit-content; display: block; } #anitracker-modal-header { padding: 5px; flex-shrink: 0; cursor: pointer; } #anitracker-modal-content:not(.shift) #anitracker-modal-header {min-height: 2.3rem;\n} #anitracker-modal-body { padding: 10px; overflow-y: auto; } #anitracker-modal-body .anitracker-switch {margin-bottom: 2px;\n} #anitracker-message-container>span { min-width: 14rem; max-width: 24rem; display: block; position: fixed; z-index: 21; padding: 10px; background-color: rgb(30,35,40); border-radius: 32px; text-align: center; bottom: 5rem; border: 5px solid var(--pahe-pink); pointer-events: none; } .anitracker-collection-image-wrapper { display: inline; aspect-ratio: 1; border-radius: 0.25rem; overflow: hidden; display: flex; align-items: center; } .anitracker-collection-image-wrapper:nth-child(1) { translate: 0px -5px; } .anitracker-collection-image-wrapper:nth-child(2) { translate: 0px 5px; } .anitracker-big-list-item { list-style: none; border-radius: 10px; margin-top: 5px; } .anitracker-big-list-item>a { font-size: 0.875rem; display: block; padding: 5px 15px; color: rgb(238, 238, 238); text-decoration: none; } .anitracker-big-list-item .anitracker-image-wrapper { width: 50px; height: 50px; border-radius: .25rem; margin: auto 0px; overflow: hidden; display: flex; align-items: center; } .anitracker-big-list-item .anitracker-image-wrapper.anitracker-inline { display: inline-flex; } .anitracker-big-list-item img { width: 100%; height: auto; } .anitracker-big-list-item .anitracker-main-text { font-weight: 700; color: rgb(238, 238, 238); } .anitracker-big-list-item .anitracker-subtext { font-size: 0.75rem; color: rgb(153, 153, 153); } .anitracker-big-list-item:hover .anitracker-main-text { color: rgb(238, 238, 238); } .anitracker-big-list-item:hover .anitracker-subtext { color: rgb(238, 238, 238); } .anitracker-big-list-item:hover, .anitracker-big-list-item:focus-within { background-color: var(--anitracker-darker); } .anitracker-big-list-item:focus-within .anitracker-main-text { color: rgb(238, 238, 238); } .anitracker-big-list-item:focus-within .anitracker-subtext { color: rgb(238, 238, 238); } .anitracker-hide-thumbnails .anitracker-thumbnail img {display: none;\n} .anitracker-hide-thumbnails .anitracker-thumbnail { border: 10px solid rgb(32, 32, 32); aspect-ratio: 16/9; } .anitracker-hide-thumbnails .episode-snapshot img { display: none; } .anitracker-hide-thumbnails .episode-snapshot { border: 4px solid var(--dark); } .anitracker-player-dropup-spinner {display: inline;\n} .anitracker-player-dropup-spinner .spinner-border { height: 0.875rem; width: 0.875rem; } .anitracker-episode-spinner { position: absolute; display: flex; justify-content: center; align-items: center; z-index: 2; width: 100%; height: 100%; } .anitracker-episode-spinner>.spinner-border { width: 5rem; height: 5rem; border-width: .5em; } .anitracker-dropdown-content { display: none; position: absolute; min-width: 100px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; max-height: 400px; overflow-y: auto; overflow-x: hidden; background-color: #171717; } .anitracker-dropdown-content button { color: white; padding: 12px 16px; text-decoration: none; display: block; width:100%; background-color: #171717; border: none; margin: 0; } .anitracker-dropdown-content button:hover, .anitracker-dropdown-content button:focus {background-color: black;\n} .anitracker-dropdown-content i { margin-right: 6px; } .anitracker-dropdown-content span { color: rgb(177, 177, 177); padding: 4px 16px; text-align: center; display: block; } .anitracker-active, .anitracker-active:hover, .anitracker-active:active { color: white!important; background-color: var(--pahe-pink)!important; } .anitracker-dropdown-content a:hover {background-color: #ddd;\n} .anitracker-dropdown:hover .anitracker-dropdown-content {display: block;\n} .anitracker-dropdown:hover .anitracker-dropbtn {background-color: #bc0150;\n} #pickDownload span, #scrollArea span { cursor: pointer; font-size: 0.875rem; } .anitracker-expand-data-icon { font-size: 24px; float: right; margin-top: 2px; margin-right: 10px; } .anitracker-modal-list-container { background-color: var(--anitracker-dark); margin-bottom: 8px; border-radius: 12px; } .anitracker-storage-data { background-color: var(--anitracker-dark); border-radius: 12px; cursor: pointer; position: relative; z-index: 1; } .anitracker-storage-data.anitracker-expanded:not(:focus-visible)::before { content: ""; background: var(--dark); position: absolute; top: 100%; left: 25%; height: 2px; width: 50%; animation: anitracker-fadeIn .3s forwards linear; } .anitracker-storage-data:focus-visible { outline: 2px solid #ddd; } .anitracker-storage-data span { display: inline-block; font-size: 1.1em; } .anitracker-storage-data, .anitracker-modal-list { padding: 8px 14px; } .anitracker-modal-list { overflow: hidden; } .anitracker-modal-list.flex { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; } .anitracker-modal-list-entry {margin-top: 8px;\n} .anitracker-modal-list-entry a { text-decoration: underline; display: inline-block; } .anitracker-modal-list-entry:hover, .anitracker-modal-list-entry:focus-within {background-color: var(--anitracker-darker);\n} .anitracker-relation-link { text-overflow: ellipsis; overflow: hidden; } .anitracker-spinner { color: var(--pahe-pink); } .anitracker-spinner>span { color: white; } #anitracker-cover-spinner .spinner-border { width:2rem; height:2rem; } .anime-cover { display: flex; justify-content: center; align-items: center; image-rendering: optimizequality; } .anitracker-filter-input { width: 12.2rem; display: inline-block; cursor: text; } .anitracker-filter-input > div { height:56px; width:100%; border-bottom: 2px solid #454d54; overflow-y: auto; } .anitracker-filter-input.active > div { border-color: rgb(213, 1, 91); } .anitracker-filter-rules { background: black; border: 1px solid #bbb; color: #bbb; padding: 5px; float: right; border-radius: 5px; font-size: .8em; width: 2em; aspect-ratio: 1; margin-bottom: -10px; z-index: 1; position: relative; min-height: 0; } .anitracker-filter-rules>i { vertical-align: super; } .anitracker-filter-rules.anitracker-active { border-color: rgb(213, 1, 91); } .anitracker-filter-rules:hover, .anitracker-filter-rules:focus-visible { background: white; color: black; border: 2px solid black; outline: 1px solid white; } .anitracker-filter-input-search { position: absolute; max-width: 150px; max-height: 45px; min-width: 150px; min-height: 45px; overflow-wrap: break-word; overflow-y: auto; } .anitracker-filter-input .placeholder { color: #999; position: absolute; z-index: -1; } .anitracker-filter-icon { padding: 0; padding-right: 4px; border-radius: 12px; display: inline-block; cursor: pointer; border: 2px solid white; margin-right: 5px; transition: background-color .3s, border-color .3s; vertical-align: text-top; font-size: .95em; } .anitracker-filter-icon>i { margin: 2px; margin-left: 3px; font-size: .8em; } .anitracker-filter-icon.included { background-color: rgba(20, 113, 30, 0.64); border-color: rgb(5, 134, 5); } .anitracker-filter-icon.included>i { color: rgb(83, 255, 83); } .anitracker-filter-icon.excluded { background-color: rgba(187, 62, 62, 0.41); border-color: #d75a5a; } .anitracker-filter-icon.excluded>i { color: rgb(227, 96, 96); } .anitracker-filter-icon:hover { border-color: white; } #anitracker-settings-invert-switch:checked ~ .custom-control-label::before { border-color: red; background-color: red; } #anitracker-settings-invert-switch:checked[disabled=""] ~ .custom-control-label::before { border-color: #e88b8b; background-color: #e88b8b; } .anitracker-text-input { display: inline-block; height: 1em; line-break: anywhere; min-width: 50px; } .anitracker-text-input-bar { background: #333; box-shadow: none; color: #bbb; } .anitracker-text-input-bar:focus { border-color: var(--pahe-pink); background: none; box-shadow: none; color: #ddd; } .anitracker-text-input-bar[disabled=""] { background: rgb(89, 89, 89); border-color: gray; cursor: not-allowed; } .anitracker-applied-filters { display: inline-block; } .anitracker-placeholder { color: gray; } .anitracker-filter-dropdown>button { transition: background-color .3s; } .anitracker-filter-dropdown>button.included { background-color: rgb(6, 130, 54); } .anitracker-filter-dropdown>button.included:focus { outline: 2px dashed rgb(141, 234, 141); } .anitracker-filter-dropdown>button.included::before { content: "\\f067"; font: normal normal normal 14px/1 ForkAwesome; margin-right: 3px; } .anitracker-filter-dropdown>button.excluded { background-color: rgb(117, 17, 17); } .anitracker-filter-dropdown>button.excluded:focus { outline: 2px dashed rgb(215, 90, 90); } .anitracker-filter-dropdown>button.excluded::before { content: "\\f068"; font: normal normal normal 14px/1 ForkAwesome; margin-right: 3px; } .anitracker-filter-dropdown>button.anitracker-active:focus { outline: 2px dashed #ffd7eb; } #anitracker-season-copy-to-lower { color:white; margin-left:14px; border-radius:5px; } .anitracker-filter-spinner.small { display: inline-flex; margin-left: 10px; justify-content: center; align-items: center; vertical-align: bottom; } .anitracker-filter-spinner.screen { width:100%; height:100%; background-color:rgba(0, 0, 0, 0.9); position:fixed; z-index:999; display:flex; justify-content:center; align-items:center; } .anitracker-filter-spinner.screen .spinner-border { width:5rem; height:5rem; border-width: 10px; } .anitracker-filter-spinner>span { position: absolute; font-weight: bold; } .anitracker-filter-spinner.small>span { font-size: .5em; } .anitracker-filter-rule-selection { margin-bottom: 2px; display: grid; grid-template-columns: 1.5em 32% auto; align-items: center; grid-gap: 5px; border-radius: 20px; padding: 5px; } .anitracker-filter-rule-selection[disabled=""]>* { opacity: 0.5; pointer-events: none; } .anitracker-filter-rule-selection>i { text-align: center; border-radius: 35%; padding: 2px; aspect-ratio: 1; } .anitracker-filter-rule-selection>i::before { vertical-align: middle; } .anitracker-filter-rule-selection>.fa-plus { color: rgb(72, 223, 58); background-color: #148214; } .anitracker-filter-rule-selection>.fa-minus { color: #ff0000; background-color: #911212; } .anitracker-filter-rule-selection button { padding: 0; padding-bottom: 1px; width: 2.5em; height: 2em; background-color: var(--secondary); border: 3px solid var(--dark); border-radius: 10px; outline: rgb(94, 96, 100) solid 3px; margin: 5px; color: white; } .anitracker-filter-rule-selection button.anitracker-active { outline: rgb(213, 1, 91) solid 3px; } .anitracker-filter-rule-selection button:hover:not([disabled=""]), .anitracker-filter-rule-selection button:focus-visible:not([disabled=""]) { outline: white solid 3px; } .anitracker-flat-button { padding-top: 0; padding-bottom: 0; } .anitracker-list-btn { height: 40px; border-radius: .25rem !important; color: #ddd !important; margin-left: 8px !important; } .anitracker-reverse-order-button { font-size: 2em; } .anitracker-reverse-order-button::after { vertical-align: 20px; } .anitracker-reverse-order-button.anitracker-up::after { border-top: 0; border-bottom: .3em solid; vertical-align: 22px; } #anitracker-time-search-button { float: right; } #anitracker-time-search-button svg { width: 24px; vertical-align: bottom; } .anitracker-season-group { display: grid; grid-template-columns: 10% 30% 10% 10%; margin-bottom: 5px; } .anitracker-season-group .btn-group { margin-left: 5px; } .anitracker-season-group>label { align-self: center; margin: 0; } a.youtube-preview::before { -webkit-transition: opacity .2s linear!important; -moz-transition: opacity .2s linear!important; transition: opacity .2s linear!important; } .anitracker-replaced-cover {background-position-y: 25%;\n} .anitracker-text-button { color:var(--pahe-pink); cursor:pointer; user-select:none; } .anitracker-text-button:hover, .anitracker-text-button:focus-visible { color:white; } .anitracker-title-icon { margin-left: 1rem!important; opacity: .8!important; color: inherit !important; font-size: 2rem!important; vertical-align: middle; cursor: pointer; padding: 0; box-shadow: none!important; } .anitracker-title-icon:hover,.anitracker-title-icon:focus-visible { opacity: 1!important; color: #ff006c!important; } .anitracker-title-icon-check { color: white; margin-left: -.7rem!important; font-size: 1rem!important; vertical-align: super; text-shadow: none; opacity: 1!important; } .anitracker-header { display: flex; justify-content: left; gap: 18px; flex-grow: 0.04; padding: 5px; } .anitracker-header-button { color: white; background: none; border: 2px solid white; border-radius: 5px; width: 2rem; } .anitracker-header-button:hover { border-color: #ff006c; color: #ff006c; } .anitracker-header-button:focus { border-color: #ff006c; color: #ff006c; } .anitracker-header-notifications-circle { color: rgb(255, 0, 108); margin-left: -.3rem; font-size: 0.7rem; position: absolute; } .anitracker-notification-item .anitracker-main-text { color: rgb(153, 153, 153); } .anitracker-notification-item-unwatched { background-color: rgb(82, 45, 50); outline: rgb(119, 62, 70) solid 2px; } .anitracker-notification-item-unwatched:hover { background-color: rgb(63, 37, 52); } .anitracker-notification-item-unwatched .anitracker-main-text { color: white!important; } .anitracker-notification-item-unwatched .anitracker-subtext { color: white!important; } .anitracker-watched-toggle { font-size: 1.7em; float: right; margin-right: 5px; margin-top: 5px; cursor: pointer; padding: 5px; border-radius: 5px; } .anitracker-watched-toggle:hover,.anitracker-watched-toggle:focus { outline: 1px solid #fff; } #anitracker-replace-cover { z-index: 99; right: 10px; position: absolute; bottom: 6em; } .anitracker-episode-date { margin-left: 5%; font-size: 0.75rem!important; cursor: default!important; } .episode>.anitracker-episode-date { white-space: nowrap; font-size: .75rem; text-shadow: 0 1px 2px #000,0 1px 2px #000; line-height: normal; position: absolute; top: 0px; margin: 5px; color: #fff; z-index: 1; right: 2rem; } .anitracker-episode-date:hover { text-decoration: none!important; } .anitracker-episode-progress { height: 8px; position: absolute; bottom: 0; background-color: #bc0150; z-index: 1; } .anitracker-episode-menu-button { top: 0; position: absolute; right: 0; width: 32px; height: 32px; z-index: 1; color: white; background: none; border: 0; transition: background-color .3s ease; border-radius: 10%; border-top-right-radius: 0; } .anitracker-episode-menu-button>svg { width: 6px; display: block; margin: auto; stroke: #424242; stroke-width: 32px; } .anitracker-episode-menu-button:hover, .anitracker-episode-menu-button:focus { background-color: rgba(0,0,0,0.8); color: #bc0150; } .anitracker-episode-menu-button:hover>svg, .anitracker-episode-menu-button:focus>svg { stroke-width: 0; } .anitracker-episode-menu-dropdown { z-index: 2; right:0; left: auto; top: 32px; } .anitracker-download-select-button { display: block; width: 100%; border: none; padding: 5px; margin: 5px 0; border-radius: 10px; background-color: #656f79; color: white; } .anitracker-download-select-button:hover, .anitracker-download-select-button:focus-visible { background-color: rgb(30,35,40); } .anitracker-watched-episodes-list { display: inline-block; max-width: 500px; overflow: hidden; text-overflow: ellipsis; color: gray; } .anitracker-bookmark-grid-entry { width: 14rem; padding: 6px; display: flex; flex-direction: column; justify-content: space-between; } .anitracker-bookmark-grid-entry a { text-align: center; flex-grow: 1; } .anitracker-secondary-info { color: lightgray; } .anitracker-thin-text { max-width: 16rem; text-align: center; } .anitracker-center-item { display: block; margin: auto; } .anitracker-dark-area { display: block; padding: 10px; background-color: rgb(30,35,40); border-radius: 5px; } .anitracker-sync-message { margin: 16px; } .anitracker-sync-message.info { color: white; } .anitracker-sync-message.warning { color: var(--warning); } .anitracker-sync-message.error { color: var(--danger); } .anitracker-sync-settings-bottom { display: flex; align-items: center; flex-direction: column; margin-top: 10px; } .anitracker-sync-code-display { background-color: rgb(30,35,40); padding: 10px; border-radius: 10px; display: flex; } .anitracker-sync-code-display>span { font-family: Consolas, monospace; font-size: 2em; padding: 8px; } .anitracker-sync-code-display>i { align-self: center; font-size: 1.5em; padding: 8px; cursor: pointer; width: 40px; height: 40px; } .anitracker-sync-code-display>i:focus-visible { outline: 2px solid white; } .anitracker-sync-code-input { height: 1.8em; font-size: 2em; width: 9em; text-align: center; text-transform: uppercase; } .anitracker-spin { animation: anitracker-spin 1s linear infinite; } .anitracker-page-selection { background: none; border: none; border-bottom: 3px solid #343a40; margin: 0 5px 0 5px; width: 2em; color: white; text-align: center; transition: border-color .5s; } .anitracker-page-selection:focus { border-color: #bc0150; } .anitracker-big-poster-icon { width:100%; aspect-ratio:1; border-radius: 10px; overflow: hidden; display: flex; align-items: center; } .anitracker-big-poster-icon img { width:100%; height:auto; opacity:0; } .anitracker-bookmark-list-entry>div { display: grid; grid-template-columns: max-content max-content; gap: 5px; padding-top: 5px; } .anitracker-bookmark-list-status { width:10.4em; display:inline-block; background-color:var(--dark); text-align:center; vertical-align:bottom; border: none; border-radius: .25rem; } .anitracker-bookmark-list-status:hover, .anitracker-bookmark-list-status:focus-visible { outline: 2px solid var(--secondary); } .anitracker-bookmark-grid-status { width:100%; text-align:center; border-radius:5px; border:2px solid var(--dark); background: none; margin-top: 5px; } .anitracker-bookmark-grid-status:hover, .anitracker-bookmark-grid-status:focus-visible { border-color: var(--secondary); } .anitracker-change-status-button:after { display: inline-block; content: ""; color: var(--secondary); border-top: .4em solid; border-right: .4em solid transparent; border-left: .4em solid transparent; vertical-align: middle; margin-left: 10px; } .anitracker-change-status-button.active:after { border-top: 0; border-bottom: .4em solid; } .anitracker-change-status-button:hover:after, .anitracker-change-status-button:focus-visible:after { color: white; } .anitracker-bookmark-list-status:after { margin-left: 5px; } .anitracker-bookmark-grid-status:active { background-color: var(--dark); } .anitracker-bookmark-list-status:active { background-color: var(--anitracker-dark); } .anitracker-status-dropdown { padding: 0; } .anitracker-status-dropdown button.anitracker-status-button { border: 3px solid rgb(23, 23, 23); border-radius: 5px; transition: none; padding: 10px 16px; } .anitracker-status-dropdown button.anitracker-status-button:hover, .anitracker-status-dropdown button.anitracker-status-button:focus-visible { border-color: white; } .anitracker-video-progress-item { display:grid; grid-template-columns:90px 19rem 8rem; height:100px; gap:20px; padding:5px; background-repeat: no-repeat; background-image: linear-gradient(to right, rgb(71, 25, 47), RGB(71, 25, 47)); background-size: 0 10%; background-position-y: bottom; } .anitracker-video-progress-item>a { padding:0; } .anitracker-video-progress-item .anitracker-image-wrapper { width: 90px; height: 90px; border-radius: 10%; overflow: hidden; } .anitracker-video-progress-item .anitracker-text-section { display:flex; flex-direction:column; justify-content:center; font-size:1em; } .anitracker-video-progress-item .anitracker-button-section { display:flex; flex-direction:column; gap:5px; justify-content:center; } .anitracker-video-progress-item .anitracker-main-text { overflow:hidden; text-overflow:ellipsis; max-height:2.8rem; text-decoration:underline; } .anitracker-video-progress-item .anitracker-normal-text { color: #eee; } .anitracker-video-progress-item .anitracker-video-progress-image-placeholder { background-color: var(--dark); display: flex; justify-content: center; align-items: center; height: 100%; width: 100%; } .anitracker-feed-schedule { border: 2px solid var(--secondary); border-radius: 5px; padding: 5px; margin-bottom: 5px; text-align: center; display: flex; justify-content: center; flex-wrap: wrap; } .anitracker-feed-schedule>div { min-width: 5rem; max-width: 10rem; position: relative; flex-direction: column; display: flex; } .anitracker-feed-schedule .anitracker-feed-schedule-header { padding: 5px; } .anitracker-feed-schedule .anitracker-feed-schedule-header:after { content: ""; background: var(--secondary); position: absolute; top: 2em; left: calc(50% - 1rem); height: 2px; width: 2rem; } .anitracker-feed-schedule .anitracker-feed-schedule-body { background-color: var(--anitracker-dark); min-height: 5rem; border-left: 1px solid black; border-right: 1px solid black; padding: 5px; flex-grow: 1; } .anitracker-feed-schedule .anitracker-feed-schedule-body.anitracker-feed-schedule-today { outline: 2px solid var(--secondary); z-index: 1; position: relative; } .anitracker-feed-schedule .anitracker-feed-schedule-body a { display: block; overflow: hidden; text-overflow: ellipsis; text-wrap: nowrap; max-width: fit-content; } .anitracker-feed-schedule .anitracker-feed-schedule-body a:hover { text-decoration: underline; } .anitracker-keybinds-section { display: grid; grid-template-columns: 45% auto 42px; gap: 5px; min-width: 24rem; } .anitracker-keybinds-section label { margin: 0; } .anitracker-keybinds-section button { overflow: hidden; text-overflow: ellipsis; } .anitracker-dl-options-section { display: grid; grid-template-columns: 40% auto; gap: 5px; min-width: 12rem; align-items: center; } .anitracker-dl-options-section label { margin: 0; height: fit-content; } .anitracker-center-content { display: flex; justify-content: center; } .anitracker-bookmark-grid-entry .anitracker-bookmark-new { display: block; width: 2rem; height: 2rem; margin: 0.4rem 0.4rem -2.4rem; background: var(--pahe-pink); position: relative; border-radius: 50%; border: 2px solid #fff; box-shadow: 0px 0px 5px black; z-index: 1; animation: anitracker-modalOpen 0.5s forwards linear; } .anitracker-bookmark-list-entry .anitracker-bookmark-new { display: inline-block; width: 1rem; height: 1rem; vertical-align: middle; background: var(--pahe-pink); border-radius: 50%; border: 2px solid #fff; } .anitracker-text-spinner>.spinner-border { display: block; } .anitracker-text-spinner>span { position: relative; font-weight: bold; font-size: 0.8em; display: block; top: -2em; } .anitracker-random-result-buttons { margin-left: 240px; } .anitracker-full-poster-link { display: block !important; background: rgba(0,0,0,0.4); width: fit-content; margin: auto; padding: 0 10px 0 10px; } #anitracker-bookmark-share-result { height: 100%; margin-left: auto; margin-right: auto; overflow: auto clip; } .anitracker-index-lower>div { float: right; margin-right: 6px; margin-bottom: 2rem; display: flex; flex-wrap: wrap; gap: 5px; align-items: center; } .anitracker-share-bookmarks-button { height: 40px; float: right; margin-right: 5px; } .anitracker-progress-bar { background-color: gray; border-radius: 4px; height: 8px; overflow: hidden; } .anitracker-progress-bar>div { background-color: var(--pahe-pink); transition: width .1s; height: 100%; width: 0; } .anitracker-button-spinner { width:1.2em; height:1.2em; vertical-align:center; border-width:3px; } #anitracker-continue-watching-progress { position: absolute; width: 100%; height: 100%; align-items: center; z-index:10; pointer-events: none; } #anitracker-continue-watching-progress>div { background-color: rgba(0,0,0,0.5); padding: 10px; border-radius: 8px; flex-direction:column; } .anitracker-relation-poster { filter: blur(5px) !important; } .anitracker-center-div { margin: 0px auto; width: fit-content; } a:hover .anitracker-relation-poster,a:focus-visible .anitracker-relation-poster { filter: none !important; } .player .prequel a:focus-visible, .player .sequel a:focus-visible { outline: 5px solid gray; } header.main-header nav .main-nav li.nav-item > a:focus { color: #fff; background-color: #bc0150; } .theatre-settings .dropup .btn[aria-expanded="true"]:focus,.theatre-settings .dropup .btn:focus-visible { outline: .15rem solid rgb(100, 100, 100)!important; } .index .col-12:nth-child(4n-3), .index .col-12:nth-child(4n-2) { background-color: rgb(20, 19, 25); } .index>* { width: 100%; } .nav-search { float: left!important; } header.main-header nav .nav-search .search-results-wrap a { width: 100%; } @media screen and (min-width: 1375px) { .theatre.anitracker-theatre-mode { margin-top: 10px!important; } .theatre.anitracker-theatre-mode>* { max-width: 81%!important; } #anitracker-modal-content { max-width: 80%; } } @media screen and (max-width: 700px) { .anitracker-video-progress-item { display: flex; flex-direction: column; gap: 0; text-align: center; height: auto; background-position-y: calc(90px - 1.4rem); } .anitracker-video-progress-item .anitracker-img-section { display:flex; justify-content: center; } .anitracker-random-result-buttons { width: fit-content; margin: auto; } .anitracker-bookmark-list-entry .anitracker-remove-bookmark-button>span { display: none; } .anitracker-bookmark-list-entry > div { gap: 12px; } .anitracker-bookmark-grid-entry { width: 9rem; } .anitracker-share-bookmarks-button { margin-right: 0; } .anitracker-keybinds-section { min-width: 0; } .anitracker-index, .anitracker-index-lower { margin-left: 10px; } .anitracker-episode-list-wrapper { padding: 0px 15px; } #anitracker { justify-content: center !important; } #anitracker-modal-close { margin-right: 0; } #anitracker-modal-content { padding: 10px; } .anitracker-modal-list { padding: 8px 6px; } .anitracker-feed-schedule>div { flex: 1 1 0%; } } @keyframes anitracker-modalOpen { 0% { transform: scale(0.5); } 50% { transform: scale(1.07); } 100% { transform: scale(1); } } @keyframes anitracker-fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes anitracker-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } @keyframes anitracker-flash { from { outline: 2px solid white; } to { outline: 2px solid rgba(0,0,0,0); } } `; applyCssSheet(_css); const siteVars = { prevDocumentTitle: undefined, episodePages: [], // element, apiFunction, cachedList, mode, features syncErrorCooldown: 0, modalEvents: [], messageTimeout: undefined, ongoingRequests: [], stalledRequests: [], // List of URLs siteSessionExpireMsg: { tabStates: [], promise: undefined, shown: false, }, cached: { animeSearch: [], firstEpisode: initialStorage.cached.firstEpisode, poster: initialStorage.cached.poster, episodePage: [], animeId: {}, animeSession: [], page: {}, }, }; const continueWatchingStatus = { queue: [], displayedEps: [], firstEpRequests: new Set(), inProgress: false, }; // Sets boolean options // The "value" is a variable and can change during usage const optionSwitches = [ { optionId: 'autoDelete', value: initialStorage.settings.autoDelete }, { optionId: 'theatreMode', value: initialStorage.settings.theatreMode, onEvent: () => {theatreMode(true)}, offEvent: () => {theatreMode(false)} }, { optionId: 'hideThumbnails', value: initialStorage.settings.hideThumbnails, onEvent: hideThumbnails, offEvent: () => {$('.main').removeClass('anitracker-hide-thumbnails')} }, { optionId: 'bestQuality', value: initialStorage.settings.bestQuality, onEvent: bestVideoQuality }, { optionId: 'autoDownload', value: initialStorage.settings.autoDownload }, { optionId: 'autoPlayNext', value: initialStorage.settings.autoPlayNext }, { optionId: 'autoPlayVideo', value: initialStorage.settings.autoPlayVideo }, { optionId: 'seekThumbnails', value: initialStorage.settings.seekThumbnails, onEvent: () => {sendMessage({action:'setting_changed',id:'seekThumbnails',value:true})}, offEvent: () => {sendMessage({action:'setting_changed',id:'seekThumbnails',value:false})} }, { optionId: 'seekPoints', value: initialStorage.settings.seekPoints, onEvent: () => {sendMessage({action:'setting_changed',id:'seekPoints',value:true})}, offEvent: () => {sendMessage({action:'setting_changed',id:'seekPoints',value:false})} }, { optionId: 'skipButton', value: initialStorage.settings.skipButton, onEvent: () => {sendMessage({action:'setting_changed',id:'skipButton',value:true})}, offEvent: () => {sendMessage({action:'setting_changed',id:'skipButton',value:false})} }, { optionId: 'copyScreenshots', value: initialStorage.settings.copyScreenshots, onEvent: () => {sendMessage({action:'setting_changed',id:'copyScreenshots',value:true})}, offEvent: () => {sendMessage({action:'setting_changed',id:'copyScreenshots',value:false})} }, { optionId: 'reduceMotion', value: initialStorage.settings.reduceMotion }, { optionId: 'stickyHeader', value: initialStorage.settings.stickyHeader, onEvent: () => {stickyHeader(true)}, offEvent: () => {stickyHeader(false)} }, { optionId: 'relativeEpNums', value: initialStorage.settings.relativeEpNums, onEvent: () => {setRelativeEpNums(true)}, offEvent: () => {setRelativeEpNums(false)} }, { optionId: 'showContinueWatching', value: initialStorage.settings.showContinueWatching, onEvent: setupContinueWatchingSection, offEvent: () => { if (isHome()) window.location.replace(window.location); } }, { optionId: 'numpadSeeking', value: initialStorage.settings.numpadSeeking, onEvent: () => {sendMessage({action:'setting_changed',id:'numpadSeeking',value:true})}, offEvent: () => {sendMessage({action:'setting_changed',id:'numpadSeeking',value:false})} }, { optionId: 'changeSpeedScroll', value: initialStorage.settings.changeSpeedScroll, onEvent: () => {sendMessage({action:'setting_changed',id:'changeSpeedScroll',value:true})}, offEvent: () => {sendMessage({action:'setting_changed',id:'changeSpeedScroll',value:false})} }, { optionId: 'changeSpeedArrows', value: initialStorage.settings.changeSpeedArrows, onEvent: () => {sendMessage({action:'setting_changed',id:'changeSpeedArrows',value:true})}, offEvent: () => {sendMessage({action:'setting_changed',id:'changeSpeedArrows',value:false})} }]; const originalEpisodeValue = (() => { if (isEpisode()) return /Watch (?:.*) - ([\d.]+)-?([\d.]+)? Online/.exec($('.theatre-info h1').text()); else return undefined; })(); function getEpisodeNum() { if (originalEpisodeValue) return +originalEpisodeValue[1]; return undefined; } async function getFirstEpisodeEntry(iinfo) { const cached = getCachedFirstEpisodeEntry(iinfo); if (cached) return cached; if (!iinfo.session) return undefined; let response = await getEpisodePageResponse(iinfo.session); if (!response && iinfo.name) { const newData = await getAnimeData(iinfo, ["session"], {requireNew:true,ignored:['current_page','anime_page']}); if (newData.session) response = await getEpisodePageResponse(newData.session); } if (!response) { console.error(`[AnimePahe Improvements] Failed getting first episode for anime with session ${iinfo.session}`); return undefined; } const ep = response.data[0]?.episode; return { first_episode: ep, session: iinfo.session, id: iinfo.id, }; } function getCachedFirstEpisodeEntry(iinfo) { if (!iinfo.id && !iinfo.session) return undefined; const found = (() => { for (const entry of siteVars.cached.firstEpisode) { if (iinfo.id === parseInt(entry[1], 36) && entry[1]) return entry; if (iinfo.session === entry[2] && entry[2]) return entry; } })(); if (!found) return undefined; return parseCachedFirstEpisodeEntry(found); } // Format: [first episode, anime id, anime session, timestamp] function cacheFirstEpisode(ep, iinfo, storage) { if (ep === undefined) return; const exists = (iinfo.id && getCachedFirstEpisodeEntry({id: iinfo.id})) || (iinfo.session && getCachedFirstEpisodeEntry({session: iinfo.session})); if ((iinfo.id || iinfo.session) && !exists) { const entry = [ep, iinfo.id?.toString(36), iinfo.session, Date.now().toString(36)]; storage.cached.firstEpisode.push(entry); } updateCache('firstEpisode',3,storage); // Saves storage as well } function updateCache(key, timeIndex, storage) { const compareDate = Date.now() - (1000 * 60 * 60 * 48); // 2 days old for (let i = 0; i < storage.cached[key].length; i++) { if (parseInt(storage.cached[key][i][timeIndex], 36) >= compareDate) continue; storage.cached[key].splice(i,1); i--; } const length = storage.cached[key].length; const limit = getStorageLimits().cached[key]; if (length > limit) storage.cached[key].splice(0, length - limit); saveData(storage); siteVars.cached[key] = storage.cached[key]; } function parseCachedFirstEpisodeEntry(entry) { return { first_episode: entry[0], id: parseInt(entry[1], 36), session: entry[2], }; } function getCachedPoster(iinfo) { if (!iinfo.id && !iinfo.poster) return undefined; const entry = siteVars.cached.poster.find(g => (parseInt(g[1], 36) === iinfo.id && iinfo.id) || g[0] === iinfo.poster); if (!entry) return undefined; return { poster: entry[0], id: parseInt(entry[1], 36), } } // Format: [poster, anime id, timestamp] function cachePoster(poster, iinfo, storage) { if (!poster) return; const exists = getCachedPoster(iinfo); if (iinfo.id && !exists) { const entry = [poster, iinfo.id.toString(36), Date.now().toString(36)]; storage.cached.poster.push(entry); } updateCache('poster',2,storage); // Saves storage as well } function invalidatePosterCache(poster, storage) { const existing = getCachedPoster({poster: poster}); if (!existing) return; storage.cached.poster = storage.cached.poster.filter(g => g[0] !== poster); updateCache('poster',2,storage); } // Things that update when focusing this tab $(document).on('visibilitychange', () => { if (document.hidden) return; updatePage(); }); function updatePage() { updateSwitches(); updateEpisodePages(); const storage = getStorage(); if (isAnime() || isEpisode()) getAnimeData({session: getAnimeSessionFromUrl()},["id"]).then(data => { if (!data.id) return; const isBookmarked = storage.bookmarks.find(a => a.id === data.id) !== undefined; if (isBookmarked) $('.anitracker-bookmark-toggle .anitracker-title-icon-check').show(); else $('.anitracker-bookmark-toggle .anitracker-title-icon-check').hide(); const hasNotifications = storage.notifications.anime.find(a => a.id === data.id) !== undefined; if (hasNotifications) $('.anitracker-notifications-toggle .anitracker-title-icon-check').show(); else $('.anitracker-notifications-toggle .anitracker-title-icon-check').hide(); }); if (!modalIsOpen()) return; if ($('.anitracker-keybinds-section').length) $('.anitracker-keybinds-section').trigger('anitracker:update'); if ($('.anitracker-view-notif-animes').length) { for (const item of $('.anitracker-notification-item')) { const entry = storage.notifications.episodes.find(a => a.animeId === +$(item).attr('anime-id') && a.episode === +$(item).attr('episode-data')); if (!entry || entry.watched !== $(item).hasClass('anitracker-notification-item-unwatched')) continue; $(item).toggleClass('anitracker-notification-item-unwatched'); $(item).find('.anitracker-watched-toggle').toggleClass('fa-eye').toggleClass('fa-eye-slash'); } } } function theatreMode(on) { if (on) $('.theatre').addClass('anitracker-theatre-mode'); else $('.theatre').removeClass('anitracker-theatre-mode'); } function stickyHeader(on) { if (on) $('.main-header').css('position', 'sticky'); else $('.main-header').css('position', ''); } function playAnimation(elem, anim, duration, type = '') { duration = duration || animationTimes[anim]; if (initialStorage.debug?.anim === true) console.log({anim:anim,type:type,duration:duration,elem:elem}); return new Promise(resolve => { elem.css('animation', `anitracker-${anim} ${duration}s forwards linear ${type}`); elem.css('-webkit-animation', `anitracker-${anim} ${duration}s forwards linear ${type}`); if (animationTimes[anim] === undefined) resolve(); setTimeout(() => { elem.css('animation', '').css('-webkit-animation', ''); if (initialStorage.debug?.anim === true) console.log('Anim debug: completed'); resolve(); }, duration * 1000); }); } const posterRegex = /^(?:https:\/\/)?(?:i\.\w+\.\w+)?\/?([^.]*)(?:\.md|\.th|\.sm)?(\..*)?$/; function trimPosterUrl(posterUrl) { const parts = posterRegex.exec(posterUrl); if (!parts) return undefined; return parts[1]+parts[2]; } function makePosterUrl(poster, format = '') { const parts = posterRegex.exec(poster); let path = `${parts[1]}${parts[2]}`; if (format) path = `${parts[1]}.${format}${parts[2]}`; return `https://i.${window.location.host}/${path}`; } // See if all data matches between data1 and data2 function matchDataFull(data1, data2, keys) { if (Array.isArray(keys)) for (const key of keys) { // If both object have the same key names if (data1[key] !== data2[key]) return false; } else for (const [key1, key2] of Object.entries(keys)) { // If key pairs if (data1[key1] !== data2[key2]) return false; } return true; } // See if any bit of data matches between data1 and data2, excluding undefined entries function matchDataPartial(data1, data2, keys) { if (Array.isArray(keys)) for (const key of keys) { // If both object have the same key names if (data1[key] === data2[key] && data1[key] !== undefined && data2[key] !== undefined) return true; } else for (const [key1, key2] of Object.entries(keys)) { // If key pairs if (data1[key1] === data2[key2] && data1[key1] !== undefined && data2[key2] !== undefined) return true; } return false; } // List of info-getting functions, from fastest to slowest const animeInfoFunctions = [ { "id": "current_page", "outputs": ["name","session","id","anidb_id","poster"], "instant": true, "fn": (iinfo = {}, config = {}) => { if ((!isAnime() && !isEpisode()) || is404) return undefined; const data = getAnimeDataFromPage($(document), isEpisode()); cachePoster(data?.poster, {...data}, getStorage()); data.session = getAnimeSessionFromUrl(); // Require at least one part of iinfo to match if (!matchDataPartial(iinfo, data, ["name","session","id","anidb_id","poster"])) return undefined; return { old: {}, new: { name: data.name, session: data.session, id: data.id, anidb_id: data.anidb_id, poster: data.poster, } } } }, { "id": "storage_session", "outputs": ["id","session","name"], "instant": true, "fn": (iinfo = {}, config = {}) => { const storage = getStorage(); const list = [...storage.linkList].reverse(); // Reverse to prioritize newer entries const found = list.find(a => matchDataPartial(a,iinfo,{"animeName":"name","animeId":"id","animeSession":"session"})); if (!found) return undefined; return { old: { name: found.animeName, session: found.animeSession, }, new: { id: found.animeId, } }; } }, { "id": "storage_episode_session", "outputs": ["id","session","name","episode_session"], "instant": true, "fn": (iinfo = {}, config = {}) => { if (iinfo.episode === undefined) return undefined; // Can be falsy const storage = getStorage(); const list = [...storage.linkList].reverse(); // Reverse to prioritize newer entries const found = list.find(a => a.type === 'episode' && a.episodeNum === iinfo.episode && (matchDataPartial(a,iinfo,{"animeName":"name","animeId":"id","animeSession":"session"}) || iinfo.videoPaths?.find(g => a.videoPaths?.includes(g)))); if (!found) return undefined; return { old: { name: found.animeName, session: found.animeSession, episode_session: found.episodeSession, }, new: { id: found.animeId, } }; } }, { "id": "storage_bookmark", "outputs": ["id","name","poster"], "instant": true, "fn": (iinfo = {}, config = {}) => { const storage = getStorage(); const found = storage.bookmarks.find(a => matchDataPartial(a,iinfo,{"name":"name","id":"id","posterUrl":"poster"})); if (!found) return undefined; return { old: { name: found.name, poster: found.posterUrl, }, new: { id: found.id, } }; } }, { "id": "storage_notification_anime", "outputs": ["id","name","poster","session"], "instant": true, "fn": (iinfo = {}, config = {}) => { const storage = getStorage(); const found = storage.notifications.anime.find(a => matchDataPartial(a,iinfo,["name","id","poster"])); if (!found) return undefined; return { old: { name: found.name, poster: found.poster, session: found.session, }, new: { id: found.id, } }; } }, { "id": "cached_poster", "outputs": ["id","poster"], "instant": true, "fn": (iinfo = {}, config = {}) => { const found = getCachedPoster(iinfo); if (!found) return undefined; return { old: { poster: found.poster, }, new: { id: found.id, } } } }, { "id": "storage_video", "outputs": ["id","name"], "instant": true, "fn": (iinfo = {}, config = {}) => { const storage = getStorage(); const found = storage.videoTimes.find(a => matchDataPartial(a,iinfo,{"animeName":"name","animeId":"id"}) || iinfo.videoPaths?.find(g => a.videoPaths?.includes(g))); if (!found) return undefined; return { old: { name: found.animeName, }, new: { id: found.animeId, } }; } }, { "id": "cached_anime_page", "outputs": ["session","name","id","anidb_id","poster"], "instant": true, "fn": (iinfo = {}, config = {}) => { if (!iinfo.session) return undefined; const cached = siteVars.cached.page[`/anime/${iinfo.session}`]; if (!cached) return undefined; const data = getAnimeDataFromPage(wrapPageText(cached), false); if (!data) return undefined; return { old: { session: iinfo.session, name: data.name, poster: data.poster, }, new: { id: data.id, anidb_id: data.anidb_id, } } } }, { "id": "cached_first_episode_entry", "outputs": ["first_episode","id","session"], "instant": true, "fn": async (iinfo = {}, config = {}) => { const firstEpEntry = getCachedFirstEpisodeEntry(iinfo); if (!firstEpEntry) return undefined; return { old: { session: firstEpEntry.session, }, new: { id: firstEpEntry.id, first_episode: firstEpEntry.first_episode, } } } }, { "id": "cached_index", "outputs": ["session","name"], "instant": true, "fn": (iinfo = {}, config = {}) => { const cached = siteVars.cached.animeSession.find(a => matchDataPartial(a,iinfo,["name","session"])); if (!cached) return undefined; return {old:{},new:{...cached}}; } }, { "id": "cached_search_query", "outputs": ["name","id","session","poster"], "instant": true, "fn": (iinfo = {}, config = {}) => { const cached = siteVars.cached.animeSearch.find(a => matchDataPartial(a,iinfo,["id","name","session","poster"])); if (!cached) return undefined; return {old:{},new:{...cached}}; } }, { "id": "anime_page", "outputs": ["session","name","id","anidb_id","poster"], "fn": async (iinfo = {}, config = {}) => { if (!iinfo.session) return undefined; const data = await getPageDataFromSession(iinfo.session); if (!data) return undefined; return { old: {}, new: { session: iinfo.session, name: data.name, id: data.id, anidb_id: data.anidb_id, poster: data.poster, } } } }, { "id": "index", "outputs": ["session","name"], "fn": getAnimeSession, }, { "id": "episode_list", "outputs": ["id"], "fn": async (iinfo = {}, config = {}) => { if (!iinfo.session) return undefined; const cached = siteVars.cached.animeId[iinfo.session]; if (cached) return cached; const response = await getEpisodePageResponse(iinfo.session); if (!response) return undefined; siteVars.cached.animeId[iinfo.session] = response.data[0].anime_id; return { old: {}, new: { id: response[0].anime_id, } }; } }, { "id": "first_episode_entry", "outputs": ["first_episode","id","session"], "fn": async (iinfo = {}, config = {}) => { const firstEpEntry = await getFirstEpisodeEntry(iinfo); if (!firstEpEntry) return undefined; return { old: { session: firstEpEntry.session, }, new: { id: firstEpEntry.id, first_episode: firstEpEntry.first_episode, } } } }, { "id": "search_query", "outputs": ["name","id","session","poster"], "fn": getAnimeDataFromSearch }, { "id": "relation_tree", // Very slow "outputs": ["session","name","poster","id","anidb_id"], "cost": 3, "fn": async (iinfo = {}, config = {}) => { if (!iinfo.startSession && !iinfo.name) return undefined; const searchedSessions = []; async function searchBranches(session) { if (searchedSessions.includes(session)) return undefined; const pageData = await getPageDataFromSession(session); if (pageData && matchDataPartial(pageData,iinfo,["name","id","anidb_id","poster"])) { pageData.session = session; return pageData; } searchedSessions.push(session); const relations = await getBranches(session); for (const rel of relations) { if (!matchDataPartial(rel,iinfo,{"session":"session","title":"name","poster":"poster"})) continue; const pageData2 = await getPageDataFromSession(rel.session); if (pageData2) { pageData2.session = rel.session; return pageData2; } return { name: rel.title, session: rel.session, poster: rel.poster, }; } for (const rel of relations) { const result = await searchBranches(rel.session); if (result) return result; } return undefined; } let startSession = iinfo.startSession; if (!startSession) { const data = await getAnimeDataFromSearch(iinfo, { allowGuessing: true }); if (!data?.new.session && !data?.old.session) return undefined; startSession = data.new.session ?? data.old.session; } if (!startSession) return undefined; const result = await searchBranches(startSession); if (!result) return undefined; return {old:{},new:{...result}}; async function getBranches(session) { const relations = await getRelationList(session); if (!relations) return []; return relations.filter(a => a.relation_type !== 'character'); } } } ] // Gets any anime info except for video player stuff // Available inputs & outputs: name, id, session, poster async function getAnimeData(_iinfo = {}, _reqinfo = [], config = {}) { /* - has a list of each info-getting function, ordered in speed with fastest first. each entry has a list of output keys - does a while loop while reqdata length is > 0. finds out which function encompasses the most of reqdata by making a .map and sorts the map by amount of reqdata support, then sorts by instant first, then uses the function. at the end of each loop, if the function was successful, removes all data from reqdata that the function outputs. makes sure that function isn't run again, no matter the outcome */ const iinfo = copyObj(_iinfo); let reqinfo = copyObj(_reqinfo); const debug = initialStorage.debug?.animeInfo; const oinfo = {old:{},new:{}}; const used = []; const dontUseAgain = []; const candidateFunctions = animeInfoFunctions.filter(a => !(config.requireInstant && !a.instant) && !config.ignored?.includes(a.id)); if (!iinfo || !Object.values(iinfo).find(a => a)) return {}; if (debug) console.log('starting search for',copyObj(reqinfo)); for (let i = 0; i < 1; i++) { while (reqinfo.length) { // Find out which function is the most appropriate for the needed data // Run instant functions first, no matter what const chosenFunction = candidateFunctions.map(a => { const matches = used.includes(a.id) ? 0 : a.outputs.filter(g => reqinfo.includes(g)).length; return { fn: a.fn, matches: matches ? Math.max(1, matches - (a.cost ?? 0)) : 0, id: a.id, instant: a.instant, }; }).filter(a => a.matches).sort((a,b) => b.matches - a.matches).sort((a,b) => { if (a.instant === b.instant) return 0; if (!a.instant) return 1; if (!b.instant) return -1; })[0]; if (!chosenFunction?.matches) { console.warn(`[AnimePahe Improvements] After ${used.length} functions, no remaining function matched ${reqinfo}`); break; } if (debug) console.log('chose',chosenFunction.id,'for #',used.length); used.push(chosenFunction.id); const result = await chosenFunction.fn(iinfo, config); if (debug) console.log('got result',result,'from function',chosenFunction.id,'with iinfo',copyObj(iinfo)); if (!result) continue; dontUseAgain.push(chosenFunction.id) for (const [key, value] of Object.entries(result.new)) { if (!value) continue; if (!oinfo.new[key]) oinfo.new[key] = value; iinfo[key] = value; if (value) reqinfo = reqinfo.filter(a => a !== key); } if (result.new.episode_session) oinfo.new.session = result.new.session; for (const [key, value] of Object.entries(result.old)) { if (!value) continue; if (!iinfo[key]) iinfo[key] = value; if (config.requireNew) continue; // If requireNew is true, only add to iinfo (and not oinfo) if (!oinfo.old[key]) oinfo.old[key] = value; if (value) reqinfo = reqinfo.filter(a => a !== key); } if (!config.requireNew && result.old.episode_session) oinfo.old.session = result.old.session; } if (!reqinfo.length || i === 1) break; if (debug) console.log('round two with left:',reqinfo); used.length = 0; used.push(...dontUseAgain); } const output = oinfo.new; for (const [key,value] of Object.entries(oinfo.old)) { if (!output[key]) output[key] = value; } if (debug) console.log('result',output); return output; } // MARKER:MODAL let modalBackFunction; // Add AnimePahe Improvements modal and message container function addPermanentElements() { $(`

`).insertBefore('.main-header'); $('#anitracker-modal').on('click', (e) => { if (e.target !== e.currentTarget) return; closeModal(); }); $('#anitracker-modal-close').on('click keydown', (e) => { if (e.type === 'keydown' && e.key !== "Enter") return; modalBackFunction(); }); $('#anitracker-modal-header').on('click', () => { $('#anitracker-modal-body')[0].scrollTo({top:0, behavior: getStorage().settings.reduceMotion ? 'auto' : 'smooth'}) }); } addPermanentElements(); function openModal(title = '', backFunction, options = {}) { modalBackFunction = backFunction || closeModal; $('#anitracker-modal').trigger('anitracker:open'); const close = $('#anitracker-modal-close'); if (backFunction) close.replaceClass('fa-close', 'fa-arrow-left').attr('title', 'Go back to previous menu'); else close.replaceClass('fa-arrow-left', 'fa-close').attr('title', 'Close modal'); $('#anitracker-modal-title').text(title); setModalSubtitle(options.subtitle ?? ''); const isOpen = modalIsOpen(); $('#anitracker-modal').css('visibility','visible'); $('#anitracker-modal').focus(); setModalShift(options.shiftContent ?? shouldShiftModal()); // options.shiftContent is allowed to be false return new Promise(resolve => { if (!options.hideAnimation && getStorage().settings.reduceMotion !== true) { if (!isOpen) { playAnimation($('#anitracker-modal-content'), 'modalOpen'); playAnimation($('#anitracker-modal'), 'fadeIn').then(() => { resolve(); }); } else { playAnimation($('#anitracker-modal-content'), 'modalOpen').then(() => { resolve(); }); } } else resolve(); }); } function closeModal() { $('#anitracker-modal').trigger('anitracker:close'); siteVars.modalEvents.forEach(g => { g.elem.off(g.events, null, g.handler); }); siteVars.modalEvents = []; const storage = getStorage(); if (storage.settings.reduceMotion === true || !$('#anitracker-modal').css('animation').startsWith('none')) { $('#anitracker-modal').css('visibility','hidden'); return; } playAnimation($('#anitracker-modal'), 'fadeIn', 0.1, 'reverse').then(() => { $('#anitracker-modal').css('visibility','hidden'); }); } function modalIsOpen() { return $('#anitracker-modal').css('visibility') === 'visible'; } function setModalSubtitle(text = '') { $('#anitracker-modal-subtitle').text(text); } function shouldShiftModal() { let diff = $('#anitracker-modal-title').offset().left - ($('#anitracker-modal-close').offset().left + $('#anitracker-modal-close').outerWidth()); if ($('#anitracker-modal-content').hasClass('shift')) diff -= $('#anitracker-modal-close').outerWidth(true); return diff < 30; } function setModalShift(shift) { if (shift) $('#anitracker-modal-content').addClass('shift'); else $('#anitracker-modal-content').removeClass('shift'); } function addModalEvent(elem, events, handler) { elem.on(events, handler); siteVars.modalEvents.push({ elem: elem, events: events, handler: handler }); } function scrollModalToTop() { $('#anitracker-modal-body')[0].scrollTop = 0; } function showMessage(text, time = 2000) { clearTimeout(siteVars.messageTimeout); $('#anitracker-message-container>span').remove(); const elem = $(``).text(text).appendTo('#anitracker-message-container'); playAnimation(elem, 'fadeIn'); siteVars.messageTimeout = setTimeout(() => { playAnimation(elem, 'fadeIn', animationTimes.fadeIn, 'reverse').then(() => { elem.remove(); }); }, time); } // MARKER:MESSAGES FROM IFRAME let currentEpisodeTime = 0; let timestampEditMode = false; // Messages received from iframe if (isEpisode()) { window.onmessage = function(e) { const data = e.data; if (initialStorage.debug?.msg) console.log('Received from iframe: ' + (typeof(data) === 'object' ? JSON.stringify(data) : data)); if (typeof(data) === 'number') { currentEpisodeTime = Math.trunc(data); return; } const action = data?.action; if (action === 'request') { if (data.type === 'id') { getAnimeData({session: getAnimeSessionFromUrl()},["id"]).then(data => { if (!data.id) return console.error("[AnimePahe Improvements] Couldn't get anime ID to send to iframe"); sendMessage({action:"response",type:'id',value:data.id}); }); } else if (data.type === 'anidb_id') { const pageData = getAnimeDataFromPage($(document), true); cachePoster(pageData?.poster, pageData, getStorage()); sendMessage({action:"response",type:'anidb_id',value:pageData.anidb_id}); } else if (data.type === 'name') { sendMessage({action:"response",type:'name',value:getAnimeName()}); } else if (data.type === 'first_episode') { getFirstEpisodeEntry({ session: animeSession, name: getAnimeName(), }).then(firstEpEntry => { sendMessage({action:"response",type:'first_episode',value:firstEpEntry?.first_episode}); }); } else if (data.type === 'video_source') { const thumbnailUrl = getBestThumbnailUrl(); if (!thumbnailUrl) return; // Don't respond getVideoSourceUrl(thumbnailUrl).then(sourceUrl => { if (!sourceUrl) return; sendMessage({action:"response",type:'video_source',value:sourceUrl}); }); } } else if (action === 'timestamp_edit_mode_done') { $('#anitracker-modal-body').empty() const timestamps = { "episode_number": getEpisodeNum(), "recap": { "start": -2, "end": -2 }, "opening": { "start": -2, "end": -2 }, "ending": { "start": -2, "end": -2 }, "preview_start": -2 }; for (const timestamp of data.timestamps) { if (timestamp.type === 'preview') { if (timestamp.start !== undefined) timestamps.preview_start = timestamp.start; continue; } if (timestamp.start !== undefined) timestamps[timestamp.type].start = timestamp.start; if (timestamp.end !== undefined) timestamps[timestamp.type].end = timestamp.end; } $(`

You can open an issue here to get these added.

`).appendTo('#anitracker-modal-body'); openModal('Timestamp Results'); } else if (action === 'timestamp_edit_mode_toggle') { timestampEditMode = Boolean(data.value); } else if (action === 'key') { $(document).trigger('keydown', {event: data.event}); } else if (data === 'ended') { const storage = getStorage(); if (storage.settings.autoPlayNext !== true || timestampEditMode || document.readyState !== 'complete') return; setTimeout(() => { $('.sequel a')[0]?.click(); }, 100); // Wait for video data to be saved } }; } function sendMessage(message) { const iframe = $('.embed-responsive-item'); if (!iframe.length) return; iframe[0].contentWindow.postMessage(message,'*'); } function toUTCDate(timeString) { if (!timeString) return new Date(timeString); const parts = timeString.split(' '); return new Date([parts[0],'T',parts[1],'Z'].join('')); } function toggleTheatreMode() { const storage = getStorage(); theatreMode(!storage.settings.theatreMode); storage.settings.theatreMode = !storage.settings.theatreMode; saveData(storage); updateSwitches(); } function getSeasonValue(season) { return ({winter:0, spring:1, summer:2, fall:3})[season.toLowerCase()]; } function getSeasonName(season) { return ["winter","spring","summer","fall"][season]; } function getBestThumbnailUrl() { if (!isEpisode()) return; const selected = { src: undefined, res: undefined, audio: undefined }; for (const btn of $('#resolutionMenu>button')) { const src = $(btn).data('src'); const res = +$(btn).data('resolution'); const audio = $(btn).data('audio'); if (selected.src && selected.res < res) continue; if (selected.audio && audio === 'jpn' && selected.res <= res) continue; // Prefer dubs, since they don't have subtitles selected.src = src; selected.res = res; selected.audio = audio; } if (!selected.src) { console.error("[AnimePahe Improvements] Couldn't find thumbnail URL"); return; } console.log('[AnimePahe Improvements] Found thumbnail URL ' + selected.src); return selected.src; } function getVideoSourceUrl(videoPageUrl) { return new Promise(resolve => { const request = new XMLHttpRequest(); request.open('GET', videoPageUrl, true); request.onload = () => { if (request.status !== 200) { console.error('[AnimePahe Improvements] Could not get kwik page for video source'); return resolve(undefined); } const pageElements = Array.from($(request.response)); // Elements that are not buried cannot be found with jQuery.find() const hostInfo = (() => { for (const link of pageElements.filter(a => a.tagName === 'LINK')) { const href = $(link).attr('href'); if (!href.includes('vault')) continue; const result = /vault-(\d+)\.(\w+\.\w+)$/.exec(href); return { vaultId: result[1], hostName: result[2] }; } })(); const searchInfo = (() => { for (const script of pageElements.filter(a => a.tagName === 'SCRIPT')) { if ($(script).attr('url') || !$(script).text().startsWith('eval')) continue; const result = /(\w{64})\|((?:\w+\|){4,5})https/.exec($(script).text()); let extraNumber; result[2].split('|').forEach(a => {if (/\d{2}/.test(a)) extraNumber = a;}); // Some number that's needed for the url (doesn't always exist here) if (extraNumber === undefined) { const result2 = /q=\\'\w+:\/{2}\w+-\w+\.\w+\.\w+\/((?:\w+\/)+)/.exec($(script).text()); result2[1].split('/').forEach(a => {if (/\d{2}/.test(a) && a !== hostInfo.vaultId) extraNumber = a;}); } if (extraNumber === undefined) { const result2 = /source\|(\d{2})\|ended/.exec($(script).text()); if (result2 !== null) extraNumber = result2[1]; } return { part1: extraNumber ?? hostInfo.vaultId, part2: result[1] }; } })(); if (searchInfo.part1 === undefined) { console.error('[AnimePahe Improvements] Could not find "extraNumber" from ' + videoPageUrl); return resolve(undefined); } resolve(`https://vault-${hostInfo.vaultId}.${hostInfo.hostName}/stream/${hostInfo.vaultId}/${searchInfo.part1}/${searchInfo.part2}/uwu.m3u8`); }; request.send(); }); } const is404 = $('h1').text().includes('404'); function updateFromImport(diff, force = {}) { if (force.page || (diff.bookmarksAdded + diff.notificationsAdded + diff.settingsUpdated)) updatePage(); if (force.epPage || diff.watchedEpisodesAdded || diff.videoTimesUpdated || diff.videoTimeEntryUpdated) updateEpisodePages(); if (diff.videoTimesUpdated || diff.videoTimesAdded) { if (isEpisode()) { const videoPath = getVideoPath(stripUrl($('.embed-responsive-item')[0].src)); sendMessage({action:"newer_time", time:getStorage().videoTimes.find(a => a.videoPaths.includes(videoPath))?.time}); } if (isHome() && !$('#anitracker-continue-watching-section').length) setupContinueWatchingSection(); } } function importData(data, importedData, save = true, ignored = {settings:{}}, fromSync = false) { const changed = { linkListAdded: 0, // Session entries added videoTimesAdded: 0, // Video progress entries added videoTimesUpdated: 0, // Video progress times updated videoTimeEntryUpdated: 0, // Video progress entries with other added info bookmarksAdded: 0, // Bookmarks added bookmarksUpdated: 0, // Bookmarks updated notificationsAdded: 0, // Anime added to episode feed episodeFeedUpdated: 0, // Episodes either added to episode feed or that had their watched status updated videoSpeedUpdated: 0, // Video speed entries added or updated watchedEpisodesAdded: 0, // Amount of episodes marked as watched that are added settingsUpdated: 0 // Settings updated }; const defaultData = getDefaultData(); if (importedData.version !== defaultData.version) { upgradeData(importedData, importedData.version); } for (const [key, value] of Object.entries(importedData)) { if (defaultData[key] === undefined) continue; if (!ignored.linkList && key === 'linkList') { if (value.length === undefined) { console.warn('[AnimePahe Improvements] Imported "linkList" has an incorrect format.'); continue; } value.forEach(g => { if ((g.type === 'episode' && data.linkList.find(h => h.type === 'episode' && h.animeSession === g.animeSession && h.episodeSession === g.episodeSession) === undefined) || (g.type === 'anime' && data.linkList.find(h => h.type === 'anime' && h.animeSession === g.animeSession) === undefined)) { data.linkList.push(g); changed.linkListAdded++; if (data.linkList.length > getStorageLimits().linkList) { data.linkList.splice(0,1); } if (save && isSyncEnabled(data) && !fromSync) { if (g.type === 'episode') data.sync.temp.addedData.push({type: 'linkList', episodeSession: g.episodeSession}); else if (g.type === 'anime') data.sync.temp.addedData.push({type: 'linkList', animeSession: g.animeSession}); } } }); continue; } else if (!ignored.videoTimes && key === 'videoTimes') { if (value.length === undefined) { console.warn('[AnimePahe Improvements] Imported "videoTimes" has an incorrect format.'); continue; } value.forEach(g => { const foundTime = data.videoTimes.find(h => h.videoPaths.find(a => g.videoPaths.includes(a))); if (foundTime === undefined) { data.videoTimes.push(g); changed.videoTimesAdded++; if (data.videoTimes.length > getStorageLimits().videoTimes) { data.videoTimes.splice(0,1); } if (save && isSyncEnabled(data) && !fromSync) data.sync.temp.addedData.push({type: 'videoTimes', animeName: g.animeName, episodeNum: g.episodeNum}); } else { if (foundTime.time < g.time) { foundTime.time = g.time; changed.videoTimesUpdated++; } let updated = false; if (g.duration && !foundTime.duration) { foundTime.duration = g.duration; updated = true; } if (g.animeId && !foundTime.animeId) { foundTime.animeId = g.animeId; updated = true; } if (updated) changed.videoTimeEntryUpdated++; } }); continue; } else if (!ignored.bookmarks && key === 'bookmarks') { if (value.length === undefined) { console.warn('[AnimePahe Improvements] Imported "bookmarks" has an incorrect format.'); continue; } value.forEach(g => { const found = data.bookmarks.find(h => h.id === g.id); if (found !== undefined) { if (g.status === found.status || !g.status) return; if (fromSync && data.sync.temp.addedData.find(h => h.type === 'updated_bookmark' && h.id === g.id)) return; found.status = g.status; changed.bookmarksUpdated++; if (save && isSyncEnabled(data) && !fromSync) data.sync.temp.addedData.push({type: 'updated_bookmark', id: g.id}); return; } if (data.bookmarks.length >= getStorageLimits().bookmarks) return; data.bookmarks.push(g); changed.bookmarksAdded++; if (save && isSyncEnabled(data) && !fromSync) data.sync.temp.addedData.push({type: 'bookmarks', id: g.id}); }); continue; } else if (!ignored.notifications && key === 'notifications') { if ((value.anime && value.anime?.length === undefined) || (value.episodes && value.episodes?.length === undefined)) { console.warn('[AnimePahe Improvements] Imported "notifications" has an incorrect format.'); continue; } if (value.anime) value.anime.forEach(g => { if (data.notifications.anime.find(h => h.id === g.id) !== undefined) return; if (data.notifications.anime.length >= getStorageLimits().notifications.anime) return; delete g.hasFirstEpisode; data.notifications.anime.push(g); changed.notificationsAdded++; if (save && isSyncEnabled(data) && !fromSync) data.sync.temp.addedData.push({type: 'notification_anime', name: g.name}); }); // Checking if there exists any gap between the imported episodes and the existing ones if (save && value.episodes) data.notifications.anime.forEach(g => { const existingEpisodes = data.notifications.episodes.filter(a => (a.animeName === g.name || a.animeId === g.id)); const addedEpisodes = value.episodes.filter(a => (a.animeName === g.name || a.animeId === g.id)); if (existingEpisodes.length > 0 && addedEpisodes.length > 0 && (existingEpisodes[existingEpisodes.length-1].episode - addedEpisodes[0].episode > 1.5)) { g.updateFrom = toUTCDate(addedEpisodes[0].time).getTime(); } }); if (value.episodes) value.episodes.forEach(g => { const anime = (() => { if (g.animeId !== undefined) return data.notifications.anime.find(a => a.id === g.animeId); const fromNew = data.notifications.anime.find(a => a.name === g.animeName); if (fromNew !== undefined) return fromNew; const id = value.anime.find(a => a.name === g.animeName); return data.notifications.anime.find(a => a.id === id); })(); if (anime === undefined) return; if (g.animeName !== anime.name) g.animeName = anime.name; if (g.animeId === undefined) g.animeId = anime.id; const foundEpisode = data.notifications.episodes.find(h => h.animeId === anime.id && h.episode === g.episode); if (foundEpisode !== undefined) { if (g.watched === true && !foundEpisode.watched) { foundEpisode.watched = true; changed.episodeFeedUpdated++; } return; } data.notifications.episodes.push(g); changed.episodeFeedUpdated++; }); if (save && value.episodes) { data.notifications.episodes.sort((a,b) => a.time < b.time ? 1 : -1); if (value.episodes.length > 0) { data.notifications.lastUpdated = toUTCDate(value.episodes[0].time).getTime(); } const limit = getStorageLimits().notifications.episodes; if (data.notifications.episodes.length > limit) { data.notifications.episodes = data.notifications.episodes.slice(0, limit); } } continue; } else if (!ignored.watchedEpisodes && key === 'watched') { const watched = decodeWatched(data.watched); const watchedNew = decodeWatched(value); if (value.length === undefined || (value.length > 0 && watchedNew.length === 0)) { console.warn('[AnimePahe Improvements] Imported "watched" has an incorrect format.'); continue; } for (const anime of watchedNew) { const found = watched.find(a => a.animeId === anime.animeId); if (found === undefined) { watched.push({ animeId: anime.animeId, episodes: anime.episodes }); changed.watchedEpisodesAdded += anime.episodes.length; if (save && isSyncEnabled(data) && !fromSync) data.sync.temp.addedData.push({type: 'watched', animeId: anime.animeId, episodes: anime.episodes}); } else for (const ep of anime.episodes) { if (found.episodes.includes(ep)) continue; found.episodes.push(ep); changed.watchedEpisodesAdded++; } } data.watched = encodeWatched(watched); } else if (!ignored.videoSpeed && key === 'videoSpeed') { if (value.length === undefined) { console.warn('[AnimePahe Improvements] Imported "videoSpeed" has an incorrect format.'); continue; } for (const anime of value) { const found = data.videoSpeed.find(a => a.animeId === anime.animeId); if (found !== undefined) { if (found.speed === anime.speed) continue; found.speed = anime.speed; changed.videoSpeedUpdated++; continue; } data.videoSpeed.push(anime); changed.videoSpeedUpdated++; } } else if (ignored.settings !== true && key === 'settings') { for (const [key, value2] of Object.entries(value)) { if (defaultData.settings[key] === undefined || ignored.settings[key] || typeof(value2) !== typeof(defaultData.settings[key])) continue; if (data.settings[key] === value2) continue; data.settings[key] = value2; changed.settingsUpdated++; } } } if (save) saveData(data); return changed; } const syncApi = 'https://ap-improvements-database.ellivers.workers.dev'; let syncInterval; const tabUUID = crypto.randomUUID(); const receivedTabUUIDs = []; function broadcastTabMessage(key, value) { // Also sends message to itself localStorage.setItem(key, value); receiveTabMessage({originalEvent: {key: key, newValue: value}}); localStorage.removeItem(key); } // MARKER:TAB MESSAGES function receiveTabMessage(e) { // Values received from other tabs are always strings const message = e.originalEvent.newValue; if (!message) return; // Ignore empty msg or msg reset const key = e.originalEvent.key; if (key === 'anitracker_sync_deletion_confirmation') { showMessage('Potential sync issue. Check the log!'); const removed = JSON.parse(message); const restore = confirm(`[AnimePahe Improvements]\n\nPotential sync issue! The latest sync deleted the following amounts of data: Session entries: ${removed.linkList.length} Video progress entries: ${removed.videoTimes.length} Bookmarks: ${removed.bookmarks.length} Episode feed entries: ${removed.notifications.anime.length} Watched anime: ${removed.watched.length} \nIf you believe this is an error, click OK to restore the removed data.`); if (!restore) return; removed.watched = encodeWatched(removed.watched); importData(getStorage(), removed); showMessage('Restored data'); return; } if (key === 'anitracker_auto_sync_started') { const syncBtn = $('.anitracker-sync-button'); if (syncBtn) syncBtn.find('i').addClass('anitracker-spin'); return; } if (key === 'anitracker_auto_sync_ended') { const msg = JSON.parse(message); const syncBtn = $('.anitracker-sync-button'); if (syncBtn) syncBtn.find('i').removeClass('anitracker-spin'); const syncSinceText = $('.anitracker-time-since-sync'); if (syncSinceText && msg?.lastSynced) { syncSinceText.text(timeSince(+msg.lastSynced) + ' ago'); syncSinceText.parent().attr('title', new Date(+msg.lastSynced).toLocaleString()); } if (msg?.imported) updateFromImport(msg.imported, { page: (msg?.removed && msg?.removed?.bookmarks.length), epPage: (msg?.removed && (msg?.removed?.watched.length || msg?.removed?.linkList.length || msg?.removed?.videoTimes.length)) }); return; } if (key === 'anitracker_update_auto_sync') { if (syncInterval === undefined) return; const value = +message; if (value) setAutoSync(value); else unsetAutoSync(); return; } if (key === 'send_site_expired_message_state') { broadcastTabMessage('site_expired_message_state_response', +siteVars.siteSessionExpireMsg.shown); return; } if (key === 'site_expired_message_state_response') { siteVars.siteSessionExpireMsg.tabStates.push(+message); // Will be 0 or 1 return; } if (key !== 'anitracker_decide_sync') return; const instruction = JSON.parse(message); if (instruction.action === "send_uuids") { const msgToSend = syncInterval !== undefined ? 'enabled' : tabUUID; const sendObj = JSON.stringify({action: "add_value", value: msgToSend}); localStorage.setItem('anitracker_decide_sync', sendObj); receiveTabMessage({originalEvent: {key: 'anitracker_decide_sync', newValue: sendObj}}); return; } if (instruction.action === "add_value") { receivedTabUUIDs.push(instruction.value); if (receivedTabUUIDs.length !== 1) return; setTimeout(() => { if (!receivedTabUUIDs.find(a => a === 'enabled') && receivedTabUUIDs.sort((a,b) => a < b ? 1 : -1)[0] === tabUUID) { console.log(`[AnimePahe Improvements] This tab is now in charge of auto-syncing. (${new Date().toLocaleTimeString()})`); const storage = getStorage(); setAutoSync(storage.sync.settings.interval); } receivedTabUUIDs.length = 0; }, 100); return; } } $(window).on('storage', receiveTabMessage); function setupAutoSync(includeSelf = true) { localStorage.setItem('anitracker_decide_sync', JSON.stringify({action: "send_uuids"})); if (includeSelf) receiveTabMessage({originalEvent: {key: 'anitracker_decide_sync', newValue: JSON.stringify({action: "send_uuids"})}}); } if (isSyncEnabled(initialStorage) && initialStorage.sync.settings.interval) setupAutoSync(); $(window).on('beforeunload', () => { const storage = getStorage(); storage.sync.temp.inProgress = false; saveData(storage); if (syncInterval !== undefined) setupAutoSync(false); }); function stringSimilarity(s1, s2) { let longer = s1; let shorter = s2; if (s1.length < s2.length) { longer = s2; shorter = s1; } const longerLength = longer.length; if (longerLength == 0) { return 1.0; } return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength); } function editDistance(s1, s2) { s1 = s1.toLowerCase(); s2 = s2.toLowerCase(); const costs = []; for (let i = 0; i <= s1.length; i++) { let lastValue = i; for (let j = 0; j <= s2.length; j++) { if (i == 0) costs[j] = j; else { if (j > 0) { let newValue = costs[j - 1]; if (s1.charAt(i - 1) != s2.charAt(j - 1)) newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; costs[j - 1] = lastValue; lastValue = newValue; } } } if (i > 0) costs[s2.length] = lastValue; } return costs[s2.length]; } function getTextContent(elem) { let text = ''; Array.from(elem.contents().filter(function() { return this.nodeType === 3; })).forEach(t => { text += t.textContent; }); return text; } async function searchForCollections() { if (!$('.search-results a').length) return; const baseName = $($('.search-results .result-title')[0]).text(); const response = await getResponseData('/api?m=search&q=' + makeSearchable(baseName)); if (!response || response.length < 2) return; const elem = $(`
  • Loading...
  • `).prependTo('.search-results'); let seriesList = []; for (const anime of response) { if (stringSimilarity(baseName, anime.title) >= 0.42 || (anime.title.startsWith(baseName) && stringSimilarity(baseName, anime.title) >= 0.25)) { seriesList.push(anime); } } const additional = await getRelationList(sortAnimesChronologically(seriesList)[0].session); seriesList.push(...additional.filter(a => !seriesList.find(g => g.title === a.title) && !['character'].includes(a.relation_type))); if (seriesList.length < 2) { elem.remove(); return; } seriesList = sortAnimesChronologically(seriesList); displayCollection(seriesList, elem); } new MutationObserver(function() { if (!searchComplete()) return; searchForCollections(); for (const elem of $('.search-results a')) { $(elem).attr('title', $(elem).find('.result-title').text()); } }).observe($('.search-results-wrap')[0], { childList: true }); function searchComplete() { return $('.search-results').length !== 0 && $('.search-results a').length; } function displayCollection(seriesList, elem) { elem.empty().css('padding', ''); $(`
    `).appendTo(elem); elem.on('click', () => { $('#anitracker-modal-body').empty(); $(`
    `).appendTo('#anitracker-modal-body'); for (const anime of seriesList) { $(`
    [Thumbnail of ${toHtmlCodes(anime.title)}]
    ${toHtmlCodes(anime.title)}
    ${anime.type} ∙ ${anime.episodes ? anime.episodes : '?'} Ep${anime.episodes === 1 ? '' : 's'} ∙ ${anime.season} ${anime.year}
    ${anime.status !== 'Finished Airing' ? `
    ${anime.status}
    ` : ''}
    `).appendTo('#anitracker-modal-body .anitracker-modal-list'); } openModal(`Collection - ${seriesList.length} Entries`, undefined, {subtitle: 'May not be entirely accurate'}); scrollModalToTop(); }); } $('.input-search').attr('title','Search for anime'); $('.input-search').on('keyup', (e) => { const collectionElem = $('.search-results').find('.anitracker-collection'); if (collectionElem.length && e.key === "Enter" && collectionElem.hasClass('selected')) collectionElem.trigger('click'); if ($(e.currentTarget).val() === '') $('.search-results-wrap').empty(); }); function getSeasonTimeframe(from, to) { const filters = []; for (let i = from.year; i <= to.year; i++) { const start = i === from.year ? from.season : 0; const end = i === to.year ? to.season : 3; for (let d = start; d <= end; d++) { filters.push({type: 'season_entry', value: {year: i, season: d}}); } } return filters; } if (initialStorage.temp !== undefined && !isRandomAnime()) { const storage = getStorage(); delete storage.temp; saveData(storage); } const filterSearchCache = {}; const filterValues = { "genre":[ {"name":"Comedy","value":"comedy"},{"name":"Slice of Life","value":"slice-of-life"},{"name":"Romance","value":"romance"},{"name":"Ecchi","value":"ecchi"},{"name":"Drama","value":"drama"}, {"name":"Supernatural","value":"supernatural"},{"name":"Sports","value":"sports"},{"name":"Horror","value":"horror"},{"name":"Sci-Fi","value":"sci-fi"},{"name":"Action","value":"action"}, {"name":"Fantasy","value":"fantasy"},{"name":"Mystery","value":"mystery"},{"name":"Suspense","value":"suspense"},{"name":"Adventure","value":"adventure"},{"name":"Boys Love","value":"boys-love"}, {"name":"Girls Love","value":"girls-love"},{"name":"Hentai","value":"hentai"},{"name":"Gourmet","value":"gourmet"},{"name":"Erotica","value":"erotica"},{"name":"Avant Garde","value":"avant-garde"}, {"name":"Award Winning","value":"award-winning"} ], "theme":[ {"name":"Adult Cast","value":"adult-cast"},{"name":"Anthropomorphic","value":"anthropomorphic"},{"name":"Detective","value":"detective"},{"name":"Love Polygon","value":"love-polygon"}, {"name":"Mecha","value":"mecha"},{"name":"Music","value":"music"},{"name":"Psychological","value":"psychological"},{"name":"School","value":"school"},{"name":"Super Power","value":"super-power"}, {"name":"Space","value":"space"},{"name":"CGDCT","value":"cgdct"},{"name":"Romantic Subtext","value":"romantic-subtext"},{"name":"Historical","value":"historical"},{"name":"Video Game","value":"video-game"}, {"name":"Martial Arts","value":"martial-arts"},{"name":"Idols (Female)","value":"idols-female"},{"name":"Idols (Male)","value":"idols-male"},{"name":"Gag Humor","value":"gag-humor"},{"name":"Parody","value":"parody"}, {"name":"Performing Arts","value":"performing-arts"},{"name":"Military","value":"military"},{"name":"Harem","value":"harem"},{"name":"Reverse Harem","value":"reverse-harem"},{"name":"Samurai","value":"samurai"}, {"name":"Vampire","value":"vampire"},{"name":"Mythology","value":"mythology"},{"name":"High Stakes Game","value":"high-stakes-game"},{"name":"Strategy Game","value":"strategy-game"}, {"name":"Magical Sex Shift","value":"magical-sex-shift"},{"name":"Racing","value":"racing"},{"name":"Isekai","value":"isekai"},{"name":"Workplace","value":"workplace"},{"name":"Iyashikei","value":"iyashikei"}, {"name":"Time Travel","value":"time-travel"},{"name":"Gore","value":"gore"},{"name":"Educational","value":"educational"},{"name":"Delinquents","value":"delinquents"},{"name":"Organized Crime","value":"organized-crime"}, {"name":"Otaku Culture","value":"otaku-culture"},{"name":"Medical","value":"medical"},{"name":"Survival","value":"survival"},{"name":"Reincarnation","value":"reincarnation"},{"name":"Showbiz","value":"showbiz"}, {"name":"Team Sports","value":"team-sports"},{"name":"Mahou Shoujo","value":"mahou-shoujo"},{"name":"Combat Sports","value":"combat-sports"},{"name":"Crossdressing","value":"crossdressing"}, {"name":"Visual Arts","value":"visual-arts"},{"name":"Childcare","value":"childcare"},{"name":"Pets","value":"pets"},{"name":"Love Status Quo","value":"love-status-quo"},{"name":"Urban Fantasy","value":"urban-fantasy"}, {"name":"Villainess","value":"villainess"} ], "type":[ {"name":"TV","value":"tv"},{"name":"Movie","value":"movie"},{"name":"OVA","value":"ova"},{"name":"ONA","value":"ona"},{"name":"Special","value":"special"},{"name":"Music","value":"music"} ], "demographic":[ {"name":"Shounen","value":"shounen"},{"name":"Shoujo","value":"shoujo"},{"name":"Seinen","value":"seinen"},{"name":"Kids","value":"kids"},{"name":"Josei","value":"josei"} ], "status":[ {"value":"airing"},{"value":"completed"} ] }; const filterDefaultRules = { genre: { include: "and", exclude: "and" }, theme: { include: "and", exclude: "and" }, demographic: { include: "or", exclude: "and" }, type: { include: "or", exclude: "and" }, season: { include: "or", exclude: "and" }, status: { include: "or" } }; // MARKER:SEARCH FILTER LOGIC const filterRules = copyObj(filterDefaultRules); function buildFilterString(type, value) { if (type === 'status') return value; if (type === 'season_entry') return `season/${getSeasonName(value.season)}-${value.year}`; return type + '/' + value; } const seasonFilterRegex = /^!?(spring|summer|winter|fall)-(\d{4})\.\.(spring|summer|winter|fall)-(\d{4})$/; function getFilteredList(filtersInput) { let filtersChecked = 0; let filtersTotal = 0; function getPage(pageUrl) { return new Promise((resolve, reject) => { const cached = filterSearchCache[pageUrl]; if (cached !== undefined) { // If cache exists if (cached === 'invalid') { // Not sure if it ever is 'invalid' resolve([]); return; } resolve(cached); return; } const req = new XMLHttpRequest(); req.open('GET', pageUrl, true); req.onload = () => { if (req.status !== 200) { filterSearchCache[pageUrl] = []; resolve([]); return; } const animeList = getAnimeList($(req.response)); filterSearchCache[pageUrl] = animeList; resolve(animeList); }; req.onerror = () => { reject('A network error occurred.'); return; }; req.send(); }); } function getLists(filters) { const lists = []; return new Promise(resolve => { function check() { if (filters.length > 0) { repeat(filters.shift()); } else { resolve(lists); } } function repeat(filter) { const filterType = filter.type; if (filter.value === 'none') { filtersTotal += filterValues[filterType].length; getLists(filterValues[filterType].map(a => {return {type: filterType, value: a.value, exclude: false};})).then((filtered) => { getPage('/anime').then((unfiltered) => { const none = []; for (const entry of unfiltered) { const found = filtered.find(list => list.entries.find(a => a.name === entry.name)); if (!filter.exclude && found !== undefined) continue; if (filter.exclude && found === undefined) continue; none.push(entry); } lists.push({ type: filterType, excludedFilter: false, entries: none }); check(); }); }); return; } if (filterType === 'season') { const seasonFilters = getSeasonTimeframe(filter.value.from, filter.value.to); filtersTotal += seasonFilters.length; getLists(seasonFilters).then((filtered) => { const filtersResult = []; if (filter.exclude) getPage('/anime').then((unfiltered) => { for (const entry of unfiltered) { if (filtered.find(list => list.entries.find(a => a.name === entry.name)) !== undefined) continue; filtersResult.push(entry); } lists.push({ type: 'season', excludedFilter: true, entries: filtersResult }); check(); }); else { for (const list of filtered) { filtersResult.push(...list.entries); } lists.push({ type: 'season', excludedFilter: false, entries: filtersResult }); check(); } }); return; } if (filter.exclude) { getPage('/anime/' + buildFilterString(filterType, filter.value)).then((filtered) => { getPage('/anime').then((unfiltered) => { const included = []; for (const entry of unfiltered) { if (filtered.find(a => a.name === entry.name) !== undefined) continue; included.push(entry); } lists.push({ type: filterType, excludedFilter: true, entries: included }); check(); }); }); return; } getPage('/anime/' + buildFilterString(filterType, filter.value)).then((result) => { if (result !== undefined) { lists.push({ type: filterType, excludedFilter: false, entries: result }); } if (filtersTotal > 0) { filtersChecked++; $($('.anitracker-filter-spinner>span')[0]).text(Math.floor((filtersChecked/filtersTotal) * 100).toString() + '%'); } check(); }); } check(); }); } function combineLists(lists, rule) { if (lists.length === 0) return []; // Start with the first filter list result, then compare others to it let combinedList = lists[0]; lists.splice(0,1); // Remove the first entry for (const list of lists) { // If the rule of this filter type is 'or,' start from the current list // Otherwise, start from an empty list const updatedList = rule === 'or' ? combinedList : []; if (rule === 'and') for (const anime of list) { // The anime has to exist in both the current and the checked list if (combinedList.find(a => a.name === anime.name) === undefined) continue; updatedList.push(anime); } else if (rule === 'or') for (const anime of list) { // The anime just has to not already exist in the current list if (combinedList.find(a => a.name === anime.name) !== undefined) continue; updatedList.push(anime); } combinedList = updatedList; } return combinedList; } return new Promise((resolve, reject) => { const filters = copyObj(filtersInput); if (filters.length === 0) { getPage('/anime').then((response) => { if (response === undefined) { alert('Page loading failed.'); reject('Anime index page not reachable.'); return; } resolve(response); }); return; } filtersTotal = filters.length; getLists(filters).then((listsInput) => { const lists = copyObj(listsInput); // groupedLists entries have the following format: /* { type, // the type of filter, eg. 'genre' includeLists: [ ], excludeLists: [ ] } */ const groupedLists = []; for (const list of lists) { let foundGroup = groupedLists.find(a => a.type === list.type); if (foundGroup === undefined) { groupedLists.push({ type: list.type, includeLists: [], excludeLists: [] }); foundGroup = groupedLists[groupedLists.length - 1]; } if (list.excludedFilter) foundGroup.excludeLists.push(list.entries); else foundGroup.includeLists.push(list.entries); } let finalList; for (const group of groupedLists) { const includeList = combineLists(group.includeLists, filterRules[group.type].include); const excludeList = combineLists(group.excludeLists, filterRules[group.type].exclude); // Combine the include and exclude lists // If the exclude list exists, start from an empty list // Otherwise, just default to the include list let groupFinalList = []; if (excludeList.length > 0 && includeList.length > 0) { const combineRule = filterRules[group.type].combined; for (const entry of excludeList) { if (groupFinalList.find(a => a.name === entry.name) !== undefined) continue; // Don't include duplicates if (combineRule === 'or') { if (includeList.find(a => a.name === entry.name) !== undefined) continue; groupFinalList.push(entry); continue; } // Otherwise, the rule is 'and' if (includeList.find(a => a.name === entry.name) === undefined) continue; groupFinalList.push(entry); } } else if (excludeList.length === 0) groupFinalList = includeList; else if (includeList.length === 0) groupFinalList = excludeList; // If the current final list is undefined, just add the resulting list to it and continue if (finalList === undefined) { finalList = groupFinalList; continue; } const newFinalList = []; // Loop through the resulting list // Join together with 'and' for (const anime of groupFinalList) { if (finalList.find(a => a.name === anime.name) === undefined) continue; newFinalList.push(anime); } finalList = newFinalList; } resolve(finalList); }); }); } function searchList(fuseClass, list, query, limit = 80) { const fuse = new fuseClass(list, { keys: ['name'], findAllMatches: true }); const lowercaseQuery = query.toLowerCase(); const results = fuse.search(query).map(a => {return a.item}); const includesMatch = []; const other = []; for (const result of results) { if (result.name.toLowerCase().includes(lowercaseQuery)) { includesMatch.push(result); continue; } other.push(result); } return [...includesMatch, ...other].splice(0,limit); } function timeSince(date) { const seconds = Math.floor((new Date() - date) / 1000); let interval = Math.floor(seconds / 31536000); if (interval >= 1) { return interval + " year" + (interval !== 1 ? 's' : ''); } interval = Math.floor(seconds / 2592000); if (interval >= 1) { return interval + " month" + (interval !== 1 ? 's' : ''); } interval = Math.floor(seconds / 86400); if (interval >= 1) { return interval + " day" + (interval !== 1 ? 's' : ''); } interval = Math.floor(seconds / 3600); if (interval >= 1) { return interval + " hour" + (interval !== 1 ? 's' : ''); } interval = Math.floor(seconds / 60); if (interval >= 1) { return interval + " minute" + (interval !== 1 ? 's' : ''); } return seconds + " second" + (seconds !== 1 ? 's' : ''); } if (/^\/(customlink|anitracker-redirect)/.test(window.location.pathname)) { (async () => { document.title = "Redirecting... :: animepahe"; $('h1').text('Redirecting...'); const includeRef = window.location.pathname.startsWith('/customlink'); const parts = { animeSession: undefined, episodeSession: undefined, time: -1 }; const searchParams = new URLSearchParams(window.location.search); const sessionParam = searchParams.get('s'); const animeParam = searchParams.get('a'); const episodeParam = searchParams.get('e'); const timeParam = searchParams.get('t'); const destination = await (async () => { if (sessionParam) { const sessionResponse = await getPageResponse(`/anime/${sessionParam}`); if (sessionResponse.status === 200) parts.animeSession = sessionParam; } if (animeParam && !parts.animeSession) { const iinfo = {}; if (+animeParam) iinfo.id = +animeParam; // animeParam can be both an ID (legacy) and a name else iinfo.name = decodeURIComponent(animeParam); let animeData; animeData = await getAnimeData(iinfo,["session","name"]); if (!animeData.session) { animeData = await getAnimeData(iinfo,["session","name"],{allowGuessing:true}); if (!animeData.session) return; } if (iinfo.name && iinfo.name !== animeData.name && !confirm(`[AnimePahe Improvements]\n\nCouldn't find any anime with name "${iinfo.name}".\nGo to "${animeData.name}" instead?`)) return; parts.animeSession = animeData.session; } if (!parts.animeSession) return; if (episodeParam) { const epData = await getEpisodeData(parts.animeSession, +episodeParam); parts.episodeSession = epData?.session; } if (timeParam) parts.time = +timeParam; if (parts.animeSession && parts.episodeSession && parts.time >= 0) { return '/play/' + parts.animeSession + '/' + parts.episodeSession + '?time=' + parts.time + (includeRef ? '&ref=customlink' : ''); } if (parts.animeSession && parts.episodeSession && parts.time === -1) { return '/play/' + parts.animeSession + '/' + parts.episodeSession + (includeRef ? '?ref=customlink' : ''); } if (parts.animeSession && !parts.episodeSession) { return '/anime/' + parts.animeSession + (includeRef ? '?ref=customlink' : ''); } return undefined; })(); if (destination) window.location.replace(destination); else { document.title = "Couldn't find anime :: animepahe"; $('h1').text("Failed: Couldn't find anime"); } })(); return; } // MARKER:MAIN PAGE KEYBOARD SHORTCUTS // Main key events $(document).on('keydown', (e, other = undefined) => { if (other) { e = other.event; e.preventDefault = function() {}; } if (!e.key) return; const isTextInput = $(e.target).is('input[type=text],input[type=number],input[type=""],input:not([type]),textarea,*[role=textbox]'); const storage = getStorage(); // In case a keybind would scroll the page if (!isTextInput && [" ","Home","End","ArrowDown","ArrowUp","PageUp","PageDown"].includes(e.key) && Object.entries(storage.settings).find( ([key,val]) => key.startsWith('keybind') && val.includes(e.key) )) e.preventDefault(); if (modalIsOpen()) { if (e.key === 'Escape') return closeModal(); if (pressedKeybind(e, storage.settings.keybindModalBack) && !isTextInput) return modalBackFunction(); if (e.ctrlKey && e.key === 'f' && $('.anitracker-modal-search').length) { const elems = $('.anitracker-modal-search'); elems[0].scrollIntoView(true); elems[0].focus(); e.preventDefault(); } return; } if (isTextInput) return; if (!document.fullscreenElement) { if (pressedKeybind(e, storage.settings.keybindBookmarks)) return openBookmarksModal(); if (pressedKeybind(e, storage.settings.keybindNotifications)) return openNotificationsModal(); if (pressedKeybind(e, storage.settings.keybindSearch)) return setTimeout(() => {$('.input-search').focus()}, 1); } if (!isEpisode()) return; // Everything below is for episode pages if (pressedKeybind(e, storage.settings.keybindResetPlayer)) return resetPlayer(); if (pressedKeybind(e, storage.settings.keybindTheatreMode)) { if (document.fullscreenElement) return document.exitFullscreen(); else return toggleTheatreMode(); } if (pressedKeybind(e, storage.settings.keybindNextEpisode)) return $('.sequel a')[0]?.click(); if (pressedKeybind(e, storage.settings.keybindPrevEpisode)) return $('.prequel a')[0]?.click(); else if (!['Control','Shift','Alt','Enter'].includes(e.key) && !e.msg /*If this was a message from iframe, don't do recursive stuff*/) { sendMessage({action:"key",key:e.key,event:{key:e.key, code:e.originalEvent.code, ctrlKey:e.ctrlKey, shiftKey:e.shiftKey, altKey:e.altKey, metaKey:e.metaKey, msg:true}}); $('.embed-responsive-item')[0].contentWindow.focus(); if ([" "].includes(e.key) || (["ArrowUp", "ArrowDown"].includes(e.key) && e.ctrlKey)) e.preventDefault(); } }); // Redirect filter pages if (/^\/anime\/\w+(\/[\w\-.]+)?$/.test(window.location.pathname)) { if (is404) return; const filter = /\/anime\/([^/]+)\/?([^/]+)?/.exec(window.location.pathname); if (filter[2] !== undefined) { if (filterRules[filter[1]] === undefined) return; if (filter[1] === 'season') { window.location.replace(`/anime?${filter[1]}=${filter[2]}..${filter[2]}`); return; } window.location.replace(`/anime?${filter[1]}=${filter[2]}`); } else { window.location.replace(`/anime?status=${filter[1]}`); } return; } function getDayName(day) { return [ "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" ][day]; } function toHtmlCodes(string) { return $('
    ').text(string).html().replace(/"/g, """).replace(/'/g, "'"); } // MARKER:HEADER BUTTONS // Bookmark & episode feed header buttons $(`
    `).insertAfter('.navbar-nav'); let currentNotificationIndex = 0; function openNotificationsModal() { const oldStorage = getStorage(); $('#anitracker-modal-body').empty(); $(`
    Last refreshed: ${getLastRefreshedText(oldStorage.notifications.lastUpdated)}
    `).appendTo('#anitracker-modal-body'); $('.anitracker-view-notif-animes').on('click', openNotifAnimesModal); const animeData = [...oldStorage.notifications.anime]; const queue = []; const errorAnime = []; openModal('Episode Feed').then(() => { if (animeData.find(a => (a.updateFrom !== undefined || !a.session))) startLoading(); else done(false); }); function startLoading() { if (!modalIsOpen() || $('#anitracker-notifications-list-spinner').length) return; $('#anitracker-modal-body .anitracker-modal-list').empty(); $(`
    Loading...
    0/${oldStorage.notifications.anime.length}
    `).appendTo('#anitracker-modal-body .anitracker-modal-list'); $('.anitracker-last-refreshed').parent().css('height','0'); queue.push(...animeData); animeData.length = 0; if (queue.length) next(); else done(); } $('.anitracker-refresh-notifs').on('click', function() { startLoading(); }); async function next() { if (!modalIsOpen() || !$('#anitracker-notifications-list-spinner').length) return; $('.anitracker-loaded-amount').text(1 + +$('.anitracker-loaded-amount').text()); if (!queue.length) done(); const anime = queue.shift(); const data = await updateNotifications(anime.name); if (typeof data !== 'object') { console.error(`[AnimePahe Improvements] Received response ${data} with anime ${anime.name}`); errorAnime.push(anime.name); animeData.push(anime); } else animeData.push(data); if (queue.length) next(); else done(); } function done(fromRefresh = true) { const storage = getStorage(); let removedAnime = 0; for (const anime of storage.notifications.anime) { if (!anime.latest_episode || anime.dont_ask === true) continue; const time = Date.now() - anime.latest_episode; if ((time / 1000 / 60 / 60 / 24 / 7) > 2) { const remove = confirm(`[AnimePahe Improvements]\n\nThe latest episode for ${anime.name} was more than 2 weeks ago. Remove it from the feed?\n\nThis prompt will not be shown again.`); if (remove === true) { toggleNotifications(anime.name, anime.id); removedAnime++; showMessage('Removed from feed'); } else { anime.dont_ask = true; saveData(storage); } } } if (removedAnime > 0) { openNotificationsModal(); return; } $('#anitracker-modal-body .anitracker-modal-list').empty(); if (errorAnime.length) { $(`An error occurred with the following anime:
    ${errorAnime.map(g => `${toHtmlCodes(g)}`).join('')} `) .appendTo('#anitracker-modal-body .anitracker-modal-list'); $('#anitracker-notif-error-ok').on('click', () => { done(false); $('.anitracker-last-refreshed').parent().css('height',''); }); errorAnime.length = 0; return; } if (fromRefresh) { storage.notifications.episodes.sort((a,b) => a.time < b.time ? 1 : -1); storage.notifications.lastUpdated = Date.now(); saveData(storage); $('.anitracker-last-refreshed').text(getLastRefreshedText(storage.notifications.lastUpdated)) .parent().css('height','').attr('title',getLastRefreshedTitle(storage.notifications.lastUpdated)); } currentNotificationIndex = 0; if (!storage.notifications.episodes.length) { $('
    Nothing here yet!
    ') .appendTo('#anitracker-modal-body .anitracker-modal-list'); } else { addToList(20); setModalShift(shouldShiftModal()); } } function getLastRefreshedTitle(value) { if (!value) return "Not yet refreshed"; return new Date(value).toLocaleString(); } function getLastRefreshedText(value) { if (!value) return "Never"; return `${timeSince(value)} ago`; } function addToList(num) { const storage = getStorage(); const index = currentNotificationIndex; for (let i = currentNotificationIndex; i < storage.notifications.episodes.length; i++) { const ep = storage.notifications.episodes[i]; if (!ep) break; currentNotificationIndex++; const data = animeData.find(a => a.id === ep.animeId); if (!data) { console.error(`[AnimePahe Improvements] Could not find corresponding anime "${ep.animeName}" with ID ${ep.animeId} (episode ${ep.episode})`); continue; } const releaseTime = toUTCDate(ep.time); const elem = $(` `).appendTo('#anitracker-modal-body .anitracker-modal-list'); if (storage.settings.relativeEpNums) { getFirstEpisodeEntry({ session: data.session, name: data.name, id: data.id, }).then(firstEpEntry => { elem.find('.anitracker-episode-text').text(getRelativeEpisodeNum(ep.episode, firstEpEntry?.first_episode)); }); } if (i >= index+num) break; } $('.anitracker-notification-item.anitracker-temp').on('click', (e) => { $(e.currentTarget).find('a').blur(); }); $('.anitracker-notification-item.anitracker-temp .anitracker-watched-toggle').on('click keydown', (e) => { if (e.type === 'keydown' && e.key !== "Enter") return; e.preventDefault(); const storage = getStorage(); const elem = $(e.currentTarget); const parent = elem.parents().eq(1); const animeId = +parent.attr('anime-id'); const episode = +parent.attr('episode-data'); const ep = storage.notifications.episodes.find(a => a.animeId === animeId && a.episode === episode); if (ep === undefined) { console.error("[AnimePahe Improvements] couldn't mark episode as watched/unwatched"); return; } parent.toggleClass('anitracker-notification-item-unwatched'); elem.toggleClass('fa-eye').toggleClass('fa-eye-slash'); if (e.type === 'click') elem.blur(); ep.watched = !ep.watched; elem.attr('title', `Mark this episode as ${ep.watched ? 'unwatched' : 'watched'}`); saveData(storage); if (ep.watched) { addWatched(animeId, episode, storage); } else { removeWatched(animeId, episode, storage); } if (isAnime()) getAnimeData({ session: getAnimeSessionFromUrl() }, ["id"]).then(data => { if (data.id !== animeId) return; updateEpisodePages(); }); }); $('.anitracker-notification-item.anitracker-temp').removeClass('anitracker-temp'); // Temporary class for adding event listeners for (const data of animeData) { const elems = $(`.anitracker-notification-item[anime-id="${data.id}"]`); if (!elems.length || $(elems[0]).hasClass('anitracker-has-img-error-event')) continue; $(elems[0]).addClass('anitracker-has-img-error-event'); $(elems[0]).find('img').data('anime-data', data).on('error', function() { $(this).off('error'); const oldData = $(this).data('anime-data'); invalidatePosterCache(oldData.poster, getStorage()); addImageSpinner(elems.find('.anitracker-image-wrapper')); getAnimeData(oldData, ["poster"], {requireNew: true}).then(newData => { removeImageSpinner(elems.find('.anitracker-image-wrapper')); if (!newData?.poster) return; $(`.anitracker-notification-item[anime-id="${data.id}"]`).find('img').attr('src', makePosterUrl(newData.poster,'th')); const storage = getStorage(); const found = storage.notifications.anime.find(a => a.id === oldData.id); const foundTemp = animeData.find(a => a.id === oldData.id); foundTemp.poster = newData.poster; if (found) { found.poster = newData.poster; saveData(storage); } }); }); } } addModalEvent($('#anitracker-modal-body'), 'scroll', function() { if ($(this).scrollTop() < this.scrollTopMax) return; if (!$('.anitracker-view-notif-animes').length) return; addToList(20); }); function openNotifAnimesModal(animation = true) { $('#anitracker-modal-body').empty(); const storage = getStorage(); $(`
    `).appendTo('#anitracker-modal-body'); [0,1,6].forEach(g => $(``).appendTo('.anitracker-week-start-dropdown').data('value', g)); $('#anitracker-week-start-dropdown-toggle').text(getDayName(storage.settings.notifScheduleStart)); const schedule = [0,1,2,3,4,5,6].map(g => {return {num: g, list:[]}}); $('.anitracker-week-start-dropdown>button').on('click', function() { const storage = getStorage(); const day = +$(this).data('value'); storage.settings.notifScheduleStart = day; saveData(storage); $('#anitracker-week-start-dropdown-toggle').text(getDayName(day)); makeSchedule(day); }); openModal('Manage Episode Feed', openNotificationsModal, {hideAnimation: !animation}); if (!storage.notifications.anime.length) { $(`Use the button on an ongoing anime to add it to the feed.`).appendTo('#anitracker-modal-body .anitracker-modal-list'); makeSchedule(storage.settings.notifScheduleStart); return; } const promise = siteVars.cached.animeSession.length ? waitTime(200) : getAnimeSession({},{justCache:true}); loadUntilPromise($('#anitracker-modal-body .anitracker-modal-list'), promise).then(async () => { for (const g of [...storage.notifications.anime].sort((a,b) => a.latest_episode > b.latest_episode ? 1 : -1)) { const latestEp = new Date(g.latest_episode); const latestEpString = g.latest_episode !== undefined ? `${getDayName(latestEp.getDay())} ${latestEp.toLocaleTimeString([], {timeStyle:'short'})} (${timeSince(latestEp.getTime())} ago)` : "None found"; const data = await getAnimeData({ id: g.id, name: g.name }, ["session"], {requireInstant:true,ignored:['storage_notification_anime']}); const href = data.session ? `/anime/${data.session}` : `/anitracker-redirect?a=${encodeURIComponent(g.name)}`; $(`
    ${toHtmlCodes(g.name)}
    Latest episode: ${latestEpString}
    `).appendTo('#anitracker-modal-body .anitracker-modal-list'); const scheduleEntry = schedule.find(a => a.num === latestEp.getDay()); if (scheduleEntry) scheduleEntry.list.push({ time: latestEp, name: g.name, href: href, }); } makeSchedule(storage.settings.notifScheduleStart); setModalShift(false); $('.anitracker-modal-list-entry .anitracker-get-all-button').on('click', (e) => { const elem = $(e.currentTarget); const id = +elem.parents().eq(1).attr('animeid'); const storage = getStorage(); const found = storage.notifications.anime.find(a => a.id === id); if (!found) { console.error("[AnimePahe Improvements] Couldn't find feed for anime with ID " + id); return; } found.hasFirstEpisode = true; found.updateFrom = 0; saveData(storage); elem.replaceClass("btn-secondary", "btn-primary"); setTimeout(() => { elem.replaceClass("btn-primary", "btn-secondary"); elem.prop('disabled', true); }, 200); showMessage('Added all episodes to feed'); }); $('.anitracker-modal-list-entry .anitracker-delete-button').on('click', (e) => { const parent = $(e.currentTarget).parents().eq(1); const name = parent.attr('animename'); toggleNotifications(name, +parent.attr('animeid')); showMessage(`Removed "${name?.slice(0,20)}${name?.length > 20 ? '...' : ''}"`, 4000); const name2 = getAnimeName(); if (name2.length > 0 && name2 === name) $('.anitracker-notifications-toggle .anitracker-title-icon-check').hide(); parent.remove(); openNotifAnimesModal(false); }); }); function makeSchedule(startDay) { const today = new Date().getDay(); $('.anitracker-feed-schedule>div').remove(); for (let i = 0; i < schedule.length; i++) { if (schedule[0].num === startDay) break; schedule.push(schedule.shift()); } for (const entry of schedule) { entry.list.sort((a,b) => a.time.toLocaleTimeString() > b.time.toLocaleTimeString() ? 1 : -1); $(`
    ${getDayName(entry.num).slice(0,3)}
    ${entry.list.map(g => { return `${g.name}`; }).join('')}
    `).appendTo($('.anitracker-feed-schedule')); } } } } $('.anitracker-header-notifications').on('click', openNotificationsModal); // Format: [name, bg_color, text_color, ordering] const statuses = { watching: ['Watching', '#109d4e', '#86ccb2', 0], planning_to_watch: ['Planning to Watch', '#a95cbd', '#e08ef5', 1], on_hold: ['On Hold', '#ca9c30', '#f5d98e', 2], completed: ['Completed', 'rgb(62, 62, 176)', '#8383ee', 3], } const defaultStatus = 'watching'; function getStatusAttributes(status) { return statuses[status] ?? statuses[defaultStatus]; } function openBookmarksModal() { $('#anitracker-modal-body').empty(); const storage = getStorage(); let layout = storage.settings.bookmarkLayout; let sort = storage.settings.bookmarkSort; const sessionCache = {}; // {id:session} $(`
    ${storage.bookmarks.length ?`
    ` : ''}
    `).appendTo('#anitracker-modal-body'); function sortEntries(entries) { if (['alphabetical','status'].includes(sort)) entries.sort((a,b) => a.name < b.name ? 1 : -1); if (sort === 'status') entries.sort((a, b) => getStatusAttributes(a.status)[3] < getStatusAttributes(b.status)[3] ? 1 : -1) if ($('.anitracker-reverse-order-button').attr('dir') === 'down') entries.reverse(); } async function layoutEntries(storage = getStorage(), goToTop = true) { $('.anitracker-modal-list').empty(); const entries = [...storage.bookmarks]; if (!entries.length) { $('.anitracker-modal-list').addClass('flex'); return $(`No bookmarks yet!`).appendTo('#anitracker-modal-body .anitracker-modal-list'); } sortEntries(entries); const searchInput = $('.anitracker-modal-search').val().toLowerCase(); if (layout === 'list') $('.anitracker-modal-list').removeClass('flex'); else $('.anitracker-modal-list').addClass('flex'); for (const g of entries) { const statusAttrs = getStatusAttributes(g.status); let session = sessionCache[g.id]; let name = g.name; if (!session) { const foundData = await getAnimeData({ name: g.name, id: g.id, poster: g.posterUrl }, ["session","name"], {requireInstant: true, ignored:['storage_bookmark']}); session = foundData.session; if (session) sessionCache[g.id] = session; if (foundData.name) name = foundData.name; } const href = session ? `href="/anime/${session}"` : `/anitracker-redirect?a=${encodeURIComponent(name)}`; let elem; if (layout === 'list') { elem = $(`
    ${g.newlyAdded ? '' : ''} ${toHtmlCodes(name)}
    `).appendTo('#anitracker-modal-body .anitracker-modal-list'); } else { elem = $(`
    ${g.newlyAdded ? '' : ''}
    ${toHtmlCodes(name)}
    `).appendTo('#anitracker-modal-body .anitracker-modal-list'); elem.find('img').on('load', function() {$(this).css('opacity', '1')}); if (g.posterUrl === undefined) { getBookmarkImage(elem, g, session); } else elem.find('img').on('error', function() { invalidatePosterCache(g.posterUrl, getStorage()); getBookmarkImage(elem, g, session); $(this).off('error'); }); } if (!name.toLowerCase().includes(searchInput)) elem.hide(); if (!session || name !== g.name) { const spinner = $(`
    Loading...
    `).insertBefore(elem.find('a>span')); getAnimeData({ name: name, id: g.id, poster: g.poster, }, ["name","session"], {ignored: ['storage_bookmark']}).then(data => { spinner.remove(); if (!data.session) return; sessionCache[g.id] = data.session; const storage2 = getStorage(); const obj = storage2.bookmarks.find(a => a.id === g.id); if (!obj) return; if (data.name) { obj.name = data.name; elem.attr('animename',data.name).find('a').attr('title',data.name).find('span').text(data.name); console.log(`[AnimePahe Improvements] Replaced old bookmark name "${g.name}" with new "${data.name}"`); } saveData(storage2); elem.find('a').attr('href', '/anime/' + data.session); }); } } if (goToTop) scrollModalToTop(); $(` `).appendTo('.anitracker-modal-list'); Object.entries(statuses).forEach(e => { $(``).appendTo('.anitracker-status-dropdown')}); // Apply button events $('.anitracker-modal-list-entry .anitracker-change-status-button').on('click', (e) => { const elem = $(e.currentTarget); elem.removeClass('active'); const id = elem.parents().eq(1).attr('animeid'); const dropdown = $('.anitracker-status-dropdown'); if (dropdown.is(':visible') && dropdown.data('id') === id) { dropdown.hide(); return; } elem.addClass('active'); elem.focus(); dropdown.insertAfter(elem); const top = Math.min(window.innerHeight - dropdown.outerHeight(true), elem.position().top + elem.outerHeight(true)); const left = Math.min(window.innerWidth - dropdown.outerWidth(true), elem.position().left); dropdown.css('top',top).css('left',left); dropdown.show(); dropdown.scrollTop(0); dropdown.data('id', id); }) .on('blur', function() { $(this).removeClass('active'); setTimeout(() => { if (!$('.anitracker-status-dropdown button').is(':focus')) $('.anitracker-status-dropdown').hide(); }, 0); }) .on('keydown', (e) => { if (e.key !== 'Escape') return; $(e.currentTarget).trigger('blur'); e.stopPropagation(); }); $('.anitracker-modal-list-entry .anitracker-remove-bookmark-button').on('click', function() { removeBookmark(+$(this).parents().eq(1).attr('animeid')); layoutEntries(getStorage(), false); const name = $(this).parents().eq(1).attr('animename'); showMessage(`Removed "${name?.slice(0,20)}${name?.length > 20 ? '...' : ''}"`, 4000); }); $('.anitracker-status-dropdown button').on('click', function() { const pressed = $(this); const status = pressed.data('value'); const id = +pressed.parent().data('id'); setBookmarkStatus(id, status); layoutEntries(getStorage(), sort === 'status'); }).on('blur', function() { setTimeout(() => { if (!$('.anitracker-change-status-button, .anitracker-status-dropdown button').is(':focus')) $(this).parent().hide(); }, 0); }) .on('keydown', (e) => { if (e.key !== 'Escape') return; $(e.currentTarget).trigger('blur'); e.stopPropagation(); }); $('.anitracker-modal-list-entry').on('mouseenter focus', function() { const elem = $(this).find('.anitracker-bookmark-new'); if (!elem.length) return; setTimeout(() => { playAnimation(elem, 'fadeIn', 0.5, 'reverse').then(() => { elem.remove(); }); }, 1500); }); } // layoutEntries end // Other events $('.anitracker-modal-search').on('input', (e) => { setTimeout(() => { const query = $(e.target).val().toLowerCase(); for (const entry of $('.anitracker-modal-list-entry')) { if ($($(entry).find('a,span')[0]).text().toLowerCase().includes(query)) { $(entry).show(); } else $(entry).hide(); } }, 10); }); $('.anitracker-reverse-order-button').on('click', (e) => { const btn = $(e.currentTarget); if (btn.attr('dir') === 'down') { btn.attr('dir', 'up'); btn.addClass('anitracker-up'); } else { btn.attr('dir', 'down'); btn.removeClass('anitracker-up'); } layoutEntries(); }); $('.anitracker-layout-btns>button').on('click', (e) => { const elem = $(e.currentTarget); layout = elem.data('layout'); const currentStorage = getStorage(); currentStorage.settings.bookmarkLayout = layout; saveData(currentStorage); layoutEntries(currentStorage); elem.parent().children().prop('disabled', false); elem.prop('disabled', true); }); $('.anitracker-sort-method-btns>button').on('click', (e) => { const elem = $(e.currentTarget); sort = elem.data('sort'); const currentStorage = getStorage(); currentStorage.settings.bookmarkSort = sort; saveData(currentStorage); layoutEntries(currentStorage); elem.parent().children().prop('disabled', false); elem.prop('disabled', true); }); $('.anitracker-share-bookmarks-button').on('click', function() { const elem = $(this); elem.focus(); const dropdown = $('.anitracker-share-bookmarks-dropdown'); const top = elem.position().top + elem.outerHeight(true); const left = elem.position().left - (dropdown.width() - elem.outerWidth(true)); if (dropdown.is(':visible')) { dropdown.hide(); return; } dropdown.css('top',top).css('left',left); dropdown.show(); dropdown.scrollTop(0); }) .on('blur', () => { setTimeout(() => { if (!$('.anitracker-share-bookmarks-dropdown button').is(':focus')) $('.anitracker-share-bookmarks-dropdown').hide(); }, 0); }) .on('keydown', (e) => { if (e.key !== 'Escape') return; $(e.currentTarget).trigger('blur'); e.stopPropagation(); }); $('.anitracker-share-bookmarks-dropdown button').on('click', async function() { const elem = $(this); elem.parent().hide(); const action = elem.data('action'); if (action === 'image') { if ($('#anitracker-share-bookmarks-spinner').length) return; const btn = $('.anitracker-share-bookmarks-button'); btn.off(); btn.css('padding', '.2em'); btn.html(`
    Loading...
    0%
    `); if (layout === 'grid') { $('.anitracker-bookmark-grid-entry img').attr('loading', 'eager'); const total = $('.anitracker-bookmark-grid-entry img').length; for (let i = 0; i < total; i++) { $('#anitracker-share-bookmarks-spinner>span').text(`${Math.floor((i/total)*99)}%`); const img = $('.anitracker-bookmark-grid-entry img')[i]; if (img.complete) continue; await new Promise(resolve => { img.onload = resolve; img.onerror = resolve; }); } } $.anitrackerCachedScript('https://html2canvas.hertzen.com/dist/html2canvas.min.js', function() { if (!modalIsOpen() || !$('.anitracker-share-bookmarks-button').length) return; // If no longer in the right menu $('.anitracker-remove-bookmark-button').remove(); $('.anitracker-bookmark-new').remove(); const prevWidth = $('.anitracker-modal-list-container').width(); let newWidth = layout === 'grid' ? 0 : prevWidth; if (layout === 'grid') { for (const elem of $('.anitracker-bookmark-grid-entry')) { newWidth += $(elem).width(); } $('.anitracker-modal-list-container').css('width', Math.min(newWidth, 2400) + 'px'); } else if (layout === 'list') { $('.anitracker-bookmark-list-entry').css('border', '2px solid var(--secondary)').css('border-radius','5px').css('padding', '5px').css('margin', '2px'); } $('.anitracker-modal-list-container').css('border-radius', '24px'); $('.anitracker-modal-list a').css('color', '#fff').css('text-decoration', 'none'); html2canvas($('.anitracker-modal-list-container')[0], { allowTaint:true, scale: (newWidth > 1024 ? 0.8 : 1), backgroundColor:null }).then(function(canvas) { $('.anitracker-spinner').remove(); $(`

    Right-click to save

    ${layout === 'list' ? '

    Grid view is recommended over list view

    ' : ''}
    `).appendTo('#anitracker-modal-body'); $(canvas).css('height', '100%').css('width', '').appendTo('#anitracker-bookmark-share-result'); $('#anitracker-bookmark-share-result').css('max-width', Math.min($(canvas).width(), prevWidth)); scrollModalToTop(); setModalShift(shouldShiftModal()); }); $('#anitracker-modal-body').empty(); $(`
    Loading...
    `).appendTo('#anitracker-modal-body'); openModal('Share Result', openBookmarksModal); }).fail(() => { console.error("[AnimePahe Improvements] html2canvas failed to load"); $('#anitracker-modal-body').empty(); $('Failed to load!').appendTo('#anitracker-modal-body'); openModal('Share Result', openBookmarksModal); }); } else if (action === 'text') { const storage = getStorage(); const entries = [...storage.bookmarks]; sortEntries(entries); download('bookmarks-list.txt', entries.map(a => `${a.name} - ${getStatusAttributes(a.status)[0]}\n`).join('')); } }) .on('blur', () => { setTimeout(() => { if (!$('.anitracker-share-bookmarks-button, .anitracker-share-bookmarks-dropdown button').is(':focus')) $('.anitracker-share-bookmarks-dropdown').hide(); }, 0); }) .on('keydown', (e) => { if (e.key !== 'Escape') return; $(e.currentTarget).trigger('blur'); e.stopPropagation(); }); addModalEvent($('#anitracker-modal-body'), 'scroll', () => { $('#anitracker-modal-body .anitracker-dropdown-content').hide(); }); openModal('Bookmarks'); if (!storage.bookmarks.length) return layoutEntries(); const promise = siteVars.cached.animeSession.length ? waitTime(200) : getAnimeSession({},{justCache:true}); loadUntilPromise($('#anitracker-modal-body .anitracker-modal-list'), promise).then(() => { layoutEntries().then(() => { const storage = getStorage(); storage.bookmarks.forEach(b => {delete b.newlyAdded;}); saveData(storage); }); }); if (!isMobileOrTablet()) setTimeout(() => { $('.anitracker-modal-search').focus(); }, 0); } // imgWrapper cannot have inlined "display" styling function addImageSpinner(imgWrapper) { imgWrapper.css('display','revert'); $(`
    Loading...
    `).prependTo(imgWrapper); } function removeImageSpinner(imgWrapper) { imgWrapper.css('display', ''); imgWrapper.find('.anitracker-spinner-parent').remove(); } function getBookmarkImage(elem, bookmark, session = undefined) { addImageSpinner(elem.find('.anitracker-big-poster-icon')); setTimeout(async () => { const data = await getAnimeData({ name: bookmark.name, id: bookmark.id, session: session, }, ['poster'], {ignored:['storage_bookmark'],requireNew:true}); removeImageSpinner(elem.find('.anitracker-big-poster-icon')); if (!data.poster) return; elem.find('img').attr('src', makePosterUrl(data.poster,'sm')); const currentStorage = getStorage(); const found = currentStorage.bookmarks.find(b => b.name === bookmark.name && b.id === bookmark.id); if (!found) return; found.posterUrl = trimPosterUrl(data.poster); saveData(currentStorage); }, 0); } function openBookmarkStatusEditModal(id, adding=false) { const storage = getStorage(); const entry = storage.bookmarks.find(a => a.id === id) ?? { id: id, name: getAnimeName(), status: 'watching' }; const limitReached = storage.bookmarks.length >= getStorageLimits().bookmarks; $('#anitracker-modal-body').empty(); const status = entry.status ?? defaultStatus; const statusAttrs = getStatusAttributes(entry.status); $(`
    ${toHtmlCodes(entry.name)}
    `).appendTo('#anitracker-modal-body'); Object.entries(statuses).forEach(e => { $(``).appendTo('.anitracker-status-dropdown')}); $('.anitracker-status-dropdown button').on('click', (e) => { const pressed = $(e.target); const btn = pressed.parents().eq(1).find('.anitracker-status-dropdown-button'); const value = pressed.data('value'); const found = Object.entries(statuses).find(e => e[0] === value)[1]; btn.data('value', value); btn.text(found[0]); btn.css('background-color', found[1]); entry.status = value; if (adding) return; setBookmarkStatus(id, entry.status); }); if (adding) { $(` ${limitReached ? 'You already have too many bookmarks' : ''} `).appendTo('.anitracker-bookmark-edit-side'); $('#anitracker-modal-body .anitracker-confirm-button').on('click', () => { if (limitReached) return; const obj = { status: entry.status } if (entry.posterUrl) obj.posterUrl = entry.posterUrl; addBookmark(id, entry.name, obj); showMessage('Bookmark added!'); closeModal(); }); } else { $(` `).appendTo('.anitracker-bookmark-edit-side'); $('#anitracker-modal-body .anitracker-delete-button').on('click', () => { removeBookmark(id); showMessage('Bookmark removed'); closeModal(); }); } openModal(adding ? 'Add Bookmark' : 'Edit Bookmark'); const imgElem = $('.anitracker-image-wrapper'); imgElem.find('img').on('load', function() { $(this).css('opacity', '1'); entry.posterUrl = getPathname($(this).attr('src')); }); const session = (isAnime() || isEpisode()) ? getAnimeSessionFromUrl() : undefined; if (entry.posterUrl === undefined) { getBookmarkImage(imgElem, entry, session); return; } imgElem.find('img').on('error', function() { invalidatePosterCache(entry.posterUrl, getStorage()); getBookmarkImage(imgElem, entry, session); $(this).off('error'); }); } $('.anitracker-header-bookmark').on('click', openBookmarksModal); function addBookmark(id, name, additionalData = {}) { const storage = getStorage(); if (storage.bookmarks.length >= getStorageLimits().bookmarks) return; if (storage.bookmarks.find(g => g.id === +id)) return; const obj = { id: +id, name: name, newlyAdded: true, } for (const [key, value] of Object.entries(additionalData)) { obj[key] = value; } if (isSyncEnabled(storage)) { storage.sync.temp.addedData.push({type: 'bookmarks', id: +id}); } storage.bookmarks.push(obj); saveData(storage); if (isAnime() || isEpisode()) getAnimeData({ session: getAnimeSessionFromUrl() }, ["id"]).then(data => { if (data.id !== +id) return; $('.anitracker-bookmark-toggle .anitracker-title-icon-check').show(); }); } function removeBookmark(id) { const storage = getStorage(); if (!storage.bookmarks.find(g => g.id === +id)) return; if (isSyncEnabled(storage)) { storage.sync.temp.removedData.push({type: 'bookmarks', id: +id}); } storage.bookmarks = storage.bookmarks.filter(g => g.id !== +id); saveData(storage); if (isAnime() || isEpisode()) getAnimeData({ session: getAnimeSessionFromUrl() }, ["id"]).then(data => { if (data.id !== +id) return; $('.anitracker-bookmark-toggle .anitracker-title-icon-check').hide(); }); } function setBookmarkStatus(id, status) { const storage = getStorage(); const found = storage.bookmarks.find(a => a.id === id); if (!found) return; if (found.status === status) return; if (isSyncEnabled(storage)) { storage.sync.temp.addedData.push({type: 'updated_bookmark', id: id}); } found.status = status; saveData(storage); } // Calls a function each second a request that includes an entry in "match" is stalled // Returns the interval, to cancel after the request is done function onStalledRequest(match, callback, stallOver = function(){}) { let stalledSeconds = 0; const interval = setInterval(() => { if (!siteVars.stalledRequests.find(r => match.find(m => r.includes(m)))) { if (stalledSeconds) { clearInterval(interval); stallOver(stalledSeconds); } return; } stalledSeconds++; callback(stalledSeconds); }, 1000); return interval; } function toggleNotifications(name, id = undefined) { const storage = getStorage(); const found = (() => { if (id) return storage.notifications.anime.find(g => g.id === id); else return storage.notifications.anime.find(g => g.name === name); })(); if (found) { if (isSyncEnabled(storage)) { storage.sync.temp.removedData.push({type: 'notification_anime', name: found.name}); } const index = storage.notifications.anime.indexOf(found); storage.notifications.anime.splice(index, 1); storage.notifications.episodes = storage.notifications.episodes.filter(a => a.animeName !== found.name); // Uses the name, because old data might not be updated to use IDs saveData(storage); return false; } if (!id) return; if (storage.notifications.anime.length >= getStorageLimits().notifications.anime) return; if (isSyncEnabled(storage)) { storage.sync.temp.addedData.push({type: 'notification_anime', name: name}); } storage.notifications.anime.push({ name: name, id: id, updateFrom: Date.now() }); saveData(storage); return true; } // Return values: // Anime data object - success // 0 - anime was not in notifications storage (impossible?) // 1 - anime data request failed // 2 - episode list request failed async function updateNotifications(animeName) { let storage = getStorage(); let nobj = storage.notifications.anime.find(g => g.name === animeName); if (nobj === undefined) { toggleNotifications(animeName); return 0; } const compareUpdateTime = getCompareTime(); if (nobj.updateFrom !== undefined) { delete nobj.updateFrom; saveData(storage); } const stallInterval = makeStallInterval([makeSearchable(animeName)]); const reqdata = ['session','name']; if (!nobj.poster) reqdata.push('poster'); const data = await getAnimeData({ name: animeName, id: nobj.id, poster: nobj.poster, },reqdata,{ignored:['storage_notification_anime'],requireNew:true}); removeStallInterval(stallInterval); if (!data.session || !data.name) return 1; const stallInterval2 = makeStallInterval([data.session]); const newestEpisodes = await getNewestEpisodes(data.session, compareUpdateTime); removeStallInterval(stallInterval2); if (newestEpisodes === undefined) return 2; storage = getStorage(); nobj = storage.notifications.anime.find(g => g.name === animeName); // Refresh the reference const allEpisodes = storage.notifications.episodes; const episodes = allEpisodes.filter(g => g.animeName === animeName); if (nobj.name !== data.name) { for (const ep of allEpisodes) { if (ep.animeName !== animeName) continue; ep.animeName = data.name; } nobj.name = data.name; } // Add newly found episodes for (const ep of newestEpisodes.reverse()) { allEpisodes.splice(0,0,{ animeName: data.name, animeId: nobj.id, // Anime entries had ID in first iteration, but episode entries did not session: ep.session, episode: ep.episode, time: ep.created_at }); } const lastEpisodePage = siteVars.cached.episodePage.find(r => r.session === data.session && r.page === 1 && r.sort === 'episode_desc'); if (lastEpisodePage?.value.data.length) nobj.latest_episode = toUTCDate(lastEpisodePage.value.data[0].created_at).getTime(); if (data.poster) nobj.poster = data.poster; nobj.session = data.session; const watched = decodeWatched(storage.watched); for (const ep of allEpisodes) { if (ep.animeName !== data.name) continue; const epWatched = isWatched(nobj.id, ep.episode, watched) || getStoredTime(nobj.name, ep.episode, storage, nobj.id); if (!ep.watched) ep.watched = epWatched; if (!ep.animeId) ep.animeId = nobj.id; } if (storage.settings.relativeEpNums && nobj.hasFirstEpisode && episodes.length) { cacheFirstEpisode(episodes[episodes.length - 1].episode, { id: nobj.id, session: data.session, }, storage); } const limit = getStorageLimits().notifications.episodes; if (storage.notifications.episodes.length > limit) { storage.notifications.episodes = storage.notifications.episodes.slice(0, limit); } saveData(storage); if (!data.id) data.id = nobj.id; if (!data.poster) data.poster = nobj.poster; return data; // Inner functions: function getCompareTime() { if (typeof nobj.latest_episode === 'string') nobj.latest_episode = toUTCDate(nobj.latest_episode).getTime(); // For old format return nobj.updateFrom ?? nobj.latest_episode ?? storage.notifications.lastUpdated; } function removeStallInterval(interval) { clearInterval(interval); $('#anitracker-notifications-list-spinner > #anitracker-notifications-stall-info').remove(); } function makeStallInterval(match) { return onStalledRequest( [match], (secondsStalled) => { let elem = $('#anitracker-notifications-list-spinner > #anitracker-notifications-stall-info'); if (!elem.length) { elem = $(` Stalled... (0) `).appendTo('#anitracker-notifications-list-spinner'); } elem.find('.anitracker-seconds').text(secondsStalled); }, removeStallInterval ); } } async function getNewestEpisodes(session, untilTime, noCache = true) { const finalList = []; const [succeeded, episodeResponse] = await addUntilEp(1); if (!episodeResponse) return undefined; if (!episodeResponse.data.length) return finalList; if (succeeded) return finalList; if (episodeResponse.current_page === episodeResponse.last_page) return finalList; for (let i = 2; i <= episodeResponse.last_page; i++) { const [succeeded] = await(addUntilEp(i)); if (succeeded) return finalList; } return finalList; async function addUntilEp(page) { const episodeResponse = await getEpisodePageResponse(session, page, 'episode_desc', {noCache: noCache}); if (!episodeResponse) return [false, undefined]; for (const ep of episodeResponse.data) { if (toUTCDate(ep.created_at).getTime() <= untilTime) return [true, episodeResponse]; finalList.push(ep); } return [false, episodeResponse]; } } const paramArray = Array.from(new URLSearchParams(window.location.search)); const refArg01 = paramArray.find(a => a[0] === 'ref'); if (refArg01 !== undefined) { const ref = refArg01[1]; if (ref === '404') { alert('[AnimePahe Improvements]\n\nThe session was outdated, and has been refreshed. Please try that link again.'); } else if (ref === 'customlink' && isEpisode() && initialStorage.settings.autoDelete) { const name = getAnimeName(); const num = getEpisodeNum(); if (initialStorage.linkList.find(e => e.animeName === name && e.type === 'episode' && e.episodeNum !== num)) { // If another episode is already stored $(` `).prependTo('.content-wrapper'); $('.anitracker-from-share-warning>span').on('click keydown', function(e) { if (e.type === 'keydown' && e.key !== "Enter") return; $(e.target).parent().remove(); }); } } window.history.replaceState({}, document.title, window.location.origin + window.location.pathname); } function getCurrentSeason() { const month = new Date().getMonth(); return Math.trunc(month/3); } function getFiltersFromParams(params) { const filters = []; for (const [key, value] of params.entries()) { const inputFilters = value.split(','); // Get all filters of this filter type for (const filter of inputFilters) { if (filterRules[key] === undefined) continue; const exclude = filter.startsWith('!'); if (key === 'season') { if (seasonFilterRegex.test(filter)) { const parts = seasonFilterRegex.exec(filter); if (!parts.includes(undefined) && ![parseInt(parts[2]),parseInt(parts[4])].includes(NaN)) { filters.push({ type: 'season', value: { from: { season: getSeasonValue(parts[1]), year: parseInt(parts[2]) }, to: { season: getSeasonValue(parts[3]), year: parseInt(parts[4]) } }, exclude: exclude }); } } continue; } filters.push({ type: key, value: filter.replace(/^!/,''), exclude: exclude }); } } return filters; } function getSearchParamsString(params) { if (!Array.from(params.entries()).length) return ''; return '?' + decodeURIComponent(params.toString()); } // MARKER:ANIME INDEX PAGE function loadIndexPage() { const animeList = getAnimeList(); filterSearchCache['/anime'] = copyObj(animeList); $(`
    Filter results: ${animeList.length}
     Reset
    `).insertBefore('.index'); getTrackerDiv().css('justify-content', 'center').insertAfter('.index'); addGeneralButtons(); function getDropdownButtons(filters, type) { return filters.sort((a,b) => a.name > b.name ? 1 : -1).concat({value: 'none', name: '(None)'}).map(g => $(``)); } $(`