diff options
| author | Fuwn <[email protected]> | 2023-08-26 22:29:03 -0700 |
|---|---|---|
| committer | Fuwn <[email protected]> | 2023-08-26 22:29:03 -0700 |
| commit | b89d0e7dada186e31be37e62a7a75efc2dbe9c99 (patch) | |
| tree | 8c9f6b5d7aa0f709c06d5eb45fbf763883b21c89 /src | |
| download | due.moe-b89d0e7dada186e31be37e62a7a75efc2dbe9c99.tar.xz due.moe-b89d0e7dada186e31be37e62a7a75efc2dbe9c99.zip | |
feat: initial build
Diffstat (limited to 'src')
| -rw-r--r-- | src/app.d.ts | 18 | ||||
| -rw-r--r-- | src/app.html | 26 | ||||
| -rw-r--r-- | src/hooks.server.ts | 19 | ||||
| -rw-r--r-- | src/lib/AniList/activity.ts | 23 | ||||
| -rw-r--r-- | src/lib/AniList/identity.ts | 32 | ||||
| -rw-r--r-- | src/lib/AniList/media.ts | 86 | ||||
| -rw-r--r-- | src/lib/List/Due/AnimeList.svelte | 135 | ||||
| -rw-r--r-- | src/lib/List/Due/MangaList.svelte | 114 | ||||
| -rw-r--r-- | src/lib/chapterDatabase.ts | 21 | ||||
| -rw-r--r-- | src/lib/mangadex.ts | 69 | ||||
| -rw-r--r-- | src/routes/+layout.server.ts | 5 | ||||
| -rw-r--r-- | src/routes/+layout.svelte | 45 | ||||
| -rw-r--r-- | src/routes/+page.svelte | 60 | ||||
| -rw-r--r-- | src/routes/anilist/increment/+server.ts | 27 | ||||
| -rw-r--r-- | src/routes/authentication/log-out/+server.ts | 7 | ||||
| -rw-r--r-- | src/routes/oauth/callback/+server.ts | 34 | ||||
| -rw-r--r-- | src/routes/settings/+page.svelte | 67 | ||||
| -rw-r--r-- | src/stores/cacheMangaMinutes.ts | 14 | ||||
| -rw-r--r-- | src/stores/closeAnimeByDefault.ts | 14 | ||||
| -rw-r--r-- | src/stores/closeMangaByDefault.ts | 14 | ||||
| -rw-r--r-- | src/stores/displayUnresolved.ts | 14 | ||||
| -rw-r--r-- | src/stores/lastPruneAt.ts | 12 |
22 files changed, 856 insertions, 0 deletions
diff --git a/src/app.d.ts b/src/app.d.ts new file mode 100644 index 00000000..34cd4db6 --- /dev/null +++ b/src/app.d.ts @@ -0,0 +1,18 @@ +import type { AniList } from '$lib/AniList'; + +// See https://kit.svelte.dev/docs/types#app +// for information about these interfaces +declare global { + namespace App { + // interface Error {} + + interface Locals { + user: AniList; + } + + // interface PageData {} + // interface Platform {} + } +} + +export {}; diff --git a/src/app.html b/src/app.html new file mode 100644 index 00000000..1cf78223 --- /dev/null +++ b/src/app.html @@ -0,0 +1,26 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width" /> + + <title>期限</title> + + <link rel="stylesheet" type="text/css" href="https://latex.now.sh/style.css" /> + <link rel="stylesheet" type="text/css" href="https://skybox.sh/css/palettes/base16-light.css" /> + <link rel="stylesheet" type="text/css" href="https://skybox.sh/css/risotto.css" /> + <!-- <link rel="stylesheet" type="text/css" href="https://skybox.sh/css/custom.css"> --> + <link rel="icon" href="%sveltekit.assets%/favicon.ico" /> + <link + rel="shortcut icon" + type="image/x-icon" + href="https://ps.fuwn.me/-tePaWtKW2y/angry-miku-nakano.ico" + /> + + %sveltekit.head% + </head> + + <body data-sveltekit-preload-data="hover"> + <div style="display: contents">%sveltekit.body%</div> + </body> +</html> diff --git a/src/hooks.server.ts b/src/hooks.server.ts new file mode 100644 index 00000000..48fc1f1b --- /dev/null +++ b/src/hooks.server.ts @@ -0,0 +1,19 @@ +import type { Handle } from '@sveltejs/kit'; + +export const handle: Handle = async ({ event, resolve }) => { + const { cookies } = event; + const user = cookies.get('user'); + + if (user) { + const parsedUser = JSON.parse(user); + + event.locals.user = { + tokenType: parsedUser['token_type'], + expiresIn: parsedUser['expires_in'], + accessToken: parsedUser['access_token'], + refreshToken: parsedUser['refresh_token'] + }; + } + + return await resolve(event); +}; diff --git a/src/lib/AniList/activity.ts b/src/lib/AniList/activity.ts new file mode 100644 index 00000000..995ff6eb --- /dev/null +++ b/src/lib/AniList/activity.ts @@ -0,0 +1,23 @@ +import type { UserIdentity } from './identity'; + +export const lastActivityDate = async (userIdentity: UserIdentity): Promise<Date> => { + const activityHistory = await ( + await fetch('https://graphql.anilist.co', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json' + }, + body: JSON.stringify({ + query: `{ Activity(userId: ${userIdentity.id}, type: MEDIA_LIST, sort: ID_DESC) { + __typename ... on ListActivity { createdAt } + } }` + }) + }) + ).json(); + const date = new Date(0); + + date.setUTCSeconds(activityHistory['data']['Activity']['createdAt']); + + return date; +}; diff --git a/src/lib/AniList/identity.ts b/src/lib/AniList/identity.ts new file mode 100644 index 00000000..a77891d6 --- /dev/null +++ b/src/lib/AniList/identity.ts @@ -0,0 +1,32 @@ +export interface UserIdentity { + id: number; + name: string; +} + +export interface AniListAuthorisation { + tokenType: string; + accessToken: string; + expiresIn: number; + refreshToken: string; +} + +export const userIdentity = async ( + anilistAuthorisation: AniListAuthorisation +): Promise<UserIdentity> => { + const userIdResponse = await ( + await fetch('https://graphql.anilist.co', { + method: 'POST', + headers: { + Authorization: `${anilistAuthorisation.tokenType} ${anilistAuthorisation.accessToken}`, + 'Content-Type': 'application/json', + Accept: 'application/json' + }, + body: JSON.stringify({ query: `{ Viewer { id name } }` }) + }) + ).json(); + + return { + id: userIdResponse['data']['Viewer']['id'], + name: userIdResponse['data']['Viewer']['name'] + }; +}; diff --git a/src/lib/AniList/media.ts b/src/lib/AniList/media.ts new file mode 100644 index 00000000..bd481d9a --- /dev/null +++ b/src/lib/AniList/media.ts @@ -0,0 +1,86 @@ +import type { AniListAuthorisation } from '$lib/AniList/identity'; +import type { UserIdentity } from './identity'; + +export enum Type { + Anime, + Manga +} + +export interface Media { + id: number; + status: string; + type: string; + episodes: number; + format: string; + title: { + romaji: string; + english: string; + native: string; + }; + nextAiringEpisode?: { + episode: number; + timeUntilAiring?: number; + }; + mediaListEntry?: { + progress: number; + }; + startDate: { + year: number; + }; +} + +export const flattenLists = (lists: object[][]) => { + if (lists === undefined) { + return []; + } + + let flattenedList: any[] = []; + const minimisedList: Media[] = []; + + for (const list of lists) { + flattenedList = flattenedList.concat(list['entries']); + } + + for (const [position, entry] of flattenedList.entries()) { + minimisedList[position] = entry['media']; + } + + return minimisedList; +}; + +export const mediaListCollection = async ( + anilistAuthorisation: AniListAuthorisation, + userIdentity: UserIdentity, + type: Type +) => { + const userIdResponse = await ( + await fetch('https://graphql.anilist.co', { + method: 'POST', + headers: { + Authorization: `${anilistAuthorisation.tokenType} ${anilistAuthorisation.accessToken}`, + 'Content-Type': 'application/json', + Accept: 'application/json' + }, + body: JSON.stringify({ + query: `{ MediaListCollection(userId: ${userIdentity.id}, type: ${ + type === Type.Anime ? 'ANIME' : 'MANGA' + }, status_not_in: [ COMPLETED ]) { + lists { entries { media { + id + status + type + episodes + format + title { romaji english native } + nextAiringEpisode { episode timeUntilAiring } + mediaListEntry { progress } + startDate { year } + } } } + } + }` + }) + }) + ).json(); + + return userIdResponse['data']['MediaListCollection']['lists']; +}; diff --git a/src/lib/List/Due/AnimeList.svelte b/src/lib/List/Due/AnimeList.svelte new file mode 100644 index 00000000..dd19bada --- /dev/null +++ b/src/lib/List/Due/AnimeList.svelte @@ -0,0 +1,135 @@ +<script lang="ts"> + import { mediaListCollection, Type, flattenLists, type Media } from '$lib/AniList/media'; + import type { UserIdentity, AniListAuthorisation } from '$lib/AniList/identity'; + import { onMount } from 'svelte'; + + export let user: AniListAuthorisation; + export let identity: UserIdentity; + export let displayUnresolved: boolean; + + let animeLists: any; + let startTime: number; + let endTime: number; + + onMount(async () => { + animeLists = mediaListCollection(user, identity, Type.Anime); + }); + + const cleanMedia = (media: object[][], displayUnresolved: boolean) => { + startTime = performance.now(); + + const flattenedLists = flattenLists(media); + const releasingMedia = flattenedLists.filter((media: Media) => media['status'] == 'RELEASING'); + const outdatedMedia = releasingMedia.filter((media: Media) => { + return ( + (media['nextAiringEpisode'] || { episode: 0 })['episode'] - 1 != + (media['mediaListEntry'] || { progress: 0 })['progress'] + ); + }); + let finalMedia = outdatedMedia.map((media: Media) => { + if ((media['nextAiringEpisode'] || { episode: 0 })['episode'] - 1 <= 0) { + media['nextAiringEpisode'] = { episode: -1 }; + } + + return media; + }); + + if (!displayUnresolved) { + finalMedia = finalMedia.filter((media: Media) => media.nextAiringEpisode?.episode !== -1); + } + + finalMedia.sort((a: Media, b: Media) => { + const difference = (anime: Media) => { + return ( + (anime.nextAiringEpisode?.episode === -1 + ? 99999 + : anime.nextAiringEpisode?.episode || -1) - + (anime['mediaListEntry'] || { progress: 0 })['progress'] + ); + }; + + return difference(a) - difference(b); + }); + + finalMedia = finalMedia.filter((item, index, array) => { + return ( + array.findIndex((i) => { + return i.id === item.id; + }) === index + ); + }); + endTime = performance.now() - startTime; + + return finalMedia; + }; + + const airingTime = (anime: Media) => { + const untilAiring = anime.nextAiringEpisode?.timeUntilAiring; + let timeFrame; + + if (untilAiring !== undefined) { + let hours = untilAiring / 3600; + + if (hours >= 24) { + let weeks = Math.floor(Math.floor(hours / 24) / 7); + + if (weeks >= 1) { + weeks = Math.round(weeks); + + timeFrame = `${weeks} week${weeks === 1 ? '' : 's'}`; + } else { + const days = Math.round(Math.floor(hours / 24)); + + timeFrame = `${days} day${days === 1 ? '' : 's'}`; + } + } else { + hours = Math.round(hours); + + timeFrame = `${hours} hour${hours === 1 ? '' : 's'}`; + } + + return `<span style="opacity: 50%">${anime.nextAiringEpisode?.episode} in ${timeFrame}</span>`; + } + + return ''; + }; + + const totalEpisodes = (anime: Media) => { + return anime['episodes'] === null + ? '' + : `<span style="opacity: 50%">/${anime['episodes']}</span>`; + }; + + const updateMedia = async (id: number, progress: number | undefined) => { + animeLists = mediaListCollection(user, identity, Type.Anime); + + await fetch(`/anilist/increment?id=${id}&progress=${progress! + 1}`); + }; +</script> + +{#await animeLists} + <summary>Anime</summary> + + <ul><li>Loading ...</li></ul> +{:then media} + <summary + >Anime [{cleanMedia(media, displayUnresolved).length}] + <small style="opacity: 50%">{endTime / 1000}s</small></summary + > + + <ul> + {#each cleanMedia(media, displayUnresolved) as anime} + <li> + <a href={`https://anilist.co/anime/${anime['id']}`} target="_blank"> + {anime['title']['english'] || anime['title']['romaji']} + </a> + {(anime['mediaListEntry'] || { progress: 0 })['progress']}{@html totalEpisodes(anime)} + <a href="#" on:click={() => updateMedia(anime.id, anime.mediaListEntry?.progress)}>+</a> + [{anime.nextAiringEpisode?.episode === -1 + ? '?' + : (anime.nextAiringEpisode?.episode || 1) - 1}] + {@html airingTime(anime)} + </li> + {/each} + </ul> +{/await} diff --git a/src/lib/List/Due/MangaList.svelte b/src/lib/List/Due/MangaList.svelte new file mode 100644 index 00000000..3016ed57 --- /dev/null +++ b/src/lib/List/Due/MangaList.svelte @@ -0,0 +1,114 @@ +<script lang="ts"> + import { mediaListCollection, Type, flattenLists, type Media } from '$lib/AniList/media'; + import type { UserIdentity, AniListAuthorisation } from '$lib/AniList/identity'; + import { onMount } from 'svelte'; + import { chapterCount } from '$lib/mangadex'; + import lastPruneAt from '../../../stores/lastPruneAt'; + import cacheMangaMinutes from '../../../stores/cacheMangaMinutes'; + + export let user: AniListAuthorisation; + export let identity: UserIdentity; + export let displayUnresolved: boolean; + + let mangaLists: any; + let startTime: number; + let endTime: number; + + onMount(async () => { + mangaLists = mediaListCollection(user, identity, Type.Manga); + }); + + const cleanMedia = async (media: object[][], displayUnresolved: boolean) => { + startTime = performance.now(); + + if ($lastPruneAt == '') { + lastPruneAt.set(new Date().getTime().toString()); + } else { + if ((new Date().getTime() - Number($lastPruneAt)) / 1000 / 60 > Number($cacheMangaMinutes)) { + lastPruneAt.set(new Date().getTime().toString()); + } + } + + const flattenedLists = flattenLists(media); + const releasingMedia = flattenedLists.filter( + (media: Media) => + media['status'] == 'RELEASING' && + media['format'] != 'NOVEL' && + (media['mediaListEntry'] || { progress: 0 })['progress'] >= 1 + ); + let finalMedia = releasingMedia; + + const chapterPromises = finalMedia.map((m: Media) => chapterCount(m)); + const chapterCounts = await Promise.all(chapterPromises); + + finalMedia.forEach((m: Media, i) => { + m.episodes = chapterCounts[i]; + }); + + if (!displayUnresolved) { + finalMedia = finalMedia.filter((m: Media) => m.episodes !== null); + } + + finalMedia.sort((a: Media, b: Media) => { + return ( + (a.episodes || 9999) - + a.mediaListEntry!.progress - + ((b.episodes || 9999) - b.mediaListEntry!.progress) + ); + }); + + finalMedia = finalMedia.filter((item, index, array) => { + return ( + array.findIndex((i) => { + return i.id === item.id; + }) === index && + (item.episodes === null && displayUnresolved + ? true + : (item.mediaListEntry?.progress || 0) < item.episodes) + ); + }); + endTime = performance.now() - startTime; + + return finalMedia; + }; + + const updateMedia = async (id: number, progress: number | undefined) => { + mangaLists = mediaListCollection(user, identity, Type.Manga); + + await fetch(`/anilist/increment?id=${id}&progress=${progress! + 1}`); + }; +</script> + +{#await mangaLists} + <summary>Manga</summary> + + <ul><li>Loading ...</li></ul> +{:then media} + <summary> + Manga {#await cleanMedia(media, displayUnresolved) then count}[{count.length}]{/await} + <small style="opacity: 50%">{endTime / 1000}s</small> + </summary> + + <ul> + {#await cleanMedia(media, displayUnresolved)} + <li>Loading ...</li> + {:then cleanedMedia} + {#each cleanedMedia as manga} + <li> + <a href={`https://anilist.co/manga/${manga['id']}`} target="_blank"> + {manga['title']['english'] || manga['title']['romaji'] || manga['title']['native']} + </a> + {(manga['mediaListEntry'] || { progress: 0 })['progress']} + <a href="#" on:click={() => updateMedia(manga.id, manga.mediaListEntry?.progress)}>+</a> + [{manga['episodes'] || '?'}] + </li> + {/each} + {:catch} + <li> + Media could not be loaded. You might have been <a + href="https://en.wikipedia.org/wiki/Rate_limiting">rate limited</a + >. + </li> + {/await} + </ul> +{/await} diff --git a/src/lib/chapterDatabase.ts b/src/lib/chapterDatabase.ts new file mode 100644 index 00000000..d580e6fa --- /dev/null +++ b/src/lib/chapterDatabase.ts @@ -0,0 +1,21 @@ +import Dexie, { type Table } from 'dexie'; + +export interface Chapter { + id: number; + chapters: number | null; +} + +export class ChapterDatabase extends Dexie { + chapters: Table<Chapter>; + + constructor() { + super('chapterDatabase'); + this.version(1).stores({ + chapters: 'id, chapters' + }); + + this.chapters = this.table('chapters'); + } +} + +export const chapterDatabase = new ChapterDatabase(); diff --git a/src/lib/mangadex.ts b/src/lib/mangadex.ts new file mode 100644 index 00000000..c5bd87c7 --- /dev/null +++ b/src/lib/mangadex.ts @@ -0,0 +1,69 @@ +import type { Media } from '$lib/AniList/media'; +import { chapterDatabase } from './chapterDatabase'; + +export const chapterCount = async (manga: Media): Promise<number | null> => { + const chapters = await chapterDatabase.chapters.get(manga.id); + + if (chapters !== undefined) { + return chapters.chapters === -1 ? null : chapters.chapters; + } + + console.log( + `Caching ${manga.id} (${manga.title.english || manga.title.romaji || manga.title.native})` + ); + + let mangadexData = await ( + await fetch( + `https://api.mangadex.org/manga?title=${encodeURIComponent( + manga.title.english || manga.title.romaji || manga.title.native + )}&year=${manga.startDate.year}` + ) + ).json(); + + if (mangadexData['data'] === undefined || mangadexData['data'].length === 0) { + mangadexData = await ( + await fetch( + `https://api.mangadex.org/manga?title=${encodeURIComponent(manga.title.native)}&year=${ + manga.startDate.year + }` + ) + ).json(); + } + + if (mangadexData['data'] === undefined || mangadexData['data'].length === 0) { + await chapterDatabase.chapters.put({ + id: manga.id, + chapters: -1 + }); + + return null; + } + + const lastChapterData = await ( + await fetch( + `https://api.mangadex.org/manga/${mangadexData['data'][0]['id']}/feed?order[chapter]=desc` + ) + ).json(); + + if (lastChapterData['data'] === undefined || lastChapterData['data'].length === 0) { + await chapterDatabase.chapters.put({ + id: manga.id, + chapters: -1 + }); + + return null; + } + + let lastChapter = lastChapterData['data'][0]['attributes']['chapter']; + + if (lastChapter === 0) { + lastChapter = null; + } + + await chapterDatabase.chapters.put({ + id: manga.id, + chapters: lastChapter + }); + + return lastChapter; +}; diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts new file mode 100644 index 00000000..9f05cf68 --- /dev/null +++ b/src/routes/+layout.server.ts @@ -0,0 +1,5 @@ +export const load = ({ locals }) => { + const { user } = locals; + + return { user }; +}; diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte new file mode 100644 index 00000000..2445967e --- /dev/null +++ b/src/routes/+layout.svelte @@ -0,0 +1,45 @@ +<script> + import { PUBLIC_ANILIST_CLIENT_ID, PUBLIC_ANILIST_REDIRECT_URI } from '$env/static/public'; + import { userIdentity } from '$lib/AniList/identity'; + import { onMount } from 'svelte'; + import { lastActivityDate } from '$lib/AniList/activity'; + + export let data; + + let currentUserIdentity = { name: '', id: -1 }; + let lastActivityWasToday = true; + + onMount(async () => { + if (data.user !== undefined) { + currentUserIdentity = await userIdentity(data.user); + currentUserIdentity.name = `(${currentUserIdentity.name})`; + lastActivityWasToday = + (await lastActivityDate(currentUserIdentity)).toDateString() === new Date().toDateString(); + } + }); +</script> + +<p /> + +<h1><a href="/">期限</a></h1> + +{#if data.user === undefined} + <a + href={`https://anilist.co/api/v2/oauth/authorize?client_id=${PUBLIC_ANILIST_CLIENT_ID}&redirect_uri=${PUBLIC_ANILIST_REDIRECT_URI}&response_type=code`} + >Log in with AniList</a + > +{:else} + <a href="/authentication/log-out">Log out from AniList {currentUserIdentity.name}</a> +{/if} + +{#if !lastActivityWasToday} + <p /> + + <p>You don't have any new activity statuses from the past day! Create one to keep your streak!</p> +{/if} + +<p /> + +<hr /> + +<slot /> diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte new file mode 100644 index 00000000..ccd4b119 --- /dev/null +++ b/src/routes/+page.svelte @@ -0,0 +1,60 @@ +<script lang="ts"> + import { onMount } from 'svelte'; + import { userIdentity } from '$lib/AniList/identity'; + import AnimeList from '$lib/List/Due/AnimeList.svelte'; + import MangaList from '$lib/List/Due/MangaList.svelte'; + import displayUnresolved from '../stores/displayUnresolved'; + import closeAnimeByDefault from '../stores/closeAnimeByDefault'; + import closeMangaByDefault from '../stores/closeMangaByDefault'; + + export let data; + + $: displayingUnresolved = $displayUnresolved === 'true'; + $: mangaClosed = $closeMangaByDefault === 'true'; + $: animeClosed = $closeAnimeByDefault === 'true'; + + let currentUserIdentity = { name: '', id: -1 }; + + onMount(async () => { + if (data.user !== undefined) { + currentUserIdentity = await userIdentity(data.user); + currentUserIdentity.name = `(${currentUserIdentity.name})`; + } + }); +</script> + +<a href="/settings">Settings</a> + +{#if data.user === undefined} + Please log in to view due media. +{:else} + <p /> + + <details open={animeClosed}> + {#if currentUserIdentity.id != -1} + <AnimeList + user={data.user} + identity={currentUserIdentity} + displayUnresolved={displayingUnresolved} + /> + {:else} + <summary>Anime</summary> + <ul><li>Loading ...</li></ul> + {/if} + </details> + + <p /> + + <details open={mangaClosed}> + {#if currentUserIdentity.id != -1} + <MangaList + user={data.user} + identity={currentUserIdentity} + displayUnresolved={displayingUnresolved} + /> + {:else} + <summary>Manga</summary> + <ul><li>Loading ...</li></ul> + {/if} + </details> +{/if} diff --git a/src/routes/anilist/increment/+server.ts b/src/routes/anilist/increment/+server.ts new file mode 100644 index 00000000..4680236b --- /dev/null +++ b/src/routes/anilist/increment/+server.ts @@ -0,0 +1,27 @@ +export const GET = async ({ url, cookies }) => { + const userCookie = cookies.get('user'); + + if (!userCookie) { + return new Response('Unauthenticated', { status: 401 }); + } + + const user = JSON.parse(userCookie); + + return Response.json( + await ( + await fetch('https://graphql.anilist.co', { + method: 'POST', + headers: { + Authorization: `${user['token_type']} ${user['access_token']}`, + 'Content-Type': 'application/json', + Accept: 'application/json' + }, + body: JSON.stringify({ + query: `mutation { SaveMediaListEntry(mediaId: ${ + url.searchParams.get('id') || 'null' + }, progress: ${url.searchParams.get('progress') || 'null'}) { id } }` + }) + }) + ).json() + ); +}; diff --git a/src/routes/authentication/log-out/+server.ts b/src/routes/authentication/log-out/+server.ts new file mode 100644 index 00000000..22ef49d8 --- /dev/null +++ b/src/routes/authentication/log-out/+server.ts @@ -0,0 +1,7 @@ +import { redirect } from '@sveltejs/kit'; + +export const GET = ({ cookies }) => { + cookies.delete('user', { path: '/' }); + + throw redirect(303, '/'); +}; diff --git a/src/routes/oauth/callback/+server.ts b/src/routes/oauth/callback/+server.ts new file mode 100644 index 00000000..4b0b6739 --- /dev/null +++ b/src/routes/oauth/callback/+server.ts @@ -0,0 +1,34 @@ +import { dev } from '$app/environment'; +import { ANILIST_CLIENT_SECRET } from '$env/static/private'; +import { PUBLIC_ANILIST_CLIENT_ID, PUBLIC_ANILIST_REDIRECT_URI } from '$env/static/public'; +import { redirect } from '@sveltejs/kit'; + +export const GET = async ({ url, cookies }) => { + const formData = new FormData(); + + formData.append('grant_type', 'authorization_code'); + formData.append('client_id', PUBLIC_ANILIST_CLIENT_ID); + formData.append('client_secret', ANILIST_CLIENT_SECRET); + formData.append('redirect_uri', PUBLIC_ANILIST_REDIRECT_URI); + formData.append('code', url.searchParams.get('code') || "null"); + cookies.set( + 'user', + JSON.stringify( + await ( + await fetch('https://anilist.co/api/v2/oauth/token', { + method: 'POST', + body: formData + }) + ).json() + ), + { + path: '/', + maxAge: 60 * 60 * 24 * 7, + httpOnly: true, + sameSite: 'strict', + secure: !dev + } + ); + + throw redirect(303, '/'); +}; diff --git a/src/routes/settings/+page.svelte b/src/routes/settings/+page.svelte new file mode 100644 index 00000000..cdd268f9 --- /dev/null +++ b/src/routes/settings/+page.svelte @@ -0,0 +1,67 @@ +<script lang="ts"> + import displayUnresolved from '../../stores/displayUnresolved'; + import closeAnimeByDefault from '../../stores/closeAnimeByDefault'; + import closeMangaByDefault from '../../stores/closeMangaByDefault'; + import { chapterDatabase } from '$lib/chapterDatabase'; + import cacheMangaMinutes from '../../stores/cacheMangaMinutes'; + + export let data; + + $: displayingUnresolved = $displayUnresolved === 'true'; + $: mangaClosed = $closeMangaByDefault === 'true'; + $: animeClosed = $closeAnimeByDefault === 'true'; + + const pruneUnresolved = async () => { + const unresolved = await chapterDatabase.chapters.where('chapters').equals(-1).toArray(); + + const ids = unresolved.map((m) => m.id); + + await chapterDatabase.chapters.bulkDelete(ids); + }; + + const pruneAll = async () => { + const all = await chapterDatabase.chapters.toArray(); + + const ids = all.map((m) => m.id); + + await chapterDatabase.chapters.bulkDelete(ids); + }; +</script> + +<a href="/">Home</a> + +<p /> + +{#if data.user === undefined} + not +{:else} + <ul> + <li> + <a + href="#" + on:click={() => + displayingUnresolved ? displayUnresolved.set('false') : displayUnresolved.set('true')} + >{displayingUnresolved ? 'Hide' : 'Show'} unresolved</a + > + </li> + <li><a href="#" on:click={pruneUnresolved}>Prune cached, unresolved manga</a></li> + <li><a href="#" on:click={pruneAll}>Prune <b>ALL</b> cached manga</a></li> + <li> + <a + href="#" + on:click={() => + animeClosed ? closeAnimeByDefault.set('false') : closeAnimeByDefault.set('true')} + >{animeClosed ? 'Close' : 'Expand'} anime by default</a + > + </li> + <li> + <a + href="#" + on:click={() => + mangaClosed ? closeMangaByDefault.set('false') : closeMangaByDefault.set('true')} + >{mangaClosed ? 'Close' : 'Expand'} manga by default</a + > + </li> + <li>Re-cache manga every <input type="number" bind:value={$cacheMangaMinutes} /> minutes</li> + </ul> +{/if} diff --git a/src/stores/cacheMangaMinutes.ts b/src/stores/cacheMangaMinutes.ts new file mode 100644 index 00000000..f4c714ad --- /dev/null +++ b/src/stores/cacheMangaMinutes.ts @@ -0,0 +1,14 @@ +import { browser } from '$app/environment'; +import { writable } from 'svelte/store'; + +const cacheMangaMinutes = writable<string>( + browser ? localStorage.getItem('cacheMangaMinutes') ?? '120' : '120' +); + +cacheMangaMinutes.subscribe((value) => { + if (browser) { + localStorage.setItem('cacheMangaMinutes', value); + } +}); + +export default cacheMangaMinutes; diff --git a/src/stores/closeAnimeByDefault.ts b/src/stores/closeAnimeByDefault.ts new file mode 100644 index 00000000..481fabfd --- /dev/null +++ b/src/stores/closeAnimeByDefault.ts @@ -0,0 +1,14 @@ +import { browser } from '$app/environment'; +import { writable } from 'svelte/store'; + +const closeAnimeByDefault = writable<string>( + browser ? localStorage.getItem('closeAnimeByDefault') ?? 'false' : 'false' +); + +closeAnimeByDefault.subscribe((value) => { + if (browser) { + localStorage.setItem('closeAnimeByDefault', value); + } +}); + +export default closeAnimeByDefault; diff --git a/src/stores/closeMangaByDefault.ts b/src/stores/closeMangaByDefault.ts new file mode 100644 index 00000000..b0b27537 --- /dev/null +++ b/src/stores/closeMangaByDefault.ts @@ -0,0 +1,14 @@ +import { browser } from '$app/environment'; +import { writable } from 'svelte/store'; + +const closeMangaByDefault = writable<string>( + browser ? localStorage.getItem('closeMangaByDefault') ?? 'false' : 'false' +); + +closeMangaByDefault.subscribe((value) => { + if (browser) { + localStorage.setItem('closeMangaByDefault', value); + } +}); + +export default closeMangaByDefault; diff --git a/src/stores/displayUnresolved.ts b/src/stores/displayUnresolved.ts new file mode 100644 index 00000000..9b67925f --- /dev/null +++ b/src/stores/displayUnresolved.ts @@ -0,0 +1,14 @@ +import { browser } from '$app/environment'; +import { writable } from 'svelte/store'; + +const displayUnresolved = writable<string>( + browser ? localStorage.getItem('displayUnresolved') ?? 'false' : 'false' +); + +displayUnresolved.subscribe((value) => { + if (browser) { + localStorage.setItem('displayUnresolved', value); + } +}); + +export default displayUnresolved; diff --git a/src/stores/lastPruneAt.ts b/src/stores/lastPruneAt.ts new file mode 100644 index 00000000..0720bc60 --- /dev/null +++ b/src/stores/lastPruneAt.ts @@ -0,0 +1,12 @@ +import { browser } from '$app/environment'; +import { writable } from 'svelte/store'; + +const lastPruneAt = writable<string>(browser ? localStorage.getItem('lastPruneAt') ?? '' : ''); + +lastPruneAt.subscribe((value) => { + if (browser) { + localStorage.setItem('lastPruneAt', value); + } +}); + +export default lastPruneAt; |