refactor handleMediaDownload and deleteMedia

This commit is contained in:
Reinaldo Neto 2023-06-07 17:15:44 -03:00
parent 8c0c1d7dc0
commit 989e609165
2 changed files with 27 additions and 29 deletions

View File

@ -6,26 +6,23 @@ import { sanitizeLikeString } from '../database/utils';
import { store } from '../store/auxStore'; import { store } from '../store/auxStore';
import log from './helpers/log'; import log from './helpers/log';
export enum MediaTypes { export type MediaTypes = 'audio' | 'image' | 'video';
audio = 'audio',
image = 'image',
video = 'video'
}
const typeString = { const typeString = {
[MediaTypes.audio]: 'audios/', audio: 'audios/',
[MediaTypes.image]: 'images/', image: 'images/',
[MediaTypes.video]: 'videos/' video: 'videos/'
}; };
const defaultType = { const defaultType = {
[MediaTypes.audio]: 'mp3', audio: 'mp3',
[MediaTypes.image]: 'jpg', image: 'jpg',
[MediaTypes.video]: 'mp4' video: 'mp4'
}; };
const downloadQueue: { [index: string]: FileSystem.DownloadResumable } = {}; const downloadQueue: { [index: string]: FileSystem.DownloadResumable } = {};
export const mediaDownloadKey = (mediaType: MediaTypes, messageId: string) => `${mediaType}-${messageId}`; export const mediaDownloadKey = (mediaType: MediaTypes, downloadUrl: string) => `${mediaType}-${sanitizeString(downloadUrl)}`;
export function isDownloadActive(mediaType: MediaTypes, messageId: string): boolean { export function isDownloadActive(mediaType: MediaTypes, messageId: string): boolean {
return !!downloadQueue[mediaDownloadKey(mediaType, messageId)]; return !!downloadQueue[mediaDownloadKey(mediaType, messageId)];
@ -45,18 +42,16 @@ export async function cancelDownload(mediaType: MediaTypes, messageId: string):
export function downloadMediaFile({ export function downloadMediaFile({
mediaType, mediaType,
messageId,
downloadUrl, downloadUrl,
path path
}: { }: {
mediaType: MediaTypes; mediaType: MediaTypes;
messageId: string;
downloadUrl: string; downloadUrl: string;
path: string; path: string;
}): Promise<string> { }): Promise<string> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
const downloadKey = mediaDownloadKey(mediaType, messageId); const downloadKey = mediaDownloadKey(mediaType, downloadUrl);
downloadQueue[downloadKey] = FileSystem.createDownloadResumable(downloadUrl, path); downloadQueue[downloadKey] = FileSystem.createDownloadResumable(downloadUrl, path);
const result = await downloadQueue[downloadKey].downloadAsync(); const result = await downloadQueue[downloadKey].downloadAsync();
if (result?.uri) { if (result?.uri) {
@ -71,7 +66,11 @@ export function downloadMediaFile({
export const LOCAL_DOCUMENT_PATH = `${FileSystem.documentDirectory}`; export const LOCAL_DOCUMENT_PATH = `${FileSystem.documentDirectory}`;
const sanitizeString = (value: string) => sanitizeLikeString(value.substring(value.lastIndexOf('/') + 1)); const sanitizeString = (value: string) => {
const urlWithoutQueryString = value.split('?')[0];
return sanitizeLikeString(urlWithoutQueryString.substring(urlWithoutQueryString.lastIndexOf('/') + 1));
};
const serverUrlParsedAsPath = (serverURL: string) => `${sanitizeString(serverURL)}/`;
const getExtension = (type: MediaTypes, mimeType?: string) => { const getExtension = (type: MediaTypes, mimeType?: string) => {
if (!mimeType) { if (!mimeType) {
@ -105,21 +104,22 @@ const ensureDirAsync = async (dir: string, intermediates = true): Promise<void>
export const searchMediaFileAsync = async ({ export const searchMediaFileAsync = async ({
type, type,
mimeType, mimeType,
messageId urlToCache
}: { }: {
type: MediaTypes; type: MediaTypes;
mimeType?: string; mimeType?: string;
messageId: string; urlToCache: string;
}) => { }) => {
let file; let file;
let filePath = ''; let filePath = '';
try { try {
const serverUrl = store.getState().server.server; const serverUrl = store.getState().server.server;
const serverUrlParsed = sanitizeString(serverUrl); const serverUrlParsed = serverUrlParsedAsPath(serverUrl);
const folderPath = `${LOCAL_DOCUMENT_PATH}${typeString[type]}${serverUrlParsed}`; const folderPath = `${LOCAL_DOCUMENT_PATH}${serverUrlParsed}${typeString[type]}`;
const filename = `${messageId}.${getExtension(type, mimeType)}`; const fileUrlSanitized = sanitizeString(urlToCache);
filePath = `${folderPath}/${filename}`; const filename = `${fileUrlSanitized}.${getExtension(type, mimeType)}`;
filePath = `${folderPath}${filename}`;
await ensureDirAsync(folderPath); await ensureDirAsync(folderPath);
file = await FileSystem.getInfoAsync(filePath); file = await FileSystem.getInfoAsync(filePath);
} catch (e) { } catch (e) {
@ -128,10 +128,10 @@ export const searchMediaFileAsync = async ({
return { file, filePath }; return { file, filePath };
}; };
export const deleteMediaFiles = async (type: MediaTypes, serverUrl: string): Promise<void> => { export const deleteMediaFiles = async (serverUrl: string): Promise<void> => {
try { try {
const serverUrlParsed = sanitizeString(serverUrl); const serverUrlParsed = serverUrlParsedAsPath(serverUrl);
const path = `${LOCAL_DOCUMENT_PATH}${typeString[type]}${serverUrlParsed}`; const path = `${LOCAL_DOCUMENT_PATH}${serverUrlParsed}`;
await FileSystem.deleteAsync(path, { idempotent: true }); await FileSystem.deleteAsync(path, { idempotent: true });
} catch (error) { } catch (error) {
log(error); log(error);

View File

@ -21,7 +21,7 @@ import { APP_STORE_LINK, FDROID_MARKET_LINK, isFDroidBuild, LICENSE_LINK, PLAY_M
import database from '../../lib/database'; import database from '../../lib/database';
import { useAppSelector } from '../../lib/hooks'; import { useAppSelector } from '../../lib/hooks';
import { clearCache } from '../../lib/methods'; import { clearCache } from '../../lib/methods';
import { deleteMediaFiles, MediaTypes } from '../../lib/methods/handleMediaDownload'; import { deleteMediaFiles } from '../../lib/methods/handleMediaDownload';
import { getDeviceModel, getReadableVersion, isAndroid } from '../../lib/methods/helpers'; import { getDeviceModel, getReadableVersion, isAndroid } from '../../lib/methods/helpers';
import EventEmitter from '../../lib/methods/helpers/events'; import EventEmitter from '../../lib/methods/helpers/events';
import { showConfirmationAlert, showErrorAlert } from '../../lib/methods/helpers/info'; import { showConfirmationAlert, showErrorAlert } from '../../lib/methods/helpers/info';
@ -99,9 +99,7 @@ const SettingsView = (): React.ReactElement => {
confirmationText: I18n.t('Clear'), confirmationText: I18n.t('Clear'),
onPress: async () => { onPress: async () => {
dispatch(appStart({ root: RootEnum.ROOT_LOADING, text: I18n.t('Clear_cache_loading') })); dispatch(appStart({ root: RootEnum.ROOT_LOADING, text: I18n.t('Clear_cache_loading') }));
await deleteMediaFiles(MediaTypes.image, server); await deleteMediaFiles(server);
await deleteMediaFiles(MediaTypes.audio, server);
await deleteMediaFiles(MediaTypes.video, server);
await clearCache({ server }); await clearCache({ server });
await FastImage.clearMemoryCache(); await FastImage.clearMemoryCache();
await FastImage.clearDiskCache(); await FastImage.clearDiskCache();