78 lines
2.1 KiB
TypeScript
78 lines
2.1 KiB
TypeScript
import { NavigationProp } from '@react-navigation/native';
|
|
import { AndroidScoped, Dirs, FileSystem } from 'react-native-file-access';
|
|
import Share from 'react-native-share';
|
|
import Clipboard from '@react-native-clipboard/clipboard';
|
|
import { Meme } from '../database';
|
|
import { ROUTE, RootStackParamList } from '../types';
|
|
import { noOp } from './constants';
|
|
|
|
const favoriteMeme = (realm: Realm, meme: Meme) => {
|
|
realm.write(() => {
|
|
meme.isFavorite = !meme.isFavorite;
|
|
});
|
|
};
|
|
|
|
const shareMeme = async (realm: Realm, storageUri: string, meme: Meme) => {
|
|
const uri = AndroidScoped.appendPath(storageUri, meme.filename);
|
|
const cacheUri = `${Dirs.CacheDir}/${meme.filename}`;
|
|
|
|
realm.write(() => {
|
|
meme.dateUsed = new Date();
|
|
meme.timesUsed += 1;
|
|
meme.tags.forEach(tag => {
|
|
tag.dateUsed = new Date();
|
|
tag.timesUsed += 1;
|
|
});
|
|
});
|
|
|
|
await FileSystem.cp(uri, cacheUri);
|
|
await Share.open({
|
|
url: `file://${cacheUri}`,
|
|
type: meme.mimeType,
|
|
failOnCancel: false,
|
|
});
|
|
};
|
|
|
|
const copyMeme = async (realm: Realm, storageUri: string, meme: Meme) => {
|
|
const uri = AndroidScoped.appendPath(storageUri, meme.filename);
|
|
|
|
const exists = await FileSystem.exists(uri);
|
|
if (!exists) throw new Error('File does not exist');
|
|
|
|
realm.write(() => {
|
|
meme.dateUsed = new Date();
|
|
meme.timesUsed += 1;
|
|
meme.tags.forEach(tag => {
|
|
tag.dateUsed = new Date();
|
|
tag.timesUsed += 1;
|
|
});
|
|
});
|
|
|
|
Clipboard.setURI(uri);
|
|
};
|
|
|
|
const editMeme = (
|
|
navigation: NavigationProp<RootStackParamList>,
|
|
meme: Meme,
|
|
) => {
|
|
navigation.navigate(ROUTE.EDIT_MEME, { id: meme.id.toHexString() });
|
|
};
|
|
|
|
const deleteMeme = async (realm: Realm, storageUri: string, meme: Meme) => {
|
|
const uri = AndroidScoped.appendPath(storageUri, meme.filename);
|
|
|
|
await FileSystem.unlink(uri).catch(noOp);
|
|
|
|
realm.write(() => {
|
|
for (const tag of meme.tags) {
|
|
tag.dateModified = new Date();
|
|
tag.memes.slice(tag.memes.indexOf(meme), 1);
|
|
tag.memesLength -= 1;
|
|
}
|
|
|
|
realm.delete(meme);
|
|
});
|
|
};
|
|
|
|
export { favoriteMeme, shareMeme, copyMeme, editMeme, deleteMeme };
|