import {Platform} from "react-native" import {check, request, PERMISSIONS, RESULTS} from "react-native-permissions" import CrustModule from "@mentra/crust" import {deriveGalleryDisplayName} from "./galleryDisplayName" export interface MediaLibrarySaveReceipt { success: boolean platform: "ios" | "android" | "unknown" uri?: string identifier?: string error?: string } /** * MediaLibraryPermissions - Handles save-only permissions for camera roll * * Platform behavior: * - iOS: Uses PHOTO_LIBRARY (read-write) so we can manage the MentraOS album * - Android 10+ (API 29+): No permission needed to save your own files to MediaStore * - Android 9-: Uses WRITE_EXTERNAL_STORAGE (legacy) */ export class MediaLibraryPermissions { /** Limited iOS access cannot see historical, unselected assets for duplicate reconciliation. */ static async hasLimitedAccess(): Promise { if (Platform.OS !== "ios") return false try { return (await check(PERMISSIONS.IOS.PHOTO_LIBRARY)) === RESULTS.LIMITED } catch (error) { console.error("[MediaLibrary] Error checking limited-library access:", error) // Conservatively block legacy reconciliation when the scope cannot be verified. return true } } /** * Check if we have permission to save to the camera roll * Note: On Android 10+, this always returns true since no permission is needed */ static async checkPermission(): Promise { try { if (Platform.OS === "ios") { const status = await check(PERMISSIONS.IOS.PHOTO_LIBRARY) return status === RESULTS.GRANTED || status === RESULTS.LIMITED } if (Platform.OS === "android") { // Android 10+ (API 29+): No permission needed to save your own files if (Platform.Version >= 29) { return true } // Android 9 and below: Check legacy write permission const status = await check(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE) return status === RESULTS.GRANTED } return false } catch (error) { console.error("[MediaLibrary] Error checking permission:", error) // On error, assume we can try (Android 10+ doesn't need permission anyway) return Platform.OS === "android" && Platform.Version >= 29 } } /** * Request permission to save to the camera roll * Note: On Android 10+, this always returns true since no permission is needed */ static async requestPermission(): Promise { try { if (Platform.OS === "ios") { const status = await request(PERMISSIONS.IOS.PHOTO_LIBRARY) return status === RESULTS.GRANTED || status === RESULTS.LIMITED } if (Platform.OS === "android") { // Android 10+ (API 29+): No permission needed to save your own files if (Platform.Version >= 29) { return true } // Android 9 and below: Request legacy write permission const status = await request(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE) return status === RESULTS.GRANTED } return false } catch (error) { console.error("[MediaLibrary] Error requesting permission:", error) // On error, assume we can try (Android 10+ doesn't need permission anyway) return Platform.OS === "android" && Platform.Version >= 29 } } /** * Save a file to the photo library in a glasses-specific location (MentraOS album on iOS; * Pictures/MentraOS or Movies/MentraOS on Android 10+). * On Android 10+, this works without any permission. * * IMPORTANT: This method sets the DATE_TAKEN (Android) or creation date (iOS) * metadata to the original capture time, so gallery apps show the correct date. * Also saves files in chronological order for proper "date added" ordering. * * @param filePath - Path to the file to save * @param creationTime - Optional creation/capture time in milliseconds (Unix timestamp) */ static async saveToLibrary(filePath: string, creationTime?: number): Promise { return (await this.saveToLibraryWithReceipt(filePath, creationTime)).success } /** Save and return the durable MediaStore/PhotoKit identifier used as the export receipt. */ static async saveToLibraryWithReceipt(filePath: string, creationTime?: number): Promise { const platform = Platform.OS === "ios" || Platform.OS === "android" ? Platform.OS : "unknown" try { // On Android 10+, we can save without permission // On iOS and older Android, check permission first if (!(Platform.OS === "android" && Platform.Version >= 29)) { const hasPermission = await this.checkPermission() if (!hasPermission) { // Try requesting permission one more time const granted = await this.requestPermission() if (!granted) { console.warn("[MediaLibrary] No permission to save to library - photos saved to app storage only") return {success: false, platform, error: "permission denied"} } } } // Remove file:// prefix if present const cleanPath = filePath.replace("file://", "") const displayName = deriveGalleryDisplayName(cleanPath) // Use native module to save with proper DATE_TAKEN / creation date metadata // This ensures gallery apps show the correct capture date, not the sync date const result = await CrustModule.saveToGalleryWithDate(cleanPath, creationTime, displayName) if (result.success) { if (creationTime) { const captureDate = new Date(creationTime) console.log( `[MediaLibrary] Saved to camera roll with DATE_TAKEN: ${cleanPath} (captured: ${captureDate.toISOString()})`, ) } else { console.log(`[MediaLibrary] Saved to camera roll: ${cleanPath}`) } return { success: true, platform, uri: result.uri, identifier: result.identifier, } } else { console.error(`[MediaLibrary] Failed to save to library: ${result.error}`) return {success: false, platform, error: result.error || "native export failed"} } } catch (error) { console.error("[MediaLibrary] Error saving to library:", error) return {success: false, platform, error: error instanceof Error ? error.message : String(error)} } } }