UNPKG

react-native-cloud-store

Version:
457 lines (427 loc) 15.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DownloadStatus = void 0; exports.copy = copy; exports.createDir = createDir; exports.defaultICloudContainerPath = void 0; exports.download = download; exports.evictUbiquitousItem = evictUbiquitousItem; exports.exist = exist; exports.getDefaultICloudContainerPath = getDefaultICloudContainerPath; exports.getICloudURL = getICloudURL; exports.getUrlForPublishingUbiquitousItem = getUrlForPublishingUbiquitousItem; exports.isICloudAvailable = isICloudAvailable; exports.moveDir = moveDir; exports.onICloudDocumentsFinishGathering = onICloudDocumentsFinishGathering; exports.onICloudDocumentsGathering = onICloudDocumentsGathering; exports.onICloudDocumentsStartGathering = onICloudDocumentsStartGathering; exports.onICloudDocumentsUpdateGathering = onICloudDocumentsUpdateGathering; exports.onICloudIdentityDidChange = onICloudIdentityDidChange; exports.readDir = readDir; exports.readFile = readFile; exports.registerGlobalDownloadEvent = registerGlobalDownloadEvent; exports.registerGlobalUploadEvent = registerGlobalUploadEvent; exports.registerICloudIdentityDidChangeEvent = registerICloudIdentityDidChangeEvent; exports.setUbiquitous = setUbiquitous; exports.startDownloadingUbiquitousItem = startDownloadingUbiquitousItem; exports.stat = stat; exports.unlink = unlink; exports.upload = upload; exports.writeFile = writeFile; var _reactNative = require("react-native"); var _module = _interopRequireWildcard(require("./module")); var _path = require("./path"); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } function getConstants() { return _reactNative.Platform.OS === 'ios' ? _module.default.getConstants() : {}; } /** * A full icloud path string without schema, for example: * - ✅ `/path/to/icloud-container/my/file.txt` * - ❌ `file:///path/to/icloud-container/my/file.txt` * - ❌ `my/file.txt` * - ❌ `/my/file.txt` */ /** * A full file path string with or without schema, for example: * - ✅ `/path/to/app/documents/my/file.txt` * - ✅ `file:///path/to/app/documents/my/file.txt` * - ❌ `/my/file.txt` */ /** * Check whether icloud is available. This will return `false` when: * - user disabled your app from accessing icloud drive in system settings * - user did not log in with apple id * * @group Group Base */ async function isICloudAvailable() { return _module.default.isICloudAvailable(); } /** * Get the default icloud container url which is the first container selected in (xcode) settings. * * This would be an empty string or undefined if cannot get it, for example: * - the developer did not create a icloud container * - the developer did not choose a icloud container * * :::caution * The value of this property was set on app startup and will not change even if user disabled or enabled icloud later while your app was running, you can use {@link getDefaultICloudContainerPath} to get the always-new data. * ::: * @category iCloud */ const defaultICloudContainerPath = exports.defaultICloudContainerPath = getConstants().defaultICloudContainerPath; /** * Get current default container url. This function will always return the newest path or `undefined` if it cannot get it. * * @category Base */ async function getDefaultICloudContainerPath() { return _reactNative.Platform.OS === 'ios' ? _module.default.getDefaultICloudContainerPath() : undefined; } /** * Get path from specific container id * * @category Base */ async function getICloudURL(containerIdentifier) { return _module.default.getICloudURL(containerIdentifier); } /** * When `onProgress` option provided, make sure you have called {@link registerGlobalUploadEvent} at the beginning of your app * @group Group File */ async function writeFile(path, content, options) { let canProgress = false; if (options !== null && options !== void 0 && options.onProgress) { if (!calledGlobalUploadEvent) { console.error(`You didn't call registerGlobalUploadEvent(), onProgress will not be triggered `); } else { uploadId++; uploadId2CallbackDataMap[uploadId] = { path: path, callback: options.onProgress }; canProgress = true; } } return _module.default.writeFile(path, content, { ...options, id: canProgress ? uploadId.toString() : undefined }); } /** * Return utf8 string * @category File */ async function readFile(path) { return _module.default.readFile(path); } /** * Read files/directories under the provided path * @category Directory */ async function readDir(path) { return _module.default.readDir(path); } /** * * @category Directory */ async function createDir(path) { return _module.default.createDir(path); } /** * * @category Directory */ async function moveDir(pathFrom, pathTo) { return _module.default.moveDir(pathFrom, pathTo); } /** * Copy the file or directory * @category File / Directory */ async function copy(pathFrom, pathTo, options) { return _module.default.copy(pathFrom, pathTo, { ...options }); } /** * Delete the file or directory. deleting items from iCloud can’t be undone. Once deleted, the item is gone forever. * @category File / Directory */ async function unlink(path) { return _module.default.unlink(path); } /** * Check whether the file or directory exists * @category File / Directory */ async function exist(path) { return _module.default.exist(path); } /** * Values that describe the iCloud storage state of a file. ([official doc](https://developer.apple.com/documentation/foundation/urlubiquitousitemdownloadingstatus)) */ let DownloadStatus = exports.DownloadStatus = /*#__PURE__*/function (DownloadStatus) { DownloadStatus["current"] = "NSURLUbiquitousItemDownloadingStatusCurrent"; DownloadStatus["downloaded"] = "NSURLUbiquitousItemDownloadingStatusDownloaded"; DownloadStatus["notDownloaded"] = "NSURLUbiquitousItemDownloadingStatusNotDownloaded"; return DownloadStatus; }({}); /** * File/Directory detailed info */ /** * Get the detailed info of the file/directory * @param path * @category File / Directory */ async function stat(path) { return _module.default.stat(path); } /** * A wrapper of [evictUbiquitousItem](https://developer.apple.com/documentation/foundation/filemanager/1409696-evictubiquitousitem) * * Removes the local copy of the file or directory that’s stored in iCloud. This doesn't delete the file or directory, you should use {@link unlink} if you want to delete it permanently */ async function evictUbiquitousItem(path) { return _module.default.evictUbiquitousItem(path); } /** * A wrapper of [startDownloadingUbiquitousItem](https://developer.apple.com/documentation/foundation/filemanager/1410377-startdownloadingubiquitousitem) * * Starts downloading (if necessary) the specified item to the local system. */ async function startDownloadingUbiquitousItem(path) { return _module.default.startDownloadingUbiquitousItem(path); } /** * A wrapper of [setUbiquitous](https://developer.apple.com/documentation/foundation/filemanager/1413989-setubiquitous) * * Indicates whether the item at the specified URL should be stored in iCloud. * * @param flag - `true` to move the item to iCloud or `false` to remove it from iCloud (if it is there currently). * @param path - The path of the item (file or directory) that you want to store in iCloud. * @param destPath - If moving a file into iCloud, it's the location in iCloud at which to store the file or directory. If moving a file out of iCloud, it's the location on the local device. */ async function setUbiquitous(flag, path, destPath) { return _module.default.setUbiquitous(flag, path, destPath); } /** * A wrapper of [url(forPublishingUbiquitousItemAt..)](https://developer.apple.com/documentation/foundation/filemanager/1411577-url) * * Returns a URL that can be emailed to users to allow them to download a copy of a flat file item from iCloud. Your app must have access to the network for this call to succeed. * * @param path - The path in the cloud that you want to share. The file at the specified path must already be uploaded to iCloud when you call this method. * @param expirationTimestamp - Timestamp of the expiration date */ async function getUrlForPublishingUbiquitousItem(path, expirationTimestamp) { return _module.default.getUrlForPublishingUbiquitousItem(path, expirationTimestamp ?? -1); } let calledGlobalUploadEvent = false; let uploadId = 0; const uploadId2CallbackDataMap = {}; let calledGlobalDownloadEvent = false; let downloadId = 0; const downloadId2CallbackDataMap = {}; /** * Upload the local file from the app to iCloud container, `icloudPath` should not exist before uploading or it will throw error * :::info * This function will be resolved immediately, if your want to wait until uploaded, you can wrap it with `Promise` yourself * ::: */ async function upload(localPath, path, options) { uploadId++; if (options !== null && options !== void 0 && options.onProgress) { if (!calledGlobalUploadEvent) { console.error(`You didn't call registerGlobalUploadEvent(), onProgress will not be triggered `); } uploadId2CallbackDataMap[uploadId] = { path: path, callback: options.onProgress }; } return _module.default.upload(u(localPath), path, { id: uploadId.toString() }); } /** * Download file in the icloud. * If you want to put the file in the icloud to your application directories, you must download it and then move/copy the file. * :::info * This function will be resolved immediately, if your want to wait until uploaded, you can wrap it with Promise yourself * ::: * @param path * @param options */ async function download(path, options) { downloadId++; const pathWithoutDot = _path.PathUtils.iCloudRemoveDotExt(path); if (options !== null && options !== void 0 && options.onProgress) { if (!calledGlobalDownloadEvent) { console.error(`You didn't call registerGlobalDownloadEvent(), onProgress will not be triggered `); } downloadId2CallbackDataMap[downloadId] = { path: pathWithoutDot, callback: options.onProgress }; } return _module.default.download(path, { id: downloadId.toString(), pathWithoutDot }); } // TODO: upload and download logic need to be refactored to be more flexible /** * Call this function at the beginning once to make `onProgress` callback of `upload`/`writeFile` work */ function registerGlobalUploadEvent() { if (calledGlobalUploadEvent) { return; } calledGlobalUploadEvent = true; function onGatheringCallback(data) { const callbackData = uploadId2CallbackDataMap[data.id]; if (!callbackData) return; const { path, callback } = callbackData; const uploadTarget = data.detail.find(i => i.type === 'upload' && i.path === path); if (uploadTarget) { const progress = uploadTarget.progress ?? 0; if (progress === 100) { delete uploadId2CallbackDataMap[uploadId]; } callback({ progress: progress }); } } const gatheringListener = onICloudDocumentsGathering(onGatheringCallback); const gatheringUpdateListener = onICloudDocumentsUpdateGathering(onGatheringCallback); const gatheringFinishListener = onICloudDocumentsFinishGathering(onGatheringCallback); return { remove() { gatheringListener.remove(); gatheringUpdateListener.remove(); gatheringFinishListener.remove(); calledGlobalUploadEvent = false; } }; } /** * Call this function at the beginning once to make `onProgress` callback of `download` work */ function registerGlobalDownloadEvent() { if (calledGlobalDownloadEvent) { return; } calledGlobalDownloadEvent = true; function onGatheringCallback(data) { const callbackData = downloadId2CallbackDataMap[data.id]; if (!callbackData) return; const { path, callback } = callbackData; const downloadTarget = data.detail.find(i => i.type === 'download' && i.path === path); if (downloadTarget) { const progress = downloadTarget.progress ?? 0; if (progress === 100) { delete downloadId2CallbackDataMap[uploadId]; } callback({ progress: progress }); } } const gatheringListener = onICloudDocumentsGathering(onGatheringCallback); const gatheringUpdateListener = onICloudDocumentsUpdateGathering(onGatheringCallback); const gatheringFinishListener = onICloudDocumentsFinishGathering(onGatheringCallback); return { remove() { gatheringListener.remove(); gatheringUpdateListener.remove(); gatheringFinishListener.remove(); calledGlobalDownloadEvent = false; } }; } /** * This event only emits at the first search phase * @category Events */ function onICloudDocumentsStartGathering(fn) { return _module.eventEmitter.addListener('onICloudDocumentsStartGathering', nativeData => { fn(nativeData); }); } /** * This event only emits at the first search phase * @param fn * @category Events */ function onICloudDocumentsGathering(fn) { return _module.eventEmitter.addListener('onICloudDocumentsGathering', fn); } /** * This event only emits at the first search phase * @category Events */ function onICloudDocumentsFinishGathering(fn) { return _module.eventEmitter.addListener('onICloudDocumentsFinishGathering', fn); } /** * This event emits when upload/download progress updated. * :::info * `download` and `upload` have supported `onProgress`, so this event is not needed if you don't have special needs * ::: * * @category Events */ function onICloudDocumentsUpdateGathering(fn) { return _module.eventEmitter.addListener('onICloudDocumentsUpdateGathering', fn); } function u(path) { let prefix = 'file://'; if (path.startsWith(prefix)) { path = path.slice(prefix.length); } return path; } let calledIdentityDidChangeEvent = false; /** * Call this function at the beginning once to make `onICloudIdentityDidChange` event work */ function registerICloudIdentityDidChangeEvent() { if (calledIdentityDidChangeEvent) { return; } calledIdentityDidChangeEvent = true; _module.default.listenICloudNSUbiquityIdentityDidChange(); return { remove() { _module.default.unlistenICloudNSUbiquityIdentityDidChange(); calledIdentityDidChangeEvent = false; } }; } /** * Rarely used event. * From the [official doc](https://developer.apple.com/documentation/foundation/nsnotification/name/1407629-nsubiquityidentitydidchange): The system generates this notification when the user logs into or out of an iCloud account or enables or disables the syncing of documents and data. when the user logs into or out of an iCloud account or enables or disables the syncing of documents and data. * * @category Events */ function onICloudIdentityDidChange(fn) { if (!calledIdentityDidChangeEvent) { console.error(`You didn't call registerICloudIdentityDidChangeEvent(), this listener will not trigger`); } return _module.eventEmitter.addListener('onICloudIdentityDidChange', fn); } //# sourceMappingURL=icloud.js.map