1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-27 10:32:58 +02:00
joplin/packages/app-mobile/utils/fs-driver/fs-driver-rn.ts

367 lines
11 KiB
TypeScript
Raw Normal View History

import FsDriverBase, { ReadDirStatsOptions } from '@joplin/lib/fs-driver-base';
const RNFetchBlob = require('rn-fetch-blob').default;
2023-07-18 15:58:06 +02:00
import * as RNFS from 'react-native-fs';
import RNSAF, { DocumentFileDetail, openDocumentTree } from '@joplin/react-native-saf-x';
import { Platform } from 'react-native';
import tarCreate from './tarCreate';
import tarExtract from './tarExtract';
import JoplinError from '@joplin/lib/JoplinError';
const md5 = require('md5');
import { resolve } from 'path';
2023-07-18 15:58:06 +02:00
const ANDROID_URI_PREFIX = 'content://';
function isScopedUri(path: string) {
return path.includes(ANDROID_URI_PREFIX);
}
// Encodings supported by rn-fetch-blob, RNSAF, and
// RNFS.
// See also
// - https://github.com/itinance/react-native-fs#readfilefilepath-string-encoding-string-promisestring
// - https://github.com/joltup/rn-fetch-blob/blob/cf9e8843599de92031df2660d5a1da18491fa3c0/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java#L1049
export enum SupportedEncoding {
Utf8 = 'utf8',
Ascii = 'ascii',
Base64 = 'base64',
}
const supportedEncodings = Object.values<string>(SupportedEncoding);
// Converts some encodings specifiers that work with NodeJS into encodings
// that work with RNSAF, RNFetchBlob.fs, and RNFS.
//
// Throws if an encoding can't be normalized.
const normalizeEncoding = (encoding: string): SupportedEncoding => {
encoding = encoding.toLowerCase();
// rn-fetch-blob and RNSAF require the exact string "utf8", but NodeJS (and thus
// fs-driver-node) support variants on this like "UtF-8" and "utf-8". Convert them:
if (encoding === 'utf-8') {
encoding = 'utf8';
}
if (!supportedEncodings.includes(encoding)) {
throw new Error(`Unsupported encoding: ${encoding}.`);
}
return encoding as SupportedEncoding;
};
2021-01-27 19:42:58 +02:00
export default class FsDriverRN extends FsDriverBase {
public appendFileSync() {
throw new Error('Not implemented: appendFileSync');
}
// Requires that the file already exists.
// TODO: Update for compatibility with fs-driver-node's appendFile (which does not
// require that the file exists).
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public appendFile(path: string, content: any, rawEncoding = 'base64') {
const encoding = normalizeEncoding(rawEncoding);
if (isScopedUri(path)) {
return RNSAF.writeFile(path, content, { encoding, append: true });
}
return RNFS.appendFile(path, content, encoding);
}
// Encoding can be either "utf8", "utf-8", or "base64"
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public writeFile(path: string, content: any, rawEncoding = 'base64') {
const encoding = normalizeEncoding(rawEncoding);
if (isScopedUri(path)) {
return RNSAF.writeFile(path, content, { encoding: encoding });
}
// We need to use rn-fetch-blob here due to this bug:
// https://github.com/itinance/react-native-fs/issues/700
return RNFetchBlob.fs.writeFile(path, content, encoding);
}
// same as rm -rf
2021-01-27 19:42:58 +02:00
public async remove(path: string) {
2018-03-18 01:00:01 +02:00
return await this.unlink(path);
}
// Returns a format compatible with Node.js format
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2021-01-27 19:42:58 +02:00
private rnfsStatToStd_(stat: any, path: string) {
let birthtime;
const mtime = stat.lastModified ? new Date(stat.lastModified) : stat.mtime;
if (stat.lastModified) {
birthtime = new Date(stat.lastModified);
} else if (stat.ctime) {
// Confusingly, "ctime" normally means "change time" but here it's used as "creation time". Also sometimes it is null
birthtime = stat.ctime;
} else {
birthtime = stat.mtime;
}
return {
birthtime,
mtime,
isDirectory: () => stat.type ? stat.type === 'directory' : stat.isDirectory(),
path: path,
size: stat.size,
2019-07-29 15:43:53 +02:00
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2021-01-27 19:42:58 +02:00
public async readDirStats(path: string, options: any = null) {
if (!options) options = {};
if (!('recursive' in options)) options.recursive = false;
2019-07-29 15:43:53 +02:00
const isScoped = isScopedUri(path);
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2023-07-18 15:58:06 +02:00
let stats: any[] = [];
try {
if (isScoped) {
stats = await RNSAF.listFiles(path);
} else {
stats = await RNFS.readDir(path);
}
} catch (error) {
throw new Error(`Could not read directory: ${path}: ${error.message}`);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2021-01-27 19:42:58 +02:00
let output: any[] = [];
for (let i = 0; i < stats.length; i++) {
const stat = stats[i];
const relativePath = (isScoped ? stat.uri : stat.path).substr(path.length + 1);
2023-07-18 15:58:06 +02:00
const standardStat = this.rnfsStatToStd_(stat, relativePath);
output.push(standardStat);
if (isScoped) {
2023-07-18 15:58:06 +02:00
// readUriDirStatsHandleRecursion_ expects stat to have a URI property.
// Use the original stat.
output = await this.readUriDirStatsHandleRecursion_(stat, output, options);
} else {
2023-07-18 15:58:06 +02:00
output = await this.readDirStatsHandleRecursion_(path, standardStat, output, options);
}
}
return output;
}
protected async readUriDirStatsHandleRecursion_(stat: DocumentFileDetail, output: DocumentFileDetail[], options: ReadDirStatsOptions) {
if (options.recursive && stat.type === 'directory') {
const subStats = await this.readDirStats(stat.uri, options);
for (let j = 0; j < subStats.length; j++) {
const subStat = subStats[j];
output.push(subStat);
}
}
return output;
}
2021-01-27 19:42:58 +02:00
public async move(source: string, dest: string) {
if (isScopedUri(source) || isScopedUri(dest)) {
await RNSAF.moveFile(source, dest, { replaceIfDestinationExists: true });
}
return RNFS.moveFile(source, dest);
}
public async rename(source: string, dest: string) {
if (isScopedUri(source) || isScopedUri(dest)) {
await RNSAF.rename(source, dest);
}
return RNFS.moveFile(source, dest);
}
2021-01-27 19:42:58 +02:00
public async exists(path: string) {
if (isScopedUri(path)) {
return RNSAF.exists(path);
}
return RNFS.exists(path);
}
2021-01-27 19:42:58 +02:00
public async mkdir(path: string) {
if (isScopedUri(path)) {
await RNSAF.mkdir(path);
return;
}
2023-07-18 15:58:06 +02:00
// Also creates parent directories: Works like mkdir -p
return RNFS.mkdir(path);
}
2021-01-27 19:42:58 +02:00
public async stat(path: string) {
try {
let r;
if (isScopedUri(path)) {
r = await RNSAF.stat(path);
} else {
r = await RNFS.stat(path);
}
return this.rnfsStatToStd_(r, path);
} catch (error) {
2023-07-18 15:58:06 +02:00
if (error && (error.code === 'ENOENT' || !(await this.exists(path)))) {
// Probably { [Error: File does not exist] framesToPop: 1, code: 'EUNSPECIFIED' }
2023-07-18 15:58:06 +02:00
// or { [Error: The file {file} couldn’t be opened because there is no such file.], code: 'ENSCOCOAERRORDOMAIN260' }
// which unfortunately does not have a proper error code. Can be ignored.
return null;
} else {
throw error;
}
}
}
// NOTE: DOES NOT WORK - no error is thrown and the function is called with the right
// arguments but the function returns `false` and the timestamp is not set.
// Current setTimestamp is not really used so keep it that way, but careful if it
// becomes needed.
2021-01-27 19:42:58 +02:00
public async setTimestamp() {
// return RNFS.touch(path, timestampDate, timestampDate);
}
public async open(path: string, mode: string) {
if (isScopedUri(path)) {
throw new Error('open() not implemented in FsDriverAndroid');
}
// Note: RNFS.read() doesn't provide any way to know if the end of file has been reached.
// So instead we stat the file here and use stat.size to manually check for end of file.
// Bug: https://github.com/itinance/react-native-fs/issues/342
const stat = await this.stat(path);
return {
path: path,
offset: 0,
mode: mode,
stat: stat,
2019-07-29 15:43:53 +02:00
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public close(_handle: any): Promise<void> {
2021-01-27 19:42:58 +02:00
// Nothing
2021-09-06 18:05:27 +02:00
return null;
}
public readFile(path: string, rawEncoding = 'utf8') {
const encoding = normalizeEncoding(rawEncoding);
if (isScopedUri(path)) {
return RNSAF.readFile(path, { encoding: encoding });
}
return RNFS.readFile(path, encoding);
}
// Always overwrite destination
2021-01-27 19:42:58 +02:00
public async copy(source: string, dest: string) {
let retry = false;
try {
if (isScopedUri(source) || isScopedUri(dest)) {
await RNSAF.copyFile(source, dest, { replaceIfDestinationExists: true });
return;
}
await RNFS.copyFile(source, dest);
} catch (error) {
// On iOS it will throw an error if the file already exist
retry = true;
await this.unlink(dest);
}
if (retry) {
if (isScopedUri(source) || isScopedUri(dest)) {
await RNSAF.copyFile(source, dest, { replaceIfDestinationExists: true });
} else {
await RNFS.copyFile(source, dest);
}
}
}
2021-01-27 19:42:58 +02:00
public async unlink(path: string) {
try {
if (isScopedUri(path)) {
await RNSAF.unlink(path);
return;
}
await RNFS.unlink(path);
} catch (error) {
if (error && ((error.message && error.message.indexOf('exist') >= 0) || error.code === 'ENOENT')) {
// Probably { [Error: File does not exist] framesToPop: 1, code: 'EUNSPECIFIED' }
// which unfortunately does not have a proper error code. Can be ignored.
} else {
throw error;
}
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public async readFileChunk(handle: any, length: number, rawEncoding = 'base64') {
if (!handle?.stat) {
throw new JoplinError('File does not exist (reading file chunk).', 'ENOENT');
}
const encoding = normalizeEncoding(rawEncoding);
if (handle.offset + length > handle.stat.size) {
length = handle.stat.size - handle.offset;
}
if (!length) return null;
const output = await RNFS.read(handle.path, length, handle.offset, encoding);
// eslint-disable-next-line require-atomic-updates
handle.offset += length;
return output ? output : null;
}
public resolve(...paths: string[]): string {
return resolve(...paths);
Plugins: Added support for content scripts - For now, supports Markdown-it plugins - Also fixed slow rendering of notes in some cases - Simplified how Markdown-It plugins are created and cleaned MdToHtml code commit 89576de2896c99134f25f2a2db25008514cb1315 Merge: c75aa21f 5292fc14 Author: Laurent Cozic <laurent@cozic.net> Date: Wed Oct 21 00:23:00 2020 +0100 Merge branch 'release-1.3' into plugin_content_scripts commit c75aa21ffdc42764d71dc9deadba7a7ef4233995 Author: Laurent Cozic <laurent@cozic.net> Date: Wed Oct 21 00:19:52 2020 +0100 Fixed tests commit 075187729d11a16d385b651cbf1ebb89f14935e0 Author: Laurent Cozic <laurent@cozic.net> Date: Wed Oct 21 00:11:53 2020 +0100 Fixed tests commit 14696b8c651e7afdaf71269bcdbadf0d58d3ef8a Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 20 23:27:58 2020 +0100 Fixed slow rendering of note commit 61c09f5bf856481f91b00cfe87ff05596c63d4bc Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 20 22:35:21 2020 +0100 Clean up commit 9f7ea7d865a990b3a21cc8c59093390d9db61653 Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 20 20:05:31 2020 +0100 Updated doc commit 98bf3bde8d6663f2f91ff965304b4aac00bdd98b Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 20 19:56:34 2020 +0100 Finished converting plugins commit fe90d92e01427bd2b38200393713ea28763507a9 Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 20 17:52:02 2020 +0100 Simplified how Markdown-It plugins are created commit 47c7b864cbb864d5df79849f27625aecf312df4b Author: Laurent Cozic <laurent@cozic.net> Date: Mon Oct 19 16:40:11 2020 +0100 Clean up rules commit d927a238bb635a4be45f9216d776f7d07cb0a584 Author: Laurent Cozic <laurent@cozic.net> Date: Mon Oct 19 14:29:40 2020 +0100 Fixed tests commit 388a56c5dde4c382e3ee0035791137150adaba1b Author: Laurent Cozic <laurent@cozic.net> Date: Mon Oct 19 14:00:47 2020 +0100 Add support for content scripts
2020-10-21 01:23:55 +02:00
}
2021-01-27 19:42:58 +02:00
public async md5File(path: string): Promise<string> {
if (isScopedUri(path)) {
// Warning: Slow
const fileData = Buffer.from(await this.readFile(path, 'base64'), 'base64');
return md5(fileData);
} else {
return await RNFS.hash(path, 'md5');
}
2021-01-27 19:42:58 +02:00
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public async tarExtract(options: any) {
await tarExtract({
cwd: RNFS.DocumentDirectoryPath,
...options,
});
2023-07-18 15:58:06 +02:00
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2023-07-18 15:58:06 +02:00
public async tarCreate(options: any, filePaths: string[]) {
await tarCreate({
cwd: RNFS.DocumentDirectoryPath,
...options,
}, filePaths);
2023-07-18 15:58:06 +02:00
}
public async getExternalDirectoryPath(): Promise<string | undefined> {
let directory;
if (this.isUsingAndroidSAF()) {
const doc = await openDocumentTree(true);
if (doc?.uri) {
directory = doc?.uri;
}
} else {
directory = RNFS.ExternalDirectoryPath;
}
return directory;
}
public getCacheDirectoryPath() {
return RNFS.CachesDirectoryPath;
}
public getAppDirectoryPath() {
return RNFetchBlob.fs.dirs.DocumentDir;
}
public isUsingAndroidSAF() {
return Platform.OS === 'android' && Platform.Version > 28;
}
2021-01-27 19:42:58 +02:00
}