import { addFileScheme } from "@/utils/fileUtils";
import getOrCreateMMKV from "@/utils/getOrCreateMMKV";
import { safeParse } from "@/utils/jsonUtil";
import { getMediaUniqueKey } from "@/utils/mediaUtils";
import { exists, unlink } from "react-native-fs";
const mediaCacheStore = getOrCreateMMKV("cache.MediaCache", true);
const maxCacheCount = 800;
const getMediaCache = (mediaItem: ICommon.IMediaBase) => {
if (mediaItem.platform && mediaItem.id) {
const cacheMediaItem = mediaCacheStore.getString(
getMediaUniqueKey(mediaItem),
);
return cacheMediaItem
? safeParse<ICommon.IMediaBase>(cacheMediaItem)
: null;
}
return null;
};
const setMediaCache = (mediaItem: ICommon.IMediaBase) => {
if (mediaItem.platform && mediaItem.id) {
const allKeys = mediaCacheStore.getAllKeys();
if (allKeys.length >= maxCacheCount) {
for (let i = 0; i < maxCacheCount / 2; ++i) {
const rawCacheMedia = mediaCacheStore.getString(allKeys[i]);
const cacheData = rawCacheMedia
? safeParse(rawCacheMedia)
: null;
clearLocalCaches(cacheData);
mediaCacheStore.delete(allKeys[i]);
}
}
mediaCacheStore.set(getMediaUniqueKey(mediaItem), JSON.stringify(mediaItem));
return true;
}
return false;
};
async function clearLocalCaches(cacheData: IMusic.IMusicItemCache) {
if (cacheData.$localLyric) {
await checkPathAndRemove(cacheData.$localLyric.rawLrc);
await checkPathAndRemove(cacheData.$localLyric.translation);
}
}
async function checkPathAndRemove(filePath?: string) {
if (!filePath) {
return;
}
filePath = addFileScheme(filePath);
if (await exists(filePath)) {
unlink(filePath);
}
}
const removeMediaCache = (mediaItem: ICommon.IMediaBase) => {
if (mediaItem.platform && mediaItem.id) {
mediaCacheStore.delete(getMediaUniqueKey(mediaItem));
}
return false;
};
const MediaCache = {
getMediaCache,
setMediaCache,
removeMediaCache,
};
export default MediaCache;