Files
Schnappix/src/services/storage.ts
T

62 lines
1.9 KiB
TypeScript

import { getPermissionsAsync, requestPermissionsAsync, createAssetAsync, getAlbumAsync, createAlbumAsync, addAssetsToAlbumAsync } from 'expo-media-library';
const ALBUM_NAME = 'Schnappix';
/**
* Request necessary media library permissions.
* @returns Promise<boolean> True if permissions are granted.
*/
export async function requestStoragePermission(): Promise<boolean> {
const { status, canAskAgain } = await getPermissionsAsync();
if (status === 'granted') {
return true;
}
if (canAskAgain) {
const { status: newStatus } = await requestPermissionsAsync();
return newStatus === 'granted';
}
return false;
}
/**
* Saves a local image file directly to the public DCIM gallery inside the "Schnappix" album.
*
* @param localUri The local file URI of the image (temp cached file).
* @returns Promise<string> The permanent URI of the saved asset in the gallery.
*/
export async function saveToGallery(localUri: string): Promise<string> {
const hasPermission = await requestStoragePermission();
if (!hasPermission) {
throw new Error('Storage permission not granted. Cannot save photo to gallery.');
}
// 1. Create a media asset from the local file
const asset = await createAssetAsync(localUri);
try {
// 2. Check if the "Schnappix" album already exists
const album = await getAlbumAsync(ALBUM_NAME);
if (!album) {
// 3. If it doesn't exist, create it with our asset
await createAlbumAsync(ALBUM_NAME, asset, false);
console.log(`Created new album "${ALBUM_NAME}" and saved photo.`);
} else {
// 4. If it exists, add our asset to it
await addAssetsToAlbumAsync([asset], album, false);
console.log(`Saved photo to existing album "${ALBUM_NAME}".`);
}
return asset.uri;
} catch (e: any) {
console.error('Error saving asset to album, returning fallback asset URI:', e);
try {
return asset.uri;
} catch {
return asset.id;
}
}
}