diff --git a/package.json b/package.json index 128ceb26..59d8d0c5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "photon-lemmy", - "version": "0.4.17", + "version": "0.4.19", "private": true, "scripts": { "dev": "vite dev", diff --git a/src/lib/auth.ts b/src/lib/auth.ts new file mode 100644 index 00000000..f63b5270 --- /dev/null +++ b/src/lib/auth.ts @@ -0,0 +1,188 @@ +import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js' +import { DEFAULT_INSTANCE_URL, getClient, instance } from '$lib/lemmy.js' +import type { MyUserInfo } from 'lemmy-js-client' +import { get, writable } from 'svelte/store' + +function getFromStorage(key: string): T | undefined { + if (typeof localStorage == 'undefined') return undefined + const lc = localStorage.getItem(key) + if (!lc) return undefined + + return JSON.parse(lc) +} + +function setFromStorage(key: string, item: any) { + if (typeof localStorage == 'undefined') return + return localStorage.setItem(key, JSON.stringify(item)) +} + +interface Profile { + id: number + instance: string + jwt?: string + user?: PersonData + username?: string +} + +/** + * What gets stored in localstorage. + */ +interface ProfileData { + profiles: Profile[] + profile: number + defaultInstance?: string +} + +interface PersonData extends MyUserInfo { + unreads: number + reports: number +} + +export const profileData = writable( + getFromStorage('profileData') ?? { profiles: [], profile: -1 } +) + +let initialInstance = get(profileData).defaultInstance + +profileData.subscribe(async (pd) => { + setFromStorage('profileData', pd) + + if (pd.profile == -1 && pd.defaultInstance != initialInstance) { + initialInstance = get(profileData).defaultInstance ?? DEFAULT_INSTANCE_URL + instance.set(get(profileData).defaultInstance ?? DEFAULT_INSTANCE_URL) + } +}) + +export const profile = writable(getProfile()) + +profile.subscribe(async (p) => { + if (p?.id == -1) { + instance.set(get(profileData).defaultInstance ?? DEFAULT_INSTANCE_URL) + } + if (!p || !p.jwt) { + profileData.update((pd) => ({ ...pd, profile: -1 })) + return + } + if (p.user) return + + instance.set(p.instance) + // fetch the user because p.user is undefined + const user = await userFromJwt(p.jwt, p.instance) + + profile.update(() => ({ + ...p, + user: user, + })) +}) + +export async function setUser(jwt: string, instance: string, username: string) { + try { + new URL(`https://${instance}`) + } catch (err) { + return + } + + const user = await userFromJwt(jwt, instance) + if (!user) { + toast({ + content: 'Failed to fetch your user. Is your instance down?', + type: ToastType.error, + }) + } + + profileData.update((pd) => { + // too lazy to make a decent system + const id = Math.floor(Math.random() * 100000) + + const newProfile: Profile = { + id: id, + instance: instance, + jwt: jwt, + username: username, + } + + profile.set({ + ...newProfile, + user: user, + }) + + return { + profile: id, + profiles: [...pd.profiles, newProfile], + } + }) +} + +async function userFromJwt( + jwt: string, + instance: string +): Promise { + const myUser = (await getClient(instance).getSite({ auth: jwt })).my_user + if (!myUser) return undefined + + return { + unreads: 0, + reports: 0, + ...myUser, + } +} + +const userToPersonData = (user: MyUserInfo): PersonData => ({ + ...user, + unreads: 0, + reports: 0, +}) + +function getProfile() { + const id = get(profileData).profile + + if (id == -1) { + return + } + + const pd = get(profileData) + + return pd.profiles.find((p) => p.id == id) +} + +const getDefaultProfile = () => ({ + id: -1, + instance: get(instance), +}) + +export function resetProfile() { + profile.set(getDefaultProfile()) + profileData.update((p) => ({ ...p, profile: -1 })) +} + +export function deleteProfile(id: number) { + const pd = get(profileData) + + const index = pd.profiles.findIndex((p) => p.id == id) + if (index <= -1) return + + pd.profiles.splice(index, 1) + + profileData.update((p) => ({ + ...p, + profiles: pd.profiles, + })) + + if (id == get(profile)?.id) { + resetProfile() + } +} + +export function setUserID(id: number) { + const pd = get(profileData) + if (id == -1) { + resetProfile() + return + } + const prof = pd.profiles.find((p) => p.id == id) + + profile.set(prof ?? getDefaultProfile()) + profileData.update((p) => ({ ...p, profile: id })) + + return prof +} diff --git a/src/lib/components/lemmy/comment/Comment.svelte b/src/lib/components/lemmy/comment/Comment.svelte index 7b232e74..43a8ac85 100644 --- a/src/lib/components/lemmy/comment/Comment.svelte +++ b/src/lib/components/lemmy/comment/Comment.svelte @@ -11,16 +11,13 @@ import type { CommentNodeI } from './comments' import RelativeDate from '$lib/components/util/RelativeDate.svelte' import CommentForm from './CommentForm.svelte' - import { page } from '$app/stores' import UserLink from '$lib/components/lemmy/user/UserLink.svelte' import Markdown from '$lib/components/markdown/Markdown.svelte' import CommentActions from '$lib/components/lemmy/comment/CommentActions.svelte' - import { createEventDispatcher, getContext } from 'svelte' - import type { CommentView } from 'lemmy-js-client' import Modal from '$lib/components/ui/modal/Modal.svelte' - import { authData, getClient } from '$lib/lemmy.js' + import { getClient } from '$lib/lemmy.js' import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js' - import TextArea from '$lib/components/input/TextArea.svelte' + import { profile } from '$lib/auth.js' export let node: CommentNodeI export let postId: number @@ -39,11 +36,11 @@ bind:open={editing} action="Save" on:action={async () => { - if (!$authData || newComment.length <= 0) return + if (!$profile?.jwt || newComment.length <= 0) return try { await getClient().editComment({ - auth: $authData.token, + auth: $profile.jwt, comment_id: node.comment_view.comment.id, content: newComment, }) diff --git a/src/lib/components/lemmy/comment/CommentActions.svelte b/src/lib/components/lemmy/comment/CommentActions.svelte index c1869126..fd68a953 100644 --- a/src/lib/components/lemmy/comment/CommentActions.svelte +++ b/src/lib/components/lemmy/comment/CommentActions.svelte @@ -15,7 +15,7 @@ PencilSquare, Trash, } from 'svelte-hero-icons' - import { authData, getClient, user } from '$lib/lemmy.js' + import { getClient } from '$lib/lemmy.js' import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js' import Menu from '$lib/components/ui/menu/Menu.svelte' import MenuButton from '$lib/components/ui/menu/MenuButton.svelte' @@ -25,12 +25,13 @@ import { amMod, report } from '$lib/components/lemmy/moderation/moderation.js' import ModerationMenu from '$lib/components/lemmy/moderation/ModerationMenu.svelte' import CommentModerationMenu from '$lib/components/lemmy/moderation/CommentModerationMenu.svelte' + import { profile } from '$lib/auth.js' export let comment: CommentView export let replying: boolean = false async function save() { - if (!$authData) return + if (!$profile?.jwt) return const saved = comment.saved @@ -38,7 +39,7 @@ try { await getClient().saveComment({ - auth: $authData.token, + auth: $profile.jwt, comment_id: comment.comment.id, save: !saved, }) @@ -70,7 +71,7 @@ Reply - {#if $user && amMod($user, comment.community)} + {#if $profile?.user && amMod($profile?.user, comment.community)} {/if} Comment actions - {#if $authData?.token} - {#if comment.creator.id == $user?.local_user_view.person.id} + {#if $profile?.jwt} + {#if comment.creator.id == $profile.user?.local_user_view.person.id} dispatcher('edit', comment)}> Edit @@ -100,14 +101,14 @@ {comment.saved ? 'Unsave' : 'Save'} - {#if $user && $authData && isCommentMutable(comment, $user.local_user_view)} + {#if $profile?.user && $profile.jwt && isCommentMutable(comment, $profile.user.local_user_view)} { - if (!$authData) return + if (!$profile?.jwt) return try { await getClient().deleteComment({ - auth: $authData.token, + auth: $profile.jwt, comment_id: comment.comment.id, deleted: true, }) @@ -127,7 +128,7 @@ Delete {/if} - {#if $authData && $user?.local_user_view.person.id != comment.creator.id} + {#if $profile.jwt && $profile.user?.local_user_view.person.id != comment.creator.id} report(comment)} color="dangerSecondary"> Report diff --git a/src/lib/components/lemmy/comment/CommentForm.svelte b/src/lib/components/lemmy/comment/CommentForm.svelte index 4c034af7..4cae2c10 100644 --- a/src/lib/components/lemmy/comment/CommentForm.svelte +++ b/src/lib/components/lemmy/comment/CommentForm.svelte @@ -2,12 +2,13 @@ import Button from '$lib/components/input/Button.svelte' import { Color } from '$lib/ui/colors.js' import type { CommentResponse } from 'lemmy-js-client' - import { authData, getClient, user } from '$lib/lemmy.js' + import { getClient } from '$lib/lemmy.js' import { createEventDispatcher } from 'svelte' import { ToastType, addToast } from '$lib/components/ui/toasts/toasts.js' import TextArea from '$lib/components/input/TextArea.svelte' import MultiSelect from '$lib/components/input/MultiSelect.svelte' import Markdown from '$lib/components/markdown/Markdown.svelte' + import { profile } from '$lib/auth.js' export let postId: number export let parentId: number | undefined = undefined @@ -25,13 +26,13 @@ let preview = false async function submit() { - if (!$user || !$authData || value == '') return + if (!$profile?.user || !$profile?.jwt || value == '') return loading = true try { const response = await getClient().createComment({ - auth: $authData.token, + auth: $profile.jwt, content: value, post_id: postId, parent_id: parentId, diff --git a/src/lib/components/lemmy/comment/CommentVote.svelte b/src/lib/components/lemmy/comment/CommentVote.svelte index 509c3741..e454067c 100644 --- a/src/lib/components/lemmy/comment/CommentVote.svelte +++ b/src/lib/components/lemmy/comment/CommentVote.svelte @@ -1,15 +1,16 @@ @@ -53,7 +54,7 @@ {item.post.removed ? 'Restore' : 'Remove'} {/if} - {#if $user && $user.local_user_view.person.id != item.creator.id} + {#if $profile?.user && $profile.user?.local_user_view.person.id != item.creator.id} User diff --git a/src/lib/components/lemmy/moderation/ModerationMenu.svelte b/src/lib/components/lemmy/moderation/ModerationMenu.svelte index ff7c0746..461ea8ad 100644 --- a/src/lib/components/lemmy/moderation/ModerationMenu.svelte +++ b/src/lib/components/lemmy/moderation/ModerationMenu.svelte @@ -1,11 +1,6 @@ @@ -29,6 +32,7 @@ mini size="16" class="transition-transform {expanded ? '' : 'rotate-180'}" + title="Toggle expanded" /> + {#if $profileData.profiles.length >= 1} +
+ {#each $profileData.profiles as prof, index} + + {/each} + {/if}
- {#if $user} - {#each $user.follows + {#if $profile?.user} + {#each $profile.user.follows .map((f) => f.community) .sort((a, b) => a.title.localeCompare(b.title)) as follow} {/each} - {#if $user.follows.length == 0} + {#if $profile.user.follows.length == 0} +
+ { + loading = true + try { + const valid = await validateInstance(newInstance.trim()) + + if (!valid) { + throw new Error('invalid instance') + } + + toast({ + content: 'Changed guest instance.', + type: ToastType.success, + }) + } catch (err) { + toast({ + content: 'Failed to contact that instance URL. Is it down?', + type: ToastType.error, + }) + + loading = false + + return + } + + $profileData.defaultInstance = newInstance + if ($currentProfile && $currentProfile.id == -1) { + $instance = newInstance + } + loading = false + }} + placeholder="Instance URL" + bind:value={newInstance} + /> + +
+ + +{:else} +
+
+

Accounts

+ +
+ { + deleteProfile(id.detail) + }} + let:action + > + {#each $profileData.profiles as profile (profile.id)} +
+
+ {profile.username} + + {profile.instance} + +
+
+ + +
+ {/each} +
+ + Guest +
+ { + loading = true + try { + const valid = await validateInstance(newInstance.trim()) + + if (!valid) { + throw new Error('invalid instance') + } + + toast({ + content: 'Changed guest instance.', + type: ToastType.success, + }) + } catch (err) { + toast({ + content: 'Failed to contact that instance URL. Is it down?', + type: ToastType.error, + }) + } + + $profileData.defaultInstance = newInstance + if ($currentProfile && $currentProfile.id == -1) { + $instance = newInstance + } + loading = false + }} + placeholder="Instance URL" + bind:value={newInstance} + /> + +
+
+
+ + +
+ + +
+{/if} diff --git a/src/routes/c/[name]/+page.ts b/src/routes/c/[name]/+page.ts index a86275c5..6476c51d 100644 --- a/src/routes/c/[name]/+page.ts +++ b/src/routes/c/[name]/+page.ts @@ -1,4 +1,5 @@ -import { authData, getClient } from '$lib/lemmy.js' +import { profile } from '$lib/auth.js' +import { getClient } from '$lib/lemmy.js' import { userSettings } from '$lib/settings.js' import type { ListingType, SortType } from 'lemmy-js-client' import { get } from 'svelte/store' @@ -18,12 +19,12 @@ export async function load(req: any) { community_name: req.params.name, page: page, sort: sort, - auth: get(authData)?.token, + auth: get(profile)?.jwt, }), community: ( await getClient().getCommunity({ name: req.params.name, - auth: get(authData)?.token, + auth: get(profile)?.jwt, }) ).community_view, } diff --git a/src/routes/communities/+page.ts b/src/routes/communities/+page.ts index 5237fd36..2ac352fc 100644 --- a/src/routes/communities/+page.ts +++ b/src/routes/communities/+page.ts @@ -1,4 +1,5 @@ -import { authData, getClient } from '$lib/lemmy.js' +import { profile } from '$lib/auth.js' +import { getClient } from '$lib/lemmy.js' import type { ListingType } from 'lemmy-js-client' import { get } from 'svelte/store' @@ -15,7 +16,7 @@ export async function load({ url }) { type_: 'Communities', listing_type: type, q: query, - auth: get(authData)?.token, + auth: get(profile)?.jwt, }) } else { return await getClient().listCommunities({ @@ -23,7 +24,7 @@ export async function load({ url }) { page: page, sort: 'TopAll', type_: type, - auth: get(authData)?.token, + auth: get(profile)?.jwt, }) } } diff --git a/src/routes/communities/Subscribe.svelte b/src/routes/communities/Subscribe.svelte index 88da9a0e..b3d2015e 100644 --- a/src/routes/communities/Subscribe.svelte +++ b/src/routes/communities/Subscribe.svelte @@ -1,25 +1,21 @@ @@ -54,31 +26,6 @@

Settings

General

- {#if !LINKED_INSTANCE_URL} - - Instance - Changing this will log you out. -
- -
- -
-
-
- {/if} Default sort The default sort to use for feeds. diff --git a/src/routes/u/[name]/+page.svelte b/src/routes/u/[name]/+page.svelte index b36b2a27..2dcf854a 100644 --- a/src/routes/u/[name]/+page.svelte +++ b/src/routes/u/[name]/+page.svelte @@ -19,34 +19,37 @@ import { page } from '$app/stores' import { goto } from '$app/navigation' import { isComment } from '$lib/lemmy/item.js' - import { authData, getClient, user } from '$lib/lemmy.js' + import { getClient } from '$lib/lemmy.js' import { isBlocked } from '$lib/lemmy/user.js' import MultiSelect from '$lib/components/input/MultiSelect.svelte' import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js' import Modal from '$lib/components/ui/modal/Modal.svelte' import UserLink from '$lib/components/lemmy/user/UserLink.svelte' import TextArea from '$lib/components/input/TextArea.svelte' + import { profile } from '$lib/auth.js' export let data let blocking = false async function blockUser(block: number) { - if (!$user || !$authData) throw new Error('Unauthenticated') + if (!$profile?.user || !$profile?.jwt) throw new Error('Unauthenticated') blocking = true try { - const blocked = isBlocked($user, block) + const blocked = isBlocked($profile.user, block) await getClient().blockPerson({ - auth: $authData.token, + auth: $profile.jwt, block: !blocked, person_id: block, }) if (blocked) { - const index = $user.person_blocks.map((p) => p.target.id).indexOf(block) - $user.person_blocks.splice(index, 1) + const index = $profile.user.person_blocks + .map((p) => p.target.id) + .indexOf(block) + $profile.user.person_blocks.splice(index, 1) } toast({ @@ -71,13 +74,13 @@ let message = '' async function sendMessage() { - if (!$authData || message == '') return + if (!$profile?.jwt || message == '') return loadingMessage = true try { await getClient().createPrivateMessage({ - auth: $authData.token, + auth: $profile.jwt, content: message, recipient_id: data.person_view.person.id, }) @@ -103,7 +106,7 @@ {data.person_view.person.name} -{#if $authData} +{#if $profile?.user}

Message

@@ -198,7 +201,7 @@
- {#if $user && $authData && data.person_view.person.id != $user.local_user_view.person.id} + {#if $profile?.user && $profile.jwt && data.person_view.person.id != $profile.user.local_user_view.person.id}
{/if} diff --git a/src/routes/u/[name]/+page.ts b/src/routes/u/[name]/+page.ts index 85704201..5f897904 100644 --- a/src/routes/u/[name]/+page.ts +++ b/src/routes/u/[name]/+page.ts @@ -1,4 +1,5 @@ -import { authData, getClient } from '$lib/lemmy.js' +import { profile } from '$lib/auth.js' +import { getClient } from '$lib/lemmy.js' import { getItemPublished } from '$lib/lemmy/item.js' import type { SortType } from 'lemmy-js-client' import { get } from 'svelte/store' @@ -14,7 +15,7 @@ export async function load({ params, url }) { page: page, username: params.name, sort: sort, - auth: get(authData)?.token, + auth: get(profile)?.jwt, }) const items = [...user.posts, ...user.comments] diff --git a/src/service-worker.ts b/src/service-worker.ts index d6c18b06..47006c41 100644 --- a/src/service-worker.ts +++ b/src/service-worker.ts @@ -3,7 +3,7 @@ // @ts-ignore import { build, files } from '$service-worker' -const version = '0.4.17' +const version = '0.4.19' const timestamp = new Date().toLocaleString('en') const worker = self as unknown as ServiceWorkerGlobalScope const FILES = `cache${timestamp}`