diff --git a/backend/package.json b/backend/package.json index a77c7df0..8c4d9a66 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.21.62", + "version": "2.21.63", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "scripts": { diff --git a/backend/src/restful/artifacts.js b/backend/src/restful/artifacts.js index 5cb3c6f8..ee198164 100644 --- a/backend/src/restful/artifacts.js +++ b/backend/src/restful/artifacts.js @@ -5,7 +5,13 @@ import { ARTIFACTS_KEY, SETTINGS_KEY, } from '@/constants'; -import { deleteByName, findByName, updateByName } from '@/utils/database'; +import { + deleteByName, + findByName, + insertByPosition, + updateByName, +} from '@/utils/database'; +import { getCreateItemPosition } from '@/utils/create-item-position'; import { failed, success } from '@/restful/response'; import { InternalServerError, @@ -153,7 +159,7 @@ function createArtifact(req, res) { ), ); } else { - allArtifacts.push(artifact); + insertByPosition(allArtifacts, artifact, getCreateItemPosition()); $.write(allArtifacts, ARTIFACTS_KEY); success(res, artifact, 201); } diff --git a/backend/src/restful/collections.js b/backend/src/restful/collections.js index 6b3b55fc..8142cb21 100644 --- a/backend/src/restful/collections.js +++ b/backend/src/restful/collections.js @@ -1,4 +1,10 @@ -import { deleteByName, findByName, updateByName } from '@/utils/database'; +import { + deleteByName, + findByName, + insertByPosition, + updateByName, +} from '@/utils/database'; +import { getCreateItemPosition } from '@/utils/create-item-position'; import { COLLECTIONS_KEY, ARTIFACTS_KEY, FILES_KEY } from '@/constants'; import { failed, success } from '@/restful/response'; import $ from '@/core/app'; @@ -44,7 +50,7 @@ function createCollection(req, res) { ); return; } - allCols.push(collection); + insertByPosition(allCols, collection, getCreateItemPosition()); $.write(allCols, COLLECTIONS_KEY); success(res, collection, 201); } diff --git a/backend/src/restful/file.js b/backend/src/restful/file.js index 8a0714e9..34f7bc0b 100644 --- a/backend/src/restful/file.js +++ b/backend/src/restful/file.js @@ -1,4 +1,10 @@ -import { deleteByName, findByName, updateByName } from '@/utils/database'; +import { + deleteByName, + findByName, + insertByPosition, + updateByName, +} from '@/utils/database'; +import { getCreateItemPosition } from '@/utils/create-item-position'; import { getFlowHeaders, normalizeFlowHeader } from '@/utils/flow'; import { FILES_KEY, ARTIFACTS_KEY } from '@/constants'; import { failed, success } from '@/restful/response'; @@ -44,7 +50,7 @@ function createFile(req, res) { ), ); } - allFiles.push(file); + insertByPosition(allFiles, file, getCreateItemPosition()); $.write(allFiles, FILES_KEY); success(res, file, 201); } diff --git a/backend/src/restful/subscriptions.js b/backend/src/restful/subscriptions.js index 936a115b..fd3f52e9 100644 --- a/backend/src/restful/subscriptions.js +++ b/backend/src/restful/subscriptions.js @@ -4,7 +4,13 @@ import { ResourceNotFoundError, RequestInvalidError, } from './errors'; -import { deleteByName, findByName, updateByName } from '@/utils/database'; +import { + deleteByName, + findByName, + insertByPosition, + updateByName, +} from '@/utils/database'; +import { getCreateItemPosition } from '@/utils/create-item-position'; import { SUBS_KEY, COLLECTIONS_KEY, @@ -253,7 +259,7 @@ function createSubscription(req, res) { ); return; } - allSubs.push(sub); + insertByPosition(allSubs, sub, getCreateItemPosition()); $.write(allSubs, SUBS_KEY); success(res, sub, 201); } diff --git a/backend/src/restful/token.js b/backend/src/restful/token.js index df94586c..a53e9635 100644 --- a/backend/src/restful/token.js +++ b/backend/src/restful/token.js @@ -3,6 +3,8 @@ 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 { insertByPosition } from '@/utils/database'; +import { getCreateItemPosition } from '@/utils/create-item-position'; export default function register($app) { if (!$.read(TOKENS_KEY)) $.write([], TOKENS_KEY); @@ -175,13 +177,17 @@ async function signToken(req, res) { ) ); } - tokens.push({ - ...payload, - token, - createdAt: Date.now(), - expiresIn: expiresIn > 0 ? options?.expiresIn : undefined, - exp: expiresIn > 0 ? Date.now() + expiresIn : undefined, - }); + 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); return success(res, { diff --git a/backend/src/test/restful/create-position.spec.js b/backend/src/test/restful/create-position.spec.js new file mode 100644 index 00000000..c8aea498 --- /dev/null +++ b/backend/src/test/restful/create-position.spec.js @@ -0,0 +1,332 @@ +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, + SETTINGS_KEY, + SUBS_KEY, + TOKENS_KEY, +} from '@/constants'; +import { insertByPosition } from '@/utils/database'; +import { getCreateItemPosition } from '@/utils/create-item-position'; + +let $; +let registerSubscriptionRoutes; +let registerCollectionRoutes; +let registerFileRoutes; +let registerArtifactRoutes; +let registerTokenRoutes; +let originalRead; +let originalWrite; +let originalInfo; +let originalError; +let state; + +function createRouteApp() { + const handlers = new Map(); + const methods = ['get', 'post', 'put', 'patch', 'delete']; + + const app = { + handlers, + route(pattern) { + const chain = {}; + methods.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 { + statusCode: 200, + body: null, + req: { + route: { + path: routePath, + }, + }, + status(code) { + this.statusCode = code; + return this; + }, + json(payload) { + this.body = payload; + return this; + }, + }; +} + +before(async function () { + process.env.SUB_STORE_DATA_BASE_PATH = fs.mkdtempSync( + path.join(os.tmpdir(), 'sub-store-create-position-'), + ); + + ({ 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']); + }); + + it('appends when position is bottom', function () { + const list = ['existing']; + + insertByPosition(list, 'new', 'bottom'); + + 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'); + }); + + 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', + }, + }; + }); + + 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', + }, + query: {}, + }, + res, + ); + + expect(state[ARTIFACTS_KEY].map((item) => item.name)).to.deep.equal([ + 'new-artifact', + 'older-artifact', + ]); + expect(res.statusCode).to.equal(201); + }); + + 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'); + + await handler( + { + body: { + payload: { + type: 'sub', + name: 'sub-1', + token: 'new-token', + }, + options: {}, + }, + query: {}, + }, + 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); + }); + + 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/create-item-position.js b/backend/src/utils/create-item-position.js new file mode 100644 index 00000000..b1ac6169 --- /dev/null +++ b/backend/src/utils/create-item-position.js @@ -0,0 +1,9 @@ +import { SETTINGS_KEY } from '@/constants'; +import $ from '@/core/app'; + +export function getCreateItemPosition() { + const createItemPosition = + $.read(SETTINGS_KEY)?.appearanceSetting?.createItemPosition; + + return createItemPosition === 'top' ? 'top' : 'bottom'; +} diff --git a/backend/src/utils/database.js b/backend/src/utils/database.js index 9786046b..95b8b618 100644 --- a/backend/src/utils/database.js +++ b/backend/src/utils/database.js @@ -15,3 +15,12 @@ export function updateByName(list, name, newItem, field = 'name') { const idx = findIndexByName(list, name, field); list[idx] = newItem; } + +export function insertByPosition(list, item, position = 'bottom') { + if (position === 'top') { + list.unshift(item); + return; + } + + list.push(item); +}