2023-01-14 23:58:52 +03:00
|
|
|
/// <reference lib="WebWorker" />
|
|
|
|
declare const self: ServiceWorkerGlobalScope
|
|
|
|
|
2023-08-02 13:28:18 +03:00
|
|
|
const clientResolves: { [key: string]: () => void } = {}
|
2023-01-14 23:58:52 +03:00
|
|
|
|
|
|
|
self.addEventListener('message', (event) => {
|
|
|
|
if (event.data.action !== 'ready-to-receive')
|
|
|
|
return
|
|
|
|
|
|
|
|
const id: string | undefined = (event.source as any)?.id ?? undefined
|
|
|
|
|
|
|
|
if (id && clientResolves[id] !== undefined)
|
|
|
|
clientResolves[id]()
|
|
|
|
})
|
|
|
|
|
2023-03-30 22:01:24 +03:00
|
|
|
export function onShareTarget(event: FetchEvent) {
|
2023-01-14 23:58:52 +03:00
|
|
|
if (!event.request.url.endsWith('/web-share-target') || event.request.method !== 'POST')
|
|
|
|
return
|
|
|
|
|
|
|
|
event.waitUntil(handleSharedTarget(event))
|
|
|
|
}
|
|
|
|
|
|
|
|
async function handleSharedTarget(event: FetchEvent) {
|
2023-01-25 18:32:52 +03:00
|
|
|
event.respondWith(Response.redirect('/home?share-target=true', 303))
|
2023-01-14 23:58:52 +03:00
|
|
|
await waitForClientToGetReady(event.resultingClientId)
|
|
|
|
|
|
|
|
const [client, formData] = await getClientAndFormData(event)
|
|
|
|
if (client === undefined)
|
|
|
|
return
|
|
|
|
|
|
|
|
await sendShareTargetMessage(client, formData)
|
|
|
|
}
|
|
|
|
|
|
|
|
async function sendShareTargetMessage(client: Client, data: FormData) {
|
2024-03-05 17:48:58 +03:00
|
|
|
const sharedData: {
|
|
|
|
textParts: string[]
|
|
|
|
files: File[]
|
|
|
|
} = {
|
2023-02-03 17:20:32 +03:00
|
|
|
textParts: [],
|
|
|
|
files: [],
|
|
|
|
}
|
|
|
|
|
|
|
|
// We collect the text data shared with us
|
|
|
|
const title = data.get('title')
|
|
|
|
if (title !== null)
|
|
|
|
sharedData.textParts.push(title.toString())
|
2023-01-14 23:58:52 +03:00
|
|
|
|
|
|
|
const text = data.get('text')
|
|
|
|
if (text !== null)
|
2023-02-03 17:20:32 +03:00
|
|
|
sharedData.textParts.push(text.toString())
|
2023-01-14 23:58:52 +03:00
|
|
|
|
2023-02-03 17:20:32 +03:00
|
|
|
const link = data.get('link')
|
|
|
|
if (link !== null)
|
|
|
|
sharedData.textParts.push(link.toString())
|
|
|
|
|
|
|
|
// We collect the files shared with us
|
2023-01-14 23:58:52 +03:00
|
|
|
for (const [name, file] of data.entries()) {
|
|
|
|
if (name === 'files' && file instanceof File)
|
2023-02-03 17:20:32 +03:00
|
|
|
sharedData.files.push(file)
|
2023-01-14 23:58:52 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
client.postMessage({ data: sharedData, action: 'compose-with-shared-data' })
|
|
|
|
}
|
|
|
|
|
|
|
|
function waitForClientToGetReady(clientId: string) {
|
|
|
|
return new Promise<void>((resolve) => {
|
|
|
|
clientResolves[clientId] = resolve
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
function getClientAndFormData(event: FetchEvent): Promise<[client: Client | undefined, formData: FormData]> {
|
|
|
|
return Promise.all([
|
|
|
|
self.clients.get(event.resultingClientId),
|
|
|
|
event.request.formData(),
|
|
|
|
])
|
|
|
|
}
|