2022-08-19 13:24:29 +00:00
|
|
|
import * as FileSystem from 'expo-file-system';
|
|
|
|
|
2022-09-23 20:21:11 +00:00
|
|
|
import { sanitizeLikeString } from '../database/utils';
|
2022-08-19 13:24:29 +00:00
|
|
|
import { store } from '../store/auxStore';
|
|
|
|
import log from './helpers/log';
|
|
|
|
|
2023-01-14 10:07:25 +00:00
|
|
|
const DEFAULT_EXTENSION = 'mp3';
|
|
|
|
|
2022-09-23 20:21:11 +00:00
|
|
|
const sanitizeString = (value: string) => sanitizeLikeString(value.substring(value.lastIndexOf('/') + 1));
|
|
|
|
|
2023-01-14 10:07:25 +00:00
|
|
|
const getExtension = (value: string) => {
|
|
|
|
let extension = DEFAULT_EXTENSION;
|
|
|
|
const filename = value.split('/').pop();
|
|
|
|
if (filename?.includes('.')) {
|
|
|
|
extension = value.substring(value.lastIndexOf('.') + 1);
|
|
|
|
}
|
|
|
|
return extension;
|
2022-09-23 20:21:11 +00:00
|
|
|
};
|
|
|
|
|
2022-08-19 13:24:29 +00:00
|
|
|
const ensureDirAsync = async (dir: string, intermediates = true): Promise<void> => {
|
|
|
|
const info = await FileSystem.getInfoAsync(dir);
|
|
|
|
if (info.exists && info.isDirectory) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
await FileSystem.makeDirectoryAsync(dir, { intermediates });
|
|
|
|
return ensureDirAsync(dir, intermediates);
|
|
|
|
};
|
|
|
|
|
2022-09-23 20:21:11 +00:00
|
|
|
export const downloadAudioFile = async (url: string, fileUrl: string, messageId: string): Promise<string> => {
|
2022-08-19 13:24:29 +00:00
|
|
|
let path = '';
|
|
|
|
try {
|
|
|
|
const serverUrl = store.getState().server.server;
|
2022-09-23 20:21:11 +00:00
|
|
|
const serverUrlParsed = sanitizeString(serverUrl);
|
2022-08-19 13:24:29 +00:00
|
|
|
const folderPath = `${FileSystem.documentDirectory}audios/${serverUrlParsed}`;
|
2023-01-14 10:07:25 +00:00
|
|
|
const filename = `${messageId}.${getExtension(fileUrl)}`;
|
2022-09-23 20:21:11 +00:00
|
|
|
const filePath = `${folderPath}/${filename}`;
|
2022-08-19 13:24:29 +00:00
|
|
|
await ensureDirAsync(folderPath);
|
|
|
|
const file = await FileSystem.getInfoAsync(filePath);
|
|
|
|
if (!file.exists) {
|
|
|
|
const downloadedFile = await FileSystem.downloadAsync(url, filePath);
|
|
|
|
path = downloadedFile.uri;
|
|
|
|
} else {
|
|
|
|
path = file.uri;
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
log(error);
|
|
|
|
}
|
|
|
|
return path;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const deleteAllAudioFiles = async (serverUrl: string): Promise<void> => {
|
|
|
|
try {
|
2022-09-23 20:21:11 +00:00
|
|
|
const serverUrlParsed = sanitizeString(serverUrl);
|
2022-08-19 13:24:29 +00:00
|
|
|
const path = `${FileSystem.documentDirectory}audios/${serverUrlParsed}`;
|
2023-02-06 19:07:23 +00:00
|
|
|
await FileSystem.deleteAsync(path, { idempotent: true });
|
2022-08-19 13:24:29 +00:00
|
|
|
} catch (error) {
|
|
|
|
log(error);
|
|
|
|
}
|
|
|
|
};
|