From 172021d0d03096540dd5504f46b9721bb05def4b Mon Sep 17 00:00:00 2001 From: sethburkart123 Date: Tue, 12 Nov 2024 10:19:47 +1100 Subject: [PATCH] feat: background.ts loading and migration logic --- src/background.ts | 67 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/src/background.ts b/src/background.ts index e95640ce..f727dc2d 100644 --- a/src/background.ts +++ b/src/background.ts @@ -1,5 +1,20 @@ import browser from 'webextension-polyfill' import type { SettingsState } from "@/types/storage"; +import { blobToBase64 } from './seqta/utils/blobToBase64'; + +interface Data { + id: string; + blob: Blob; + type: 'image' | 'video'; +} + +interface DatabaseEventTarget extends EventTarget { + result: IDBDatabase; +} + +interface DatabaseEvent extends Event { + target: DatabaseEventTarget; +} export const openDB = () => { return new Promise((resolve, reject) => { @@ -269,11 +284,63 @@ async function UpdateCurrentValues() { } } +const getAllBackgrounds = async (): Promise => { + const db = await openDB() as IDBDatabase; + const tx = db.transaction('backgrounds', 'readonly'); + const store = tx.objectStore('backgrounds'); + const request = store.getAll(); + + return new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); +}; + +const sendBackgroundToTab = async (background: Data): Promise => { + const base64Data = await blobToBase64(background.blob); + + // Get the current active tab + const [tab] = await browser.tabs.query({ active: true, currentWindow: true }); + if (!tab?.id) return; + + // Send message to the tab + await browser.tabs.sendMessage(tab.id, { + type: 'MIGRATE_BACKGROUND', + payload: { + id: background.id, + data: base64Data, + mediaType: background.type + } + }); +}; + +const migrateBackgrounds = async (): Promise => { + try { + console.log('Starting background migration...'); + const backgrounds = await getAllBackgrounds(); + console.log(`Found ${backgrounds.length} backgrounds to migrate`); + + // Process backgrounds sequentially + for (const background of backgrounds) { + console.log(`Migrating background: ${background.id}`); + await sendBackgroundToTab(background); + console.log(`Successfully migrated background: ${background.id}`); + } + + console.log('Migration completed successfully'); + } catch (error) { + console.error('Migration failed:', error); + throw error; + } +}; + + browser.runtime.onInstalled.addListener(function (event) { browser.storage.local.remove(['justupdated']); browser.storage.local.remove(['data']); UpdateCurrentValues(); + migrateBackgrounds(); if ( event.reason == 'install', event.reason == 'update' ) { browser.storage.local.set({ justupdated: true }); }