diff --git a/backend/package.json b/backend/package.json index 6a940bca..7a58fc5b 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.21.65", + "version": "2.21.66", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "scripts": { diff --git a/backend/src/constants.js b/backend/src/constants.js index 0003e976..30492b55 100644 --- a/backend/src/constants.js +++ b/backend/src/constants.js @@ -7,6 +7,7 @@ export const MODULES_KEY = 'modules'; export const ARTIFACTS_KEY = 'artifacts'; export const RULES_KEY = 'rules'; export const TOKENS_KEY = 'tokens'; +export const ARCHIVES_KEY = 'archives'; export const GIST_BACKUP_KEY = 'Auto Generated Sub-Store Backup'; export const GIST_BACKUP_FILE_NAME = 'Sub-Store'; export const ARTIFACT_REPOSITORY_KEY = 'Sub-Store Artifacts Repository'; diff --git a/backend/src/core/proxy-utils/parsers/peggy/loon.js b/backend/src/core/proxy-utils/parsers/peggy/loon.js index 480e1173..58f5fd16 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/loon.js +++ b/backend/src/core/proxy-utils/parsers/peggy/loon.js @@ -1,4 +1,4 @@ -import * as peggy from 'peggy'; +import peggy from 'peggy'; const grammars = String.raw` // global initializer {{ diff --git a/backend/src/core/proxy-utils/parsers/peggy/qx.js b/backend/src/core/proxy-utils/parsers/peggy/qx.js index 5aeb26b7..fb2caa72 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/qx.js +++ b/backend/src/core/proxy-utils/parsers/peggy/qx.js @@ -1,4 +1,4 @@ -import * as peggy from 'peggy'; +import peggy from 'peggy'; const grammars = String.raw` // global initializer {{ diff --git a/backend/src/core/proxy-utils/parsers/peggy/surge.js b/backend/src/core/proxy-utils/parsers/peggy/surge.js index 889df467..ec8c22fb 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/surge.js +++ b/backend/src/core/proxy-utils/parsers/peggy/surge.js @@ -1,4 +1,4 @@ -import * as peggy from 'peggy'; +import peggy from 'peggy'; const grammars = String.raw` // global initializer {{ diff --git a/backend/src/core/proxy-utils/parsers/peggy/trojan-uri.js b/backend/src/core/proxy-utils/parsers/peggy/trojan-uri.js index bc27623d..92fc7a85 100644 --- a/backend/src/core/proxy-utils/parsers/peggy/trojan-uri.js +++ b/backend/src/core/proxy-utils/parsers/peggy/trojan-uri.js @@ -1,4 +1,4 @@ -import * as peggy from 'peggy'; +import peggy from 'peggy'; const grammars = String.raw` // global initializer {{ diff --git a/backend/src/restful/archives.js b/backend/src/restful/archives.js new file mode 100644 index 00000000..ae10001d --- /dev/null +++ b/backend/src/restful/archives.js @@ -0,0 +1,112 @@ +import { failed, success } from '@/restful/response'; +import { + InternalServerError, + RequestInvalidError, + ResourceNotFoundError, +} from '@/restful/errors'; +import { + ensureArchiveStore, + getArchiveEntries, + getRequiredArchiveEntry, + removeArchiveEntry, +} from '@/utils/archive'; +import { createSubscriptionItem } from '@/restful/subscriptions'; +import { createCollectionItem } from '@/restful/collections'; +import { createFileItem } from '@/restful/file'; +import { createArtifactItem } from '@/restful/artifacts'; +import { createTokenItem } from '@/restful/token'; + +export default function register($app) { + ensureArchiveStore(); + + $app.route('/api/archives').get(getAllArchiveEntries); + $app.route('/api/archives/:id') + .get(getArchiveDetail) + .delete(deleteArchiveEntry); + $app.post('/api/archives/:id/restore', restoreArchiveEntry); +} + +function getAllArchiveEntries(_, res) { + success(res, getArchiveEntries()); +} + +function getArchiveDetail(req, res) { + try { + success(res, getRequiredArchiveEntry(req.params.id)); + } catch (error) { + failed(res, error, error instanceof ResourceNotFoundError ? 404 : 500); + } +} + +function deleteArchiveEntry(req, res) { + try { + const entry = removeArchiveEntry(req.params.id); + success(res, entry); + } catch (error) { + failed(res, error, error instanceof ResourceNotFoundError ? 404 : 500); + } +} + +function restoreArchiveEntry(req, res) { + try { + const entry = getRequiredArchiveEntry(req.params.id); + const restored = restoreArchivedEntry(entry); + removeArchiveEntry(req.params.id); + success(res, restored); + } catch (error) { + const mappedError = + error instanceof RequestInvalidError || + error instanceof ResourceNotFoundError + ? error + : new InternalServerError( + 'ARCHIVE_RESTORE_FAILED', + 'Failed to restore archive entry', + `Reason: ${error.message ?? error}`, + ); + const statusCode = + mappedError instanceof ResourceNotFoundError + ? 404 + : mappedError instanceof RequestInvalidError + ? 400 + : 500; + failed( + res, + mappedError, + statusCode, + ); + } +} + +function restoreArchivedEntry(entry) { + const snapshot = JSON.parse(JSON.stringify(entry.snapshot)); + switch (entry.itemType) { + case 'sub': + return createSubscriptionItem(snapshot); + case 'col': + return createCollectionItem(snapshot); + case 'file': + return createFileItem(snapshot); + case 'artifact': + return createArtifactItem(normalizeArtifactSnapshotForRestore(snapshot)); + case 'share': + return createTokenItem(snapshot, { + expiresIn: snapshot.expiresIn, + }); + default: + throw new RequestInvalidError( + 'INVALID_ARCHIVE_TYPE', + `Unsupported archive item type: ${entry.itemType}`, + ); + } +} + +function normalizeArtifactSnapshotForRestore(snapshot) { + const nextSnapshot = { + ...snapshot, + }; + delete nextSnapshot.updated; + delete nextSnapshot.url; + return nextSnapshot; +} + +export { restoreArchivedEntry }; diff --git a/backend/src/restful/artifacts.js b/backend/src/restful/artifacts.js index ee198164..e4d82976 100644 --- a/backend/src/restful/artifacts.js +++ b/backend/src/restful/artifacts.js @@ -19,6 +19,7 @@ import { ResourceNotFoundError, } from '@/restful/errors'; import Gist from '@/utils/gist'; +import { archiveArtifact } from '@/utils/archive'; export default function register($app) { // Initialization @@ -136,32 +137,11 @@ async function getArtifact(req, res) { } function createArtifact(req, res) { - const artifact = req.body; - if (!validateArtifactName(artifact.name)) { - failed( - res, - new RequestInvalidError( - 'INVALID_ARTIFACT_NAME', - `Artifact name ${artifact.name} is invalid.`, - ), - ); - return; - } - - $.info(`正在创建远程配置:${artifact.name}`); - const allArtifacts = $.read(ARTIFACTS_KEY); - if (findByName(allArtifacts, artifact.name)) { - failed( - res, - new RequestInvalidError( - 'DUPLICATE_KEY', - `Artifact ${artifact.name} already exists.`, - ), - ); - } else { - insertByPosition(allArtifacts, artifact, getCreateItemPosition()); - $.write(allArtifacts, ARTIFACTS_KEY); + try { + const artifact = createArtifactItem(req.body); success(res, artifact, 201); + } catch (error) { + failed(res, error); } } @@ -202,44 +182,27 @@ function updateArtifact(req, res) { } async function deleteArtifact(req, res) { - let { name } = req.params; - $.info(`正在删除远程配置:${name}`); - const allArtifacts = $.read(ARTIFACTS_KEY); try { - const artifact = findByName(allArtifacts, name); - if (!artifact) throw new Error(`远程配置:${name}不存在!`); - if (artifact.updated) { - // delete gist - const files = {}; - files[encodeURIComponent(artifact.name)] = { - content: '', - }; - if (encodeURIComponent(artifact.name) !== artifact.name) { - files[artifact.name] = { - content: '', - }; - } - - // 当别的Sub 删了同步订阅 或 gist里面删了 当前设备没有删除 时 无法删除的bug - try { - await syncToGist(files); - } catch (i) { - $.error(`Function syncToGist: ${name} : ${i}`); - } + let { name } = req.params; + $.info(`正在删除远程配置:${name}`); + if (shouldArchiveDeletion(req.query.mode)) { + archiveArtifact(name); } - // delete local cache - deleteByName(allArtifacts, name); - $.write(allArtifacts, ARTIFACTS_KEY); + await deleteArtifactItem(name); success(res); } catch (err) { - $.error(`无法删除远程配置:${name},原因:${err}`); + $.error(`无法删除远程配置:${req.params.name},原因:${err}`); failed( res, - new InternalServerError( - `FAILED_TO_DELETE_ARTIFACT`, - `Failed to delete artifact ${name}`, - `Reason: ${err}`, - ), + err instanceof InternalServerError || + err instanceof RequestInvalidError || + err instanceof ResourceNotFoundError + ? err + : new InternalServerError( + `FAILED_TO_DELETE_ARTIFACT`, + `Failed to delete artifact ${req.params.name}`, + `Reason: ${err}`, + ), ); } } @@ -248,6 +211,70 @@ function validateArtifactName(name) { return /^[a-zA-Z0-9._-]*$/.test(name); } +function createArtifactItem(artifact) { + if (!validateArtifactName(artifact.name)) { + throw new RequestInvalidError( + 'INVALID_ARTIFACT_NAME', + `Artifact name ${artifact.name} is invalid.`, + ); + } + + $.info(`正在创建远程配置:${artifact.name}`); + const allArtifacts = $.read(ARTIFACTS_KEY); + if (findByName(allArtifacts, artifact.name)) { + throw new RequestInvalidError( + 'DUPLICATE_KEY', + `Artifact ${artifact.name} already exists.`, + ); + } + insertByPosition(allArtifacts, artifact, getCreateItemPosition()); + $.write(allArtifacts, ARTIFACTS_KEY); + return artifact; +} + +async function deleteArtifactItem(name) { + const allArtifacts = $.read(ARTIFACTS_KEY); + const artifact = findByName(allArtifacts, name); + if (!artifact) { + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `Artifact ${name} does not exist!`, + ); + } + if (artifact.updated) { + const files = {}; + files[encodeURIComponent(artifact.name)] = { + content: '', + }; + if (encodeURIComponent(artifact.name) !== artifact.name) { + files[artifact.name] = { + content: '', + }; + } + try { + await syncToGist(files); + } catch (error) { + $.error(`Function syncToGist: ${name} : ${error}`); + } + } + deleteByName(allArtifacts, name); + $.write(allArtifacts, ARTIFACTS_KEY); + return artifact; +} + +function shouldArchiveDeletion(mode) { + if (mode == null || mode === '' || mode === 'permanent') { + return false; + } + if (mode === 'archive') { + return true; + } + throw new RequestInvalidError( + 'INVALID_DELETE_MODE', + `Unsupported delete mode: ${mode}`, + ); +} + async function syncToGist(files) { const { gistToken, syncPlatform } = $.read(SETTINGS_KEY); if (!gistToken) { @@ -280,3 +307,4 @@ async function syncToGist(files) { } export { syncToGist }; +export { createArtifactItem, deleteArtifactItem }; diff --git a/backend/src/restful/collections.js b/backend/src/restful/collections.js index 8142cb21..a198f763 100644 --- a/backend/src/restful/collections.js +++ b/backend/src/restful/collections.js @@ -6,6 +6,7 @@ import { } from '@/utils/database'; import { getCreateItemPosition } from '@/utils/create-item-position'; import { COLLECTIONS_KEY, ARTIFACTS_KEY, FILES_KEY } from '@/constants'; +import { archiveCollection } from '@/utils/archive'; import { failed, success } from '@/restful/response'; import $ from '@/core/app'; import { RequestInvalidError, ResourceNotFoundError } from '@/restful/errors'; @@ -27,32 +28,12 @@ export default function register($app) { // collection API function createCollection(req, res) { - const collection = req.body; - $.info(`正在创建组合订阅:${collection.name}`); - if (/\//.test(collection.name)) { - failed( - res, - new RequestInvalidError( - 'INVALID_NAME', - `Collection ${collection.name} is invalid`, - ), - ); - return; + try { + const collection = createCollectionItem(req.body); + success(res, collection, 201); + } catch (error) { + failed(res, error); } - const allCols = $.read(COLLECTIONS_KEY); - if (findByName(allCols, collection.name)) { - failed( - res, - new RequestInvalidError( - 'DUPLICATE_KEY', - `Collection ${collection.name} already exists.`, - ), - ); - return; - } - insertByPosition(allCols, collection, getCreateItemPosition()); - $.write(allCols, COLLECTIONS_KEY); - success(res, collection, 201); } function getCollection(req, res) { @@ -141,12 +122,17 @@ function updateCollection(req, res) { } function deleteCollection(req, res) { - let { name } = req.params; - $.info(`正在删除组合订阅:${name}`); - let allCols = $.read(COLLECTIONS_KEY); - deleteByName(allCols, name); - $.write(allCols, COLLECTIONS_KEY); - success(res); + try { + let { name } = req.params; + $.info(`正在删除组合订阅:${name}`); + if (shouldArchiveDeletion(req.query.mode)) { + archiveCollection(name); + } + deleteCollectionItem(name); + success(res); + } catch (error) { + failed(res, error); + } } function getAllCollections(req, res) { @@ -159,3 +145,52 @@ function replaceCollection(req, res) { $.write(allCols, COLLECTIONS_KEY); success(res); } + +function createCollectionItem(collection) { + $.info(`正在创建组合订阅:${collection.name}`); + if (/\//.test(collection.name)) { + throw new RequestInvalidError( + 'INVALID_NAME', + `Collection ${collection.name} is invalid`, + ); + } + const allCols = $.read(COLLECTIONS_KEY); + if (findByName(allCols, collection.name)) { + throw new RequestInvalidError( + 'DUPLICATE_KEY', + `Collection ${collection.name} already exists.`, + ); + } + insertByPosition(allCols, collection, getCreateItemPosition()); + $.write(allCols, COLLECTIONS_KEY); + return collection; +} + +function deleteCollectionItem(name) { + const allCols = $.read(COLLECTIONS_KEY); + const collection = findByName(allCols, name); + if (!collection) { + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `Collection ${name} does not exist!`, + ); + } + deleteByName(allCols, name); + $.write(allCols, COLLECTIONS_KEY); + return collection; +} + +function shouldArchiveDeletion(mode) { + if (mode == null || mode === '' || mode === 'permanent') { + return false; + } + if (mode === 'archive') { + return true; + } + throw new RequestInvalidError( + 'INVALID_DELETE_MODE', + `Unsupported delete mode: ${mode}`, + ); +} + +export { createCollectionItem, deleteCollectionItem }; diff --git a/backend/src/restful/file.js b/backend/src/restful/file.js index 34f7bc0b..571ca4e3 100644 --- a/backend/src/restful/file.js +++ b/backend/src/restful/file.js @@ -15,6 +15,7 @@ import { InternalServerError, } from '@/restful/errors'; import { produceArtifact } from '@/restful/sync'; +import { archiveFile } from '@/utils/archive'; import { formatDateTime } from '@/utils'; export default function register($app) { @@ -35,24 +36,12 @@ export default function register($app) { // file API function createFile(req, res) { - const file = req.body; - file.name = `${file.name ?? Date.now()}`; - $.info(`正在创建文件:${file.name}`); - const allFiles = $.read(FILES_KEY); - if (findByName(allFiles, file.name)) { - return failed( - res, - new RequestInvalidError( - 'DUPLICATE_KEY', - req.body.name - ? `已存在 name 为 ${file.name} 的文件` - : `无法同时创建相同的文件 可稍后重试`, - ), - ); + try { + const file = createFileItem(req.body); + success(res, file, 201); + } catch (error) { + failed(res, error); } - insertByPosition(allFiles, file, getCreateItemPosition()); - $.write(allFiles, FILES_KEY); - success(res, file, 201); } async function getFile(req, res, next) { @@ -314,12 +303,17 @@ function updateFile(req, res) { } function deleteFile(req, res) { - let { name } = req.params; - $.info(`正在删除文件:${name}`); - let allFiles = $.read(FILES_KEY); - deleteByName(allFiles, name); - $.write(allFiles, FILES_KEY); - success(res); + try { + let { name } = req.params; + $.info(`正在删除文件:${name}`); + if (shouldArchiveDeletion(req.query.mode)) { + archiveFile(name); + } + deleteFileItem(name); + success(res); + } catch (error) { + failed(res, error); + } } function getAllFiles(req, res) { @@ -340,3 +334,52 @@ function replaceFile(req, res) { $.write(allFiles, FILES_KEY); success(res); } + +function createFileItem(rawFile) { + const file = { + ...rawFile, + }; + file.name = `${file.name ?? Date.now()}`; + $.info(`正在创建文件:${file.name}`); + const allFiles = $.read(FILES_KEY); + if (findByName(allFiles, file.name)) { + throw new RequestInvalidError( + 'DUPLICATE_KEY', + rawFile.name + ? `已存在 name 为 ${file.name} 的文件` + : `无法同时创建相同的文件 可稍后重试`, + ); + } + insertByPosition(allFiles, file, getCreateItemPosition()); + $.write(allFiles, FILES_KEY); + return file; +} + +function deleteFileItem(name) { + const allFiles = $.read(FILES_KEY); + const file = findByName(allFiles, name); + if (!file) { + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `File ${name} does not exist!`, + ); + } + deleteByName(allFiles, name); + $.write(allFiles, FILES_KEY); + return file; +} + +function shouldArchiveDeletion(mode) { + if (mode == null || mode === '' || mode === 'permanent') { + return false; + } + if (mode === 'archive') { + return true; + } + throw new RequestInvalidError( + 'INVALID_DELETE_MODE', + `Unsupported delete mode: ${mode}`, + ); +} + +export { createFileItem, deleteFileItem }; diff --git a/backend/src/restful/index.js b/backend/src/restful/index.js index b35c87b2..65fc21e4 100644 --- a/backend/src/restful/index.js +++ b/backend/src/restful/index.js @@ -13,6 +13,7 @@ import registerCollectionRoutes from './collections'; import registerArtifactRoutes from './artifacts'; import registerFileRoutes from './file'; import registerTokenRoutes from './token'; +import registerArchiveRoutes from './archives'; import registerModuleRoutes from './module'; import registerSyncRoutes from './sync'; import registerDownloadRoutes from './download'; @@ -132,6 +133,7 @@ export default function serve() { registerArtifactRoutes($app); registerFileRoutes($app); registerTokenRoutes($app); + registerArchiveRoutes($app); registerModuleRoutes($app); registerSyncRoutes($app); registerNodeInfoRoutes($app); diff --git a/backend/src/restful/miscs.js b/backend/src/restful/miscs.js index 2e0f4bf1..9e0bfb9a 100644 --- a/backend/src/restful/miscs.js +++ b/backend/src/restful/miscs.js @@ -96,6 +96,8 @@ export default function register($app) { } function getEnv(req, res) { + env.feature = env.feature || {}; + env.feature.archive = true; if (req.query.share) { env.feature.share = true; } diff --git a/backend/src/restful/sort.js b/backend/src/restful/sort.js index 3a8a9493..d0177382 100644 --- a/backend/src/restful/sort.js +++ b/backend/src/restful/sort.js @@ -7,6 +7,7 @@ import { } from '@/constants'; import $ from '@/core/app'; import { success } from '@/restful/response'; +import { sortArchiveEntries } from '@/utils/archive'; export default function register($app) { $app.post('/api/sort/subs', sortSubs); @@ -14,6 +15,7 @@ export default function register($app) { $app.post('/api/sort/artifacts', sortArtifacts); $app.post('/api/sort/files', sortFiles); $app.post('/api/sort/tokens', sortTokens); + $app.post('/api/sort/archives', sortArchive); } function sortSubs(req, res) { @@ -61,3 +63,8 @@ function sortTokens(req, res) { $.write(allTokens, TOKENS_KEY); success(res, allTokens); } + +function sortArchive(req, res) { + const entries = sortArchiveEntries(req.body); + success(res, entries); +} diff --git a/backend/src/restful/subscriptions.js b/backend/src/restful/subscriptions.js index fd3f52e9..87a13d3b 100644 --- a/backend/src/restful/subscriptions.js +++ b/backend/src/restful/subscriptions.js @@ -22,6 +22,7 @@ import { parseFlowHeaders, getRmainingDays, } from '@/utils/flow'; +import { archiveSubscription } from '@/utils/archive'; import { success, failed } from './response'; import $ from '@/core/app'; import { formatDateTime } from '@/utils'; @@ -235,33 +236,12 @@ async function getFlowInfo(req, res) { } function createSubscription(req, res) { - const sub = req.body; - delete sub.subscriptions; - $.info(`正在创建订阅: ${sub.name}`); - if (/\//.test(sub.name)) { - failed( - res, - new RequestInvalidError( - 'INVALID_NAME', - `Subscription ${sub.name} is invalid`, - ), - ); - return; + try { + const sub = createSubscriptionItem(req.body); + success(res, sub, 201); + } catch (error) { + failed(res, error); } - const allSubs = $.read(SUBS_KEY); - if (findByName(allSubs, sub.name)) { - failed( - res, - new RequestInvalidError( - 'DUPLICATE_KEY', - `Subscription ${sub.name} already exists.`, - ), - ); - return; - } - insertByPosition(allSubs, sub, getCreateItemPosition()); - $.write(allSubs, SUBS_KEY); - success(res, sub, 201); } function getSubscription(req, res) { @@ -362,21 +342,17 @@ function updateSubscription(req, res) { } function deleteSubscription(req, res) { - let { name } = req.params; - $.info(`删除订阅:${name}...`); - // delete from subscriptions - let allSubs = $.read(SUBS_KEY); - deleteByName(allSubs, name); - $.write(allSubs, SUBS_KEY); - // delete from collections - const allCols = $.read(COLLECTIONS_KEY); - for (const collection of allCols) { - collection.subscriptions = collection.subscriptions.filter( - (s) => s !== name, - ); + try { + const { name } = req.params; + $.info(`删除订阅:${name}...`); + if (shouldArchiveDeletion(req.query.mode)) { + archiveSubscription(name); + } + deleteSubscriptionItem(name); + success(res); + } catch (error) { + failed(res, error); } - $.write(allCols, COLLECTIONS_KEY); - success(res); } function getAllSubscriptions(req, res) { @@ -389,3 +365,64 @@ function replaceSubscriptions(req, res) { $.write(allSubs, SUBS_KEY); success(res); } + +function createSubscriptionItem(rawSub) { + const sub = { + ...rawSub, + }; + delete sub.subscriptions; + $.info(`正在创建订阅: ${sub.name}`); + if (/\//.test(sub.name)) { + throw new RequestInvalidError( + 'INVALID_NAME', + `Subscription ${sub.name} is invalid`, + ); + } + const allSubs = $.read(SUBS_KEY); + if (findByName(allSubs, sub.name)) { + throw new RequestInvalidError( + 'DUPLICATE_KEY', + `Subscription ${sub.name} already exists.`, + ); + } + insertByPosition(allSubs, sub, getCreateItemPosition()); + $.write(allSubs, SUBS_KEY); + return sub; +} + +function deleteSubscriptionItem(name) { + const allSubs = $.read(SUBS_KEY); + const sub = findByName(allSubs, name); + if (!sub) { + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `Subscription ${name} does not exist!`, + ); + } + deleteByName(allSubs, name); + $.write(allSubs, SUBS_KEY); + + const allCols = $.read(COLLECTIONS_KEY) || []; + for (const collection of allCols) { + collection.subscriptions = collection.subscriptions.filter( + (subscriptionName) => subscriptionName !== name, + ); + } + $.write(allCols, COLLECTIONS_KEY); + return sub; +} + +function shouldArchiveDeletion(mode) { + if (mode == null || mode === '' || mode === 'permanent') { + return false; + } + if (mode === 'archive') { + return true; + } + throw new RequestInvalidError( + 'INVALID_DELETE_MODE', + `Unsupported delete mode: ${mode}`, + ); +} + +export { createSubscriptionItem, deleteSubscriptionItem }; diff --git a/backend/src/restful/token.js b/backend/src/restful/token.js index a53e9635..0287ef7e 100644 --- a/backend/src/restful/token.js +++ b/backend/src/restful/token.js @@ -2,9 +2,14 @@ import { ENV } from '@/vendor/open-api'; import { TOKENS_KEY, SUBS_KEY, FILES_KEY, COLLECTIONS_KEY } from '@/constants'; import { failed, success } from '@/restful/response'; import $ from '@/core/app'; -import { RequestInvalidError, InternalServerError } from '@/restful/errors'; +import { + RequestInvalidError, + InternalServerError, + ResourceNotFoundError, +} from '@/restful/errors'; import { insertByPosition } from '@/utils/database'; import { getCreateItemPosition } from '@/utils/create-item-position'; +import { archiveShare } from '@/utils/archive'; export default function register($app) { if (!$.read(TOKENS_KEY)) $.write([], TOKENS_KEY); @@ -17,23 +22,24 @@ export default function register($app) { } function deleteToken(req, res) { - let { token } = req.params; - const { type, name } = req.query; - if (!type || !name) - return failed( - res, - new RequestInvalidError( + try { + let { token } = req.params; + const { type, name } = req.query; + if (!type || !name) { + throw new RequestInvalidError( 'INVALID_PAYLOAD', `Payload type and name are required. Please update your front-end(version >= 2.15.76)`, - ), - ); - $.info(`正在删除...\ntoken: ${token}, 类型:${type}, 名称:${name}`); - let allTokens = $.read(TOKENS_KEY); - allTokens = allTokens.filter( - (t) => !(t.token === token && t.type === type && t.name === name), - ); - $.write(allTokens, TOKENS_KEY); - success(res); + ); + } + $.info(`正在删除...\ntoken: ${token}, 类型:${type}, 名称:${name}`); + if (shouldArchiveDeletion(req.query.mode)) { + archiveShare(token, type, name); + } + deleteTokenItem(token, type, name); + success(res); + } catch (error) { + failed(res, error); + } } function getAllTokens(req, res) { @@ -62,146 +68,160 @@ async function signToken(req, res) { ); } try { - const { payload, options } = req.body; - const ms = eval(`require("ms")`); - const type = payload?.type; - const name = payload?.name; - if (!type || !name) - return failed( - res, - new RequestInvalidError( - 'INVALID_PAYLOAD', - `payload type and name are required`, - ), - ); - let token = payload?.token; - if (token != null) { - if (typeof token !== 'string' || token.length < 1) { - return failed( - res, - new RequestInvalidError( - 'INVALID_CUSTOM_TOKEN', - `Invalid custom token: ${token}`, - ), - ); - } - const tokens = $.read(TOKENS_KEY) || []; - if ( - tokens.find( - (t) => - t.token === token && t.type === type && t.name === name, - ) - ) { - return failed( - res, - new RequestInvalidError( - 'DUPLICATE_TOKEN', - `Token ${token} already exists`, - ), - ); - } - } - - if (type === 'col') { - const collections = $.read(COLLECTIONS_KEY) || []; - const collection = collections.find((c) => c.name === name); - if (!collection) - return failed( - res, - new RequestInvalidError( - 'INVALID_COLLECTION', - `collection ${name} not found`, - ), - ); - } else if (type === 'file') { - const files = $.read(FILES_KEY) || []; - const file = files.find((f) => f.name === name); - if (!file) - return failed( - res, - new RequestInvalidError( - 'INVALID_FILE', - `file ${name} not found`, - ), - ); - } else if (type === 'sub') { - const subs = $.read(SUBS_KEY) || []; - const sub = subs.find((s) => s.name === name); - if (!sub) - return failed( - res, - new RequestInvalidError( - 'INVALID_SUB', - `sub ${name} not found`, - ), - ); - } else { - return failed( - res, - new RequestInvalidError( - 'INVALID_TYPE', - `type ${name} not supported`, - ), - ); - } - let expiresIn = options?.expiresIn; - if (options?.expiresIn != null) { - expiresIn = ms(options.expiresIn); - if (expiresIn == null || isNaN(expiresIn) || expiresIn <= 0) { - return failed( - res, - new RequestInvalidError( - 'INVALID_EXPIRES_IN', - `Invalid expiresIn option: ${options.expiresIn}`, - ), - ); - } - } - // const secret = eval('process.env.SUB_STORE_FRONTEND_BACKEND_PATH'); - const nanoid = eval(`require("nanoid")`); - const tokens = $.read(TOKENS_KEY) || []; - // const now = Date.now(); - // for (const key in tokens) { - // const token = tokens[key]; - // if (token.exp != null || token.exp < now) { - // delete tokens[key]; - // } - // } - if (!token) { - do { - token = nanoid.customAlphabet(nanoid.urlAlphabet)(); - } while ( - tokens.find( - (t) => - t.token === token && t.type === type && t.name === name, - ) - ); - } - insertByPosition( - tokens, - { - ...payload, - token, - createdAt: Date.now(), - expiresIn: expiresIn > 0 ? options?.expiresIn : undefined, - exp: expiresIn > 0 ? Date.now() + expiresIn : undefined, - }, - getCreateItemPosition(), - ); - - $.write(tokens, TOKENS_KEY); + const tokenData = createTokenItem(req.body.payload, req.body.options); return success(res, { - token, + token: tokenData.token, // secret, }); } catch (e) { return failed( res, - new InternalServerError( - 'TOKEN_SIGN_FAILED', - `Failed to sign token`, - `Reason: ${e.message ?? e}`, - ), + e instanceof RequestInvalidError + ? e + : new InternalServerError( + 'TOKEN_SIGN_FAILED', + `Failed to sign token`, + `Reason: ${e.message ?? e}`, + ), ); } } + +function createTokenItem(payload, options = {}) { + const ms = eval(`require("ms")`); + const type = payload?.type; + const name = payload?.name; + if (!type || !name) { + throw new RequestInvalidError( + 'INVALID_PAYLOAD', + `payload type and name are required`, + ); + } + let token = payload?.token; + if (token != null) { + if (typeof token !== 'string' || token.length < 1) { + throw new RequestInvalidError( + 'INVALID_CUSTOM_TOKEN', + `Invalid custom token: ${token}`, + ); + } + const tokens = $.read(TOKENS_KEY) || []; + if ( + tokens.find( + (item) => + item.token === token && + item.type === type && + item.name === name, + ) + ) { + throw new RequestInvalidError( + 'DUPLICATE_TOKEN', + `Token ${token} already exists`, + ); + } + } + + if (type === 'col') { + const collections = $.read(COLLECTIONS_KEY) || []; + const collection = collections.find((item) => item.name === name); + if (!collection) { + throw new RequestInvalidError( + 'INVALID_COLLECTION', + `collection ${name} not found`, + ); + } + } else if (type === 'file') { + const files = $.read(FILES_KEY) || []; + const file = files.find((item) => item.name === name); + if (!file) { + throw new RequestInvalidError( + 'INVALID_FILE', + `file ${name} not found`, + ); + } + } else if (type === 'sub') { + const subs = $.read(SUBS_KEY) || []; + const sub = subs.find((item) => item.name === name); + if (!sub) { + throw new RequestInvalidError( + 'INVALID_SUB', + `sub ${name} not found`, + ); + } + } else { + throw new RequestInvalidError( + 'INVALID_TYPE', + `type ${name} not supported`, + ); + } + + let expiresIn = options?.expiresIn; + if (options?.expiresIn != null) { + expiresIn = ms(options.expiresIn); + if (expiresIn == null || isNaN(expiresIn) || expiresIn <= 0) { + throw new RequestInvalidError( + 'INVALID_EXPIRES_IN', + `Invalid expiresIn option: ${options.expiresIn}`, + ); + } + } + + const nanoid = eval(`require("nanoid")`); + const tokens = $.read(TOKENS_KEY) || []; + if (!token) { + do { + token = nanoid.customAlphabet(nanoid.urlAlphabet)(); + } while ( + tokens.find( + (item) => + item.token === token && + item.type === type && + item.name === name, + ) + ); + } + const tokenData = { + ...payload, + token, + createdAt: Date.now(), + expiresIn: expiresIn > 0 ? options?.expiresIn : undefined, + exp: expiresIn > 0 ? Date.now() + expiresIn : undefined, + }; + insertByPosition(tokens, tokenData, getCreateItemPosition()); + $.write(tokens, TOKENS_KEY); + return tokenData; +} + +function deleteTokenItem(token, type, name) { + const allTokens = $.read(TOKENS_KEY) || []; + const match = allTokens.find( + (item) => item.token === token && item.type === type && item.name === name, + ); + if (!match) { + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `Share ${type}/${name}/${token} does not exist!`, + ); + } + const filtered = allTokens.filter( + (item) => + !(item.token === token && item.type === type && item.name === name), + ); + $.write(filtered, TOKENS_KEY); + return match; +} + +function shouldArchiveDeletion(mode) { + if (mode == null || mode === '' || mode === 'permanent') { + return false; + } + if (mode === 'archive') { + return true; + } + throw new RequestInvalidError( + 'INVALID_DELETE_MODE', + `Unsupported delete mode: ${mode}`, + ); +} + +export { createTokenItem, deleteTokenItem }; diff --git a/backend/src/test/restful/archive.spec.js b/backend/src/test/restful/archive.spec.js new file mode 100644 index 00000000..09299d98 --- /dev/null +++ b/backend/src/test/restful/archive.spec.js @@ -0,0 +1,410 @@ +import { expect } from 'chai'; +import { after, before, beforeEach, describe, it } from 'mocha'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { + ARTIFACTS_KEY, + COLLECTIONS_KEY, + FILES_KEY, + ARCHIVES_KEY, + SETTINGS_KEY, + SUBS_KEY, + TOKENS_KEY, +} from '@/constants'; + +let $; +let registerCollectionRoutes; +let registerArtifactRoutes; +let registerMiscRoutes; +let registerArchiveRoutes; +let registerSortingRoutes; +let registerSubscriptionRoutes; +let registerTokenRoutes; +let originalError; +let originalInfo; +let originalRead; +let originalWrite; +let state; +let tempDir; +let previousDataBasePath; + +function createRouteApp() { + const handlers = new Map(); + const methods = ['get', 'post', 'put', 'patch', 'delete', 'all']; + + const app = { + handlers, + route(pattern) { + const chain = {}; + methods + .filter((method) => method !== 'all') + .forEach((method) => { + chain[method] = (handler) => { + handlers.set(`${method.toUpperCase()} ${pattern}`, handler); + return chain; + }; + }); + return chain; + }, + }; + + methods.forEach((method) => { + app[method] = (pattern, handler) => { + handlers.set(`${method.toUpperCase()} ${pattern}`, handler); + return app; + }; + }); + + return app; +} + +function getHandler(register, method, pattern) { + const app = createRouteApp(); + register(app); + return app.handlers.get(`${method} ${pattern}`); +} + +function createResponse(routePath) { + return { + body: null, + headers: {}, + req: { + route: { + path: routePath, + }, + }, + sent: null, + statusCode: 200, + json(payload) { + this.body = payload; + return this; + }, + send(payload) { + this.sent = payload; + return this; + }, + set(key, value) { + this.headers[key] = value; + return this; + }, + status(code) { + this.statusCode = code; + return this; + }, + }; +} + +describe('archive routes', function () { + before(async function () { + previousDataBasePath = process.env.SUB_STORE_DATA_BASE_PATH; + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sub-store-archives-')); + process.env.SUB_STORE_DATA_BASE_PATH = tempDir; + + ({ default: $ } = require('@/core/app')); + ({ default: registerSubscriptionRoutes } = require( + '@/restful/subscriptions' + )); + ({ default: registerCollectionRoutes } = require('@/restful/collections')); + ({ default: registerArtifactRoutes } = require('@/restful/artifacts')); + ({ default: registerTokenRoutes } = require('@/restful/token')); + ({ default: registerArchiveRoutes } = require('@/restful/archives')); + ({ default: registerSortingRoutes } = require('@/restful/sort')); + ({ default: registerMiscRoutes } = require('@/restful/miscs')); + + originalRead = $.read.bind($); + originalWrite = $.write.bind($); + originalInfo = $.info.bind($); + originalError = $.error.bind($); + }); + + after(function () { + if ($) { + $.read = originalRead; + $.write = originalWrite; + $.info = originalInfo; + $.error = originalError; + } + + if (previousDataBasePath == null) { + delete process.env.SUB_STORE_DATA_BASE_PATH; + } else { + process.env.SUB_STORE_DATA_BASE_PATH = previousDataBasePath; + } + + if (tempDir) { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + beforeEach(function () { + state = { + [SUBS_KEY]: [], + [COLLECTIONS_KEY]: [], + [FILES_KEY]: [], + [ARTIFACTS_KEY]: [], + [TOKENS_KEY]: [], + [ARCHIVES_KEY]: [], + [SETTINGS_KEY]: {}, + }; + + $.read = (key) => state[key]; + $.write = (data, key) => { + state[key] = data; + return true; + }; + $.info = () => {}; + $.error = () => {}; + }); + + it('archives and restores subscriptions through the live delete route', async function () { + state[SUBS_KEY] = [ + { + name: 'demo-sub', + displayName: 'Demo Sub', + source: 'remote', + tag: ['alpha'], + url: 'https://example.com/sub', + process: [], + }, + ]; + state[COLLECTIONS_KEY] = [ + { + name: 'demo-collection', + subscriptions: ['demo-sub'], + }, + ]; + + const deleteHandler = getHandler( + registerSubscriptionRoutes, + 'DELETE', + '/api/sub/:name', + ); + const deleteRes = createResponse('/api/sub/:name'); + + deleteHandler( + { + params: { name: 'demo-sub' }, + query: { mode: 'archive' }, + }, + deleteRes, + ); + + expect(deleteRes.body.status).to.equal('success'); + expect(state[SUBS_KEY]).to.deep.equal([]); + expect(state[COLLECTIONS_KEY][0].subscriptions).to.deep.equal([]); + expect(state[ARCHIVES_KEY]).to.have.length(1); + expect(state[ARCHIVES_KEY][0].itemType).to.equal('sub'); + expect(state[ARCHIVES_KEY][0].snapshot.name).to.equal('demo-sub'); + + const restoreHandler = getHandler( + registerArchiveRoutes, + 'POST', + '/api/archives/:id/restore', + ); + const restoreRes = createResponse('/api/archives/:id/restore'); + + restoreHandler( + { + params: { id: state[ARCHIVES_KEY][0].id }, + query: {}, + }, + restoreRes, + ); + + expect(restoreRes.body.status).to.equal('success'); + expect(state[SUBS_KEY]).to.have.length(1); + expect(state[SUBS_KEY][0].name).to.equal('demo-sub'); + expect(state[ARCHIVES_KEY]).to.deep.equal([]); + }); + + it('keeps archived entries when restore fails and preserves share tokens on success', async function () { + state[SUBS_KEY] = [ + { + name: 'shared-sub', + source: 'remote', + process: [], + }, + ]; + state[TOKENS_KEY] = [ + { + token: 'keep-me', + type: 'sub', + name: 'shared-sub', + displayName: 'Shared Link', + expiresIn: '1d', + }, + ]; + + const deleteHandler = getHandler( + registerTokenRoutes, + 'DELETE', + '/api/token/:token', + ); + const deleteRes = createResponse('/api/token/:token'); + + deleteHandler( + { + params: { token: 'keep-me' }, + query: { + mode: 'archive', + type: 'sub', + name: 'shared-sub', + }, + }, + deleteRes, + ); + + expect(deleteRes.body.status).to.equal('success'); + expect(state[TOKENS_KEY]).to.deep.equal([]); + expect(state[ARCHIVES_KEY]).to.have.length(1); + expect(state[ARCHIVES_KEY][0].itemType).to.equal('share'); + expect(state[ARCHIVES_KEY][0].snapshot.token).to.equal('keep-me'); + + const archivedId = state[ARCHIVES_KEY][0].id; + state[TOKENS_KEY].push({ + token: 'keep-me', + type: 'sub', + name: 'shared-sub', + }); + + const restoreHandler = getHandler( + registerArchiveRoutes, + 'POST', + '/api/archives/:id/restore', + ); + const failedRestoreRes = createResponse('/api/archives/:id/restore'); + + restoreHandler( + { + params: { id: archivedId }, + query: {}, + }, + failedRestoreRes, + ); + + expect(failedRestoreRes.body.status).to.equal('failed'); + expect(failedRestoreRes.statusCode).to.equal(400); + expect(failedRestoreRes.body.error.code).to.equal('DUPLICATE_TOKEN'); + expect(state[ARCHIVES_KEY]).to.have.length(1); + + state[TOKENS_KEY] = []; + const successfulRestoreRes = createResponse( + '/api/archives/:id/restore', + ); + + restoreHandler( + { + params: { id: archivedId }, + query: {}, + }, + successfulRestoreRes, + ); + + expect(successfulRestoreRes.body.status).to.equal('success'); + expect(state[TOKENS_KEY]).to.have.length(1); + expect(state[TOKENS_KEY][0].token).to.equal('keep-me'); + expect(state[ARCHIVES_KEY]).to.deep.equal([]); + }); + + it('restores artifacts without stale sync metadata', async function () { + state[ARTIFACTS_KEY] = [ + { + name: 'demo-artifact', + type: 'subscription', + source: 'demo-sub', + platform: 'Clash', + sync: true, + updated: 1711111111111, + url: 'https://gist.example.com/demo-artifact', + }, + ]; + + const deleteHandler = getHandler( + registerArtifactRoutes, + 'DELETE', + '/api/artifact/:name', + ); + const deleteRes = createResponse('/api/artifact/:name'); + + await deleteHandler( + { + params: { name: 'demo-artifact' }, + query: { mode: 'archive' }, + }, + deleteRes, + ); + + expect(deleteRes.body.status).to.equal('success'); + expect(state[ARTIFACTS_KEY]).to.deep.equal([]); + expect(state[ARCHIVES_KEY]).to.have.length(1); + expect(state[ARCHIVES_KEY][0].itemType).to.equal('artifact'); + expect(state[ARCHIVES_KEY][0].snapshot.updated).to.equal(1711111111111); + expect(state[ARCHIVES_KEY][0].snapshot.url).to.equal( + 'https://gist.example.com/demo-artifact', + ); + + const restoreHandler = getHandler( + registerArchiveRoutes, + 'POST', + '/api/archives/:id/restore', + ); + const restoreRes = createResponse('/api/archives/:id/restore'); + + restoreHandler( + { + params: { id: state[ARCHIVES_KEY][0].id }, + query: {}, + }, + restoreRes, + ); + + expect(restoreRes.body.status).to.equal('success'); + expect(state[ARTIFACTS_KEY]).to.have.length(1); + expect(state[ARTIFACTS_KEY][0].name).to.equal('demo-artifact'); + expect(state[ARTIFACTS_KEY][0].sync).to.equal(true); + expect(state[ARTIFACTS_KEY][0]).to.not.have.property('updated'); + expect(state[ARTIFACTS_KEY][0]).to.not.have.property('url'); + expect(state[ARCHIVES_KEY]).to.deep.equal([]); + }); + + it('sorts archive entries by id order', function () { + state[ARCHIVES_KEY] = [ + { id: 'entry-b', itemType: 'sub', name: 'b' }, + { id: 'entry-a', itemType: 'sub', name: 'a' }, + ]; + + const sortHandler = getHandler( + registerSortingRoutes, + 'POST', + '/api/sort/archives', + ); + const sortRes = createResponse('/api/sort/archives'); + + sortHandler( + { + body: ['entry-a', 'entry-b'], + query: {}, + }, + sortRes, + ); + + expect(sortRes.body.status).to.equal('success'); + expect(state[ARCHIVES_KEY].map((item) => item.id)).to.deep.equal([ + 'entry-a', + 'entry-b', + ]); + }); + + it('advertises archive capability in env payload', function () { + const envHandler = getHandler(registerMiscRoutes, 'GET', '/api/utils/env'); + const envRes = createResponse('/api/utils/env'); + + envHandler({ query: {} }, envRes); + + const payload = JSON.parse(envRes.sent); + expect(payload.status).to.equal('success'); + expect(payload.data.feature.archive).to.equal(true); + }); +}); diff --git a/backend/src/test/restful/create-position.spec.js b/backend/src/test/restful/create-position.spec.js index c8aea498..0dc47992 100644 --- a/backend/src/test/restful/create-position.spec.js +++ b/backend/src/test/restful/create-position.spec.js @@ -26,6 +26,8 @@ let originalWrite; let originalInfo; let originalError; let state; +let tempDir; +let previousDataBasePath; function createRouteApp() { const handlers = new Map(); @@ -81,252 +83,262 @@ function createResponse(routePath) { }; } -before(async function () { - process.env.SUB_STORE_DATA_BASE_PATH = fs.mkdtempSync( - path.join(os.tmpdir(), 'sub-store-create-position-'), - ); +describe('create position behavior', function () { + before(async function () { + previousDataBasePath = process.env.SUB_STORE_DATA_BASE_PATH; + tempDir = fs.mkdtempSync( + path.join(os.tmpdir(), 'sub-store-create-position-'), + ); + process.env.SUB_STORE_DATA_BASE_PATH = tempDir; - ({ default: $ } = require('@/core/app')); - ({ default: registerSubscriptionRoutes } = require( - '@/restful/subscriptions' - )); - ({ default: registerCollectionRoutes } = require('@/restful/collections')); - ({ default: registerFileRoutes } = require('@/restful/file')); - ({ default: registerArtifactRoutes } = require('@/restful/artifacts')); - ({ default: registerTokenRoutes } = require('@/restful/token')); + ({ default: $ } = require('@/core/app')); + ({ default: registerSubscriptionRoutes } = require( + '@/restful/subscriptions' + )); + ({ default: registerCollectionRoutes } = require('@/restful/collections')); + ({ default: registerFileRoutes } = require('@/restful/file')); + ({ default: registerArtifactRoutes } = require('@/restful/artifacts')); + ({ default: registerTokenRoutes } = require('@/restful/token')); - originalRead = $.read.bind($); - originalWrite = $.write.bind($); - originalInfo = $.info.bind($); - originalError = $.error.bind($); -}); - -after(function () { - if ($) { - $.read = originalRead; - $.write = originalWrite; - $.info = originalInfo; - $.error = originalError; - } - - const tempDir = process.env.SUB_STORE_DATA_BASE_PATH; - delete process.env.SUB_STORE_DATA_BASE_PATH; - fs.rmSync(tempDir, { recursive: true, force: true }); -}); - -beforeEach(function () { - state = { - [SUBS_KEY]: [], - [COLLECTIONS_KEY]: [], - [FILES_KEY]: [], - [ARTIFACTS_KEY]: [], - [TOKENS_KEY]: [], - [SETTINGS_KEY]: {}, - }; - - $.read = (key) => state[key]; - $.write = (data, key) => { - state[key] = data; - return true; - }; - $.info = () => {}; - $.error = () => {}; -}); - -describe('insertByPosition', function () { - it('prepends when position is top', function () { - const list = ['existing']; - - insertByPosition(list, 'new', 'top'); - - expect(list).to.deep.equal(['new', 'existing']); + originalRead = $.read.bind($); + originalWrite = $.write.bind($); + originalInfo = $.info.bind($); + originalError = $.error.bind($); }); - it('appends when position is bottom', function () { - const list = ['existing']; + after(function () { + if ($) { + $.read = originalRead; + $.write = originalWrite; + $.info = originalInfo; + $.error = originalError; + } - insertByPosition(list, 'new', 'bottom'); + if (previousDataBasePath == null) { + delete process.env.SUB_STORE_DATA_BASE_PATH; + } else { + process.env.SUB_STORE_DATA_BASE_PATH = previousDataBasePath; + } - expect(list).to.deep.equal(['existing', 'new']); - }); -}); - -describe('getCreateItemPosition', function () { - it('reads top from synced settings', function () { - state[SETTINGS_KEY] = { - appearanceSetting: { - createItemPosition: 'top', - }, - }; - - expect(getCreateItemPosition()).to.equal('top'); + if (tempDir) { + fs.rmSync(tempDir, { recursive: true, force: true }); + } }); - it('falls back to bottom when settings are absent', function () { - expect(getCreateItemPosition()).to.equal('bottom'); - }); -}); - -describe('create route insertion position', function () { beforeEach(function () { - state[SETTINGS_KEY] = { - appearanceSetting: { - createItemPosition: 'top', - }, + state = { + [SUBS_KEY]: [], + [COLLECTIONS_KEY]: [], + [FILES_KEY]: [], + [ARTIFACTS_KEY]: [], + [TOKENS_KEY]: [], + [SETTINGS_KEY]: {}, }; + + $.read = (key) => state[key]; + $.write = (data, key) => { + state[key] = data; + return true; + }; + $.info = () => {}; + $.error = () => {}; }); - it('creates subscriptions at the top when settings request it', function () { - state[SUBS_KEY] = [{ name: 'older-sub' }]; - const handler = getHandler( - registerSubscriptionRoutes, - 'POST', - '/api/subs', - ); - const res = createResponse('/api/subs'); + describe('insertByPosition', function () { + it('prepends when position is top', function () { + const list = ['existing']; - handler( - { - body: { name: 'new-sub', subscriptions: ['ignored'] }, - query: {}, - }, - res, - ); + insertByPosition(list, 'new', 'top'); - expect(state[SUBS_KEY].map((item) => item.name)).to.deep.equal([ - 'new-sub', - 'older-sub', - ]); - expect(state[SUBS_KEY][0]).to.not.have.property('subscriptions'); - expect(res.statusCode).to.equal(201); + expect(list).to.deep.equal(['new', 'existing']); + }); + + it('appends when position is bottom', function () { + const list = ['existing']; + + insertByPosition(list, 'new', 'bottom'); + + expect(list).to.deep.equal(['existing', 'new']); + }); }); - it('creates collections at the top when settings request it', function () { - state[COLLECTIONS_KEY] = [{ name: 'older-collection' }]; - const handler = getHandler( - registerCollectionRoutes, - 'POST', - '/api/collections', - ); - const res = createResponse('/api/collections'); - - handler( - { - body: { name: 'new-collection', subscriptions: [] }, - query: {}, - }, - res, - ); - - expect(state[COLLECTIONS_KEY].map((item) => item.name)).to.deep.equal([ - 'new-collection', - 'older-collection', - ]); - expect(res.statusCode).to.equal(201); - }); - - it('creates files at the top when settings request it', function () { - state[FILES_KEY] = [{ name: 'older-file' }]; - const handler = getHandler(registerFileRoutes, 'POST', '/api/files'); - const res = createResponse('/api/files'); - - handler( - { - body: { name: 'new-file' }, - query: {}, - }, - res, - ); - - expect(state[FILES_KEY].map((item) => item.name)).to.deep.equal([ - 'new-file', - 'older-file', - ]); - expect(res.statusCode).to.equal(201); - }); - - it('creates artifacts at the top when settings request it', function () { - state[ARTIFACTS_KEY] = [{ name: 'older-artifact' }]; - const handler = getHandler( - registerArtifactRoutes, - 'POST', - '/api/artifacts', - ); - const res = createResponse('/api/artifacts'); - - handler( - { - body: { - name: 'new-artifact', - type: 'file', - source: 'demo', - platform: 'JSON', + describe('getCreateItemPosition', function () { + it('reads top from synced settings', function () { + state[SETTINGS_KEY] = { + appearanceSetting: { + createItemPosition: 'top', }, - query: {}, - }, - res, - ); + }; - expect(state[ARTIFACTS_KEY].map((item) => item.name)).to.deep.equal([ - 'new-artifact', - 'older-artifact', - ]); - expect(res.statusCode).to.equal(201); + expect(getCreateItemPosition()).to.equal('top'); + }); + + it('falls back to bottom when settings are absent', function () { + expect(getCreateItemPosition()).to.equal('bottom'); + }); }); - it('creates tokens at the top when settings request it without persisting transport metadata', async function () { - state[SUBS_KEY] = [{ name: 'sub-1' }]; - state[TOKENS_KEY] = [ - { token: 'older-token', type: 'sub', name: 'sub-1' }, - ]; - const handler = getHandler(registerTokenRoutes, 'POST', '/api/token'); - const res = createResponse('/api/token'); + describe('create route insertion position', function () { + beforeEach(function () { + state[SETTINGS_KEY] = { + appearanceSetting: { + createItemPosition: 'top', + }, + }; + }); - await handler( - { - body: { - payload: { - type: 'sub', - name: 'sub-1', - token: 'new-token', + it('creates subscriptions at the top when settings request it', function () { + state[SUBS_KEY] = [{ name: 'older-sub' }]; + const handler = getHandler( + registerSubscriptionRoutes, + 'POST', + '/api/subs', + ); + const res = createResponse('/api/subs'); + + handler( + { + body: { name: 'new-sub', subscriptions: ['ignored'] }, + query: {}, + }, + res, + ); + + expect(state[SUBS_KEY].map((item) => item.name)).to.deep.equal([ + 'new-sub', + 'older-sub', + ]); + expect(state[SUBS_KEY][0]).to.not.have.property('subscriptions'); + expect(res.statusCode).to.equal(201); + }); + + it('creates collections at the top when settings request it', function () { + state[COLLECTIONS_KEY] = [{ name: 'older-collection' }]; + const handler = getHandler( + registerCollectionRoutes, + 'POST', + '/api/collections', + ); + const res = createResponse('/api/collections'); + + handler( + { + body: { name: 'new-collection', subscriptions: [] }, + query: {}, + }, + res, + ); + + expect(state[COLLECTIONS_KEY].map((item) => item.name)).to.deep.equal([ + 'new-collection', + 'older-collection', + ]); + expect(res.statusCode).to.equal(201); + }); + + it('creates files at the top when settings request it', function () { + state[FILES_KEY] = [{ name: 'older-file' }]; + const handler = getHandler(registerFileRoutes, 'POST', '/api/files'); + const res = createResponse('/api/files'); + + handler( + { + body: { name: 'new-file' }, + query: {}, + }, + res, + ); + + expect(state[FILES_KEY].map((item) => item.name)).to.deep.equal([ + 'new-file', + 'older-file', + ]); + expect(res.statusCode).to.equal(201); + }); + + it('creates artifacts at the top when settings request it', function () { + state[ARTIFACTS_KEY] = [{ name: 'older-artifact' }]; + const handler = getHandler( + registerArtifactRoutes, + 'POST', + '/api/artifacts', + ); + const res = createResponse('/api/artifacts'); + + handler( + { + body: { + name: 'new-artifact', + type: 'file', + source: 'demo', + platform: 'JSON', }, - options: {}, + query: {}, }, - query: {}, - }, - res, - ); + res, + ); - expect(state[TOKENS_KEY].map((item) => item.token)).to.deep.equal([ - 'new-token', - 'older-token', - ]); - expect(state[TOKENS_KEY][0]).to.not.have.property('position'); - expect(res.statusCode).to.equal(200); - }); + expect(state[ARTIFACTS_KEY].map((item) => item.name)).to.deep.equal([ + 'new-artifact', + 'older-artifact', + ]); + expect(res.statusCode).to.equal(201); + }); - it('defaults to bottom insertion when no position is provided', function () { - state[SUBS_KEY] = [{ name: 'older-sub' }]; - state[SETTINGS_KEY] = {}; - const handler = getHandler( - registerSubscriptionRoutes, - 'POST', - '/api/subs', - ); - const res = createResponse('/api/subs'); + it('creates tokens at the top when settings request it without persisting transport metadata', async function () { + state[SUBS_KEY] = [{ name: 'sub-1' }]; + state[TOKENS_KEY] = [ + { token: 'older-token', type: 'sub', name: 'sub-1' }, + ]; + const handler = getHandler(registerTokenRoutes, 'POST', '/api/token'); + const res = createResponse('/api/token'); - handler( - { - body: { name: 'new-sub' }, - query: {}, - }, - res, - ); + await handler( + { + body: { + payload: { + type: 'sub', + name: 'sub-1', + token: 'new-token', + }, + options: {}, + }, + query: {}, + }, + res, + ); - expect(state[SUBS_KEY].map((item) => item.name)).to.deep.equal([ - 'older-sub', - 'new-sub', - ]); - expect(res.statusCode).to.equal(201); + expect(state[TOKENS_KEY].map((item) => item.token)).to.deep.equal([ + 'new-token', + 'older-token', + ]); + expect(state[TOKENS_KEY][0]).to.not.have.property('position'); + expect(res.statusCode).to.equal(200); + }); + + it('defaults to bottom insertion when no position is provided', function () { + state[SUBS_KEY] = [{ name: 'older-sub' }]; + state[SETTINGS_KEY] = {}; + const handler = getHandler( + registerSubscriptionRoutes, + 'POST', + '/api/subs', + ); + const res = createResponse('/api/subs'); + + handler( + { + body: { name: 'new-sub' }, + query: {}, + }, + res, + ); + + expect(state[SUBS_KEY].map((item) => item.name)).to.deep.equal([ + 'older-sub', + 'new-sub', + ]); + expect(res.statusCode).to.equal(201); + }); }); }); diff --git a/backend/src/utils/archive.js b/backend/src/utils/archive.js new file mode 100644 index 00000000..ff7bfca3 --- /dev/null +++ b/backend/src/utils/archive.js @@ -0,0 +1,200 @@ +import $ from '@/core/app'; +import { + ARTIFACTS_KEY, + COLLECTIONS_KEY, + FILES_KEY, + ARCHIVES_KEY, + SUBS_KEY, + TOKENS_KEY, +} from '@/constants'; +import { findByName } from '@/utils/database'; +import { + RequestInvalidError, + ResourceNotFoundError, +} from '@/restful/errors'; + +function cloneSnapshot(value) { + if (value === undefined) { + return undefined; + } + return JSON.parse(JSON.stringify(value)); +} + +function ensureArchiveStore() { + const current = $.read(ARCHIVES_KEY); + if (Array.isArray(current)) { + return current; + } + + const entries = []; + $.write(entries, ARCHIVES_KEY); + return entries; +} + +function getArchiveEntries() { + return ensureArchiveStore(); +} + +function writeArchiveEntries(entries) { + $.write(entries, ARCHIVES_KEY); +} + +function createArchiveId() { + return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; +} + +function insertArchiveEntry(entry) { + const entries = ensureArchiveStore(); + const nextEntry = { + id: createArchiveId(), + archivedAt: Date.now(), + ...entry, + }; + entries.unshift(nextEntry); + writeArchiveEntries(entries); + return nextEntry; +} + +function getArchiveEntry(id) { + return ensureArchiveStore().find((entry) => entry.id === id); +} + +function getRequiredArchiveEntry(id) { + const entry = getArchiveEntry(id); + if (!entry) { + throw new ResourceNotFoundError( + 'ARCHIVE_ENTRY_NOT_FOUND', + `Archive entry ${id} does not exist`, + ); + } + return entry; +} + +function removeArchiveEntry(id) { + const entries = ensureArchiveStore(); + const index = entries.findIndex((entry) => entry.id === id); + if (index === -1) { + throw new ResourceNotFoundError( + 'ARCHIVE_ENTRY_NOT_FOUND', + `Archive entry ${id} does not exist`, + ); + } + const [removed] = entries.splice(index, 1); + writeArchiveEntries(entries); + return removed; +} + +function sortArchiveEntries(ids) { + if (!Array.isArray(ids)) { + throw new RequestInvalidError( + 'INVALID_SORT_PAYLOAD', + 'Archive sort payload must be an array of ids', + ); + } + + const entries = ensureArchiveStore(); + const orderMap = new Map(ids.map((id, index) => [id, index])); + entries.sort((a, b) => { + const left = orderMap.has(a.id) + ? orderMap.get(a.id) + : Number.MAX_SAFE_INTEGER; + const right = orderMap.has(b.id) + ? orderMap.get(b.id) + : Number.MAX_SAFE_INTEGER; + return left - right; + }); + writeArchiveEntries(entries); + return entries; +} + +function buildArchiveEntry(itemType, snapshot, overrides = {}) { + return insertArchiveEntry({ + itemType, + name: snapshot.name, + displayName: snapshot.displayName, + remark: snapshot.remark, + tag: cloneSnapshot(snapshot.tag), + snapshot: cloneSnapshot(snapshot), + ...overrides, + }); +} + +function archiveSubscription(name) { + const allSubs = $.read(SUBS_KEY) || []; + const sub = findByName(allSubs, name); + if (!sub) { + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `Subscription ${name} does not exist!`, + ); + } + return buildArchiveEntry('sub', sub); +} + +function archiveCollection(name) { + const allCollections = $.read(COLLECTIONS_KEY) || []; + const collection = findByName(allCollections, name); + if (!collection) { + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `Collection ${name} does not exist!`, + ); + } + return buildArchiveEntry('col', collection); +} + +function archiveFile(name) { + const allFiles = $.read(FILES_KEY) || []; + const file = findByName(allFiles, name); + if (!file) { + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `File ${name} does not exist!`, + ); + } + return buildArchiveEntry('file', file); +} + +function archiveArtifact(name) { + const allArtifacts = $.read(ARTIFACTS_KEY) || []; + const artifact = findByName(allArtifacts, name); + if (!artifact) { + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `Artifact ${name} does not exist!`, + ); + } + return buildArchiveEntry('artifact', artifact); +} + +function archiveShare(token, type, name) { + const allTokens = $.read(TOKENS_KEY) || []; + const share = allTokens.find( + (item) => item.token === token && item.type === type && item.name === name, + ); + if (!share) { + throw new ResourceNotFoundError( + 'RESOURCE_NOT_FOUND', + `Share ${type}/${name}/${token} does not exist!`, + ); + } + return buildArchiveEntry('share', share, { + shareType: share.type, + }); +} + +export { + archiveArtifact, + archiveCollection, + archiveFile, + archiveShare, + archiveSubscription, + getArchiveEntries, + getArchiveEntry, + getRequiredArchiveEntry, + insertArchiveEntry, + removeArchiveEntry, + sortArchiveEntries, + writeArchiveEntries, + ensureArchiveStore, +};