Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Add comprehensive PWA features: install prompt, media session, badging, push notifications, and background sync

Murtaza Nasir4a83b6d9d9cf
diff --git a/static/img/screenshots/main-view.png b/static/img/screenshots/main-view.png
new file mode 100644
index 00000000..791418df
Binary files /dev/null and b/static/img/screenshots/main-view.png differ
diff --git a/static/img/screenshots/mobile-view.png b/static/img/screenshots/mobile-view.png
new file mode 100644
index 00000000..48a6438c
Binary files /dev/null and b/static/img/screenshots/mobile-view.png differ
diff --git a/static/img/screenshots/recording-interface.png b/static/img/screenshots/recording-interface.png
new file mode 100644
index 00000000..09bd9116
Binary files /dev/null and b/static/img/screenshots/recording-interface.png differ
diff --git a/static/img/screenshots/transcript-view.png b/static/img/screenshots/transcript-view.png
new file mode 100644
index 00000000..7454f3e2
Binary files /dev/null and b/static/img/screenshots/transcript-view.png differ
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index 93580201..24af9e7d 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -12,6 +12,7 @@ import { useTranscription } from './modules/composables/transcription.js';
import { useSpeakers } from './modules/composables/speakers.js';
import { useChat } from './modules/composables/chat.js';
import { useTags } from './modules/composables/tags.js';
+import { usePWA } from './modules/composables/pwa.js';
// Import utilities
import { showToast } from './modules/utils/toast.js';
@@ -174,6 +175,16 @@ document.addEventListener('DOMContentLoaded', async () => {
const recordingNotification = ref(null);
const isPageVisible = ref(true);
+ // --- PWA Features ---
+ const deferredInstallPrompt = ref(null);
+ const showInstallButton = ref(false);
+ const isPWAInstalled = ref(false);
+ const notificationPermission = ref('default');
+ const pushSubscription = ref(null);
+ const appBadgeCount = ref(0);
+ const currentMediaMetadata = ref(null);
+ const isMediaSessionActive = ref(false);
+
// --- Recording Size Monitoring ---
const estimatedFileSize = ref(0);
const fileSizeWarningShown = ref(false);
@@ -411,6 +422,11 @@ document.addEventListener('DOMContentLoaded', async () => {
estimatedFileSize, fileSizeWarningShown, recordingQuality, actualBitrate,
maxRecordingMB, sizeCheckInterval,
+ // PWA Features
+ deferredInstallPrompt, showInstallButton, isPWAInstalled,
+ notificationPermission, pushSubscription, appBadgeCount,
+ currentMediaMetadata, isMediaSessionActive,
+
// Modals
showEditModal, showDeleteModal, showEditTagsModal, selectedNewTagId, tagSearchFilter,
showReprocessModal, showResetModal, showSpeakerModal, showShareModal, showSharesListModal,
@@ -920,6 +936,7 @@ document.addEventListener('DOMContentLoaded', async () => {
const sharingComposable = useSharing(state, utils);
const transcriptionComposable = useTranscription(state, utils);
const chatComposable = useChat(state, utils);
+ const pwaComposable = usePWA(state, utils);
const tagsComposable = useTags({
recordings,
availableTags,
@@ -1261,6 +1278,9 @@ document.addEventListener('DOMContentLoaded', async () => {
// Initialize audio capabilities
await audioComposable.initializeAudio();
+ // Initialize PWA features
+ pwaComposable.initPWA();
+
// Show app - hide loader and show main content
const loader = document.getElementById('loader');
const appEl = document.getElementById('app');
@@ -1289,6 +1309,17 @@ document.addEventListener('DOMContentLoaded', async () => {
document.addEventListener('visibilitychange', audioComposable.handleVisibilityChange);
});
+ // =========================================================================
+ // WATCHERS
+ // =========================================================================
+
+ // Update badge count when recordings change
+ watch(recordings, (newRecordings) => {
+ if (newRecordings && Array.isArray(newRecordings)) {
+ pwaComposable.updateBadgeCount(newRecordings);
+ }
+ });
+
// =========================================================================
// RETURN ALL STATE AND METHODS
// =========================================================================
@@ -1346,7 +1377,8 @@ document.addEventListener('DOMContentLoaded', async () => {
...transcriptionComposable,
...speakersComposable,
...chatComposable,
- ...tagsComposable
+ ...tagsComposable,
+ ...pwaComposable
};
},
delimiters: ['${', '}']
diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.js
index d25557dc..46095499 100644
--- a/static/js/modules/composables/audio.js
+++ b/static/js/modules/composables/audio.js
@@ -23,10 +23,27 @@ export function useAudio(state, utils) {
try {
if ('wakeLock' in navigator) {
wakeLock.value = await navigator.wakeLock.request('screen');
- console.log('[WakeLock] Acquired');
+ console.log('[WakeLock] Acquired - screen will stay awake during recording');
+
+ // Listen for wake lock release
+ wakeLock.value.addEventListener('release', () => {
+ console.log('[WakeLock] Released');
+ });
+
+ return true;
+ } else {
+ console.warn('[WakeLock] Wake Lock API not supported');
+ showToast('Screen may sleep during recording', 'info');
+ return false;
}
} catch (err) {
console.warn('[WakeLock] Could not acquire:', err.message);
+ if (err.name === 'NotAllowedError') {
+ showToast('Screen lock permission denied', 'warning');
+ } else if (err.name === 'NotSupportedError') {
+ showToast('Wake lock not supported on this device', 'info');
+ }
+ return false;
}
};
@@ -83,7 +100,12 @@ export function useAudio(state, utils) {
const handleVisibilityChange = async () => {
if (document.visibilityState === 'visible' && isRecording.value) {
console.log('[Visibility] Page visible, re-acquiring wake lock');
- await acquireWakeLock();
+ const acquired = await acquireWakeLock();
+ if (acquired) {
+ showToast('Recording resumed - screen will stay awake', 'success');
+ }
+ } else if (document.visibilityState === 'hidden' && isRecording.value) {
+ console.log('[Visibility] Page hidden, wake lock may be released by browser');
}
};
diff --git a/static/js/modules/composables/index.js b/static/js/modules/composables/index.js
index c7249ff5..5c0d970d 100644
--- a/static/js/modules/composables/index.js
+++ b/static/js/modules/composables/index.js
@@ -12,6 +12,7 @@
* - sharing: Public/internal sharing
* - modals: Modal dialog management
* - chat: AI chat functionality
+ * - pwa: PWA features (install prompt, notifications, badging, media session)
*/
export { useRecordings } from './recordings.js';
@@ -24,3 +25,4 @@ export { useReprocess } from './reprocess.js';
export { useTranscription } from './transcription.js';
export { useSpeakers } from './speakers.js';
export { useChat } from './chat.js';
+export { usePWA } from './pwa.js';
diff --git a/static/js/modules/composables/pwa.js b/static/js/modules/composables/pwa.js
new file mode 100644
index 00000000..bec82be4
--- /dev/null
+++ b/static/js/modules/composables/pwa.js
@@ -0,0 +1,413 @@
+/**
+ * PWA Features Composable
+ * Handles install prompt, push notifications, badging, and other PWA APIs
+ */
+
+export function usePWA(state, utils) {
+ const {
+ deferredInstallPrompt,
+ showInstallButton,
+ isPWAInstalled,
+ notificationPermission,
+ pushSubscription,
+ appBadgeCount
+ } = state;
+
+ const { showToast } = utils;
+
+ // --- Install Prompt ---
+
+ /**
+ * Handle beforeinstallprompt event
+ * This event is fired when the browser detects the app can be installed
+ */
+ const handleBeforeInstallPrompt = (e) => {
+ console.log('[PWA] beforeinstallprompt event fired');
+ // Prevent the mini-infobar from appearing on mobile
+ e.preventDefault();
+ // Stash the event so it can be triggered later
+ deferredInstallPrompt.value = e;
+ // Show our custom install button
+ showInstallButton.value = true;
+ };
+
+ /**
+ * Prompt user to install the PWA
+ */
+ const promptInstall = async () => {
+ if (!deferredInstallPrompt.value) {
+ console.log('[PWA] No deferred install prompt available');
+ return;
+ }
+
+ // Show the install prompt
+ deferredInstallPrompt.value.prompt();
+
+ // Wait for the user's response
+ const { outcome } = await deferredInstallPrompt.value.userChoice;
+ console.log(`[PWA] User response to install prompt: ${outcome}`);
+
+ if (outcome === 'accepted') {
+ showToast('Installing Speakr...', 'success');
+ }
+
+ // Clear the deferred prompt since it can only be used once
+ deferredInstallPrompt.value = null;
+ showInstallButton.value = false;
+ };
+
+ /**
+ * Check if app is already installed
+ */
+ const checkIfInstalled = () => {
+ // Check if running in standalone mode (installed PWA)
+ if (window.matchMedia('(display-mode: standalone)').matches ||
+ window.navigator.standalone === true) {
+ isPWAInstalled.value = true;
+ showInstallButton.value = false;
+ console.log('[PWA] App is installed and running in standalone mode');
+ }
+ };
+
+ /**
+ * Handle appinstalled event
+ */
+ const handleAppInstalled = () => {
+ console.log('[PWA] App was installed');
+ isPWAInstalled.value = true;
+ showInstallButton.value = false;
+ showToast('Speakr installed successfully!', 'success');
+ };
+
+ // --- Push Notifications ---
+
+ /**
+ * Request notification permission
+ */
+ const requestNotificationPermission = async () => {
+ if (!('Notification' in window)) {
+ console.warn('[PWA] This browser does not support notifications');
+ return false;
+ }
+
+ try {
+ const permission = await Notification.requestPermission();
+ notificationPermission.value = permission;
+ console.log(`[PWA] Notification permission: ${permission}`);
+
+ if (permission === 'granted') {
+ showToast('Notifications enabled', 'success');
+ return true;
+ } else if (permission === 'denied') {
+ showToast('Notification permission denied', 'error');
+ return false;
+ }
+ } catch (error) {
+ console.error('[PWA] Error requesting notification permission:', error);
+ return false;
+ }
+ };
+
+ /**
+ * Subscribe to push notifications
+ */
+ const subscribeToPushNotifications = async () => {
+ if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
+ console.warn('[PWA] Push notifications not supported');
+ return null;
+ }
+
+ try {
+ const registration = await navigator.serviceWorker.ready;
+
+ // Check if already subscribed
+ let subscription = await registration.pushManager.getSubscription();
+
+ if (!subscription) {
+ // Subscribe to push notifications
+ // Note: You'll need to generate VAPID keys and add them here
+ // For now, we'll just set up the structure
+ console.log('[PWA] Push notification subscription would be created here');
+ // subscription = await registration.pushManager.subscribe({
+ // userVisibleOnly: true,
+ // applicationServerKey: urlBase64ToUint8Array(vapidPublicKey)
+ // });
+ }
+
+ pushSubscription.value = subscription;
+ return subscription;
+ } catch (error) {
+ console.error('[PWA] Failed to subscribe to push notifications:', error);
+ return null;
+ }
+ };
+
+ /**
+ * Show a local notification
+ */
+ const showNotification = async (title, options = {}) => {
+ if (!('Notification' in window)) {
+ console.warn('[PWA] Notifications not supported');
+ return;
+ }
+
+ if (Notification.permission !== 'granted') {
+ const granted = await requestNotificationPermission();
+ if (!granted) return;
+ }
+
+ try {
+ const registration = await navigator.serviceWorker.ready;
+
+ const defaultOptions = {
+ icon: '/static/img/icon-192x192.png',
+ badge: '/static/img/icon-192x192.png',
+ vibrate: [200, 100, 200],
+ tag: 'speakr-notification',
+ renotify: true,
+ ...options
+ };
+
+ await registration.showNotification(title, defaultOptions);
+ } catch (error) {
+ console.error('[PWA] Error showing notification:', error);
+ }
+ };
+
+ // --- Badging API ---
+
+ /**
+ * Set app badge count
+ */
+ const setAppBadge = async (count) => {
+ if (!('setAppBadge' in navigator)) {
+ console.log('[PWA] Badging API not supported');
+ return;
+ }
+
+ try {
+ if (count > 0) {
+ await navigator.setAppBadge(count);
+ appBadgeCount.value = count;
+ console.log(`[PWA] App badge set to ${count}`);
+ } else {
+ await navigator.clearAppBadge();
+ appBadgeCount.value = 0;
+ console.log('[PWA] App badge cleared');
+ }
+ } catch (error) {
+ console.error('[PWA] Error setting app badge:', error);
+ }
+ };
+
+ /**
+ * Clear app badge
+ */
+ const clearAppBadge = async () => {
+ await setAppBadge(0);
+ };
+
+ /**
+ * Update badge with unread count
+ */
+ const updateBadgeCount = async (audioFiles) => {
+ if (!audioFiles || !Array.isArray(audioFiles)) return;
+
+ // Count unread recordings (those still in inbox)
+ const unreadCount = audioFiles.filter(file => file.in_inbox).length;
+ await setAppBadge(unreadCount);
+ };
+
+ // --- Media Session API ---
+
+ /**
+ * Set up Media Session for audio playback control
+ * @param {Object} metadata - Track metadata { title, artist, album, artwork }
+ * @param {Object} handlers - Action handlers { play, pause, seekbackward, seekforward, previoustrack, nexttrack }
+ */
+ const setupMediaSession = (metadata, handlers = {}) => {
+ if (!('mediaSession' in navigator)) {
+ console.log('[PWA] Media Session API not supported');
+ return false;
+ }
+
+ try {
+ // Set metadata
+ if (metadata) {
+ navigator.mediaSession.metadata = new MediaMetadata({
+ title: metadata.title || 'Untitled Recording',
+ artist: metadata.artist || 'Speakr',
+ album: metadata.album || 'Recordings',
+ artwork: metadata.artwork || [
+ { src: '/static/img/icon-192x192.png', sizes: '192x192', type: 'image/png' },
+ { src: '/static/img/icon-512x512.png', sizes: '512x512', type: 'image/png' }
+ ]
+ });
+ currentMediaMetadata.value = metadata;
+ }
+
+ // Set action handlers
+ const actions = ['play', 'pause', 'seekbackward', 'seekforward', 'previoustrack', 'nexttrack', 'stop'];
+
+ actions.forEach(action => {
+ if (handlers[action]) {
+ try {
+ navigator.mediaSession.setActionHandler(action, handlers[action]);
+ } catch (error) {
+ console.warn(`[PWA] The ${action} action is not supported`);
+ }
+ }
+ });
+
+ // Set position state if provided
+ if (handlers.setPositionState) {
+ try {
+ navigator.mediaSession.setPositionState(handlers.setPositionState);
+ } catch (error) {
+ console.warn('[PWA] setPositionState not supported:', error);
+ }
+ }
+
+ isMediaSessionActive.value = true;
+ console.log('[PWA] Media Session configured successfully');
+ return true;
+ } catch (error) {
+ console.error('[PWA] Error setting up Media Session:', error);
+ return false;
+ }
+ };
+
+ /**
+ * Update Media Session position state
+ * @param {Object} state - { duration, playbackRate, position }
+ */
+ const updateMediaSessionPosition = (state) => {
+ if (!('mediaSession' in navigator) || !isMediaSessionActive.value) return;
+
+ try {
+ navigator.mediaSession.setPositionState({
+ duration: state.duration || 0,
+ playbackRate: state.playbackRate || 1.0,
+ position: state.position || 0
+ });
+ } catch (error) {
+ console.warn('[PWA] Error updating position state:', error);
+ }
+ };
+
+ /**
+ * Update Media Session playback state
+ * @param {string} state - 'playing' | 'paused' | 'none'
+ */
+ const updateMediaSessionPlaybackState = (state) => {
+ if (!('mediaSession' in navigator) || !isMediaSessionActive.value) return;
+
+ try {
+ navigator.mediaSession.playbackState = state;
+ } catch (error) {
+ console.warn('[PWA] Error updating playback state:', error);
+ }
+ };
+
+ /**
+ * Clear Media Session
+ */
+ const clearMediaSession = () => {
+ if (!('mediaSession' in navigator)) return;
+
+ try {
+ navigator.mediaSession.metadata = null;
+ const actions = ['play', 'pause', 'seekbackward', 'seekforward', 'previoustrack', 'nexttrack', 'stop'];
+ actions.forEach(action => {
+ try {
+ navigator.mediaSession.setActionHandler(action, null);
+ } catch (e) { /* ignore */ }
+ });
+ isMediaSessionActive.value = false;
+ currentMediaMetadata.value = null;
+ console.log('[PWA] Media Session cleared');
+ } catch (error) {
+ console.error('[PWA] Error clearing Media Session:', error);
+ }
+ };
+
+ // --- Background Sync ---
+
+ /**
+ * Register background sync for upload retry
+ */
+ const registerBackgroundSync = async (tag = 'sync-uploads') => {
+ if (!('serviceWorker' in navigator) || !('sync' in ServiceWorkerRegistration.prototype)) {
+ console.log('[PWA] Background sync not supported');
+ return false;
+ }
+
+ try {
+ const registration = await navigator.serviceWorker.ready;
+ await registration.sync.register(tag);
+ console.log(`[PWA] Background sync registered: ${tag}`);
+ return true;
+ } catch (error) {
+ console.error('[PWA] Failed to register background sync:', error);
+ return false;
+ }
+ };
+
+ /**
+ * Initialize PWA features
+ */
+ const initPWA = () => {
+ // Check if already installed
+ checkIfInstalled();
+
+ // Listen for beforeinstallprompt event
+ window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
+
+ // Listen for appinstalled event
+ window.addEventListener('appinstalled', handleAppInstalled);
+
+ // Check notification permission status
+ if ('Notification' in window) {
+ notificationPermission.value = Notification.permission;
+ }
+
+ console.log('[PWA] PWA features initialized');
+ };
+
+ /**
+ * Cleanup PWA event listeners
+ */
+ const cleanupPWA = () => {
+ window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
+ window.removeEventListener('appinstalled', handleAppInstalled);
+ };
+
+ return {
+ // Install prompt
+ promptInstall,
+ checkIfInstalled,
+
+ // Notifications
+ requestNotificationPermission,
+ subscribeToPushNotifications,
+ showNotification,
+
+ // Badging
+ setAppBadge,
+ clearAppBadge,
+ updateBadgeCount,
+
+ // Media Session
+ setupMediaSession,
+ updateMediaSessionPosition,
+ updateMediaSessionPlaybackState,
+ clearMediaSession,
+
+ // Background sync
+ registerBackgroundSync,
+
+ // Initialization
+ initPWA,
+ cleanupPWA
+ };
+}
diff --git a/static/js/modules/state/pwa.js b/static/js/modules/state/pwa.js
new file mode 100644
index 00000000..a8bfcb83
--- /dev/null
+++ b/static/js/modules/state/pwa.js
@@ -0,0 +1,39 @@
+/**
+ * PWA state management
+ */
+
+export function createPWAState(ref) {
+ // --- Install Prompt ---
+ const deferredInstallPrompt = ref(null);
+ const showInstallButton = ref(false);
+ const isPWAInstalled = ref(false);
+
+ // --- Notifications ---
+ const notificationPermission = ref('default');
+ const pushSubscription = ref(null);
+
+ // --- Badging ---
+ const appBadgeCount = ref(0);
+
+ // --- Media Session ---
+ const currentMediaMetadata = ref(null);
+ const isMediaSessionActive = ref(false);
+
+ return {
+ // Install prompt
+ deferredInstallPrompt,
+ showInstallButton,
+ isPWAInstalled,
+
+ // Notifications
+ notificationPermission,
+ pushSubscription,
+
+ // Badging
+ appBadgeCount,
+
+ // Media session
+ currentMediaMetadata,
+ isMediaSessionActive
+ };
+}
diff --git a/static/manifest.json b/static/manifest.json
index 673eaeb3..2b527d77 100644
--- a/static/manifest.json
+++ b/static/manifest.json
@@ -22,8 +22,8 @@
"purpose": "any"
},
{
- "src": "/static/img/icon-192x192.png",
- "sizes": "192x192",
+ "src": "/static/img/icon-maskable-512x512.png",
+ "sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
},
@@ -33,12 +33,6 @@
"type": "image/png",
"purpose": "any"
},
- {
- "src": "/static/img/icon-512x512.png",
- "sizes": "512x512",
- "type": "image/png",
- "purpose": "maskable"
- },
{
"src": "/static/img/icon-180x180.png",
"sizes": "180x180",
@@ -46,6 +40,36 @@
"purpose": "any"
}
],
+ "screenshots": [
+ {
+ "src": "/static/img/screenshots/main-view.png",
+ "sizes": "1920x1080",
+ "type": "image/png",
+ "form_factor": "wide",
+ "label": "Main recording gallery view"
+ },
+ {
+ "src": "/static/img/screenshots/recording-interface.png",
+ "sizes": "1920x1080",
+ "type": "image/png",
+ "form_factor": "wide",
+ "label": "Live recording interface with notes"
+ },
+ {
+ "src": "/static/img/screenshots/transcript-view.png",
+ "sizes": "1920x1080",
+ "type": "image/png",
+ "form_factor": "wide",
+ "label": "Transcript view with speaker identification"
+ },
+ {
+ "src": "/static/img/screenshots/mobile-view.png",
+ "sizes": "390x844",
+ "type": "image/png",
+ "form_factor": "narrow",
+ "label": "Mobile recording view"
+ }
+ ],
"shortcuts": [
{
"name": "New Recording",
@@ -80,5 +104,19 @@
},
"edge_side_panel": {
"preferred_width": 480
- }
+ },
+ "file_handlers": [
+ {
+ "action": "/",
+ "accept": {
+ "audio/*": [".mp3", ".wav", ".m4a", ".ogg", ".webm", ".flac", ".aac", ".wma", ".opus"]
+ }
+ }
+ ],
+ "protocol_handlers": [
+ {
+ "protocol": "web+speakr",
+ "url": "/?audio=%s"
+ }
+ ]
}
diff --git a/static/service-worker.js b/static/service-worker.js
deleted file mode 100644
index 3a5845d0..00000000
--- a/static/service-worker.js
+++ /dev/null
@@ -1,158 +0,0 @@
-// Speakr Service Worker
-// Provides offline support and background capabilities for recording
-
-const CACHE_VERSION = 'speakr-v2';
-const CACHE_STATIC = `${CACHE_VERSION}-static`;
-const CACHE_DYNAMIC = `${CACHE_VERSION}-dynamic`;
-
-// Files to cache for offline functionality
-const STATIC_ASSETS = [
- '/',
- '/static/css/styles.css',
- '/static/js/app.modular.js',
- '/static/manifest.json',
- '/static/offline.html',
- '/static/img/icon-192x192.png',
- '/static/img/icon-512x512.png'
-];
-
-// Install event - cache static assets
-self.addEventListener('install', (event) => {
- console.log('[Service Worker] Installing...');
- event.waitUntil(
- caches.open(CACHE_STATIC)
- .then((cache) => {
- console.log('[Service Worker] Caching static assets');
- return cache.addAll(STATIC_ASSETS.map(url => new Request(url, { credentials: 'same-origin' })));
- })
- .catch((error) => {
- console.error('[Service Worker] Failed to cache static assets:', error);
- })
- );
- // Force the waiting service worker to become the active service worker
- self.skipWaiting();
-});
-
-// Activate event - clean up old caches
-self.addEventListener('activate', (event) => {
- console.log('[Service Worker] Activating...');
- event.waitUntil(
- caches.keys().then((cacheNames) => {
- return Promise.all(
- cacheNames.map((cacheName) => {
- if (cacheName.startsWith('speakr-') &&
- cacheName !== CACHE_STATIC &&
- cacheName !== CACHE_DYNAMIC) {
- console.log('[Service Worker] Deleting old cache:', cacheName);
- return caches.delete(cacheName);
- }
- })
- );
- })
- );
- // Ensure the service worker takes control of all clients immediately
- return self.clients.claim();
-});
-
-// Fetch event - serve from cache when offline, otherwise fetch from network
-self.addEventListener('fetch', (event) => {
- const { request } = event;
- const url = new URL(request.url);
-
- // Skip caching for:
- // - API calls
- // - File uploads
- // - WebSocket connections
- // - Chrome extensions
- if (request.method !== 'GET' ||
- url.pathname.startsWith('/api/') ||
- url.pathname.startsWith('/upload') ||
- url.pathname.startsWith('/transcribe') ||
- url.protocol === 'chrome-extension:') {
- return;
- }
-
- event.respondWith(
- caches.match(request)
- .then((cachedResponse) => {
- if (cachedResponse) {
- // Return cached version
- return cachedResponse;
- }
-
- // Fetch from network and cache dynamically
- return fetch(request).then((response) => {
- // Only cache successful responses
- if (!response || response.status !== 200 || response.type === 'error') {
- return response;
- }
-
- // Clone the response (can only use once)
- const responseToCache = response.clone();
-
- caches.open(CACHE_DYNAMIC).then((cache) => {
- cache.put(request, responseToCache);
- });
-
- return response;
- }).catch(() => {
- // If network fails and not cached, show offline page
- if (request.mode === 'navigate') {
- return caches.match('/static/offline.html');
- }
- });
- })
- );
-});
-
-// Message event - handle messages from the client
-self.addEventListener('message', (event) => {
- console.log('[Service Worker] Received message:', event.data);
-
- if (event.data && event.data.type === 'SKIP_WAITING') {
- self.skipWaiting();
- }
-
- // Handle recording state updates
- if (event.data && event.data.type === 'RECORDING_STATE') {
- if (event.data.isRecording) {
- console.log('[Service Worker] Recording started, maintaining background state');
- } else {
- console.log('[Service Worker] Recording stopped');
- }
- }
-});
-
-// Background sync for failed uploads (future enhancement)
-self.addEventListener('sync', (event) => {
- if (event.tag === 'sync-uploads') {
- console.log('[Service Worker] Background sync triggered');
- // Future: Handle failed upload retry
- }
-});
-
-// Notification click handler
-self.addEventListener('notificationclick', (event) => {
- console.log('[Service Worker] Notification clicked');
- event.notification.close();
-
- // Focus or open the app
- event.waitUntil(
- clients.matchAll({ type: 'window', includeUncontrolled: true })
- .then((clientList) => {
- // If app is already open, focus it
- for (let i = 0; i < clientList.length; i++) {
- const client = clientList[i];
- if (client.url.includes('/') && 'focus' in client) {
- return client.focus();
- }
- }
- // Otherwise, open a new window
- if (clients.openWindow) {
- return clients.openWindow('/');
- }
- })
- );
-});
-
-console.log('[Service Worker] Script loaded');
diff --git a/static/sw.js b/static/sw.js
index 7a6e5b7f..68688e57 100644
--- a/static/sw.js
+++ b/static/sw.js
@@ -261,3 +261,99 @@ self.addEventListener('message', (event) => {
self.skipWaiting();
}
});
+
+// Background sync for failed uploads
+self.addEventListener('sync', (event) => {
+ console.log('[Service Worker] Background sync triggered:', event.tag);
+
+ if (event.tag === 'sync-uploads') {
+ event.waitUntil(syncFailedUploads());
+ }
+});
+
+// Sync failed uploads from IndexedDB
+async function syncFailedUploads() {
+ console.log('[Service Worker] Syncing failed uploads');
+
+ try {
+ // Notify that sync is checking for failed uploads
+ await self.registration.showNotification('Speakr Upload Sync', {
+ body: 'Checking for failed uploads to retry...',
+ icon: '/static/img/icon-192x192.png',
+ badge: '/static/img/icon-192x192.png',
+ tag: 'upload-sync',
+ requireInteraction: false
+ });
+
+ // Future: Retrieve and retry failed uploads from IndexedDB
+ // This would require storing failed uploads in IndexedDB from the main app
+ // const db = await openIndexedDB();
+ // const failedUploads = await getFailedUploads(db);
+ // for (const upload of failedUploads) {
+ // await retryUpload(upload);
+ // }
+
+ return Promise.resolve();
+ } catch (error) {
+ console.error('[Service Worker] Failed to sync uploads:', error);
+ return Promise.reject(error);
+ }
+}
+
+// Push notification handler
+self.addEventListener('push', (event) => {
+ console.log('[Service Worker] Push notification received');
+
+ const options = {
+ icon: '/static/img/icon-192x192.png',
+ badge: '/static/img/icon-192x192.png',
+ vibrate: [200, 100, 200],
+ data: {
+ dateOfArrival: Date.now(),
+ primaryKey: 1
+ }
+ };
+
+ if (event.data) {
+ const data = event.data.json();
+ event.waitUntil(
+ self.registration.showNotification(data.title || 'Speakr Notification', {
+ body: data.body || 'You have a new notification',
+ ...options,
+ data: data
+ })
+ );
+ } else {
+ event.waitUntil(
+ self.registration.showNotification('Speakr Notification', {
+ body: 'You have a new notification',
+ ...options
+ })
+ );
+ }
+});
+
+// Notification click handler
+self.addEventListener('notificationclick', (event) => {
+ console.log('[Service Worker] Notification clicked:', event.notification.tag);
+ event.notification.close();
+
+ // Handle different notification types
+ const urlToOpen = event.notification.data?.url || '/';
+
+ event.waitUntil(
+ clients.matchAll({ type: 'window', includeUncontrolled: true })
+ .then((clientList) => {
+ // Check if there's already a window open
+ for (const client of clientList) {
+ if (client.url === urlToOpen && 'focus' in client) {
+ return client.focus();
+ }
+ }
+ // If no window is open, open a new one
+ if (clients.openWindow) {
+ return clients.openWindow(urlToOpen);
+ }
+ })
+ );
+});
diff --git a/templates/components/header.html b/templates/components/header.html
index ca38f816..34dfabc7 100644
--- a/templates/components/header.html
+++ b/templates/components/header.html
@@ -26,6 +26,15 @@
</a>
{% endif %}
+ <!-- Install PWA Button -->
+ <button v-if="showInstallButton && !isPWAInstalled"
+ @click="promptInstall"
+ class="px-2 py-1.5 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors text-sm sm:px-4 sm:py-2 sm:flex sm:items-center sm:gap-2"
+ title="Install Speakr">
+ <i class="fas fa-download"></i>
+ <span class="hidden sm:inline">Install App</span>
+ </button>
+
<!-- New Recording Button -->
<button @click="switchToUploadView"
class="px-3 py-1.5 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors text-sm sm:px-4 sm:py-2 sm:min-w-[120px] sm:flex sm:items-center sm:gap-2 sm:justify-center">