impr: isolate inbox handling code into separate service class

This commit is contained in:
Xylight authored and xylight committed 2025-11-04 17:56:37 -08:00
1 parent 72bb10b924
commit b8f69dda95
12 files changed
+201 -170

No files matched your search

+158 -128
View File
@@ -1,12 +1,10 @@
import { browser } from '$app/environment'
import { env } from '$env/dynamic/public'
import { DEFAULT_CLIENT_TYPE, type ClientType } from '$lib/api/base'
import { client, getClient, site } from '$lib/api/client.svelte'
import { client, site } from '$lib/api/client.svelte'
import type { Community, GetSiteResponse, MyUserInfo } from '$lib/api/types'
import { publishedToDate } from '$lib/ui/util/date'
import { toast } from 'mono-svelte'
import { writable } from 'svelte/store'
import { errorMessage } from './error'
import { t } from './i18n'
import { DEFAULT_INSTANCE_URL } from './instance.svelte'
import { instanceToURL, moveItem } from './util.svelte'
@@ -62,6 +60,9 @@ const getCookie = (key: string): string | undefined => {
}
class Profile {
private static readonly DONATION_CHECK_TIMEOUT = 3 * 1000
private static readonly DONATION_REMINDER_INTERVAL = 375 * 24 * 60 * 60 * 1000
meta = $state<ProfileData>(
getFromStorage<ProfileData>('profileData') ?? {
profiles: [
@@ -80,6 +81,7 @@ class Profile {
this.meta.profiles.find((i) => i.id == this.meta.profile) ??
this.getDefaultProfile(),
)
inbox: InboxService = $state(new InboxService(this))
getDefaultProfile(): ProfileInfo {
return {
@@ -90,41 +92,47 @@ class Profile {
}
constructor() {
// cookie migration code
this.initCookieMigrate()
this.donationPoll(Profile.DONATION_CHECK_TIMEOUT)
}
get current() {
return this.#current
}
set current(value) {
if (!value) return
const index = this.meta.profiles.findLastIndex((i) => i.id === value.id)
if (index != -1) this.meta.profiles[index] = value
}
private async initCookieMigrate() {
if (
env.PUBLIC_MIGRATE_COOKIE &&
this.meta.profiles.length == 0 &&
env.PUBLIC_INSTANCE_URL
) {
const jwt = getCookie('jwt')
if (jwt) {
;(async () => {
const result = await this.add(
jwt,
env.PUBLIC_INSTANCE_URL ?? '',
DEFAULT_CLIENT_TYPE,
)
!(
env.PUBLIC_MIGRATE_COOKIE &&
this.meta.profiles.length == 0 &&
env.PUBLIC_INSTANCE_URL
)
)
return
if (result)
toast({
content:
'Your instance migrated to Photon, and your account was transferred.',
type: 'success',
})
})()
}
}
setInterval(
() => {
if (profile.current.jwt)
this.checkInbox().then((res) => notifications.update(() => res))
},
4 * 60 * 1000,
const jwt = getCookie('jwt')
if (!jwt) return
const result = await this.add(
jwt,
env.PUBLIC_INSTANCE_URL ?? '',
DEFAULT_CLIENT_TYPE,
)
// hacky way to check donation status
setTimeout(() => {
if (result)
toast({
content:
'Your instance migrated frontends, and your account was transferred.',
type: 'success',
})
}
private donationPoll(delay: number) {
return setTimeout(() => {
if (
profile.current.user?.local_user_view.local_user
.last_donation_notification
@@ -133,7 +141,10 @@ class Profile {
profile.current.user?.local_user_view.local_user
.last_donation_notification,
)
if (Date.now() - donationDate.getTime() > 365 * 24 * 60 * 60 * 1000) {
if (
Date.now() - donationDate.getTime() >
Profile.DONATION_REMINDER_INTERVAL
) {
toast({
content: t.get('toast.lemmyDonate'),
duration: 3600 * 1000,
@@ -152,23 +163,13 @@ class Profile {
)
}
}
}, 3 * 1000)
}
get current() {
return this.#current
}
set current(value) {
if (!value) return
const index = this.meta.profiles.findIndex((i) => i.id == value?.id)
this.meta.profiles[index] = value
}, delay)
}
async fetchUserData() {
const startId = this.#current.id
if (this.#current.jwt) {
site.data = undefined
notifications.set({ applications: 0, inbox: 0, reports: 0 })
const res = await userFromJwt(this.#current.jwt, this.#current.instance)
if (!res?.user)
@@ -190,6 +191,7 @@ class Profile {
this.#current.avatar = res?.user?.local_user_view.person.avatar
this.#current.username = res?.user?.local_user_view.person.name
}
this.inbox.init()
} else {
if (browser) {
site.data = undefined
@@ -202,44 +204,31 @@ class Profile {
return this
}
async checkInbox() {
const { user, jwt } = profile.current
if (!user || !jwt) throw new Error('checkInbox() called with invalid user')
const notifs = await getNotificationCount(jwt, this.isMod(), this.isAdmin)
return {
inbox: notifs.unreads,
applications: notifs.applications,
reports: notifs.reports,
}
}
async add(jwt: string, instance: string, type: ClientType) {
const user = await userFromJwt(jwt, instance)
.then((u) => u)
.catch((err) => {
toast({ content: errorMessage(err as string), type: 'error' })
try {
const user = await userFromJwt(jwt, instance)
if (!user?.user) {
throw new Error('No user data received')
}
const id = Math.max(...this.meta.profiles.map((p) => p.id), 0) + 1
this.meta.profiles.unshift({
id,
instance,
jwt,
username: user.user.local_user_view.person.name,
avatar: user.user.local_user_view.person.avatar,
client: type,
})
if (!user?.user) {
this.meta.profile = id
return user
} catch (err) {
toast({
content: "Your instance's API did not return your user data.",
content: err as string,
type: 'error',
})
return null
}
const id = Math.max(...this.meta.profiles.map((p) => p.id)) + 1
this.meta.profile = id
this.meta.profiles.unshift({
id: id,
instance: instance,
jwt: jwt,
username: user?.user?.local_user_view.person.name,
avatar: user?.user?.local_user_view.person.avatar,
client: type,
})
return user
}
remove(id: number) {
@@ -263,7 +252,7 @@ class Profile {
}
}
isMod(community?: Community) {
isMod(community?: Community): boolean {
if (community)
return (
(this.#current.user?.moderates.some(
@@ -275,7 +264,7 @@ class Profile {
else return (this.#current.user?.moderates.length ?? 0) > 0
}
get isAdmin() {
get isAdmin(): boolean {
return (
site.data?.admins.some(
(i) => i.person.id == this.#current.user?.local_user_view.person.id,
@@ -283,6 +272,10 @@ class Profile {
)
}
get isDefaultProfile(): boolean {
return !this.#current.jwt && this.#current.instance == DEFAULT_INSTANCE_URL
}
mainEffect = $effect.root(() => {
// Sync with localStorage
$effect(() => {
@@ -301,22 +294,97 @@ class Profile {
})
$effect(() => {
this.fetchUserData().then(() => {
if (this.current.jwt)
this.checkInbox().then((res) => notifications.update(() => res))
})
this.fetchUserData()
})
})
}
class InboxService {
private readonly POLL_INTERVAL = 4 * 60 * 1000
#pollInterval: NodeJS.Timeout | null = null
#profile: Profile
notifications = $state<Notifications>({
applications: 0,
inbox: 0,
reports: 0,
})
constructor(profile: Profile) {
this.#profile = profile
}
async init(): Promise<void> {
this.cleanup()
this.notifications = await this.checkInbox()
this.#pollInterval = setInterval(async () => {
this.notifications = await this.checkInbox()
}, this.POLL_INTERVAL)
}
cleanup(): void {
if (this.#pollInterval) clearInterval(this.#pollInterval)
this.#pollInterval = null
}
clear(): Notifications {
this.notifications = {
applications: 0,
inbox: 0,
reports: 0,
}
return this.notifications
}
async checkInbox(): Promise<Notifications> {
if (!this.#profile.current.user || !this.#profile.current.jwt)
return this.clear()
const unreadsPromise = client()
.getUnreadCount()
.then((res) => res.mentions + res.private_messages + res.replies)
.catch(() => 0)
const reportsPromise = this.#profile.isMod()
? client()
.getReportCount({})
.then(
(res) =>
res.comment_reports +
res.post_reports +
(res.private_message_reports ?? 0),
)
.catch(() => 0)
: new Promise<number>((res) => res(0))
const applicationsPromise = this.#profile.isAdmin
? client()
.getUnreadRegistrationApplicationCount()
.then((res) => res.registration_applications)
.catch(() => 0)
: new Promise<number>((res) => res(0))
const [unreads, reports, applications] = await Promise.all([
unreadsPromise,
reportsPromise,
applicationsPromise,
])
return {
inbox: unreads,
reports: reports,
applications: applications,
}
}
}
export const profile = new Profile()
export const notifications = writable<Notifications>({
applications: 0,
inbox: 0,
reports: 0,
})
// this is all garbage legacy code, remove later
async function userFromJwt(
jwt: string,
instance: string,
@@ -358,41 +426,3 @@ function serializeUser(user: ProfileInfo): ProfileInfo {
user: undefined,
}
}
async function getNotificationCount(jwt: string, mod: boolean, admin: boolean) {
const unreadsPromise = getClient()
.getUnreadCount()
.then((res) => res.mentions + res.private_messages + res.replies)
.catch(() => 0)
const reportsPromise = mod
? getClient()
.getReportCount({})
.then(
(res) =>
res.comment_reports +
res.post_reports +
(res.private_message_reports ?? 0),
)
.catch(() => 0)
: new Promise<number>((res) => res(0))
const applicationsPromise = admin
? getClient()
.getUnreadRegistrationApplicationCount()
.then((res) => res.registration_applications)
.catch(() => 0)
: new Promise<number>((res) => res(0))
const [unreads, reports, applications] = await Promise.all([
unreadsPromise,
reportsPromise,
applicationsPromise,
])
return {
unreads: unreads,
reports: reports,
applications: applications,
}
}
+6 -2
View File
@@ -315,12 +315,16 @@
"loadComments": "Load comments"
},
"postRedirect": {
"title": "Mismatching server",
"description": "That link resolves to a post not on your account's server, {{homeInstance}}.",
"title": "Cross-server content",
"description": "That content does not originate from {{homeInstance}}. You can load it on your instance here.",
"actions": {
"back": "Go back",
"fetch": "Locate post on {{homeInstance}}",
"switch": "Switch to an account on {{destInstance}}"
},
"automatic": {
"title": "Locating post",
"description": "That content does not originate on your account's server."
}
},
"inbox": {
+1 -6
View File
@@ -23,17 +23,12 @@
none: '',
}
const alignments = {
default: '',
center: '',
}
interface Props {
class?: ClassValue
size?: keyof typeof sizes
color?: keyof typeof colors
margin?: keyof typeof margins
alignment?: keyof typeof alignments
alignment?: 'default' | 'center'
border?: boolean
children?: import('svelte').Snippet
action?: import('svelte').Snippet
+2 -2
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { site } from '$lib/api/client.svelte'
import { notifications, profile } from '$lib/app/auth.svelte'
import { profile } from '$lib/app/auth.svelte'
import { t } from '$lib/app/i18n'
import { LINKED_INSTANCE_URL } from '$lib/app/instance.svelte'
import { Menu, Spinner } from 'mono-svelte'
@@ -140,7 +140,7 @@
<Icon src={Bars3} micro size="18" />
</div>
{/if}
{#if Math.max(...Object.values($notifications)) > 0}
{#if Math.max(...Object.values(profile.inbox.notifications)) > 0}
<div
class="w-2 h-2 absolute top-0.5 right-0.5 bg-red-500 rounded-full"
></div>
+6 -5
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import { env } from '$env/dynamic/public'
import { site } from '$lib/api/client.svelte'
import { notifications, profile } from '$lib/app/auth.svelte'
import { profile } from '$lib/app/auth.svelte'
import { t } from '$lib/app/i18n'
import { settings } from '$lib/app/settings.svelte'
import { theme } from '$lib/app/theme/theme.svelte'
@@ -61,11 +61,12 @@
{/snippet}
{#if profile.current?.jwt}
{@const notifications = profile.inbox.notifications}
<MenuButton href="/inbox" icon={Inbox}>
{$t('profile.inbox')}
{#if $notifications.inbox > 0}
{#if notifications.inbox > 0}
<Badge color="red-subtle" class="text-xs ml-auto font-bold py-0.5!">
{$notifications.inbox > 99 ? '∞' : $notifications.inbox}
{notifications.inbox > 99 ? '∞' : notifications.inbox}
</Badge>
{/if}
</MenuButton>
@@ -73,7 +74,7 @@
<MenuButton href="/moderation" icon={ShieldCheck}>
{$t('routes.moderation.feed')}
{#snippet suffix()}
{@render notifBadge($notifications.reports)}
{@render notifBadge(notifications.reports)}
{/snippet}
</MenuButton>
{/if}
@@ -81,7 +82,7 @@
<MenuButton href="/admin/applications" icon={ServerStack}>
{$t('routes.admin.applications.title')}
{#snippet suffix()}
{@render notifBadge($notifications.applications)}
{@render notifBadge(notifications.applications)}
{/snippet}
</MenuButton>
{/if}
+4 -3
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { env } from '$env/dynamic/public'
import { notifications, profile } from '$lib/app/auth.svelte'
import { profile } from '$lib/app/auth.svelte'
import { t } from '$lib/app/i18n'
import { LINKED_INSTANCE_URL } from '$lib/app/instance.svelte'
import { settings } from '$lib/app/settings.svelte'
@@ -52,18 +52,19 @@
/>
<EndPlaceholder margin="sm" size="xs">{$t('profile.profile')}</EndPlaceholder>
{#if profile.current?.jwt}
{@const notifications = profile.inbox.notifications}
<SidebarButton
icon={UserCircle}
href="/profile"
label={$t('profile.profile')}
/>
<SidebarButton icon={Inbox} href="/inbox" label={$t('profile.inbox')}>
{#if $notifications.inbox}
{#if notifications.inbox}
<Badge
class="min-w-5 h-5 p-0! px-0.5 grid place-items-center ml-auto"
color="red-subtle"
>
{$notifications.inbox > 99 ? '∞' : $notifications.inbox}
{notifications.inbox > 99 ? '∞' : notifications.inbox}
</Badge>
{/if}
</SidebarButton>
+11 -8
View File
@@ -1,5 +1,5 @@
<script>
import { notifications } from '$lib/app/auth.svelte'
import { profile } from '$lib/app/auth.svelte'
import { t } from '$lib/app/i18n'
import { Tabs } from '$lib/ui/layout'
import { Badge } from 'mono-svelte'
@@ -7,13 +7,16 @@
let { children } = $props()
</script>
{#if $notifications.applications > 0}
<span class="flex flex-row text-red-500 gap-2">
<Badge color="red-subtle" class="w-max">
{$notifications.applications > 99 ? '∞' : $notifications.applications}
</Badge> unread applications
</span>
{/if}
<svelte:boundary>
{@const notifications = profile.inbox.notifications}
{#if notifications.applications > 0}
<span class="flex flex-row text-red-500 gap-2">
<Badge color="red-subtle" class="w-max">
{notifications.applications > 99 ? '∞' : notifications.applications}
</Badge> unread applications
</span>
{/if}
</svelte:boundary>
<Tabs
routes={[
@@ -4,7 +4,7 @@
ApproveRegistrationApplication,
RegistrationApplicationView,
} from '$lib/api/types'
import { notifications, profile } from '$lib/app/auth.svelte'
import { profile } from '$lib/app/auth.svelte'
import { errorMessage } from '$lib/app/error'
import { t } from '$lib/app/i18n'
import ApplicationDenyModal from '$lib/feature/moderation/ApplicationDenyModal.svelte'
@@ -69,7 +69,7 @@
application.admin = profile.current.user!.local_user_view.person
application.registration_application.deny_reason = denyReason
$notifications.applications -= 1
profile.inbox.notifications.applications -= 1
} catch (err) {
toast({
content: errorMessage(err as string),
+2 -2
View File
@@ -2,7 +2,7 @@
import { goto } from '$app/navigation'
import { page } from '$app/state'
import { getClient } from '$lib/api/client.svelte'
import { notifications, profile } from '$lib/app/auth.svelte'
import { profile } from '$lib/app/auth.svelte'
import { t } from '$lib/app/i18n'
import { searchParam } from '$lib/app/util.svelte'
import Fixate from '$lib/ui/generic/Fixate.svelte'
@@ -26,7 +26,7 @@
const response = await getClient().markAllAsRead()
$notifications.inbox = 0
profile.inbox.notifications.inbox = 0
goto(page.url, {
invalidateAll: true,
+2 -6
View File
@@ -1,5 +1,5 @@
import { getClient } from '$lib/api/client.svelte'
import { notifications, profile } from '$lib/app/auth.svelte'
import { profile } from '$lib/app/auth.svelte'
import { ReactiveState } from '$lib/app/util.svelte'
import {
generalizeCommentReply,
@@ -64,11 +64,7 @@ export async function load({ url, fetch }) {
? data.filter((i) => i.type != 'private_message' && !i.read).length
: 0
notifications.update((i) => ({
applications: i.applications,
reports: i.reports,
inbox: totalNotifs,
}))
profile.inbox.notifications.inbox = totalNotifs
return {
unreadOnly: new ReactiveState(unreadOnly),
+3 -2
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { getClient } from '$lib/api/client.svelte'
import { notifications, profile } from '$lib/app/auth.svelte'
import { profile } from '$lib/app/auth.svelte'
import { t } from '$lib/app/i18n'
import Markdown from '$lib/app/markdown/Markdown.svelte'
import { escapeHtml } from '$lib/app/util.svelte'
@@ -50,7 +50,8 @@
}
item.read = isRead
if (profile.current.user) $notifications.inbox += isRead ? -1 : 1
if (profile.current.user)
profile.inbox.notifications.inbox += isRead ? -1 : 1
loading = false
}
+4 -4
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { getClient } from '$lib/api/client.svelte'
import { notifications, profile } from '$lib/app/auth.svelte'
import { profile } from '$lib/app/auth.svelte'
import { errorMessage } from '$lib/app/error'
import { t } from '$lib/app/i18n'
import CommentItem from '$lib/feature/comment/CommentItem.svelte'
@@ -39,7 +39,7 @@
.then((res) => {
i.resolved = res.comment_report_view.comment_report.resolved
i.resolver = res.comment_report_view.resolver
$notifications.reports += i.resolved ? -1 : 1
profile.inbox.notifications.reports += i.resolved ? -1 : 1
}),
),
)
@@ -59,7 +59,7 @@
i.resolver = res.post_report_view.resolver
$notifications.reports += i.resolved ? -1 : 1
profile.inbox.notifications.reports += i.resolved ? -1 : 1
}),
),
)
@@ -80,7 +80,7 @@
i.resolver = res.private_message_report_view.resolver
$notifications.reports += i.resolved ? -1 : 1
profile.inbox.notifications.reports += i.resolved ? -1 : 1
}),
),
)