feat: add push notification support (#73)

* feat: add push notification support

* misc: set localstorage on start
This commit is contained in:
Xylight authored and GitHub committed 2023-08-06 13:00:35 -07:00
1 parent 4f898915b2
commit fc38560eda
6 files changed
+204 -24

No files matched your search

+73 -19
View File
@@ -2,6 +2,8 @@ import { amModOfAny } from '$lib/components/lemmy/moderation/moderation.js'
import { toast } from '$lib/components/ui/toasts/toasts.js'
import { DEFAULT_INSTANCE_URL, instance } from '$lib/instance.js'
import { getClient } from '$lib/lemmy.js'
import { getInbox, getInboxItemPublished } from '$lib/lemmy/inbox.js'
import { userSettings } from '$lib/settings.js'
import type { MyUserInfo } from 'lemmy-js-client'
import { get, writable } from 'svelte/store'
@@ -18,9 +20,9 @@ function getFromStorage<T>(key: string): T | undefined {
return JSON.parse(lc)
}
function setFromStorage(key: string, item: any) {
function setFromStorage(key: string, item: any, stringify: boolean = true) {
if (typeof localStorage == 'undefined') return
return localStorage.setItem(key, JSON.stringify(item))
return localStorage.setItem(key, stringify ? JSON.stringify(item) : item)
}
interface Profile {
@@ -192,32 +194,84 @@ export function setUserID(id: number) {
return prof
}
const getNotificationCount = async (jwt: string, mod: boolean) => {
const unreads = await getClient().getUnreadCount({
auth: jwt,
})
let reports: number = 0
if (mod) {
const reportRes = await getClient().getReportCount({
auth: jwt,
})
reports =
reportRes.comment_reports +
reportRes.post_reports +
(reportRes.private_message_reports ?? 0)
}
return {
unreads: unreads.mentions + unreads.private_messages + unreads.replies,
reports: reports,
}
}
// show unread dot
setInterval(async () => {
if (!get(profile)) return
const { user, jwt } = get(profile)!
if (!jwt || !user) return
const response = await getClient().getUnreadCount({
auth: jwt,
})
const notifs = await getNotificationCount(jwt, amModOfAny(user) ?? false)
user.unreads =
response.mentions + response.private_messages + response.replies
if (amModOfAny(user)) {
const reports = await getClient().getReportCount({
auth: jwt,
})
user.reports =
reports.comment_reports +
reports.post_reports +
(reports.private_message_reports ?? 0)
}
user.unreads = notifs.unreads
user.reports = notifs.reports
profile.update((p) => ({
...p!,
user: user,
}))
}, 30 * 1000)
}, get(userSettings).notifications.pollRate ?? 30 * 1000)
setFromStorage('seenUntil', Date.now().toString(), false)
export async function getInboxNotifications(dontUpdate: boolean = false) {
if (!get(profile) || !get(userSettings).notifications.enabled) return
const { jwt } = get(profile)!
if (!jwt) return
let until = Number(localStorage.getItem('seenUntil'))
if (Number.isNaN(until) || until == 0) {
const now = Date.now()
localStorage.setItem('seenUntil', now.toString())
until = now
}
const inbox = await getInbox(jwt, until)
inbox.forEach((item) => {
const notif = new Notification(
item.person.display_name ?? item.person.name,
{
body: item.body,
timestamp: item.created,
icon: item.person.avatar,
}
)
notif.onclick = (e) => {
window.open('/inbox')
}
})
if (dontUpdate) return
localStorage.setItem('seenUntil', Date.now().toString())
}
setInterval(async () => getInboxNotifications(), 30 * 1000)
+11 -1
View File
@@ -1,5 +1,8 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte'
export let enabled = false
const dispatcher = createEventDispatcher<{ change: boolean }>()
</script>
<label>
@@ -14,5 +17,12 @@
bg-white dark:bg-zinc-700 {enabled ? 'translate-x-4' : 'translate-x-0'}"
/>
</div>
<input type="checkbox" bind:checked={enabled} class="hidden" />
<input
type="checkbox"
bind:checked={enabled}
class="hidden"
on:input={(e) => {
dispatcher('change', !enabled)
}}
/>
</label>
+82
View File
@@ -1,6 +1,10 @@
import { getClient } from '$lib/lemmy.js'
import type { Result } from '$lib/lemmy/item.js'
import type {
CommentReplyView,
Person,
PersonMentionView,
PersonView,
PrivateMessageView,
} from 'lemmy-js-client'
@@ -38,3 +42,81 @@ export function isRead(
return false
}
export const getInbox = async (
jwt: string,
until?: number
): Promise<InboxItem[]> => {
const client = getClient()
const params = {
limit: 50,
auth: jwt,
unread_only: true,
}
const [replies, mentions, privateMessages] = await Promise.all([
client.getReplies({
...params,
sort: 'New',
}),
client.getPersonMentions({
...params,
sort: 'New',
}),
client.getPrivateMessages({ ...params }),
])
let items = [
...replies.replies,
...mentions.mentions,
...privateMessages.private_messages,
]
.map(toInboxItem)
.sort((a, b) => b.created - a.created)
if (until) {
items = items.filter((item) => item.created > until)
}
return items
}
const toInboxItem = (item: InboxItemView): InboxItem => {
let type: 'private_message' | 'comment_reply' | 'person_mention'
let body: string
let personView: Person
let created: number
if ('comment_reply' in item) {
type = 'comment_reply'
body = item.comment.content
personView = item.creator
created = Date.parse(`${item.comment_reply.published}Z`)
} else if ('person_mention' in item) {
type = 'person_mention'
body = item.comment.content
personView = item.creator
created = Date.parse(`${item.person_mention.published}Z`)
} else if ('private_message' in item) {
type = 'private_message'
body = item.private_message.content
personView = item.creator
created = Date.parse(`${item.private_message.published}Z`)
} else {
throw new Error('Invalid item')
}
return {
type: type,
body: body,
person: personView,
created,
}
}
interface InboxItem {
type: 'private_message' | 'comment_reply' | 'person_mention'
body: string
person: Person
created: number
}
+1 -1
View File
@@ -10,7 +10,7 @@ import type {
PrivateMessageView,
} from 'lemmy-js-client'
type Result =
export type Result =
| PostView
| CommentView
| PersonView
+14 -3
View File
@@ -18,11 +18,17 @@ interface Settings {
feed: 'All' | 'Subscribed' | 'Local'
}
hidePosts: {
deleted: boolean,
removed: boolean,
},
deleted: boolean
removed: boolean
}
fullWidthLayout: boolean
expandSidebar: boolean
notifications: {
enabled: boolean
pollRate: number
// how often to check in the background
notifRate: number
}
}
const defaultSettings: Settings = {
@@ -46,6 +52,11 @@ const defaultSettings: Settings = {
},
fullWidthLayout: false,
expandSidebar: true,
notifications: {
enabled: false,
pollRate: 60 * 1000,
notifRate: 10 * 60 * 1000,
},
}
export const userSettings = writable(defaultSettings)
+23
View File
@@ -4,6 +4,9 @@
import Setting from './Setting.svelte'
import MultiSelect from '$lib/components/input/MultiSelect.svelte'
import Sort from '$lib/components/lemmy/Sort.svelte'
import { toast } from '$lib/components/ui/toasts/toasts.js'
import Button from '$lib/components/input/Button.svelte'
import { getInboxNotifications } from '$lib/auth.js'
let data = {
loading: false,
@@ -91,4 +94,24 @@
</div>
</div>
</Setting>
<h2 class="uppercase font-bold opacity-80 text-sm mt-4">Notifications</h2>
<Setting>
<span slot="title">Push notifications</span>
<span slot="description">Get notified for new items in your inbox.</span>
<Switch
bind:enabled={$userSettings.notifications.enabled}
on:change={async (e) => {
if (e.detail == false) return
const res = await Notification.requestPermission()
if (res != 'granted') {
$userSettings.notifications.enabled = false
toast({
content: 'Notification permission denied',
type: 'error',
})
return
}
}}
/>
</Setting>
</div>