Browse Source

feat(notifications): integrate daily notification plugin into AccountViewView

- Add notification methods to PlatformService interface
- Implement notification support in CapacitorPlatformService with plugin integration
- Add stub implementations in WebPlatformService and ElectronPlatformService
- Add nativeNotificationTime, nativeNotificationTitle, and nativeNotificationMessage fields to Settings interface
- Create DailyNotificationSection component for AccountViewView integration
- Add Android manifest permissions (POST_NOTIFICATIONS, SCHEDULE_EXACT_ALARM, RECEIVE_BOOT_COMPLETED)
- Register daily-notification-plugin in capacitor.plugins.json
- Integrate DailyNotificationSection into AccountViewView

Features:
- Platform capability detection (hides on unsupported platforms)
- Permission request flow with fallback to settings
- Schedule/cancel notifications
- Time editing with HTML5 time input
- Settings persistence
- Plugin state synchronization on app load

NOTE: Currently storing notification schedule in SQLite database, but plugin
was designed to store schedule internally. Consider migrating to plugin's
internal storage to avoid database initialization issues.
pull/214/head
Matthew Raymer 1 week ago
parent
commit
5f17f6cb4e
  1. 11
      android/app/src/main/AndroidManifest.xml
  2. 4
      android/app/src/main/assets/capacitor.plugins.json
  3. 676
      src/components/notifications/DailyNotificationSection.vue
  4. 5
      src/db/tables/settings.ts
  5. 114
      src/services/PlatformService.ts
  6. 358
      src/services/platforms/CapacitorPlatformService.ts
  7. 91
      src/services/platforms/ElectronPlatformService.ts
  8. 82
      src/services/platforms/WebPlatformService.ts
  9. 5
      src/views/AccountViewView.vue

11
android/app/src/main/AndroidManifest.xml

@ -45,4 +45,15 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" /> <uses-feature android:name="android.hardware.camera" android:required="true" />
<!-- Notification permissions -->
<!-- POST_NOTIFICATIONS required for Android 13+ (API 33+) -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- SCHEDULE_EXACT_ALARM required for Android 12+ (API 31+) to schedule exact alarms -->
<!-- Note: On Android 12+, users can grant/deny this permission -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<!-- RECEIVE_BOOT_COMPLETED needed to reschedule notifications after device reboot -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest> </manifest>

4
android/app/src/main/assets/capacitor.plugins.json

@ -35,6 +35,10 @@
"pkg": "@capawesome/capacitor-file-picker", "pkg": "@capawesome/capacitor-file-picker",
"classpath": "io.capawesome.capacitorjs.plugins.filepicker.FilePickerPlugin" "classpath": "io.capawesome.capacitorjs.plugins.filepicker.FilePickerPlugin"
}, },
{
"pkg": "@timesafari/daily-notification-plugin",
"classpath": "com.timesafari.dailynotification.DailyNotificationPlugin"
},
{ {
"pkg": "@timesafari/daily-notification-plugin", "pkg": "@timesafari/daily-notification-plugin",
"classpath": "com.timesafari.dailynotification.DailyNotificationPlugin" "classpath": "com.timesafari.dailynotification.DailyNotificationPlugin"

676
src/components/notifications/DailyNotificationSection.vue

@ -0,0 +1,676 @@
<template>
<section
v-if="notificationsSupported"
id="sectionDailyNotifications"
class="bg-slate-100 rounded-md overflow-hidden px-4 py-4 mt-8 mb-8"
aria-labelledby="dailyNotificationsHeading"
>
<h2 id="dailyNotificationsHeading" class="mb-2 font-bold">
Daily Notifications
<button
class="text-slate-400 fa-fw cursor-pointer"
aria-label="Learn more about native notifications"
@click.stop="showNativeNotificationInfo"
>
<font-awesome icon="circle-question" aria-hidden="true" />
</button>
</h2>
<div class="flex items-center justify-between">
<div>Daily Notification</div>
<!-- Toggle switch -->
<div
class="relative ml-2 cursor-pointer"
role="switch"
:aria-checked="nativeNotificationEnabled"
:aria-label="
nativeNotificationEnabled
? 'Disable daily notifications'
: 'Enable daily notifications'
"
tabindex="0"
@click="toggleNativeNotification"
>
<!-- input -->
<input
:checked="nativeNotificationEnabled"
type="checkbox"
class="sr-only"
tabindex="-1"
readonly
/>
<!-- line -->
<div
class="block bg-slate-500 w-14 h-8 rounded-full transition"
:class="{
'bg-blue-600': nativeNotificationEnabled,
}"
></div>
<!-- dot -->
<div
class="dot absolute left-1 top-1 bg-slate-400 w-6 h-6 rounded-full transition"
:class="{
'left-7 bg-white': nativeNotificationEnabled,
}"
></div>
</div>
</div>
<!-- Show "Open Settings" button when permissions are denied -->
<div
v-if="
notificationsSupported &&
notificationStatus &&
notificationStatus.permissions.notifications === 'denied'
"
class="mt-2"
>
<button
class="w-full px-3 py-2 bg-blue-600 text-white rounded text-sm font-medium"
@click="openNotificationSettings"
>
Open Settings
</button>
<p class="text-xs text-slate-500 mt-1 text-center">
Enable notifications in Settings > App info > Notifications
</p>
</div>
<!-- Time input section - show when enabled OR when no time is set -->
<div
v-if="nativeNotificationEnabled || !nativeNotificationTimeStorage"
class="mt-2"
>
<div
v-if="nativeNotificationEnabled"
class="flex items-center justify-between mb-2"
>
<span
>Scheduled for:
<span v-if="nativeNotificationTime">{{
nativeNotificationTime
}}</span>
<span v-else class="text-slate-500">Not set</span></span
>
<button
class="text-blue-500 text-sm"
@click="editNativeNotificationTime"
>
{{ showTimeEdit ? "Cancel" : "Edit Time" }}
</button>
</div>
<!-- Time input (shown when editing or when no time is set) -->
<div v-if="showTimeEdit || !nativeNotificationTimeStorage" class="mt-2">
<label class="block text-sm text-slate-600 mb-1">
Notification Time
</label>
<div class="flex items-center gap-2">
<input
v-model="nativeNotificationTimeStorage"
type="time"
class="rounded border border-slate-400 px-2 py-2"
@change="onTimeChange"
/>
<button
v-if="showTimeEdit || nativeNotificationTimeStorage"
class="px-3 py-2 bg-blue-600 text-white rounded"
@click="saveTimeChange"
>
Save
</button>
</div>
<p
v-if="!nativeNotificationTimeStorage"
class="text-xs text-slate-500 mt-1"
>
Set a time before enabling notifications
</p>
</div>
</div>
<!-- Loading state -->
<div v-if="loading" class="mt-2 text-sm text-slate-500">Loading...</div>
</section>
</template>
<script lang="ts">
/**
* DailyNotificationSection Component
*
* A self-contained component for managing daily notification scheduling
* in AccountViewView. This component handles platform detection, permission
* requests, scheduling, and state management for daily notifications.
*
* Features:
* - Platform capability detection (hides on unsupported platforms)
* - Permission request flow
* - Schedule/cancel notifications
* - Time editing with HTML5 time input
* - Settings persistence
* - Plugin state synchronization
*
* @author Generated for TimeSafari Daily Notification Integration
* @component
*/
import { Component, Vue } from "vue-facing-decorator";
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
import { logger } from "@/utils/logger";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
import type {
NotificationStatus,
PermissionStatus,
} from "@/services/PlatformService";
import { createNotifyHelpers, TIMEOUTS } from "@/utils/notify";
import type { NotificationIface } from "@/constants/app";
/**
* Convert 24-hour time format ("09:00") to 12-hour display format ("9:00 AM")
*/
function formatTimeForDisplay(time24: string): string {
if (!time24) return "";
const [hours, minutes] = time24.split(":");
const hourNum = parseInt(hours);
const isPM = hourNum >= 12;
const displayHour =
hourNum === 0 ? 12 : hourNum > 12 ? hourNum - 12 : hourNum;
return `${displayHour}:${minutes} ${isPM ? "PM" : "AM"}`;
}
@Component({
name: "DailyNotificationSection",
mixins: [PlatformServiceMixin],
})
export default class DailyNotificationSection extends Vue {
$notify!: (notification: NotificationIface, timeout?: number) => void;
// Component state
notificationsSupported: boolean = false;
nativeNotificationEnabled: boolean = false;
nativeNotificationTime: string = ""; // Display format: "9:00 AM"
nativeNotificationTimeStorage: string = ""; // Plugin format: "09:00"
nativeNotificationTitle: string = "Daily Update";
nativeNotificationMessage: string = "Your daily notification is ready!";
showTimeEdit: boolean = false;
loading: boolean = false;
notificationStatus: NotificationStatus | null = null;
// Notify helpers
private notify!: ReturnType<typeof createNotifyHelpers>;
async created(): Promise<void> {
this.notify = createNotifyHelpers(this.$notify);
}
/**
* Initialize component state on mount
* Checks platform support and syncs with plugin state
*/
async mounted(): Promise<void> {
await this.initializeState();
}
/**
* Initialize component state
* Checks platform support and syncs with plugin state
*/
async initializeState(): Promise<void> {
try {
this.loading = true;
const platformService = PlatformServiceFactory.getInstance();
// Check if notifications are supported on this platform
// This also verifies plugin availability (returns null if plugin unavailable)
const status = await platformService.getDailyNotificationStatus();
if (status === null) {
// Notifications not supported or plugin unavailable - don't initialize
this.notificationsSupported = false;
logger.warn(
"[DailyNotificationSection] Notifications not supported or plugin unavailable",
);
return;
}
this.notificationsSupported = true;
this.notificationStatus = status;
// CRITICAL: Sync with plugin state first (source of truth)
// Plugin may have an existing schedule even if settings don't
if (status.isScheduled && status.scheduledTime) {
// Plugin has a scheduled notification - sync UI to match
this.nativeNotificationEnabled = true;
this.nativeNotificationTimeStorage = status.scheduledTime;
this.nativeNotificationTime = formatTimeForDisplay(
status.scheduledTime,
);
// Also sync settings to match plugin state
const settings = await this.$accountSettings();
if (settings.nativeNotificationTime !== status.scheduledTime) {
await this.$saveSettings({
nativeNotificationTime: status.scheduledTime,
nativeNotificationTitle:
settings.nativeNotificationTitle || this.nativeNotificationTitle,
nativeNotificationMessage:
settings.nativeNotificationMessage ||
this.nativeNotificationMessage,
});
}
} else {
// No plugin schedule - check settings for user preference
const settings = await this.$accountSettings();
const nativeNotificationTime = settings.nativeNotificationTime || "";
this.nativeNotificationEnabled = !!nativeNotificationTime;
this.nativeNotificationTimeStorage = nativeNotificationTime;
if (nativeNotificationTime) {
this.nativeNotificationTime = formatTimeForDisplay(
nativeNotificationTime,
);
}
}
} catch (error) {
logger.error("[DailyNotificationSection] Failed to initialize:", error);
this.notificationsSupported = false;
} finally {
this.loading = false;
}
}
/**
* Toggle notification on/off
*/
async toggleNativeNotification(): Promise<void> {
// Prevent multiple simultaneous toggles
if (this.loading) {
logger.warn(
"[DailyNotificationSection] Toggle ignored - operation in progress",
);
return;
}
logger.info(
`[DailyNotificationSection] Toggling notification: ${this.nativeNotificationEnabled} -> ${!this.nativeNotificationEnabled}`,
);
if (this.nativeNotificationEnabled) {
await this.disableNativeNotification();
} else {
await this.enableNativeNotification();
}
}
/**
* Enable daily notification
*/
async enableNativeNotification(): Promise<void> {
try {
this.loading = true;
const platformService = PlatformServiceFactory.getInstance();
// Check if we have a time set
if (!this.nativeNotificationTimeStorage) {
this.notify.error(
"Please set a notification time first",
TIMEOUTS.SHORT,
);
this.loading = false;
return;
}
// Check permissions first - this also verifies plugin availability
let permissions: PermissionStatus | null;
try {
permissions = await platformService.checkNotificationPermissions();
logger.info(
`[DailyNotificationSection] Permission check result:`,
permissions,
);
} catch (error) {
// Plugin may not be available or there's an error
logger.error(
"[DailyNotificationSection] Failed to check permissions (plugin may be unavailable):",
error,
);
this.notify.error(
"Unable to check notification permissions. The notification plugin may not be installed.",
TIMEOUTS.LONG,
);
this.nativeNotificationEnabled = false;
return;
}
if (permissions === null) {
// Platform doesn't support notifications or plugin unavailable
logger.warn(
"[DailyNotificationSection] Notifications not supported or plugin unavailable",
);
this.notify.error(
"Notifications are not supported on this platform or the plugin is not installed.",
TIMEOUTS.SHORT,
);
this.nativeNotificationEnabled = false;
return;
}
logger.info(
`[DailyNotificationSection] Permission state: ${permissions.notifications}`,
);
// If permissions are explicitly denied, don't try to request again
// (this prevents the plugin crash when handling denied permissions)
// Android won't show the dialog again if permissions are permanently denied
if (permissions.notifications === "denied") {
logger.warn(
"[DailyNotificationSection] Permissions already denied, directing user to settings",
);
this.notify.error(
"Notification permissions were denied. Tap 'Open Settings' to enable them.",
TIMEOUTS.LONG,
);
this.nativeNotificationEnabled = false;
return;
}
// Only request if permissions are in "prompt" state (not denied, not granted)
// This ensures we only call requestPermissions when Android will actually show a dialog
if (permissions.notifications === "prompt") {
logger.info(
"[DailyNotificationSection] Permission state is 'prompt', requesting permissions...",
);
try {
const result = await platformService.requestNotificationPermissions();
logger.info(
`[DailyNotificationSection] Permission request result:`,
result,
);
if (result === null) {
// Plugin unavailable or request failed
logger.error(
"[DailyNotificationSection] Permission request returned null",
);
this.notify.error(
"Unable to request notification permissions. The plugin may not be available.",
TIMEOUTS.LONG,
);
this.nativeNotificationEnabled = false;
return;
}
if (!result.notifications) {
// Permission request was denied
logger.warn(
"[DailyNotificationSection] Permission request denied by user",
);
this.notify.error(
"Notification permissions are required. Tap 'Open Settings' to enable them.",
TIMEOUTS.LONG,
);
this.nativeNotificationEnabled = false;
return;
}
// Permissions granted - continue
logger.info(
"[DailyNotificationSection] Permissions granted successfully",
);
} catch (error) {
// Handle permission request errors (including plugin crashes)
logger.error(
"[DailyNotificationSection] Permission request failed:",
error,
);
this.notify.error(
"Unable to request notification permissions. Tap 'Open Settings' to enable them.",
TIMEOUTS.LONG,
);
this.nativeNotificationEnabled = false;
return;
}
} else if (permissions.notifications !== "granted") {
// Unexpected state - shouldn't happen, but handle gracefully
logger.warn(
`[DailyNotificationSection] Unexpected permission state: ${permissions.notifications}`,
);
this.notify.error(
"Unable to determine notification permission status. Tap 'Open Settings' to check.",
TIMEOUTS.LONG,
);
this.nativeNotificationEnabled = false;
return;
} else {
logger.info("[DailyNotificationSection] Permissions already granted");
}
// Permissions are granted - continue with scheduling
// Schedule notification via PlatformService
await platformService.scheduleDailyNotification({
time: this.nativeNotificationTimeStorage, // "09:00" in local time
title: this.nativeNotificationTitle,
body: this.nativeNotificationMessage,
sound: true,
priority: "high",
});
// Save to settings
await this.$saveSettings({
nativeNotificationTime: this.nativeNotificationTimeStorage,
nativeNotificationTitle: this.nativeNotificationTitle,
nativeNotificationMessage: this.nativeNotificationMessage,
});
// Update UI state
this.nativeNotificationEnabled = true;
this.notify.success(
"Daily notification scheduled successfully",
TIMEOUTS.SHORT,
);
} catch (error) {
logger.error(
"[DailyNotificationSection] Failed to enable notification:",
error,
);
this.notify.error(
"Failed to schedule notification. Please try again.",
TIMEOUTS.LONG,
);
this.nativeNotificationEnabled = false;
} finally {
this.loading = false;
}
}
/**
* Disable daily notification
*/
async disableNativeNotification(): Promise<void> {
try {
this.loading = true;
const platformService = PlatformServiceFactory.getInstance();
// Cancel notification via PlatformService
await platformService.cancelDailyNotification();
// Clear settings
await this.$saveSettings({
nativeNotificationTime: "",
nativeNotificationTitle: "",
nativeNotificationMessage: "",
});
// Update UI state
this.nativeNotificationEnabled = false;
this.nativeNotificationTime = "";
this.nativeNotificationTimeStorage = "";
this.showTimeEdit = false;
this.notify.success("Daily notification disabled", TIMEOUTS.SHORT);
} catch (error) {
logger.error(
"[DailyNotificationSection] Failed to disable notification:",
error,
);
this.notify.error(
"Failed to disable notification. Please try again.",
TIMEOUTS.LONG,
);
} finally {
this.loading = false;
}
}
/**
* Show/hide time edit input
*/
editNativeNotificationTime(): void {
this.showTimeEdit = !this.showTimeEdit;
}
/**
* Handle time input change
*/
onTimeChange(): void {
// Time is already in nativeNotificationTimeStorage via v-model
// Just update display format
if (this.nativeNotificationTimeStorage) {
this.nativeNotificationTime = formatTimeForDisplay(
this.nativeNotificationTimeStorage,
);
}
}
/**
* Save time change and update notification schedule
*/
async saveTimeChange(): Promise<void> {
if (!this.nativeNotificationTimeStorage) {
this.notify.error("Please select a time", TIMEOUTS.SHORT);
return;
}
// Update display format
this.nativeNotificationTime = formatTimeForDisplay(
this.nativeNotificationTimeStorage,
);
// If notification is enabled, update the schedule
if (this.nativeNotificationEnabled) {
await this.updateNotificationTime(this.nativeNotificationTimeStorage);
} else {
// Just save the time preference
await this.$saveSettings({
nativeNotificationTime: this.nativeNotificationTimeStorage,
});
this.showTimeEdit = false;
this.notify.success("Notification time saved", TIMEOUTS.SHORT);
}
}
/**
* Update notification time
* If notification is enabled, immediately updates the schedule
*/
async updateNotificationTime(newTime: string): Promise<void> {
// newTime is in "HH:mm" format from HTML5 time input
if (!this.nativeNotificationEnabled) {
// If notification is disabled, just save the time preference
this.nativeNotificationTimeStorage = newTime;
this.nativeNotificationTime = formatTimeForDisplay(newTime);
await this.$saveSettings({
nativeNotificationTime: newTime,
});
this.showTimeEdit = false;
return;
}
// Notification is enabled - update the schedule
try {
this.loading = true;
const platformService = PlatformServiceFactory.getInstance();
// 1. Cancel existing notification
await platformService.cancelDailyNotification();
// 2. Schedule with new time
await platformService.scheduleDailyNotification({
time: newTime, // "09:00" in local time
title: this.nativeNotificationTitle,
body: this.nativeNotificationMessage,
sound: true,
priority: "high",
});
// 3. Update local state
this.nativeNotificationTimeStorage = newTime;
this.nativeNotificationTime = formatTimeForDisplay(newTime);
// 4. Save to settings
await this.$saveSettings({
nativeNotificationTime: newTime,
});
this.notify.success(
"Notification time updated successfully",
TIMEOUTS.SHORT,
);
this.showTimeEdit = false;
} catch (error) {
logger.error(
"[DailyNotificationSection] Failed to update notification time:",
error,
);
this.notify.error(
"Failed to update notification time. Please try again.",
TIMEOUTS.LONG,
);
} finally {
this.loading = false;
}
}
/**
* Show info dialog about native notifications
*/
showNativeNotificationInfo(): void {
// TODO: Implement info dialog or navigate to help page
this.notify.info(
"Daily notifications use your device's native notification system. They work even when the app is closed.",
TIMEOUTS.STANDARD,
);
}
/**
* Open app notification settings
*/
async openNotificationSettings(): Promise<void> {
try {
const platformService = PlatformServiceFactory.getInstance();
const result = await platformService.openAppNotificationSettings();
if (result === null) {
this.notify.error(
"Unable to open settings. Please go to Settings > Apps > TimeSafari > Notifications manually.",
TIMEOUTS.LONG,
);
} else {
this.notify.success("Opening notification settings...", TIMEOUTS.SHORT);
}
} catch (error) {
logger.error(
"[DailyNotificationSection] Failed to open notification settings:",
error,
);
this.notify.error(
"Unable to open settings. Please go to Settings > Apps > TimeSafari > Notifications manually.",
TIMEOUTS.LONG,
);
}
}
}
</script>
<style scoped>
.dot {
transition: left 0.2s ease;
}
</style>

5
src/db/tables/settings.ts

@ -53,6 +53,11 @@ export type Settings = {
notifyingReminderMessage?: string; // set to their chosen message for a daily reminder notifyingReminderMessage?: string; // set to their chosen message for a daily reminder
notifyingReminderTime?: string; // set to their chosen time for a daily reminder notifyingReminderTime?: string; // set to their chosen time for a daily reminder
// Native notification settings (Capacitor only)
nativeNotificationTime?: string; // "09:00" format (24-hour) - scheduled time for daily notification
nativeNotificationTitle?: string; // Default: "Daily Update" - notification title
nativeNotificationMessage?: string; // Default message - notification body text
partnerApiServer?: string; // partner server API URL partnerApiServer?: string; // partner server API URL
passkeyExpirationMinutes?: number; // passkey access token time-to-live in minutes passkeyExpirationMinutes?: number; // passkey access token time-to-live in minutes

114
src/services/PlatformService.ts

@ -32,6 +32,68 @@ export interface PlatformCapabilities {
isNativeApp: boolean; isNativeApp: boolean;
} }
/**
* Permission status for notifications
*/
export interface PermissionStatus {
/** Notification permission status */
notifications: "granted" | "denied" | "prompt";
/** Exact alarms permission status (Android only) */
exactAlarms?: "granted" | "denied" | "prompt";
}
/**
* Result of permission request
*/
export interface PermissionResult {
/** Whether notification permission was granted */
notifications: boolean;
/** Whether exact alarms permission was granted (Android only) */
exactAlarms?: boolean;
}
/**
* Status of scheduled daily notifications
*/
export interface NotificationStatus {
/** Whether a notification is currently scheduled */
isScheduled: boolean;
/** Scheduled time in "HH:mm" format (24-hour) */
scheduledTime?: string;
/** Last time the notification was triggered (ISO string) */
lastTriggered?: string;
/** Current permission status */
permissions: PermissionStatus;
}
/**
* Options for scheduling a daily notification
*/
export interface ScheduleOptions {
/** Time in "HH:mm" format (24-hour) in local time */
time: string;
/** Notification title */
title: string;
/** Notification body text */
body: string;
/** Whether to play sound (default: true) */
sound?: boolean;
/** Notification priority */
priority?: "high" | "normal" | "low";
}
/**
* Configuration for native fetcher background operations
*/
export interface NativeFetcherConfig {
/** API server URL */
apiServer: string;
/** JWT token for authentication */
jwt: string;
/** Array of starred plan handle IDs */
starredPlanHandleIds: string[];
}
/** /**
* Platform-agnostic interface for handling platform-specific operations. * Platform-agnostic interface for handling platform-specific operations.
* Provides a common API for file system operations, camera interactions, * Provides a common API for file system operations, camera interactions,
@ -209,6 +271,58 @@ export interface PlatformService {
*/ */
retrieveSettingsForActiveAccount(): Promise<Record<string, unknown> | null>; retrieveSettingsForActiveAccount(): Promise<Record<string, unknown> | null>;
// Daily notification operations
/**
* Get the status of scheduled daily notifications
* @returns Promise resolving to notification status, or null if not supported
*/
getDailyNotificationStatus(): Promise<NotificationStatus | null>;
/**
* Check notification permissions
* @returns Promise resolving to permission status, or null if not supported
*/
checkNotificationPermissions(): Promise<PermissionStatus | null>;
/**
* Request notification permissions
* @returns Promise resolving to permission result, or null if not supported
*/
requestNotificationPermissions(): Promise<PermissionResult | null>;
/**
* Schedule a daily notification
* @param options - Notification scheduling options
* @returns Promise that resolves when scheduled, or rejects if not supported
*/
scheduleDailyNotification(options: ScheduleOptions): Promise<void>;
/**
* Cancel scheduled daily notification
* @returns Promise that resolves when cancelled, or rejects if not supported
*/
cancelDailyNotification(): Promise<void>;
/**
* Configure native fetcher for background operations
* @param config - Native fetcher configuration
* @returns Promise that resolves when configured, or null if not supported
*/
configureNativeFetcher(config: NativeFetcherConfig): Promise<void | null>;
/**
* Update starred plans for background fetcher
* @param plans - Starred plan IDs
* @returns Promise that resolves when updated, or null if not supported
*/
updateStarredPlans(plans: { planIds: string[] }): Promise<void | null>;
/**
* Open the app's notification settings in the system settings
* @returns Promise that resolves when the settings page is opened, or null if not supported
*/
openAppNotificationSettings(): Promise<void | null>;
// --- PWA/Web-only methods (optional, only implemented on web) --- // --- PWA/Web-only methods (optional, only implemented on web) ---
/** /**
* Registers the service worker for PWA support (web only) * Registers the service worker for PWA support (web only)

358
src/services/platforms/CapacitorPlatformService.ts

@ -20,6 +20,11 @@ import {
ImageResult, ImageResult,
PlatformService, PlatformService,
PlatformCapabilities, PlatformCapabilities,
NotificationStatus,
PermissionStatus,
PermissionResult,
ScheduleOptions,
NativeFetcherConfig,
} from "../PlatformService"; } from "../PlatformService";
import { logger } from "../../utils/logger"; import { logger } from "../../utils/logger";
import { BaseDatabaseService } from "./BaseDatabaseService"; import { BaseDatabaseService } from "./BaseDatabaseService";
@ -1333,6 +1338,359 @@ export class CapacitorPlatformService
// --- PWA/Web-only methods (no-op for Capacitor) --- // --- PWA/Web-only methods (no-op for Capacitor) ---
public registerServiceWorker(): void {} public registerServiceWorker(): void {}
// Daily notification operations
/**
* Get the status of scheduled daily notifications
* @see PlatformService.getDailyNotificationStatus
*/
async getDailyNotificationStatus(): Promise<NotificationStatus | null> {
try {
// Dynamic import to avoid build issues if plugin unavailable
const { DailyNotification } = await import(
"@timesafari/daily-notification-plugin"
);
const pluginStatus = await DailyNotification.getNotificationStatus();
// Get permissions separately
const permissions = await DailyNotification.checkPermissions();
// Map plugin PermissionState to our PermissionStatus format
const notificationsPermission = permissions.notifications;
let notifications: "granted" | "denied" | "prompt";
if (notificationsPermission === "granted") {
notifications = "granted";
} else if (notificationsPermission === "denied") {
notifications = "denied";
} else {
notifications = "prompt";
}
// Handle lastNotificationTime which can be a Promise<number>
let lastTriggered: string | undefined;
const lastNotificationTime = pluginStatus.lastNotificationTime;
if (lastNotificationTime) {
const timeValue = await Promise.resolve(lastNotificationTime);
if (typeof timeValue === "number") {
lastTriggered = new Date(timeValue).toISOString();
}
}
return {
isScheduled: pluginStatus.isScheduled ?? false,
scheduledTime: pluginStatus.settings?.time,
lastTriggered,
permissions: {
notifications,
exactAlarms: undefined, // Plugin doesn't expose this in status
},
};
} catch (error) {
logger.error(
"[CapacitorPlatformService] Failed to get notification status:",
error,
);
return null;
}
}
/**
* Check notification permissions
* @see PlatformService.checkNotificationPermissions
*/
async checkNotificationPermissions(): Promise<PermissionStatus | null> {
try {
const { DailyNotification } = await import(
"@timesafari/daily-notification-plugin"
);
const permissions = await DailyNotification.checkPermissions();
// Log the raw permission state for debugging
logger.info(
`[CapacitorPlatformService] Raw permission state from plugin:`,
permissions,
);
// Map plugin PermissionState to our PermissionStatus format
const notificationsPermission = permissions.notifications;
let notifications: "granted" | "denied" | "prompt";
// Handle all possible PermissionState values
if (notificationsPermission === "granted") {
notifications = "granted";
} else if (
notificationsPermission === "denied" ||
notificationsPermission === "ephemeral"
) {
notifications = "denied";
} else {
// Treat "prompt", "prompt-with-rationale", "unknown", "provisional" as "prompt"
// This allows Android to show the permission dialog
notifications = "prompt";
}
logger.info(
`[CapacitorPlatformService] Mapped permission state: ${notifications} (from ${notificationsPermission})`,
);
return {
notifications,
exactAlarms: undefined, // Plugin doesn't expose this directly
};
} catch (error) {
logger.error(
"[CapacitorPlatformService] Failed to check permissions:",
error,
);
return null;
}
}
/**
* Request notification permissions
* @see PlatformService.requestNotificationPermissions
*/
async requestNotificationPermissions(): Promise<PermissionResult | null> {
try {
const { DailyNotification } = await import(
"@timesafari/daily-notification-plugin"
);
logger.info(
`[CapacitorPlatformService] Requesting notification permissions...`,
);
const result = await DailyNotification.requestPermissions();
logger.info(
`[CapacitorPlatformService] Permission request result:`,
result,
);
// Map plugin PermissionState to boolean
const notificationsGranted = result.notifications === "granted";
logger.info(
`[CapacitorPlatformService] Mapped permission result: ${notificationsGranted} (from ${result.notifications})`,
);
return {
notifications: notificationsGranted,
exactAlarms: undefined, // Plugin doesn't expose this directly
};
} catch (error) {
logger.error(
"[CapacitorPlatformService] Failed to request permissions:",
error,
);
return null;
}
}
/**
* Schedule a daily notification
* @see PlatformService.scheduleDailyNotification
*/
async scheduleDailyNotification(options: ScheduleOptions): Promise<void> {
try {
const { DailyNotification } = await import(
"@timesafari/daily-notification-plugin"
);
await DailyNotification.scheduleDailyNotification({
time: options.time,
title: options.title,
body: options.body,
sound: options.sound ?? true,
priority: options.priority ?? "high",
});
logger.info(
`[CapacitorPlatformService] Scheduled daily notification for ${options.time}`,
);
} catch (error) {
logger.error(
"[CapacitorPlatformService] Failed to schedule notification:",
error,
);
throw error;
}
}
/**
* Cancel scheduled daily notification
* @see PlatformService.cancelDailyNotification
*/
async cancelDailyNotification(): Promise<void> {
try {
const { DailyNotification } = await import(
"@timesafari/daily-notification-plugin"
);
await DailyNotification.cancelAllNotifications();
logger.info("[CapacitorPlatformService] Cancelled daily notification");
} catch (error) {
logger.error(
"[CapacitorPlatformService] Failed to cancel notification:",
error,
);
throw error;
}
}
/**
* Configure native fetcher for background operations
* @see PlatformService.configureNativeFetcher
*/
async configureNativeFetcher(
config: NativeFetcherConfig,
): Promise<void | null> {
try {
const { DailyNotification } = await import(
"@timesafari/daily-notification-plugin"
);
// Plugin expects apiBaseUrl, activeDid, and jwtToken
// We'll need to get activeDid from somewhere - for now pass empty string
// Components should provide activeDid when calling this
await DailyNotification.configureNativeFetcher({
apiBaseUrl: config.apiServer,
activeDid: "", // Should be provided by caller
jwtToken: config.jwt,
});
logger.info("[CapacitorPlatformService] Configured native fetcher");
} catch (error) {
logger.error(
"[CapacitorPlatformService] Failed to configure native fetcher:",
error,
);
return null;
}
}
/**
* Update starred plans for background fetcher
* @see PlatformService.updateStarredPlans
*/
async updateStarredPlans(plans: { planIds: string[] }): Promise<void | null> {
try {
const { DailyNotification } = await import(
"@timesafari/daily-notification-plugin"
);
await DailyNotification.updateStarredPlans({
planIds: plans.planIds,
});
logger.info(
`[CapacitorPlatformService] Updated starred plans: ${plans.planIds.length} plans`,
);
} catch (error) {
logger.error(
"[CapacitorPlatformService] Failed to update starred plans:",
error,
);
return null;
}
}
/**
* Open the app's notification settings in the system settings
* @see PlatformService.openAppNotificationSettings
*/
async openAppNotificationSettings(): Promise<void | null> {
try {
const platform = Capacitor.getPlatform();
if (platform === "android") {
// Android: Open app details settings page
// From there, users can navigate to "Notifications" section
// This is more reliable than trying to open notification settings directly
const packageName = "app.timesafari.app"; // Full application ID from build.gradle
// Use APPLICATION_DETAILS_SETTINGS which opens the app's settings page
// Users can then navigate to "Notifications" section
// Try multiple URL formats to ensure compatibility
const intentUrl1 = `intent:#Intent;action=android.settings.APPLICATION_DETAILS_SETTINGS;data=package:${packageName};end`;
const intentUrl2 = `intent://settings/app_detail?package=${packageName}#Intent;scheme=android-app;end`;
logger.info(
`[CapacitorPlatformService] Opening Android app settings for ${packageName}`,
);
// Log current permission state before opening settings
try {
const currentPerms = await this.checkNotificationPermissions();
logger.info(
`[CapacitorPlatformService] Current permission state before opening settings:`,
currentPerms,
);
} catch (e) {
logger.warn(
`[CapacitorPlatformService] Could not check permissions before opening settings:`,
e,
);
}
// Try multiple approaches to ensure it works
try {
// Method 1: Direct window.location.href (most reliable)
window.location.href = intentUrl1;
// Method 2: Fallback with window.open
setTimeout(() => {
try {
window.open(intentUrl1, "_blank");
} catch (e) {
logger.warn(
"[CapacitorPlatformService] window.open fallback failed:",
e,
);
}
}, 100);
// Method 3: Alternative format
setTimeout(() => {
try {
window.location.href = intentUrl2;
} catch (e) {
logger.warn(
"[CapacitorPlatformService] Alternative format failed:",
e,
);
}
}, 200);
} catch (e) {
logger.error(
"[CapacitorPlatformService] Failed to open intent URL:",
e,
);
}
} else if (platform === "ios") {
// iOS: Use app settings URL scheme
const settingsUrl = `app-settings:`;
window.location.href = settingsUrl;
logger.info("[CapacitorPlatformService] Opening iOS app settings");
} else {
logger.warn(
`[CapacitorPlatformService] Cannot open settings on platform: ${platform}`,
);
return null;
}
} catch (error) {
logger.error(
"[CapacitorPlatformService] Failed to open app notification settings:",
error,
);
return null;
}
}
// Database utility methods - inherited from BaseDatabaseService // Database utility methods - inherited from BaseDatabaseService
// generateInsertStatement, updateDefaultSettings, updateActiveDid, // generateInsertStatement, updateDefaultSettings, updateActiveDid,
// getActiveIdentity, insertNewDidIntoSettings, updateDidSpecificSettings, // getActiveIdentity, insertNewDidIntoSettings, updateDidSpecificSettings,

91
src/services/platforms/ElectronPlatformService.ts

@ -22,6 +22,13 @@
import { CapacitorPlatformService } from "./CapacitorPlatformService"; import { CapacitorPlatformService } from "./CapacitorPlatformService";
import { logger } from "../../utils/logger"; import { logger } from "../../utils/logger";
import {
NotificationStatus,
PermissionStatus,
PermissionResult,
ScheduleOptions,
NativeFetcherConfig,
} from "../PlatformService";
/** /**
* Electron-specific platform service implementation. * Electron-specific platform service implementation.
@ -166,4 +173,88 @@ export class ElectronPlatformService extends CapacitorPlatformService {
// --- PWA/Web-only methods (no-op for Electron) --- // --- PWA/Web-only methods (no-op for Electron) ---
public registerServiceWorker(): void {} public registerServiceWorker(): void {}
// Daily notification operations
// Override CapacitorPlatformService methods to return null/throw errors
// since Electron doesn't support native daily notifications
/**
* Get the status of scheduled daily notifications
* @see PlatformService.getDailyNotificationStatus
* @returns null - notifications not supported on Electron platform
*/
async getDailyNotificationStatus(): Promise<NotificationStatus | null> {
return null;
}
/**
* Check notification permissions
* @see PlatformService.checkNotificationPermissions
* @returns null - notifications not supported on Electron platform
*/
async checkNotificationPermissions(): Promise<PermissionStatus | null> {
return null;
}
/**
* Request notification permissions
* @see PlatformService.requestNotificationPermissions
* @returns null - notifications not supported on Electron platform
*/
async requestNotificationPermissions(): Promise<PermissionResult | null> {
return null;
}
/**
* Schedule a daily notification
* @see PlatformService.scheduleDailyNotification
* @throws Error - notifications not supported on Electron platform
*/
async scheduleDailyNotification(_options: ScheduleOptions): Promise<void> {
throw new Error(
"Daily notifications are not supported on Electron platform",
);
}
/**
* Cancel scheduled daily notification
* @see PlatformService.cancelDailyNotification
* @throws Error - notifications not supported on Electron platform
*/
async cancelDailyNotification(): Promise<void> {
throw new Error(
"Daily notifications are not supported on Electron platform",
);
}
/**
* Configure native fetcher for background operations
* @see PlatformService.configureNativeFetcher
* @returns null - native fetcher not supported on Electron platform
*/
async configureNativeFetcher(
_config: NativeFetcherConfig,
): Promise<void | null> {
return null;
}
/**
* Update starred plans for background fetcher
* @see PlatformService.updateStarredPlans
* @returns null - native fetcher not supported on Electron platform
*/
async updateStarredPlans(_plans: {
planIds: string[];
}): Promise<void | null> {
return null;
}
/**
* Open the app's notification settings in the system settings
* @see PlatformService.openAppNotificationSettings
* @returns null - not supported on Electron platform
*/
async openAppNotificationSettings(): Promise<void | null> {
return null;
}
} }

82
src/services/platforms/WebPlatformService.ts

@ -2,6 +2,11 @@ import {
ImageResult, ImageResult,
PlatformService, PlatformService,
PlatformCapabilities, PlatformCapabilities,
NotificationStatus,
PermissionStatus,
PermissionResult,
ScheduleOptions,
NativeFetcherConfig,
} from "../PlatformService"; } from "../PlatformService";
import { logger } from "../../utils/logger"; import { logger } from "../../utils/logger";
import { QueryExecResult } from "@/interfaces/database"; import { QueryExecResult } from "@/interfaces/database";
@ -677,4 +682,81 @@ export class WebPlatformService
// generateInsertStatement, updateDefaultSettings, updateActiveDid, // generateInsertStatement, updateDefaultSettings, updateActiveDid,
// getActiveIdentity, insertNewDidIntoSettings, updateDidSpecificSettings, // getActiveIdentity, insertNewDidIntoSettings, updateDidSpecificSettings,
// retrieveSettingsForActiveAccount are all inherited from BaseDatabaseService // retrieveSettingsForActiveAccount are all inherited from BaseDatabaseService
// Daily notification operations
/**
* Get the status of scheduled daily notifications
* @see PlatformService.getDailyNotificationStatus
* @returns null - notifications not supported on web platform
*/
async getDailyNotificationStatus(): Promise<NotificationStatus | null> {
return null;
}
/**
* Check notification permissions
* @see PlatformService.checkNotificationPermissions
* @returns null - notifications not supported on web platform
*/
async checkNotificationPermissions(): Promise<PermissionStatus | null> {
return null;
}
/**
* Request notification permissions
* @see PlatformService.requestNotificationPermissions
* @returns null - notifications not supported on web platform
*/
async requestNotificationPermissions(): Promise<PermissionResult | null> {
return null;
}
/**
* Schedule a daily notification
* @see PlatformService.scheduleDailyNotification
* @throws Error - notifications not supported on web platform
*/
async scheduleDailyNotification(_options: ScheduleOptions): Promise<void> {
throw new Error("Daily notifications are not supported on web platform");
}
/**
* Cancel scheduled daily notification
* @see PlatformService.cancelDailyNotification
* @throws Error - notifications not supported on web platform
*/
async cancelDailyNotification(): Promise<void> {
throw new Error("Daily notifications are not supported on web platform");
}
/**
* Configure native fetcher for background operations
* @see PlatformService.configureNativeFetcher
* @returns null - native fetcher not supported on web platform
*/
async configureNativeFetcher(
_config: NativeFetcherConfig,
): Promise<void | null> {
return null;
}
/**
* Update starred plans for background fetcher
* @see PlatformService.updateStarredPlans
* @returns null - native fetcher not supported on web platform
*/
async updateStarredPlans(_plans: {
planIds: string[];
}): Promise<void | null> {
return null;
}
/**
* Open the app's notification settings in the system settings
* @see PlatformService.openAppNotificationSettings
* @returns null - not supported on web platform
*/
async openAppNotificationSettings(): Promise<void | null> {
return null;
}
} }

5
src/views/AccountViewView.vue

@ -161,6 +161,9 @@
</section> </section>
<PushNotificationPermission ref="pushNotificationPermission" /> <PushNotificationPermission ref="pushNotificationPermission" />
<!-- Daily Notifications (Native) -->
<DailyNotificationSection />
<!-- User Profile --> <!-- User Profile -->
<section <section
v-if="isRegistered" v-if="isRegistered"
@ -790,6 +793,7 @@ import IdentitySection from "@/components/IdentitySection.vue";
import RegistrationNotice from "@/components/RegistrationNotice.vue"; import RegistrationNotice from "@/components/RegistrationNotice.vue";
import LocationSearchSection from "@/components/LocationSearchSection.vue"; import LocationSearchSection from "@/components/LocationSearchSection.vue";
import UsageLimitsSection from "@/components/UsageLimitsSection.vue"; import UsageLimitsSection from "@/components/UsageLimitsSection.vue";
import DailyNotificationSection from "@/components/notifications/DailyNotificationSection.vue";
import { import {
AppString, AppString,
DEFAULT_IMAGE_API_SERVER, DEFAULT_IMAGE_API_SERVER,
@ -858,6 +862,7 @@ interface UserNameDialogRef {
RegistrationNotice, RegistrationNotice,
LocationSearchSection, LocationSearchSection,
UsageLimitsSection, UsageLimitsSection,
DailyNotificationSection,
}, },
mixins: [PlatformServiceMixin], mixins: [PlatformServiceMixin],
}) })

Loading…
Cancel
Save