Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

feat(files): add file favorites across repositories

johavend3724ec5f48d
diff --git a/backend/migrations/0004_gigantic_romulus.sql b/backend/migrations/0004_gigantic_romulus.sql
deleted file mode 100644
index 8f0b20ce..00000000
--- a/backend/migrations/0004_gigantic_romulus.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-ALTER TABLE `users` ADD `externalId` varchar(255);--> statement-breakpoint
-ALTER TABLE `users` ADD CONSTRAINT `external_id_idx` UNIQUE(`externalId`);
\ No newline at end of file
diff --git a/backend/migrations/0004_light_venom.sql b/backend/migrations/0004_light_venom.sql
new file mode 100644
index 00000000..862f02db
--- /dev/null
+++ b/backend/migrations/0004_light_venom.sql
@@ -0,0 +1,13 @@
+CREATE TABLE `files_favorites` (
+ `userId` bigint unsigned NOT NULL,
+ `fileId` bigint unsigned NOT NULL,
+ `createdAt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CONSTRAINT `files_favorites_userId_fileId_pk` PRIMARY KEY(`userId`,`fileId`)
+);
+--> statement-breakpoint
+ALTER TABLE `users` ADD `externalId` varchar(255);--> statement-breakpoint
+ALTER TABLE `users` ADD CONSTRAINT `external_id_idx` UNIQUE(`externalId`);--> statement-breakpoint
+ALTER TABLE `files_favorites` ADD CONSTRAINT `files_favorites_userId_users_id_fk` FOREIGN KEY (`userId`) REFERENCES `users`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE `files_favorites` ADD CONSTRAINT `files_favorites_fileId_files_id_fk` FOREIGN KEY (`fileId`) REFERENCES `files`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+CREATE INDEX `file_idx` ON `files_favorites` (`fileId`);--> statement-breakpoint
+CREATE INDEX `user_created_idx` ON `files_favorites` (`userId`,`createdAt`);
\ No newline at end of file
diff --git a/backend/migrations/meta/0004_snapshot.json b/backend/migrations/meta/0004_snapshot.json
index b984acfc..b05f5c43 100644
--- a/backend/migrations/meta/0004_snapshot.json
+++ b/backend/migrations/meta/0004_snapshot.json
@@ -1,7 +1,7 @@
{
"version": "5",
"dialect": "mysql",
- "id": "2f63e809-e21d-48a9-bcb6-1d64255bd1b1",
+ "id": "0e329e81-02d6-4c0d-8c44-641efb30b285",
"prevId": "da1a6d68-b222-46e6-bda9-2a917b447be2",
"tables": {
"cache": {
@@ -1667,6 +1667,89 @@
"uniqueConstraints": {},
"checkConstraint": {}
},
+ "files_favorites": {
+ "name": "files_favorites",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fileId": {
+ "name": "fileId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "file_idx": {
+ "name": "file_idx",
+ "columns": [
+ "fileId"
+ ],
+ "isUnique": false
+ },
+ "user_created_idx": {
+ "name": "user_created_idx",
+ "columns": [
+ "userId",
+ "createdAt"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "files_favorites_userId_users_id_fk": {
+ "name": "files_favorites_userId_users_id_fk",
+ "tableFrom": "files_favorites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_favorites_fileId_files_id_fk": {
+ "name": "files_favorites_fileId_files_id_fk",
+ "tableFrom": "files_favorites",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "files_favorites_userId_fileId_pk": {
+ "name": "files_favorites_userId_fileId_pk",
+ "columns": [
+ "userId",
+ "fileId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
"files_recents": {
"name": "files_recents",
"columns": {
diff --git a/backend/migrations/meta/_journal.json b/backend/migrations/meta/_journal.json
index 6c38fe97..1e39e006 100644
--- a/backend/migrations/meta/_journal.json
+++ b/backend/migrations/meta/_journal.json
@@ -33,8 +33,8 @@
{
"idx": 4,
"version": "5",
- "when": 1786979666928,
- "tag": "0004_gigantic_romulus",
+ "when": 1787432793784,
+ "tag": "0004_light_venom",
"breakpoints": true
}
]
diff --git a/backend/src/applications/comments/services/comments-queries.service.ts b/backend/src/applications/comments/services/comments-queries.service.ts
index 2360fdfa..81754025 100644
--- a/backend/src/applications/comments/services/comments-queries.service.ts
+++ b/backend/src/applications/comments/services/comments-queries.service.ts
@@ -146,6 +146,8 @@ export class CommentsQueries {
and(
isNotNull(shareFile.id),
eq(shareFile.isDir, true),
+ // A file moved to trash leaves the storage scope of its former share root.
+ eq(files.inTrash, shareFile.inTrash),
sql`${files.spaceId} <=> ${shareFile.spaceId}`,
sql`${files.ownerId} <=> ${shareFile.ownerId}`,
sql`${files.spaceExternalRootId} <=> ${shareFile.spaceExternalRootId}`,
@@ -232,6 +234,8 @@ export class CommentsQueries {
and(
isNotNull(spaceRootFile.id),
eq(spaceRootFile.isDir, true),
+ // A file moved to trash leaves the storage scope of its former anchored root.
+ eq(files.inTrash, spaceRootFile.inTrash),
sql`${files.ownerId} <=> ${spaceRootFile.ownerId}`,
sql`${files.path} REGEXP CONCAT('^', IF(${spaceRootFile.path} = '.', CONCAT(${spaceRootFile.name}, '(/.*|)$'), CONCAT(${spaceRootFile.path}, '/')))`
)
diff --git a/backend/src/applications/files/constants/routes.ts b/backend/src/applications/files/constants/routes.ts
index ec9b6db2..ad0c768b 100644
--- a/backend/src/applications/files/constants/routes.ts
+++ b/backend/src/applications/files/constants/routes.ts
@@ -10,6 +10,7 @@ export const FILES_ROUTE = {
TASKS_DELETE: 'delete',
TASKS_DOWNLOAD: 'download',
TASKS_POLL: 'poll',
+ FAVORITES: 'favorites',
RECENTS: 'recents',
SEARCH: 'search',
INDEXING: 'indexing',
@@ -30,6 +31,7 @@ export const API_FILES_TASKS_CANCEL = `${API_FILES_TASKS}/${FILES_ROUTE.TASKS_CA
export const API_FILES_TASKS_DELETE = `${API_FILES_TASKS}/${FILES_ROUTE.TASKS_DELETE}`
export const API_FILES_TASKS_DOWNLOAD = `${FILES_ROUTE.BASE}/${FILES_ROUTE.TASKS}/${FILES_ROUTE.TASKS_DOWNLOAD}`
export const API_FILES_TASKS_POLL = `${API_FILES_TASKS}/${FILES_ROUTE.TASKS_POLL}`
+export const API_FILES_FAVORITES = `${FILES_ROUTE.BASE}/${FILES_ROUTE.FAVORITES}`
export const API_FILES_RECENTS = `${FILES_ROUTE.BASE}/${FILES_ROUTE.RECENTS}`
export const API_FILES_SEARCH = `${FILES_ROUTE.BASE}/${FILES_ROUTE.SEARCH}`
export const API_FILES_INDEXING = `${FILES_ROUTE.BASE}/${FILES_ROUTE.INDEXING}`
diff --git a/backend/src/applications/files/dto/file-favorite.dto.ts b/backend/src/applications/files/dto/file-favorite.dto.ts
new file mode 100644
index 00000000..dbd8fdba
--- /dev/null
+++ b/backend/src/applications/files/dto/file-favorite.dto.ts
@@ -0,0 +1,14 @@
+import { IsInt, IsNotEmpty, Min } from 'class-validator'
+
+export class FileFavoriteDto {
+ @IsNotEmpty()
+ @IsInt()
+ fileId: number
+}
+
+export class DeleteFileFavoriteDto {
+ @IsNotEmpty()
+ @IsInt()
+ @Min(1)
+ fileId: number
+}
diff --git a/backend/src/applications/files/files.controller.spec.ts b/backend/src/applications/files/files.controller.spec.ts
index d09740da..64ada721 100644
--- a/backend/src/applications/files/files.controller.spec.ts
+++ b/backend/src/applications/files/files.controller.spec.ts
@@ -4,6 +4,7 @@ import { ContextManager } from '../../infrastructure/context/services/context-ma
import { SpaceGuard } from '../spaces/guards/space.guard'
import { FILE_OPERATION } from './constants/operations'
import { FilesController } from './files.controller'
+import { FilesFavoritesManager } from './services/files-favorites-manager.service'
import { FilesMethods } from './services/files-methods.service'
import { FilesRecents } from './services/files-recents.service'
import { FilesSearchManager } from './services/files-search-manager.service'
@@ -55,6 +56,7 @@ describe(FilesController.name, () => {
{ provide: FilesSearchManager, useValue: filesSearchMock },
{ provide: ContextManager, useValue: filesSearchMock },
{ provide: FilesContentIndexer, useValue: {} },
+ { provide: FilesFavoritesManager, useValue: {} },
ContextInterceptor
]
})
diff --git a/backend/src/applications/files/files.controller.ts b/backend/src/applications/files/files.controller.ts
index b52e3930..9b9c7711 100644
--- a/backend/src/applications/files/files.controller.ts
+++ b/backend/src/applications/files/files.controller.ts
@@ -36,15 +36,18 @@ import { UserModel } from '../users/models/user.model'
import { FILE_OPERATION, FORCE_AS_FILE_OWNER } from './constants/operations'
import { FILES_ROUTE } from './constants/routes'
import { CompressFileDto, CopyMoveFileDto, DownloadFileDto, MakeFileDto, SearchFilesDto } from './dto/file-operations.dto'
+import { DeleteFileFavoriteDto, FileFavoriteDto } from './dto/file-favorite.dto'
import { FileLockProps } from './interfaces/file-props.interface'
import { FileTask } from './models/file-task'
import { FileContent } from './schemas/file-content.interface'
+import type { FileFavorite, FileFavoriteIdentity } from './schemas/file-favorite.interface'
import { FileRecent } from './schemas/file-recent.interface'
import { FilesMethods } from './services/files-methods.service'
import { FilesRecents } from './services/files-recents.service'
import { FilesSearchManager } from './services/files-search-manager.service'
import { FilesTasksManager } from './services/tasks/files-tasks-manager.service'
import { FilesContentIndexer } from './services/files-content-indexer.service'
+import { FilesFavoritesManager } from './services/files-favorites-manager.service'
import { UserHaveRole } from '../users/decorators/roles.decorator'
import { USER_ROLE } from '../users/constants/user'
import { UserRolesGuard } from '../users/guards/roles.guard'
@@ -61,7 +64,8 @@ export class FilesController {
private readonly filesTasksManager: FilesTasksManager,
private readonly filesRecents: FilesRecents,
private readonly filesSearch: FilesSearchManager,
- private readonly filesContentIndexer: FilesContentIndexer
+ private readonly filesContentIndexer: FilesContentIndexer,
+ private readonly filesFavoritesManager: FilesFavoritesManager
) {}
// OPERATIONS
@@ -185,6 +189,33 @@ export class FilesController {
return this.filesTasksManager.createTask(FILE_OPERATION.DELETE, user, space, null, this.filesMethods.delete.name)
}
+ // FAVORITES
+
+ @Get(FILES_ROUTE.FAVORITES)
+ @SkipSpaceGuard()
+ @UserHaveRole(USER_ROLE.GUEST)
+ @UseGuards(UserRolesGuard)
+ getFavorites(@GetUser() user: UserModel): Promise<FileFavorite[]> {
+ return this.filesFavoritesManager.getFavorites(user)
+ }
+
+ @Post(`${FILES_ROUTE.FAVORITES}/*`)
+ // only writes user metadata; SpaceGuard still resolves and validates access to the requested location.
+ @SkipSpacePermissionsCheck()
+ @UserHaveRole(USER_ROLE.GUEST)
+ @UseGuards(UserRolesGuard)
+ addFavorite(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body() favoriteDto: FileFavoriteDto): Promise<FileFavoriteIdentity> {
+ return this.filesFavoritesManager.addFavorite(user, space, favoriteDto.fileId)
+ }
+
+ @Delete(FILES_ROUTE.FAVORITES)
+ @SkipSpaceGuard()
+ @UserHaveRole(USER_ROLE.GUEST)
+ @UseGuards(UserRolesGuard)
+ removeFavorite(@GetUser() user: UserModel, @Body() favoriteDto: DeleteFileFavoriteDto): Promise<void> {
+ return this.filesFavoritesManager.removeFavorite(user, favoriteDto.fileId)
+ }
+
// RECENT FILES
@Get(FILES_ROUTE.RECENTS)
diff --git a/backend/src/applications/files/files.module.ts b/backend/src/applications/files/files.module.ts
index 6bec636b..87e23cea 100644
--- a/backend/src/applications/files/files.module.ts
+++ b/backend/src/applications/files/files.module.ts
@@ -22,6 +22,8 @@ import { FilesTasksWatcher } from './services/tasks/files-tasks-watcher.service'
import { FilesEventManager } from './services/files-event-manager.service'
import { FilesQuotaManager } from './services/files-quota-manager.service'
import { FilesTrashRetention } from './services/files-trash-retention.service'
+import { FilesFavoritesManager } from './services/files-favorites-manager.service'
+import { FilesFavoritesQueries } from './services/files-favorites-queries.service'
@Module({
imports: [
@@ -48,7 +50,9 @@ import { FilesTrashRetention } from './services/files-trash-retention.service'
FilesSearchManager,
FilesEventManager,
FilesQuotaManager,
- FilesTrashRetention
+ FilesTrashRetention,
+ FilesFavoritesQueries,
+ FilesFavoritesManager
],
exports: [FilesManager, FilesQueries, FilesLockManager, FilesQuotaManager, FilesMethods, FilesRecents]
})
diff --git a/backend/src/applications/files/interfaces/file-props.interface.ts b/backend/src/applications/files/interfaces/file-props.interface.ts
index 25573a8a..098cb046 100644
--- a/backend/src/applications/files/interfaces/file-props.interface.ts
+++ b/backend/src/applications/files/interfaces/file-props.interface.ts
@@ -45,4 +45,5 @@ export interface FileProps extends Omit<File, 'ownerId' | 'spaceId' | 'spaceExte
shares?: Pick<Share, 'id' | 'alias' | 'name' | 'type'>[]
syncs?: Pick<SyncPath, 'clientId' | 'id'> & { clientName: string }[]
hasComments?: boolean
+ isFavorite?: boolean
}
diff --git a/backend/src/applications/files/schemas/file-favorite.interface.ts b/backend/src/applications/files/schemas/file-favorite.interface.ts
new file mode 100644
index 00000000..654db43d
--- /dev/null
+++ b/backend/src/applications/files/schemas/file-favorite.interface.ts
@@ -0,0 +1,26 @@
+import { SPACE_ALIAS } from '../../spaces/constants/spaces'
+import { FILE_REPOSITORY } from '../constants/operations'
+import type { FileProps } from '../interfaces/file-props.interface'
+
+export type FileFavoriteRepository = SPACE_ALIAS.PERSONAL | FILE_REPOSITORY.SPACE | FILE_REPOSITORY.SHARE
+
+export interface FileFavorite extends FileProps {
+ fileId: number
+ createdAt: Date
+ isDisabled: boolean
+ // `path` contains the logical parent location when the file remains accessible.
+ repository?: FileFavoriteRepository
+ displayRootName?: string
+}
+
+export interface FileFavoriteLocation {
+ fileId: number
+ repository: FileFavoriteRepository
+ path: string
+ name: string
+ displayRootName?: string
+ contextId: number
+ rootId: number
+}
+
+export type FileFavoriteIdentity = Pick<FileFavorite, 'fileId'>
diff --git a/backend/src/applications/files/schemas/files-favorites.schema.ts b/backend/src/applications/files/schemas/files-favorites.schema.ts
new file mode 100644
index 00000000..02208530
--- /dev/null
+++ b/backend/src/applications/files/schemas/files-favorites.schema.ts
@@ -0,0 +1,24 @@
+import { sql } from 'drizzle-orm'
+import { bigint, datetime, index, mysqlTable, primaryKey } from 'drizzle-orm/mysql-core'
+import { users } from '../../users/schemas/users.schema'
+import { files } from './files.schema'
+
+export const filesFavorites = mysqlTable(
+ 'files_favorites',
+ {
+ userId: bigint('userId', { mode: 'number', unsigned: true })
+ .references(() => users.id, { onDelete: 'cascade' })
+ .notNull(),
+ fileId: bigint('fileId', { mode: 'number', unsigned: true })
+ .references(() => files.id, { onDelete: 'cascade' })
+ .notNull(),
+ createdAt: datetime('createdAt', { mode: 'date' })
+ .default(sql`CURRENT_TIMESTAMP`)
+ .notNull()
+ },
+ (table) => [
+ primaryKey({ columns: [table.userId, table.fileId] }),
+ index('file_idx').on(table.fileId),
+ index('user_created_idx').on(table.userId, table.createdAt)
+ ]
+)
diff --git a/backend/src/applications/files/services/files-content-parser.service.ts b/backend/src/applications/files/services/files-content-parser.service.ts
index 48d4ea49..6d825e74 100644
--- a/backend/src/applications/files/services/files-content-parser.service.ts
+++ b/backend/src/applications/files/services/files-content-parser.service.ts
@@ -92,19 +92,11 @@ export class FilesContentParser {
continue
}
const spacePath: FileParseContext[] = [{ realPath: spaceFilesPath, pathPrefix: `${SPACE_REPOSITORY.FILES}/${space.alias}`, isDir: true }]
- const rootPaths = space.roots.map((r: any): FileParseContext =>
- r.externalPath
- ? {
- realPath: r.externalPath,
- pathPrefix: `${SPACE_REPOSITORY.FILES}/${space.alias}/${r.alias}`,
- isDir: r.isDir
- }
- : {
- realPath: path.join(UserModel.getFilesPath(r.file.fromOwner), r.file.path),
- pathPrefix: `${SPACE_REPOSITORY.FILES}/${space.alias}/${r.alias}`,
- isDir: r.isDir
- }
- )
+ const rootPaths = space.roots.map((r: any): FileParseContext => ({
+ realPath: r.externalPath || path.join(UserModel.getFilesPath(r.file.fromOwner), r.file.path),
+ pathPrefix: `${SPACE_REPOSITORY.FILES}/${space.alias}/${r.alias}`,
+ isDir: r.isDir
+ }))
paths.push({ id: space.id, type: FILE_REPOSITORY.SPACE, paths: [...spacePath, ...rootPaths] })
}
return paths
diff --git a/backend/src/applications/files/services/files-favorites-manager.service.spec.ts b/backend/src/applications/files/services/files-favorites-manager.service.spec.ts
new file mode 100644
index 00000000..e7afe1e4
--- /dev/null
+++ b/backend/src/applications/files/services/files-favorites-manager.service.spec.ts
@@ -0,0 +1,208 @@
+import { HttpStatus } from '@nestjs/common'
+import { Test, TestingModule } from '@nestjs/testing'
+import { SharesQueries } from '../../shares/services/shares-queries.service'
+import { SPACE_ALIAS } from '../../spaces/constants/spaces'
+import { SpacesQueries } from '../../spaces/services/spaces-queries.service'
+import { USER_PERMISSION } from '../../users/constants/user'
+import { FILE_REPOSITORY } from '../constants/operations'
+import type { FileProps } from '../interfaces/file-props.interface'
+import { getProps, isPathExists } from '../utils/files'
+import { FilesFavoritesManager } from './files-favorites-manager.service'
+import { FilesFavoritesQueries } from './files-favorites-queries.service'
+import { FilesQueries } from './files-queries.service'
+import type { Mock } from 'vitest'
+
+vi.mock('../utils/files', () => ({
+ getProps: vi.fn(),
+ isPathExists: vi.fn()
+}))
+
+describe(FilesFavoritesManager.name, () => {
+ let service: FilesFavoritesManager
+ let filesQueries: {
+ getSpaceFileId: Mock
+ getOrCreateSpaceFile: Mock
+ }
+ let filesFavoritesQueries: {
+ getFavoritesFromUser: Mock
+ getFavoriteLocationsFromSpaces: Mock
+ getFavoriteLocationsFromShares: Mock
+ addFavorite: Mock
+ removeFavorite: Mock
+ }
+ let spacesQueries: { spaceIdentities: Mock }
+ let sharesQueries: { shareIdentities: Mock }
+
+ beforeEach(async () => {
+ vi.clearAllMocks()
+ vi.mocked(isPathExists).mockResolvedValue(true)
+ vi.mocked(getProps).mockResolvedValue({ name: 'file.txt', path: 'docs' } as FileProps)
+ filesQueries = {
+ getSpaceFileId: vi.fn(),
+ getOrCreateSpaceFile: vi.fn()
+ }
+ filesFavoritesQueries = {
+ getFavoritesFromUser: vi.fn().mockResolvedValue([]),
+ getFavoriteLocationsFromSpaces: vi.fn().mockResolvedValue([]),
+ getFavoriteLocationsFromShares: vi.fn().mockResolvedValue([]),
+ addFavorite: vi.fn().mockResolvedValue(undefined),
+ removeFavorite: vi.fn().mockResolvedValue(undefined)
+ }
+ spacesQueries = { spaceIdentities: vi.fn().mockResolvedValue([]) }
+ sharesQueries = { shareIdentities: vi.fn().mockResolvedValue([]) }
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ FilesFavoritesManager,
+ { provide: FilesQueries, useValue: filesQueries },
+ { provide: FilesFavoritesQueries, useValue: filesFavoritesQueries },
+ { provide: SpacesQueries, useValue: spacesQueries },
+ { provide: SharesQueries, useValue: sharesQueries }
+ ]
+ }).compile()
+
+ module.useLogger(['fatal'])
+ service = module.get(FilesFavoritesManager)
+ })
+
+ const userWithPermissions = (applications: USER_PERMISSION[] = [], isAdmin = false) =>
+ ({
+ id: 7,
+ isAdmin,
+ havePermission: (permission: USER_PERMISSION) => isAdmin || applications.includes(permission)
+ }) as any
+
+ const makeSpace = (dbFile: Record<string, unknown> = {}) =>
+ ({
+ realPath: '/storage/docs/file.txt',
+ dbFile: {
+ path: 'docs',
+ ownerId: 7,
+ spaceExternalRootId: null,
+ shareExternalId: null,
+ ...dbFile
+ }
+ }) as any
+
+ it('should resolve favorites from cached accessible locations by repository priority', async () => {
+ filesFavoritesQueries.getFavoritesFromUser.mockResolvedValueOnce([
+ {
+ fileId: 1,
+ id: 1,
+ repository: SPACE_ALIAS.PERSONAL,
+ name: 'personal.txt',
+ path: 'files/personal/docs',
+ isDisabled: false
+ },
+ { fileId: 2, id: 2, name: 'missing.txt', path: 'missing', isDisabled: true }
+ ])
+ spacesQueries.spaceIdentities.mockResolvedValueOnce([{ id: 10 }])
+ sharesQueries.shareIdentities.mockResolvedValueOnce([{ id: 20 }])
+ filesFavoritesQueries.getFavoriteLocationsFromSpaces.mockResolvedValueOnce([
+ {
+ fileId: 2,
+ repository: FILE_REPOSITORY.SPACE,
+ path: 'files/project/docs',
+ name: 'space.txt',
+ displayRootName: 'Project',
+ contextId: 10,
+ rootId: 0
+ }
+ ])
+ filesFavoritesQueries.getFavoriteLocationsFromShares.mockResolvedValueOnce([
+ {
+ fileId: 2,
+ repository: FILE_REPOSITORY.SHARE,
+ path: 'shares/public/docs',
+ name: 'share.txt',
+ contextId: 20,
+ rootId: 0
+ }
+ ])
+
+ const result = await service.getFavorites(
+ userWithPermissions([USER_PERMISSION.PERSONAL_SPACE, USER_PERMISSION.SPACES, USER_PERMISSION.SHARES], true)
+ )
+
+ expect(spacesQueries.spaceIdentities).toHaveBeenCalledWith(7)
+ expect(sharesQueries.shareIdentities).toHaveBeenCalledWith(7, 1)
+ expect(filesFavoritesQueries.getFavoritesFromUser).toHaveBeenCalledWith(7, true)
+ expect(filesFavoritesQueries.getFavoriteLocationsFromSpaces).toHaveBeenCalledWith(7, [10])
+ expect(filesFavoritesQueries.getFavoriteLocationsFromShares).toHaveBeenCalledWith(7, [20])
+ expect(result[0]).toMatchObject({
+ fileId: 1,
+ repository: SPACE_ALIAS.PERSONAL,
+ path: 'files/personal/docs',
+ name: 'personal.txt',
+ isDisabled: false
+ })
+ expect(result[0]).not.toHaveProperty('priority')
+ expect(result[1]).toMatchObject({
+ fileId: 2,
+ repository: FILE_REPOSITORY.SPACE,
+ path: 'files/project/docs',
+ name: 'space.txt',
+ displayRootName: 'Project',
+ isDisabled: false
+ })
+ expect(result[1]).not.toHaveProperty('priority')
+ })
+
+ it('should skip inaccessible repositories', async () => {
+ filesFavoritesQueries.getFavoritesFromUser.mockResolvedValueOnce([{ fileId: 1, id: 1, name: 'stored.txt', path: 'stored', isDisabled: true }])
+
+ const result = await service.getFavorites(userWithPermissions())
+
+ expect(spacesQueries.spaceIdentities).not.toHaveBeenCalled()
+ expect(sharesQueries.shareIdentities).not.toHaveBeenCalled()
+ expect(filesFavoritesQueries.getFavoritesFromUser).toHaveBeenCalledWith(7, false)
+ expect(filesFavoritesQueries.getFavoriteLocationsFromSpaces).not.toHaveBeenCalled()
+ expect(filesFavoritesQueries.getFavoriteLocationsFromShares).not.toHaveBeenCalled()
+ expect(result).toEqual([{ fileId: 1, id: 1, name: 'stored.txt', path: 'stored', isDisabled: true }])
+ })
+
+ it('should add an already indexed favorite', async () => {
+ filesQueries.getSpaceFileId.mockResolvedValueOnce(42)
+
+ await expect(service.addFavorite(userWithPermissions(), makeSpace(), 42)).resolves.toEqual({ fileId: 42 })
+
+ expect(filesQueries.getOrCreateSpaceFile).not.toHaveBeenCalled()
+ expect(filesFavoritesQueries.addFavorite).toHaveBeenCalledWith(7, 42)
+ })
+
+ it('should index an untracked file before adding it', async () => {
+ filesQueries.getSpaceFileId.mockResolvedValueOnce(undefined)
+ filesQueries.getOrCreateSpaceFile.mockResolvedValueOnce(84)
+ const space = makeSpace()
+
+ await expect(service.addFavorite(userWithPermissions(), space, -1)).resolves.toEqual({ fileId: 84 })
+
+ const fileProps = { name: 'file.txt', path: 'docs', id: undefined }
+ expect(filesQueries.getSpaceFileId).toHaveBeenCalledWith(fileProps, space.dbFile)
+ expect(filesQueries.getOrCreateSpaceFile).toHaveBeenCalledWith(-1, fileProps, space.dbFile)
+ expect(filesFavoritesQueries.addFavorite).toHaveBeenCalledWith(7, 84)
+ })
+
+ it('should reject a favorite when the provided file id does not match the indexed file', async () => {
+ filesQueries.getSpaceFileId.mockResolvedValueOnce(43)
+
+ await expect(service.addFavorite(userWithPermissions(), makeSpace(), 42)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+
+ expect(filesQueries.getOrCreateSpaceFile).not.toHaveBeenCalled()
+ expect(filesFavoritesQueries.addFavorite).not.toHaveBeenCalled()
+ })
+
+ it.each(['spaceExternalRootId', 'shareExternalId'])('should reject a virtual external root identified by %s', async (externalId) => {
+ const space = makeSpace({ path: '.', [externalId]: 10 })
+
+ await expect(service.addFavorite(userWithPermissions(), space, -1)).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST })
+
+ expect(isPathExists).not.toHaveBeenCalled()
+ expect(filesFavoritesQueries.addFavorite).not.toHaveBeenCalled()
+ })
+
+ it('should remove only the current user favorite', async () => {
+ await service.removeFavorite(userWithPermissions(), 42)
+
+ expect(filesFavoritesQueries.removeFavorite).toHaveBeenCalledWith(7, 42)
+ })
+})
diff --git a/backend/src/applications/files/services/files-favorites-manager.service.ts b/backend/src/applications/files/services/files-favorites-manager.service.ts
new file mode 100644
index 00000000..c29623c0
--- /dev/null
+++ b/backend/src/applications/files/services/files-favorites-manager.service.ts
@@ -0,0 +1,121 @@
+import { HttpException, HttpStatus, Injectable } from '@nestjs/common'
+import { SharesQueries } from '../../shares/services/shares-queries.service'
+import { SPACE_ALIAS } from '../../spaces/constants/spaces'
+import { SpaceEnv } from '../../spaces/models/space-env.model'
+import { SpacesQueries } from '../../spaces/services/spaces-queries.service'
+import { USER_PERMISSION } from '../../users/constants/user'
+import { UserModel } from '../../users/models/user.model'
+import { FILE_REPOSITORY } from '../constants/operations'
+import { FileProps } from '../interfaces/file-props.interface'
+import type { FileFavorite, FileFavoriteIdentity, FileFavoriteLocation, FileFavoriteRepository } from '../schemas/file-favorite.interface'
+import { getProps, isPathExists } from '../utils/files'
+import { FilesFavoritesQueries } from './files-favorites-queries.service'
+import { FilesQueries } from './files-queries.service'
+
+const FAVORITE_REPOSITORY_PRIORITY: Record<FileFavoriteRepository, number> = {
+ [SPACE_ALIAS.PERSONAL]: 0,
+ [FILE_REPOSITORY.SPACE]: 1,
+ [FILE_REPOSITORY.SHARE]: 2
+}
+
+@Injectable()
+export class FilesFavoritesManager {
+ constructor(
+ private readonly filesQueries: FilesQueries,
+ private readonly filesFavoritesQueries: FilesFavoritesQueries,
+ private readonly spacesQueries: SpacesQueries,
+ private readonly sharesQueries: SharesQueries
+ ) {}
+
+ async getFavorites(user: UserModel): Promise<FileFavorite[]> {
+ const hasPersonal = user.havePermission(USER_PERMISSION.PERSONAL_SPACE)
+ const [favorites, spaces, shares] = await Promise.all([
+ this.filesFavoritesQueries.getFavoritesFromUser(user.id, hasPersonal),
+ user.havePermission(USER_PERMISSION.SPACES) ? this.spacesQueries.spaceIdentities(user.id) : Promise.resolve([]),
+ user.havePermission(USER_PERMISSION.SHARES) ? this.sharesQueries.shareIdentities(user.id, +user.isAdmin) : Promise.resolve([])
+ ])
+ if (!favorites.length) {
+ return []
+ }
+ if (!favorites.some(({ isDisabled }) => isDisabled)) {
+ return favorites
+ }
+ const [spaceLocations, shareLocations] = await Promise.all([
+ spaces.length
+ ? this.filesFavoritesQueries.getFavoriteLocationsFromSpaces(
+ user.id,
+ spaces.map(({ id }) => id)
+ )
+ : Promise.resolve([]),
+ shares.length
+ ? this.filesFavoritesQueries.getFavoriteLocationsFromShares(
+ user.id,
+ shares.map(({ id }) => id)
+ )
+ : Promise.resolve([])
+ ])
+ const locations = [...spaceLocations, ...shareLocations].sort(
+ (a, b) =>
+ FAVORITE_REPOSITORY_PRIORITY[a.repository] - FAVORITE_REPOSITORY_PRIORITY[b.repository] || a.contextId - b.contextId || a.rootId - b.rootId
+ )
+ const locationsByFileId = new Map<number, FileFavoriteLocation>()
+ for (const location of locations) {
+ if (!locationsByFileId.has(location.fileId)) {
+ locationsByFileId.set(location.fileId, location)
+ }
+ }
+ return favorites.map((favorite) => {
+ if (!favorite.isDisabled) {
+ return favorite
+ }
+ const location = locationsByFileId.get(favorite.fileId)
+ if (!location) {
+ return favorite
+ }
+ return {
+ ...favorite,
+ repository: location.repository,
+ path: location.path,
+ name: location.name,
+ displayRootName: location.displayRootName,
+ isDisabled: false
+ }
+ })
+ }
+
+ async addFavorite(user: UserModel, space: SpaceEnv, fileId: number): Promise<FileFavoriteIdentity> {
+ this.checkSupportedTarget(space)
+ const resolvedFileId = await this.resolveFileId(space, fileId)
+ await this.filesFavoritesQueries.addFavorite(user.id, resolvedFileId)
+ return { fileId: resolvedFileId }
+ }
+
+ removeFavorite(user: UserModel, fileId: number): Promise<void> {
+ return this.filesFavoritesQueries.removeFavorite(user.id, fileId)
+ }
+
+ private async resolveFileId(space: SpaceEnv, fileId: number): Promise<number> {
+ if (!(await isPathExists(space.realPath))) {
+ throw new HttpException('Location not found', HttpStatus.NOT_FOUND)
+ }
+ const fileProps: FileProps = { ...(await getProps(space.realPath, space.dbFile.path)), id: undefined }
+ const dbFileId = await this.filesQueries.getSpaceFileId(fileProps, space.dbFile)
+ if (dbFileId !== undefined) {
+ if (fileId > 0 && fileId !== dbFileId) {
+ throw new HttpException('File id mismatch', HttpStatus.BAD_REQUEST)
+ }
+ return dbFileId
+ }
+ return this.filesQueries.getOrCreateSpaceFile(fileId, fileProps, space.dbFile)
+ }
+
+ private checkSupportedTarget(space: SpaceEnv): void {
+ if (space.inTrashRepository) {
+ throw new HttpException('The trash is read-only', HttpStatus.FORBIDDEN)
+ }
+ // Virtual external roots have no persisted file row and therefore no stable id to favorite.
+ if ((space.dbFile.spaceExternalRootId || space.dbFile.shareExternalId) && space.dbFile.path === '.') {
+ throw new HttpException('Not supported on this kind of location', HttpStatus.BAD_REQUEST)
+ }
+ }
+}
diff --git a/backend/src/applications/files/services/files-favorites-queries.e2e-spec.ts b/backend/src/applications/files/services/files-favorites-queries.e2e-spec.ts
new file mode 100644
index 00000000..5ecdc2e3
--- /dev/null
+++ b/backend/src/applications/files/services/files-favorites-queries.e2e-spec.ts
@@ -0,0 +1,162 @@
+import { Test, TestingModule } from '@nestjs/testing'
+import { eq, inArray } from 'drizzle-orm'
+import { randomUUID } from 'node:crypto'
+import type { Cache } from '../../../infrastructure/cache/cache.service'
+import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'
+import { DatabaseModule } from '../../../infrastructure/database/database.module'
+import type { DBSchema } from '../../../infrastructure/database/interfaces/database.interface'
+import { dbGetInsertedId } from '../../../infrastructure/database/utils'
+import { comments } from '../../comments/schemas/comments.schema'
+import { CommentsQueries } from '../../comments/services/comments-queries.service'
+import { sharesMembers } from '../../shares/schemas/shares-members.schema'
+import { shares } from '../../shares/schemas/shares.schema'
+import { SharesQueries } from '../../shares/services/shares-queries.service'
+import { SPACE_ALIAS } from '../../spaces/constants/spaces'
+import { spacesMembers } from '../../spaces/schemas/spaces-members.schema'
+import { spacesRoots } from '../../spaces/schemas/spaces-roots.schema'
+import { spaces } from '../../spaces/schemas/spaces.schema'
+import { SpacesQueries } from '../../spaces/services/spaces-queries.service'
+import { users } from '../../users/schemas/users.schema'
+import { FILE_REPOSITORY } from '../constants/operations'
+import { filesFavorites } from '../schemas/files-favorites.schema'
+import { files } from '../schemas/files.schema'
+import { FilesFavoritesQueries } from './files-favorites-queries.service'
+import { FilesQueries } from './files-queries.service'
+
+describe('Files favorites queries (e2e)', () => {
+ let module: TestingModule
+ let db: DBSchema
+ let favoritesQueries: FilesFavoritesQueries
+ let commentsQueries: CommentsQueries
+ let spacesQueries: SpacesQueries
+ let sharesQueries: SharesQueries
+ let ownerId: number | undefined
+ let memberId: number | undefined
+ let spaceId: number | undefined
+ let shareId: number | undefined
+ let activeFileId: number | undefined
+ let trashedFileId: number | undefined
+
+ const suffix = randomUUID().replaceAll('-', '').slice(0, 12)
+ const rootName = `favorite-root-${suffix}`
+ const spaceAlias = `e2e-favorite-space-${suffix}`
+ const shareAlias = `e2e-favorite-share-${suffix}`
+ const noCache = {
+ genSlugKey: vi.fn((...args: unknown[]) => args.join(':')),
+ get: vi.fn().mockResolvedValue(undefined),
+ set: vi.fn().mockResolvedValue(true)
+ } as unknown as Cache
+
+ beforeAll(async () => {
+ module = await Test.createTestingModule({ imports: [DatabaseModule] }).compile()
+ module.useLogger(['fatal'])
+ db = await module.resolve<DBSchema>(DB_TOKEN_PROVIDER)
+ const filesQueries = new FilesQueries(db)
+ favoritesQueries = new FilesFavoritesQueries(db)
+ spacesQueries = new SpacesQueries(db, noCache, filesQueries)
+ sharesQueries = new SharesQueries(db, noCache)
+ commentsQueries = new CommentsQueries(db, spacesQueries, sharesQueries)
+
+ ownerId = dbGetInsertedId(
+ await db.insert(users).values({
+ login: `e2e-favorite-owner-${suffix}`,
+ email: `e2e-favorite-owner-${suffix}@example.test`,
+ password: 'password'
+ })
+ )
+ memberId = dbGetInsertedId(
+ await db.insert(users).values({
+ login: `e2e-favorite-member-${suffix}`,
+ email: `e2e-favorite-member-${suffix}@example.test`,
+ password: 'password'
+ })
+ )
+
+ const rootFileId = dbGetInsertedId(await db.insert(files).values({ ownerId, path: '.', name: rootName, isDir: true }))
+ activeFileId = dbGetInsertedId(await db.insert(files).values({ ownerId, path: rootName, name: 'active.txt', isDir: false }))
+ trashedFileId = dbGetInsertedId(await db.insert(files).values({ ownerId, path: rootName, name: 'trashed.txt', isDir: false, inTrash: true }))
+ spaceId = dbGetInsertedId(await db.insert(spaces).values({ alias: spaceAlias, name: 'Favorite space' }))
+ await db.insert(spacesRoots).values({ spaceId, fileId: rootFileId, alias: 'anchor', name: 'Anchor' })
+ await db.insert(spacesMembers).values({ spaceId, userId: memberId, permissions: 'a:d:m:so' })
+
+ shareId = dbGetInsertedId(await db.insert(shares).values({ ownerId, fileId: rootFileId, alias: shareAlias, name: 'Favorite share' }))
+ await db.insert(sharesMembers).values({ shareId, userId: memberId, permissions: 'd:m' })
+ await db.insert(filesFavorites).values([
+ { userId: ownerId, fileId: trashedFileId },
+ { userId: memberId, fileId: trashedFileId },
+ { userId: memberId, fileId: activeFileId }
+ ])
+ await db.insert(comments).values([
+ { userId: ownerId, fileId: trashedFileId, content: 'Comment from owner' },
+ { userId: memberId, fileId: trashedFileId, content: 'Comment from member' }
+ ])
+ })
+
+ afterAll(async () => {
+ try {
+ if (shareId) await db.delete(shares).where(eq(shares.id, shareId))
+ if (spaceId) await db.delete(spaces).where(eq(spaces.id, spaceId))
+ const userIds = [ownerId, memberId].filter((id): id is number => Number.isInteger(id))
+ if (userIds.length) await db.delete(users).where(inArray(users.id, userIds))
+ } finally {
+ await module?.close()
+ }
+ })
+
+ it('resolves an active anchored file through its accessible space and direct share', async () => {
+ const [spaceIds, shareIds] = await Promise.all([
+ spacesQueries.spaceIdentities(memberId).then((identities) => identities.map(({ id }) => id)),
+ sharesQueries.shareIdentities(memberId, 0).then((identities) => identities.map(({ id }) => id))
+ ])
+ const [spaceLocations, shareLocations] = await Promise.all([
+ favoritesQueries.getFavoriteLocationsFromSpaces(memberId, spaceIds),
+ favoritesQueries.getFavoriteLocationsFromShares(memberId, shareIds)
+ ])
+
+ expect(spaceLocations).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ fileId: activeFileId,
+ repository: FILE_REPOSITORY.SPACE,
+ path: `files/${spaceAlias}/anchor`,
+ displayRootName: 'Favorite space'
+ })
+ ])
+ )
+ expect(shareLocations).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ fileId: activeFileId,
+ repository: FILE_REPOSITORY.SHARE,
+ path: `shares/${shareAlias}`,
+ displayRootName: 'Favorite share'
+ })
+ ])
+ )
+ })
+
+ it('does not resolve a trashed child through its former space anchor', async () => {
+ const spaceIds = (await spacesQueries.spaceIdentities(memberId)).map(({ id }) => id)
+ const locations = await favoritesQueries.getFavoriteLocationsFromSpaces(memberId, spaceIds)
+
+ expect(spaceIds).toContain(spaceId)
+ expect(locations.some(({ fileId }) => fileId === trashedFileId)).toBe(false)
+ await expect(commentsQueries.getRecentsFromSpaces(memberId, spaceIds, 10)).resolves.toEqual([])
+
+ await expect(favoritesQueries.getFavoritesFromUser(ownerId, true)).resolves.toEqual([
+ expect.objectContaining({ fileId: trashedFileId, repository: SPACE_ALIAS.PERSONAL, path: `trash/personal/${rootName}`, isDisabled: false })
+ ])
+ await expect(commentsQueries.getRecentsFromPersonal(ownerId, 10)).resolves.toEqual([
+ expect.objectContaining({ file: expect.objectContaining({ path: `trash/personal/${rootName}` }) })
+ ])
+ })
+
+ it('does not resolve a trashed child through its former share', async () => {
+ const shareIds = (await sharesQueries.shareIdentities(memberId, 0)).map(({ id }) => id)
+ const locations = await favoritesQueries.getFavoriteLocationsFromShares(memberId, shareIds)
+
+ expect(shareIds).toContain(shareId)
+ expect(locations.some(({ fileId }) => fileId === trashedFileId)).toBe(false)
+ await expect(commentsQueries.getRecentsFromShares(memberId, shareIds, 10)).resolves.toEqual([])
+ })
+})
diff --git a/backend/src/applications/files/services/files-favorites-queries.service.ts b/backend/src/applications/files/services/files-favorites-queries.service.ts
new file mode 100644
index 00000000..4a8d81d5
--- /dev/null
+++ b/backend/src/applications/files/services/files-favorites-queries.service.ts
@@ -0,0 +1,244 @@
+import { Inject, Injectable } from '@nestjs/common'
+import { and, desc, eq, inArray, isNotNull, isNull, or, SelectedFields, sql } from 'drizzle-orm'
+import { alias, unionAll } from 'drizzle-orm/mysql-core'
+import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'
+import type { DBSchema } from '../../../infrastructure/database/interfaces/database.interface'
+import { shares } from '../../shares/schemas/shares.schema'
+import { externalShareScopeSQL } from '../../shares/utils/external-share-scope.sql'
+import { SPACE_ALIAS, SPACE_REPOSITORY } from '../../spaces/constants/spaces'
+import { spacesRoots } from '../../spaces/schemas/spaces-roots.schema'
+import { spaces } from '../../spaces/schemas/spaces.schema'
+import { FILE_REPOSITORY } from '../constants/operations'
+import type { FileFavorite, FileFavoriteLocation, FileFavoriteRepository } from '../schemas/file-favorite.interface'
+import { filesFavorites } from '../schemas/files-favorites.schema'
+import { filePathSQL, files } from '../schemas/files.schema'
+
+@Injectable()
+export class FilesFavoritesQueries {
+ constructor(@Inject(DB_TOKEN_PROVIDER) private readonly db: DBSchema) {}
+
+ getFavoritesFromUser(userId: number, withPersonal: boolean): Promise<FileFavorite[]> {
+ const isPersonal = sql`${+withPersonal} = 1 AND ${files.ownerId} <=> ${userId}`
+ return this.db
+ .select({
+ fileId: filesFavorites.fileId,
+ createdAt: filesFavorites.createdAt,
+ isDisabled: sql<boolean>`NOT (${isPersonal})`.mapWith(Boolean),
+ id: files.id,
+ path: sql<string>`
+ IF (${isPersonal},
+ CONCAT_WS('/',
+ IF (${files.inTrash} = 0, ${SPACE_REPOSITORY.FILES}, ${SPACE_REPOSITORY.TRASH}),
+ ${SPACE_ALIAS.PERSONAL},
+ IF (${files.path} = '.', NULL, ${files.path})
+ ),
+ ${files.path}
+ )
+ `.as('path'),
+ name: files.name,
+ isDir: files.isDir,
+ inTrash: files.inTrash,
+ mime: files.mime,
+ size: files.size,
+ mtime: files.mtime,
+ ctime: files.ctime,
+ repository: sql<FileFavoriteRepository>`IF (${isPersonal}, ${SPACE_ALIAS.PERSONAL}, NULL)`.as('repository'),
+ displayRootName: sql<string>`NULL`.as('displayRootName')
+ } satisfies FileFavorite | SelectedFields<any, any>)
+ .from(filesFavorites)
+ .innerJoin(files, eq(files.id, filesFavorites.fileId))
+ .where(eq(filesFavorites.userId, userId))
+ .orderBy(desc(filesFavorites.createdAt), desc(filesFavorites.fileId))
+ }
+
+ getFavoriteLocationsFromSpaces(userId: number, spaceIds: number[]): Promise<FileFavoriteLocation[]> {
+ if (!spaceIds.length) return Promise.resolve([])
+ const directSpaceRoot: any = alias(spacesRoots, 'favoriteDirectSpaceRoot')
+ const anchoredSpaceRoot: any = alias(spacesRoots, 'favoriteAnchoredSpaceRoot')
+ const spaceRootFile: any = alias(files, 'favoriteSpaceRootFile')
+ const fileFromSpaceRoot = or(
+ eq(files.id, spaceRootFile.id),
+ and(
+ eq(spaceRootFile.isDir, true),
+ // A file moved to trash leaves the storage scope of its former anchored root.
+ eq(files.inTrash, spaceRootFile.inTrash),
+ sql`${files.spaceId} <=> ${spaceRootFile.spaceId}`,
+ sql`${files.ownerId} <=> ${spaceRootFile.ownerId}`,
+ sql`${files.spaceExternalRootId} <=> ${spaceRootFile.spaceExternalRootId}`,
+ sql`${files.shareExternalId} <=> ${spaceRootFile.shareExternalId}`,
+ sql`LEFT(CONCAT(${files.path}, '/'), CHAR_LENGTH(${filePathSQL(spaceRootFile)}) + 1) = CONCAT(${filePathSQL(spaceRootFile)}, '/')`
+ )
+ )
+ const directFiles = this.db
+ .select({
+ fileId: sql<number>`${files.id}`.as('fileId'),
+ repository: sql<FileFavoriteRepository>`${FILE_REPOSITORY.SPACE}`.as('repository'),
+ path: sql<string>`
+ CONCAT_WS('/',
+ IF (${files.inTrash} = 0, ${SPACE_REPOSITORY.FILES}, ${SPACE_REPOSITORY.TRASH}),
+ ${spaces.alias},
+ IF (${files.spaceExternalRootId} IS NULL, NULL, ${directSpaceRoot.alias}),
+ IF (${files.path} = '.', NULL, ${files.path})
+ )
+ `.as('path'),
+ name: sql<string>`${files.name}`.as('name'),
+ displayRootName: sql<string>`${spaces.name}`.as('displayRootName'),
+ contextId: sql<number>`${spaces.id}`.as('contextId'),
+ rootId: sql<number>`0`.as('rootId')
+ } satisfies FileFavoriteLocation | SelectedFields<any, any>)
+ .from(filesFavorites)
+ .innerJoin(files, eq(files.id, filesFavorites.fileId))
+ .innerJoin(spaces, and(eq(spaces.id, files.spaceId), inArray(spaces.id, spaceIds), eq(spaces.enabled, true)))
+ .leftJoin(directSpaceRoot, eq(directSpaceRoot.id, files.spaceExternalRootId))
+ .where(eq(filesFavorites.userId, userId))
+ const anchoredFiles = this.db
+ .select({
+ fileId: sql<number>`${files.id}`.as('fileId'),
+ repository: sql<FileFavoriteRepository>`${FILE_REPOSITORY.SPACE}`.as('repository'),
+ path: sql<string>`
+ CONCAT_WS('/',
+ IF (${files.inTrash} = 0, ${SPACE_REPOSITORY.FILES}, ${SPACE_REPOSITORY.TRASH}),
+ ${spaces.alias},
+ IF (
+ ${files.id} = ${spaceRootFile.id},
+ NULL,
+ CONCAT(${anchoredSpaceRoot.alias}, SUBSTRING(${files.path}, CHAR_LENGTH(${filePathSQL(spaceRootFile)}) + 1))
+ )
+ )
+ `.as('path'),
+ name: sql<string>`IF (${files.id} = ${spaceRootFile.id}, ${anchoredSpaceRoot.name}, ${files.name})`.as('name'),
+ displayRootName: sql<string>`${spaces.name}`.as('displayRootName'),
+ contextId: sql<number>`${spaces.id}`.as('contextId'),
+ rootId: sql<number>`${anchoredSpaceRoot.id}`.as('rootId')
+ } satisfies FileFavoriteLocation | SelectedFields<any, any>)
+ .from(filesFavorites)
+ .innerJoin(files, eq(files.id, filesFavorites.fileId))
+ .innerJoin(spaceRootFile, fileFromSpaceRoot)
+ .innerJoin(anchoredSpaceRoot, eq(anchoredSpaceRoot.fileId, spaceRootFile.id))
+ .innerJoin(spaces, and(eq(spaces.id, anchoredSpaceRoot.spaceId), inArray(spaces.id, spaceIds), eq(spaces.enabled, true)))
+ .where(eq(filesFavorites.userId, userId))
+ return unionAll(directFiles, anchoredFiles)
+ }
+
+ getFavoriteLocationsFromShares(userId: number, shareIds: number[]): Promise<FileFavoriteLocation[]> {
+ if (!shareIds.length) return Promise.resolve([])
+ const directShareRootFile: any = alias(files, 'favoriteDirectShareRootFile')
+ const directShareSpaceRoot: any = alias(spacesRoots, 'favoriteDirectShareSpaceRoot')
+ const spaceShareRootFile: any = alias(files, 'favoriteSpaceShareRootFile')
+ const spaceShareRoot: any = alias(spacesRoots, 'favoriteSpaceShareRoot')
+ const externalShareSpaceRoot: any = alias(spacesRoots, 'favoriteExternalShareSpaceRoot')
+ const externalSpaceRoot: any = alias(spacesRoots, 'favoriteExternalSpaceRoot')
+ const fileFromRoot = (rootFile: any) =>
+ or(
+ eq(files.id, rootFile.id),
+ and(
+ eq(rootFile.isDir, true),
+ // A file moved to trash leaves the storage scope of its former share root.
+ eq(files.inTrash, rootFile.inTrash),
+ sql`${files.spaceId} <=> ${rootFile.spaceId}`,
+ sql`${files.ownerId} <=> ${rootFile.ownerId}`,
+ sql`${files.spaceExternalRootId} <=> ${rootFile.spaceExternalRootId}`,
+ sql`${files.shareExternalId} <=> ${rootFile.shareExternalId}`,
+ sql`LEFT(CONCAT(${files.path}, '/'), CHAR_LENGTH(${filePathSQL(rootFile)}) + 1) = CONCAT(${filePathSQL(rootFile)}, '/')`
+ )
+ )
+ const rootLocationSelect = (rootFile: any, spaceRoot: any) =>
+ ({
+ fileId: sql<number>`${files.id}`.as('fileId'),
+ repository: sql<FileFavoriteRepository>`${FILE_REPOSITORY.SHARE}`.as('repository'),
+ path: sql<string>`
+ CONCAT_WS('/', ${SPACE_REPOSITORY.SHARES},
+ IF (
+ ${files.id} = ${rootFile.id},
+ NULL,
+ CONCAT(${shares.alias}, SUBSTRING(${files.path}, CHAR_LENGTH(${filePathSQL(rootFile)}) + 1))
+ )
+ )
+ `.as('path'),
+ name: sql<string>`IF (${files.id} = ${rootFile.id}, ${shares.name}, ${files.name})`.as('name'),
+ displayRootName: sql<string>`${shares.name}`.as('displayRootName'),
+ contextId: sql<number>`${shares.id}`.as('contextId'),
+ rootId: sql<number>`COALESCE(${spaceRoot.id}, 0)`.as('rootId')
+ }) satisfies FileFavoriteLocation | SelectedFields<any, any>
+ const externalLocationSelect = (spaceRoot: any) =>
+ ({
+ fileId: sql<number>`${files.id}`.as('fileId'),
+ repository: sql<FileFavoriteRepository>`${FILE_REPOSITORY.SHARE}`.as('repository'),
+ path: sql<string>`
+ CONCAT_WS('/',
+ ${SPACE_REPOSITORY.SHARES},
+ ${shares.alias},
+ IF (${files.path} = '.', NULL, ${files.path})
+ )
+ `.as('path'),
+ name: sql<string>`${files.name}`.as('name'),
+ displayRootName: sql<string>`${shares.name}`.as('displayRootName'),
+ contextId: sql<number>`${shares.id}`.as('contextId'),
+ rootId: sql<number>`COALESCE(${spaceRoot.id}, 0)`.as('rootId')
+ }) satisfies FileFavoriteLocation | SelectedFields<any, any>
+ const externalShareTargets = this.db
+ .select({ id: shares.id, parentId: shares.parentId, externalPath: shares.externalPath })
+ .from(shares)
+ .where(and(isNull(shares.fileId), isNotNull(shares.externalPath), inArray(shares.id, shareIds), eq(shares.enabled, true)))
+ const externalShareScope = externalShareScopeSQL(externalShareTargets, 'favoriteExternalShareScope', {
+ oneTargetPerStorage: true
+ })
+ const directShareFiles = this.db
+ .select(rootLocationSelect(directShareRootFile, directShareSpaceRoot))
+ .from(filesFavorites)
+ .innerJoin(files, eq(files.id, filesFavorites.fileId))
+ .innerJoin(directShareRootFile, fileFromRoot(directShareRootFile))
+ .innerJoin(shares, and(eq(shares.fileId, directShareRootFile.id), inArray(shares.id, shareIds), eq(shares.enabled, true)))
+ .leftJoin(directShareSpaceRoot, eq(directShareSpaceRoot.id, shares.spaceRootId))
+ .where(eq(filesFavorites.userId, userId))
+ const spaceRootShareFiles = this.db
+ .select(rootLocationSelect(spaceShareRootFile, spaceShareRoot))
+ .from(filesFavorites)
+ .innerJoin(files, eq(files.id, filesFavorites.fileId))
+ .innerJoin(spaceShareRootFile, fileFromRoot(spaceShareRootFile))
+ .innerJoin(spaceShareRoot, eq(spaceShareRoot.fileId, spaceShareRootFile.id))
+ .innerJoin(
+ shares,
+ and(isNull(shares.fileId), eq(shares.spaceRootId, spaceShareRoot.id), inArray(shares.id, shareIds), eq(shares.enabled, true))
+ )
+ .where(eq(filesFavorites.userId, userId))
+ const externalShareFiles = this.db
+ .select(externalLocationSelect(externalShareSpaceRoot))
+ .from(filesFavorites)
+ .innerJoin(files, eq(files.id, filesFavorites.fileId))
+ .innerJoin(externalShareScope.table, eq(externalShareScope.storageShareId, files.shareExternalId))
+ .innerJoin(shares, eq(shares.id, externalShareScope.targetShareId))
+ .leftJoin(externalShareSpaceRoot, eq(externalShareSpaceRoot.id, shares.spaceRootId))
+ .where(and(eq(filesFavorites.userId, userId), isNull(externalShareSpaceRoot.fileId)))
+ const externalSpaceRootFiles = this.db
+ .select(externalLocationSelect(externalSpaceRoot))
+ .from(filesFavorites)
+ .innerJoin(files, eq(files.id, filesFavorites.fileId))
+ .innerJoin(
+ externalSpaceRoot,
+ and(
+ eq(externalSpaceRoot.id, files.spaceExternalRootId),
+ eq(externalSpaceRoot.spaceId, files.spaceId),
+ isNull(externalSpaceRoot.fileId),
+ isNotNull(externalSpaceRoot.externalPath)
+ )
+ )
+ .innerJoin(
+ shares,
+ and(isNull(shares.fileId), eq(shares.spaceRootId, externalSpaceRoot.id), inArray(shares.id, shareIds), eq(shares.enabled, true))
+ )
+ .where(eq(filesFavorites.userId, userId))
+ return unionAll(directShareFiles, spaceRootShareFiles, externalShareFiles, externalSpaceRootFiles)
+ }
+
+ async addFavorite(userId: number, fileId: number): Promise<void> {
+ await this.db.insert(filesFavorites).values({ userId, fileId }).onDuplicateKeyUpdate({ set: { fileId } })
+ }
+
+ async removeFavorite(userId: number, fileId: number): Promise<void> {
+ await this.db
+ .delete(filesFavorites)
+ .where(and(eq(filesFavorites.userId, userId), eq(filesFavorites.fileId, fileId)))
+ .limit(1)
+ }
+}
diff --git a/backend/src/applications/files/services/files-queries.service.ts b/backend/src/applications/files/services/files-queries.service.ts
index bae54131..96d1d548 100644
--- a/backend/src/applications/files/services/files-queries.service.ts
+++ b/backend/src/applications/files/services/files-queries.service.ts
@@ -1,10 +1,11 @@
import { Inject, Injectable, Logger } from '@nestjs/common'
-import { and, desc, eq, getTableColumns, inArray, isNull, or, SelectedFields, sql, SQL } from 'drizzle-orm'
+import { and, desc, eq, getTableColumns, inArray, isNotNull, isNull, or, SelectedFields, sql, SQL } from 'drizzle-orm'
import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'
import { DBSchema } from '../../../infrastructure/database/interfaces/database.interface'
import { concatDistinctObjectsInArray, convertToWhere, dbCheckAffectedRows, dbGetInsertedId } from '../../../infrastructure/database/utils'
import { fileHasCommentsSubquerySQL } from '../../comments/schemas/comments.schema'
import { shares } from '../../shares/schemas/shares.schema'
+import type { SpaceBrowseContext, SpaceBrowseDetails } from '../../spaces/interfaces/space-files.interface'
import { spacesRoots } from '../../spaces/schemas/spaces-roots.schema'
import { spaces } from '../../spaces/schemas/spaces.schema'
import { syncClients } from '../../sync/schemas/sync-clients.schema'
@@ -13,6 +14,7 @@ import { FileDBProps } from '../interfaces/file-db-props.interface'
import { FileProps } from '../interfaces/file-props.interface'
import type { FileRecent, FileRecentLocation, FileRecentUpdate } from '../schemas/file-recent.interface'
import { File } from '../schemas/file.interface'
+import { filesFavorites } from '../schemas/files-favorites.schema'
import { filesRecents } from '../schemas/files-recents.schema'
import { childFilesMatch, childFilesReplacePath, childPathMatch, filePathSQL, files } from '../schemas/files.schema'
import { dirName, fileName, isPathInside } from '../utils/files'
@@ -23,17 +25,8 @@ export class FilesQueries {
constructor(@Inject(DB_TOKEN_PROVIDER) private readonly db: DBSchema) {}
- browseFiles(
- userId: number,
- dbFile: FileDBProps,
- options: {
- withSpaces?: boolean
- withShares?: boolean
- withSyncs?: boolean
- withHasComments?: boolean
- ignoreChildShares?: boolean
- }
- ): Promise<FileProps[]> {
+ browseFiles(userId: number, context: SpaceBrowseContext, details: SpaceBrowseDetails): Promise<FileProps[]> {
+ const withSpaces = !!details && context.inPersonalSpace
const q = this.db
.select({
id: files.id,
@@ -44,8 +37,8 @@ export class FilesQueries {
size: files.size,
mtime: files.mtime,
ctime: files.ctime,
- ...(options.withSpaces && { spaces: concatDistinctObjectsInArray(spaces.id, { id: spaces.id, alias: spaces.alias, name: spaces.name }) }),
- ...(options.withShares && {
+ ...(withSpaces && { spaces: concatDistinctObjectsInArray(spaces.id, { id: spaces.id, alias: spaces.alias, name: spaces.name }) }),
+ ...(!!details && {
shares: concatDistinctObjectsInArray(shares.id, {
id: shares.id,
alias: shares.alias,
@@ -53,33 +46,37 @@ export class FilesQueries {
type: shares.type
})
}),
- ...(options.withSyncs && {
+ ...(details?.syncs && {
syncs: concatDistinctObjectsInArray(syncPaths.id, {
id: syncPaths.id,
clientId: syncClients.id,
clientName: sql`JSON_VALUE(${syncClients.info}, '$.node')`
})
}),
- ...(options.withHasComments && { hasComments: sql`${fileHasCommentsSubquerySQL(files.id)}`.mapWith(Boolean) })
+ ...(!!details && { hasComments: sql`${fileHasCommentsSubquerySQL(files.id)}`.mapWith(Boolean) }),
+ ...(details?.favorites && { isFavorite: isNotNull(filesFavorites.fileId).mapWith(Boolean) })
})
.from(files)
- .where(and(...convertToWhere(files, dbFile)))
+ .where(and(...convertToWhere(files, context.dbFile)))
.groupBy(files.id)
- if (options.withSpaces) {
+ if (withSpaces) {
// show spaces for files in personal space
q.leftJoin(spacesRoots, eq(spacesRoots.fileId, files.id))
q.leftJoin(spaces, eq(spaces.id, spacesRoots.spaceId))
}
- if (options.withShares) {
+ if (details) {
q.leftJoin(
shares,
- and(...[eq(shares.ownerId, userId), eq(shares.fileId, files.id)], ...(options.ignoreChildShares ? [isNull(shares.parentId)] : []))
+ and(...[eq(shares.ownerId, userId), eq(shares.fileId, files.id)], ...(!context.inSharesRepository ? [isNull(shares.parentId)] : []))
)
}
- if (options.withSyncs) {
+ if (details?.syncs) {
q.leftJoin(syncClients, eq(syncClients.ownerId, userId))
q.leftJoin(syncPaths, and(eq(syncPaths.clientId, syncClients.id), eq(syncPaths.fileId, files.id)))
}
+ if (details?.favorites) {
+ q.leftJoin(filesFavorites, and(eq(filesFavorites.userId, userId), eq(filesFavorites.fileId, files.id)))
+ }
return q
}
diff --git a/backend/src/applications/shares/services/shares-queries.service.ts b/backend/src/applications/shares/services/shares-queries.service.ts
index 4b38d98c..193180d1 100644
--- a/backend/src/applications/shares/services/shares-queries.service.ts
+++ b/backend/src/applications/shares/services/shares-queries.service.ts
@@ -650,13 +650,11 @@ export class SharesQueries {
return r
}
- async shareRootFiles(user: UserModel, options: { withShares?: boolean; withHasComments?: boolean; withSyncs?: boolean }): Promise<FileProps[]> {
+ async shareRootFiles(user: UserModel, details: SpaceBrowseDetails): Promise<FileProps[]> {
if (!this.shareRootFilesQuery) {
const shareSpaceRoot: any = alias(spacesRoots, 'shareSpaceRoot')
const originOwner: any = alias(users, 'originOwner')
const childShare: any = alias(shares, 'childShare')
- const externalParentShare: any = alias(shares, 'externalParentShare')
- const externalRootScopeAlias = 'externalRootScope'
const selectUnion: FileProps | SelectedFields<any, any> = {
id: files.id,
path: sql`IF (${files.id} IS NOT NULL, ${filePathSQL(files)}, '')`.as('path'),
@@ -726,7 +724,7 @@ export class SharesQueries {
.leftJoin(
childShare,
and(
- eq(sql.placeholder('withShares'), sql`1`),
+ eq(sql.placeholder('withDetails'), sql`1`),
eq(childShare.ownerId, sql.placeholder('userId')),
eq(childShare.parentId, shares.id),
or(
@@ -788,7 +786,7 @@ export class SharesQueries {
fullName: unionAlias.rootOwnerFullName
} satisfies Owner
},
- shares: sql`IF (${sql.placeholder('withShares')}, ${concatDistinctObjectsInArray(unionAlias.childShareId, {
+ shares: sql`IF (${sql.placeholder('withDetails')}, ${concatDistinctObjectsInArray(unionAlias.childShareId, {
id: unionAlias.childShareId,
alias: unionAlias.childShareAlias,
name: unionAlias.childShareName,
@@ -799,12 +797,21 @@ export class SharesQueries {
clientId: unionAlias.syncPathClientId,
clientName: unionAlias.syncPathClientName
})}, '[]')`.mapWith(dbParseJson),
- hasComments: sql<boolean>`IF (${sql.placeholder('withHasComments')}, ${fileHasCommentsSubquerySQL(unionAlias.id)}, 0)`.mapWith(Boolean)
+ hasComments: sql<boolean>`IF (${sql.placeholder('withDetails')}, ${fileHasCommentsSubquerySQL(unionAlias.id)}, 0)`.mapWith(Boolean),
+ isFavorite: isNotNull(filesFavorites.fileId).mapWith(Boolean)
}
this.shareRootFilesQuery = this.db
.select(select)
.from(unionAlias)
- .leftJoin(externalRootScope, eq(externalRootScopeTargetId, unionAlias.rootId))
+ .leftJoin(
+ filesFavorites,
+ and(
+ eq(sql.placeholder('withFavorites'), sql`1`),
+ eq(filesFavorites.userId, sql.placeholder('userId')),
+ eq(filesFavorites.fileId, unionAlias.id)
+ )
+ )
+ .leftJoin(externalRootScope.table, eq(externalRootScope.targetShareId, unionAlias.rootId))
// Non-external shares do not need this scope. An external share must
// resolve one: otherwise omit it so `updateRootFile()` cannot mistake
// the share-record owner for the owner of its external storage.
@@ -815,9 +822,9 @@ export class SharesQueries {
const fps: FileProps[] = await this.shareRootFilesQuery.execute({
userId: user.id,
isAdmin: +user.isAdmin,
- withHasComments: +!!options.withHasComments,
- withShares: +!!options.withShares,
- withSyncs: +!!options.withSyncs
+ withDetails: +!!details,
+ withFavorites: +(details?.favorites ?? false),
+ withSyncs: +(details?.syncs ?? false)
})
for (const f of fps) {
f.root.permissions = uniquePermissions(f.root.permissions)
diff --git a/backend/src/applications/shares/shares.e2e-spec.ts b/backend/src/applications/shares/shares.e2e-spec.ts
index 4341da08..abb563af 100644
--- a/backend/src/applications/shares/shares.e2e-spec.ts
+++ b/backend/src/applications/shares/shares.e2e-spec.ts
@@ -6,6 +6,13 @@ import { DB_TOKEN_PROVIDER } from '../../infrastructure/database/constants'
import { DatabaseModule } from '../../infrastructure/database/database.module'
import type { DBSchema } from '../../infrastructure/database/interfaces/database.interface'
import { dbGetInsertedId } from '../../infrastructure/database/utils'
+import { comments } from '../comments/schemas/comments.schema'
+import { CommentsQueries } from '../comments/services/comments-queries.service'
+import { filesFavorites } from '../files/schemas/files-favorites.schema'
+import { files } from '../files/schemas/files.schema'
+import { FilesFavoritesQueries } from '../files/services/files-favorites-queries.service'
+import { FilesQueries } from '../files/services/files-queries.service'
+import { SpacesQueries } from '../spaces/services/spaces-queries.service'
import type { UserModel } from '../users/models/user.model'
import { users } from '../users/schemas/users.schema'
import { SharesQueries } from './services/shares-queries.service'
@@ -17,11 +24,13 @@ describe('Shares (e2e)', () => {
let db: DBSchema
let sharesQueries: SharesQueries
let actorId: number | undefined
+ let childActorId: number | undefined
let ownerId: number | undefined
let externalRootId: number | undefined
let childId: number | undefined
let grandchildId: number | undefined
let internalRootId: number | undefined
+ let externalFileId: number | undefined
const suffix = randomUUID().replaceAll('-', '').slice(0, 12)
const aliases = {
@@ -52,6 +61,13 @@ describe('Shares (e2e)', () => {
password: 'password'
})
)
+ childActorId = dbGetInsertedId(
+ await db.insert(users).values({
+ login: `e2e-share-child-actor-${suffix}`,
+ email: `e2e-share-child-actor-${suffix}@example.test`,
+ password: 'password'
+ })
+ )
ownerId = dbGetInsertedId(
await db.insert(users).values({
login: `e2e-share-owner-${suffix}`,
@@ -104,8 +120,16 @@ describe('Shares (e2e)', () => {
{ shareId: externalRootId, userId: actorId, permissions: 'a:d:m:so' },
{ shareId: childId, userId: actorId, permissions: 'd:m' },
{ shareId: grandchildId, userId: actorId, permissions: 'm' },
- { shareId: malformedChildId, userId: actorId, permissions: 'd:m' }
+ { shareId: malformedChildId, userId: actorId, permissions: 'd:m' },
+ { shareId: childId, userId: childActorId, permissions: 'd:m' },
+ { shareId: grandchildId, userId: childActorId, permissions: 'm' }
])
+
+ externalFileId = dbGetInsertedId(
+ await db.insert(files).values({ shareExternalId: externalRootId, path: '.', name: 'external-file.txt', isDir: false })
+ )
+ await db.insert(filesFavorites).values({ userId: childActorId, fileId: externalFileId })
+ await db.insert(comments).values({ userId: ownerId, fileId: externalFileId, content: 'External child comment' })
})
afterAll(async () => {
@@ -114,7 +138,7 @@ describe('Shares (e2e)', () => {
if (rootIds.length) {
await db.delete(shares).where(inArray(shares.id, rootIds))
}
- const userIds = [actorId, ownerId].filter((id): id is number => Number.isInteger(id))
+ const userIds = [actorId, childActorId, ownerId].filter((id): id is number => Number.isInteger(id))
if (userIds.length) {
await db.delete(users).where(inArray(users.id, userIds))
}
@@ -147,7 +171,7 @@ describe('Shares (e2e)', () => {
})
it('uses the same external root scope without replacing each listed share permissions', async () => {
- const roots = await sharesQueries.shareRootFiles({ id: actorId, isAdmin: false } as UserModel, {})
+ const roots = await sharesQueries.shareRootFiles({ id: actorId, isAdmin: false } as UserModel, null)
const child = roots.find((root) => root.root.alias === aliases.child)
const grandchild = roots.find((root) => root.root.alias === aliases.grandchild)
@@ -159,10 +183,30 @@ describe('Shares (e2e)', () => {
await expect(sharesQueries.permissions(actorId, aliases.unauthorizedChild)).resolves.toBeUndefined()
})
+ it('resolves favorite and recent-comment locations through an external child only', async () => {
+ const favoritesQueries = new FilesFavoritesQueries(db)
+ const spacesQueries = new SpacesQueries(db, noCache, new FilesQueries(db))
+ const commentsQueries = new CommentsQueries(db, spacesQueries, sharesQueries)
+ const shareIds = (await sharesQueries.shareIdentities(childActorId, 0)).map(({ id }) => id)
+
+ expect(shareIds).toEqual(expect.arrayContaining([childId, grandchildId]))
+ expect(shareIds).not.toContain(externalRootId)
+
+ const favorites = await favoritesQueries.getFavoriteLocationsFromShares(childActorId, shareIds)
+ const recentComments = await commentsQueries.getRecentsFromShares(childActorId, shareIds, 10)
+
+ expect(favorites).toEqual([
+ expect.objectContaining({ fileId: externalFileId, path: `shares/${aliases.child}`, displayRootName: 'External child' })
+ ])
+ expect(recentComments).toEqual([
+ expect.objectContaining({ file: expect.objectContaining({ path: `shares/${aliases.child}`, displayRootName: 'External child' }) })
+ ])
+ })
+
it('fails closed when an external child has a non-external parent', async () => {
await expect(sharesQueries.permissions(actorId, aliases.malformedChild)).resolves.toBeUndefined()
- const roots = await sharesQueries.shareRootFiles({ id: actorId, isAdmin: false } as UserModel, {})
+ const roots = await sharesQueries.shareRootFiles({ id: actorId, isAdmin: false } as UserModel, null)
expect(roots.some((root) => root.root.alias === aliases.malformedChild)).toBe(false)
})
})
diff --git a/backend/src/applications/spaces/interfaces/space-files.interface.ts b/backend/src/applications/spaces/interfaces/space-files.interface.ts
index bf748b54..c495c3ef 100644
--- a/backend/src/applications/spaces/interfaces/space-files.interface.ts
+++ b/backend/src/applications/spaces/interfaces/space-files.interface.ts
@@ -1,5 +1,17 @@
+import type { FileDBProps } from '../../files/interfaces/file-db-props.interface'
import type { FileProps } from '../../files/interfaces/file-props.interface'
+export interface SpaceBrowseContext {
+ dbFile: FileDBProps
+ inPersonalSpace: boolean
+ inSharesRepository: boolean
+}
+
+export type SpaceBrowseDetails = {
+ syncs: boolean
+ favorites: boolean
+} | null
+
export interface SpaceFiles {
space: {
alias: string
diff --git a/backend/src/applications/spaces/services/spaces-browser.service.spec.ts b/backend/src/applications/spaces/services/spaces-browser.service.spec.ts
index 720064cc..b18908be 100644
--- a/backend/src/applications/spaces/services/spaces-browser.service.spec.ts
+++ b/backend/src/applications/spaces/services/spaces-browser.service.spec.ts
@@ -13,6 +13,7 @@ import { LinksQueries } from '../../links/services/links-queries.service'
import { NotificationsManager } from '../../notifications/services/notifications-manager.service'
import { SharesManager } from '../../shares/services/shares-manager.service'
import { SharesQueries } from '../../shares/services/shares-queries.service'
+import { USER_PERMISSION } from '../../users/constants/user'
import type { UserModel } from '../../users/models/user.model'
import { UsersQueries } from '../../users/services/users-queries.service'
import type { SpaceEnv } from '../models/space-env.model'
@@ -73,13 +74,51 @@ describe(SpacesBrowser.name, () => {
} as unknown as SpaceEnv
vi.spyOn(spacesBrowserService as any, 'parseFS').mockResolvedValue([])
- vi.spyOn(spacesBrowserService as any, 'parseDB').mockResolvedValue([])
- vi.spyOn(spacesBrowserService as any, 'parseRootFiles').mockResolvedValue([])
+ const parseDB = vi.spyOn(spacesBrowserService as any, 'parseDB').mockResolvedValue([])
+ const parseRootFiles = vi.spyOn(spacesBrowserService as any, 'parseRootFiles').mockResolvedValue([])
vi.spyOn((spacesBrowserService as any).filesRecents, 'updateRecents').mockResolvedValue(undefined)
const result = await spacesBrowserService.browse(user, space)
expect(result.space).toEqual({ alias: 'communication', name: 'Communication' })
+ expect(parseDB).toHaveBeenCalledWith(user.id, space, null)
+ expect(parseRootFiles).toHaveBeenCalledWith(user, space, null)
+ })
+
+ it.each([
+ {
+ name: 'regular user with sync permissions',
+ isLink: false,
+ permissions: [USER_PERMISSION.DESKTOP_APP, USER_PERMISSION.DESKTOP_APP_SYNC],
+ syncs: true,
+ favorites: true
+ },
+ { name: 'regular user without all sync permissions', isLink: false, permissions: [USER_PERMISSION.DESKTOP_APP], syncs: false, favorites: true },
+ { name: 'link user', isLink: true, permissions: [], syncs: false, favorites: false }
+ ])('resolves and propagates browse details for a $name', async ({ isLink, permissions, syncs, favorites }) => {
+ const user = {
+ id: 1,
+ isLink,
+ havePermission: vi.fn((permission: USER_PERMISSION) => permissions.includes(permission))
+ } as unknown as UserModel
+ const space = {
+ alias: 'communication',
+ name: 'Communication',
+ inSharesList: false,
+ inTrashRepository: true,
+ browsePermissions: vi.fn().mockReturnValue('a:m')
+ } as unknown as SpaceEnv
+ const parseDB = vi.spyOn(spacesBrowserService as any, 'parseDB').mockResolvedValue([])
+ const parseRootFiles = vi.spyOn(spacesBrowserService as any, 'parseRootFiles').mockResolvedValue([])
+ vi.spyOn(spacesBrowserService as any, 'parseFS').mockResolvedValue([])
+ vi.spyOn((spacesBrowserService as any).filesRecents, 'updateRecents').mockResolvedValue(undefined)
+
+ await spacesBrowserService.browse(user, space, true)
+
+ const details = { syncs, favorites }
+ expect(parseDB).toHaveBeenCalledWith(user.id, space, details)
+ expect(parseRootFiles).toHaveBeenCalledWith(user, space, details)
+ expect(parseDB.mock.calls[0][2]).toBe(parseRootFiles.mock.calls[0][2])
})
it('always hides internal temporary entries from filesystem browsing', async () => {
diff --git a/backend/src/applications/spaces/services/spaces-browser.service.ts b/backend/src/applications/spaces/services/spaces-browser.service.ts
index 42e38881..2c31eace 100644
--- a/backend/src/applications/spaces/services/spaces-browser.service.ts
+++ b/backend/src/applications/spaces/services/spaces-browser.service.ts
@@ -12,7 +12,7 @@ import { dirName, fileName, getProps, isInternalTemporaryEntry } from '../../fil
import { SharesQueries } from '../../shares/services/shares-queries.service'
import { USER_PERMISSION } from '../../users/constants/user'
import { UserModel } from '../../users/models/user.model'
-import { SpaceFiles } from '../interfaces/space-files.interface'
+import { SpaceBrowseDetails, SpaceFiles } from '../interfaces/space-files.interface'
import { SpaceEnv } from '../models/space-env.model'
import { IsRealPathIsDirAndExists, realPathFromRootFile } from '../utils/paths'
import { SpacesManager } from './spaces-manager.service'
@@ -31,18 +31,13 @@ export class SpacesBrowser {
private readonly filesRecents: FilesRecents
) {}
- async browse(
- user: UserModel,
- space: SpaceEnv,
- options: {
- withLocks?: boolean
- withSpacesAndShares?: boolean
- withSyncs?: boolean
- withHasComments?: boolean
- } = {}
- ): Promise<SpaceFiles> {
- // check sync permission
- options.withSyncs = options.withSyncs && user.havePermission(USER_PERMISSION.DESKTOP_APP) && user.havePermission(USER_PERMISSION.DESKTOP_APP_SYNC)
+ async browse(user: UserModel, space: SpaceEnv, withDetails = false): Promise<SpaceFiles> {
+ const details: SpaceBrowseDetails = withDetails
+ ? {
+ syncs: user.havePermission(USER_PERMISSION.DESKTOP_APP) && user.havePermission(USER_PERMISSION.DESKTOP_APP_SYNC),
+ favorites: !user.isLink
+ }
+ : null
const spaceFiles: SpaceFiles = {
space: { alias: space.alias, name: space.name },
files: [],
@@ -51,16 +46,11 @@ export class SpacesBrowser {
}
const [fsFiles, dbFiles, rootFiles] = await Promise.all([
this.parseFS(space),
- this.parseDB(user.id, space, options),
- this.parseRootFiles(user, space, {
- withShares: options.withSpacesAndShares,
- withHasComments: options.withHasComments,
- withSyncs: options.withSyncs,
- withLocks: options.withLocks
- })
+ this.parseDB(user.id, space, details),
+ this.parseRootFiles(user, space, details)
])
const visibleRootFiles = rootFiles.filter((file) => !isInternalTemporaryEntry(file.name))
- this.updateDBFiles(user, space, dbFiles, fsFiles, options)
+ this.updateDBFiles(user, space, dbFiles, fsFiles, details)
if (space.inSharesList) {
// the share space includes shares as root files
spaceFiles.files = [...visibleRootFiles, ...fsFiles]
@@ -68,7 +58,7 @@ export class SpacesBrowser {
} else {
await this.mergeSpaceRootFiles(space, visibleRootFiles, fsFiles, spaceFiles)
}
- if (options.withLocks && !space.inTrashRepository) {
+ if (details && !space.inTrashRepository) {
// locks were removed when files were moved to the trash, no need to parse locks
await this.enrichWithLocks(space, spaceFiles.files)
}
@@ -77,44 +67,20 @@ export class SpacesBrowser {
return spaceFiles
}
- private async parseRootFiles(
- user: UserModel,
- space: SpaceEnv,
- options: {
- withShares?: boolean
- withHasComments?: boolean
- withSyncs?: boolean
- withLocks?: boolean
- }
- ): Promise<FileProps[]> {
+ private async parseRootFiles(user: UserModel, space: SpaceEnv, details: SpaceBrowseDetails): Promise<FileProps[]> {
if (space.inFilesRepository && space.id && !space.root.alias) {
// list roots in the space
- return Promise.all((await this.spacesQueries.spaceRootFiles(user.id, space.id, options)).map((f) => this.updateRootFile(f, options)))
+ return Promise.all((await this.spacesQueries.spaceRootFiles(user.id, space.id, details)).map((f) => this.updateRootFile(f, details)))
} else if (space.inSharesList) {
// list shares as roots
- return Promise.all((await this.sharesQueries.shareRootFiles(user, options)).map((f) => this.updateRootFile(f, options)))
+ return Promise.all((await this.sharesQueries.shareRootFiles(user, details)).map((f) => this.updateRootFile(f, details)))
}
return []
}
- private async parseDB(
- userId: number,
- space: SpaceEnv,
- options: {
- withSpacesAndShares?: boolean
- withSyncs?: boolean
- withHasComments?: boolean
- }
- ): Promise<FileProps[]> {
+ private async parseDB(userId: number, space: SpaceEnv, details: SpaceBrowseDetails): Promise<FileProps[]> {
if (space.inSharesList) return []
- const dbOptions = {
- withSpaces: options.withSpacesAndShares && space.inPersonalSpace,
- withShares: options.withSpacesAndShares,
- withSyncs: options.withSyncs,
- withHasComments: options.withHasComments,
- ignoreChildShares: !space.inSharesRepository
- }
- return this.filesQueries.browseFiles(userId, space.dbFile, dbOptions)
+ return this.filesQueries.browseFiles(userId, space, details)
}
private async parseFS(space: SpaceEnv): Promise<FileProps[]> {
@@ -161,25 +127,23 @@ export class SpacesBrowser {
}
}
- private async updateRootFile(
- f: FileProps,
- options: { withShares?: boolean; withHasComments?: boolean; withSyncs?: boolean; withLocks?: boolean }
- ): Promise<FileProps> {
+ private async updateRootFile(f: FileProps, details: SpaceBrowseDetails): Promise<FileProps> {
const realPath = realPathFromRootFile(f)
const originalPath = f.path
f.path = f.root.name
try {
const fileProps: FileProps = await getProps(realPath, f.path)
- if (options.withShares) {
+ if (details) {
fileProps.shares = f.shares
- }
- if (options.withHasComments) {
fileProps.hasComments = f.hasComments
}
- if (options.withSyncs) {
+ if (details?.favorites) {
+ fileProps.isFavorite = f.isFavorite
+ }
+ if (details?.syncs) {
fileProps.syncs = f.syncs
}
- if (options.withLocks && (f.origin || f.root?.owner)) {
+ if (details && (f.origin || f.root?.owner)) {
// `f.origin` is used for shares
// `f.root.owner` is used for anchored files in spaces
// all other files are handled in the `enrichWithLocks` function
@@ -197,7 +161,7 @@ export class SpacesBrowser {
fileProps.lock = this.filesLockManager.convertLockToFileLockProps(locks[0])
}
}
- // `owner.id` is only used in the `withLocks` condition
+ // `owner.id` is only used for lock details
delete f.root.owner?.id
// check `f.id`; it can be null for external roots
if (f.id) {
@@ -222,39 +186,30 @@ export class SpacesBrowser {
}
}
- private updateDBFiles(
- user: UserModel,
- space: SpaceEnv,
- dbFiles: FileProps[],
- fsFiles: FileProps[],
- options: {
- withSpacesAndShares?: boolean
- withSyncs?: boolean
- withHasComments?: boolean
- }
- ) {
+ private updateDBFiles(user: UserModel, space: SpaceEnv, dbFiles: FileProps[], fsFiles: FileProps[], details: SpaceBrowseDetails) {
for (const dbFile of dbFiles) {
if (isInternalTemporaryEntry(dbFile.name)) continue
const fsFile = fsFiles.find((f: FileProps) => dbFile.name === f.name)
if (fsFile) {
/* important: inherits from the file id in database */
fsFile.id = dbFile.id
- if (options.withSpacesAndShares) {
+ if (details) {
fsFile.spaces = dbFile.spaces
fsFile.shares = dbFile.shares
+ fsFile.hasComments = dbFile.hasComments
}
- if (options.withSyncs) {
+ if (details?.syncs) {
fsFile.syncs = dbFile.syncs
}
- if (options.withHasComments) {
- fsFile.hasComments = dbFile.hasComments
+ if (details?.favorites) {
+ fsFile.isFavorite = dbFile.isFavorite
}
this.filesQueries
.compareAndUpdateFileProps(dbFile, fsFile)
.catch((e: Error) => this.logger.error({ tag: this.updateDBFiles.name, msg: `${e}` }))
} else {
this.logger.warn({ tag: this.updateDBFiles.name, msg: `missing ${dbFile.path}/${dbFile.name} (${dbFile.id}) from fs, delete it from db` })
- if (options.withSpacesAndShares) {
+ if (details) {
if (dbFile.spaces) {
for (const space of dbFile.spaces) {
this.logger.warn({
diff --git a/backend/src/applications/spaces/services/spaces-queries.service.ts b/backend/src/applications/spaces/services/spaces-queries.service.ts
index dcd38816..1dcf2225 100644
--- a/backend/src/applications/spaces/services/spaces-queries.service.ts
+++ b/backend/src/applications/spaces/services/spaces-queries.service.ts
@@ -20,6 +20,7 @@ import {
import { fileHasCommentsSubquerySQL } from '../../comments/schemas/comments.schema'
import { FileDBProps } from '../../files/interfaces/file-db-props.interface'
import { FileProps } from '../../files/interfaces/file-props.interface'
+import { filesFavorites } from '../../files/schemas/files-favorites.schema'
import { File } from '../../files/schemas/file.interface'
import { filePathSQL, files } from '../../files/schemas/files.schema'
import { FilesQueries } from '../../files/services/files-queries.service'
@@ -37,6 +38,7 @@ import { usersGroups } from '../../users/schemas/users-groups.schema'
import { userFullNameSQL, users } from '../../users/schemas/users.schema'
import { SPACE_ROLE } from '../constants/spaces'
import { SpaceMemberDto } from '../dto/create-or-update-space.dto'
+import type { SpaceBrowseDetails } from '../interfaces/space-files.interface'
import { SpaceEnv } from '../models/space-env.model'
import { SpaceProps } from '../models/space-props.model'
import { SpaceRootProps } from '../models/space-root-props.model'
@@ -246,15 +248,7 @@ export class SpacesQueries {
}
}
- async spaceRootFiles(
- userId: number,
- spaceId: number,
- options: {
- withShares?: boolean
- withHasComments?: boolean
- withSyncs?: boolean
- }
- ): Promise<FileProps[]> {
+ async spaceRootFiles(userId: number, spaceId: number, details: SpaceBrowseDetails): Promise<FileProps[]> {
if (!this.spaceRootFilesQuery) {
const select: FileProps | SelectedFields<any, any> = {
id: files.id,
@@ -273,7 +267,7 @@ export class SpacesQueries {
permissions: spacesRoots.permissions,
owner: { id: users.id, login: users.login, email: users.email, fullName: userFullNameSQL(users) }
},
- shares: sql`IF (${sql.placeholder('withShares')}, ${concatDistinctObjectsInArray(shares.id, {
+ shares: sql`IF (${sql.placeholder('withDetails')}, ${concatDistinctObjectsInArray(shares.id, {
id: shares.id,
alias: shares.alias,
name: shares.name,
@@ -284,17 +278,22 @@ export class SpacesQueries {
clientId: syncClients.id,
clientName: sql`JSON_VALUE(${syncClients.info}, '$.node')`
})}, '[]')`.mapWith(dbParseJson),
- hasComments: sql<boolean>`IF (${sql.placeholder('withHasComments')}, ${fileHasCommentsSubquerySQL(files.id)}, 0)`.mapWith(Boolean)
+ hasComments: sql<boolean>`IF (${sql.placeholder('withDetails')}, ${fileHasCommentsSubquerySQL(files.id)}, 0)`.mapWith(Boolean),
+ isFavorite: isNotNull(filesFavorites.fileId).mapWith(Boolean)
}
this.spaceRootFilesQuery = this.db
.select(select)
.from(spacesRoots)
.leftJoin(files, eq(files.id, spacesRoots.fileId))
.leftJoin(users, eq(users.id, files.ownerId))
+ .leftJoin(
+ filesFavorites,
+ and(eq(sql.placeholder('withFavorites'), sql`1`), eq(filesFavorites.userId, sql.placeholder('userId')), eq(filesFavorites.fileId, files.id))
+ )
.leftJoin(
shares,
and(
- eq(sql.placeholder('withShares'), sql`1`),
+ eq(sql.placeholder('withDetails'), sql`1`),
eq(shares.ownerId, sql.placeholder('userId')),
isNull(shares.fileId),
isNull(shares.parentId),
@@ -319,9 +318,9 @@ export class SpacesQueries {
return this.spaceRootFilesQuery.execute({
userId,
spaceId,
- withHasComments: +!!options.withHasComments,
- withShares: +!!options.withShares,
- withSyncs: +!!options.withSyncs
+ withDetails: +!!details,
+ withFavorites: +(details?.favorites ?? false),
+ withSyncs: +(details?.syncs ?? false)
})
}
diff --git a/backend/src/applications/spaces/spaces.controller.ts b/backend/src/applications/spaces/spaces.controller.ts
index a11c5e05..4ece5874 100644
--- a/backend/src/applications/spaces/spaces.controller.ts
+++ b/backend/src/applications/spaces/spaces.controller.ts
@@ -63,7 +63,7 @@ export class SpacesController {
@UserHavePermission() // override: checked in space guard
@UseGuards(SpaceGuard)
async browseSpace(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv): Promise<SpaceFiles> {
- return this.spacesBrowser.browse(user, space, { withLocks: true, withSpacesAndShares: true, withSyncs: true, withHasComments: true })
+ return this.spacesBrowser.browse(user, space, true)
}
@Get(`${SPACES_ROUTE.TREE}/${SPACES_BASE_ROUTE}`)
diff --git a/backend/src/infrastructure/database/schema.ts b/backend/src/infrastructure/database/schema.ts
index 95cc1599..6514e2bb 100644
--- a/backend/src/infrastructure/database/schema.ts
+++ b/backend/src/infrastructure/database/schema.ts
@@ -9,6 +9,7 @@ export * from '../../applications/spaces/schemas/spaces-roots.schema'
export * from '../../applications/shares/schemas/shares.schema'
export * from '../../applications/shares/schemas/shares-members.schema'
export * from '../../applications/files/schemas/files.schema'
+export * from '../../applications/files/schemas/files-favorites.schema'
export * from '../../applications/files/schemas/files-recents.schema'
export * from '../../applications/links/schemas/links.schema'
export * from '../../applications/comments/schemas/comments.schema'
diff --git a/frontend/src/app/app.routes.ts b/frontend/src/app/app.routes.ts
index eda35ded..7aeeec43 100644
--- a/frontend/src/app/app.routes.ts
+++ b/frontend/src/app/app.routes.ts
@@ -1,6 +1,7 @@
import { Routes } from '@angular/router'
import { APP_PATH } from './app.constants'
import { adminRoutes } from './applications/admin/admin.routes'
+import { favoritesRoutes } from './applications/favorites/favorites.routes'
import { homeRoutes } from './applications/home/home.routes'
import { linksRoutes } from './applications/links/links.routes'
import { recentsRoutes } from './applications/recents/recents.routes'
@@ -17,7 +18,7 @@ export const routes: Routes = [
path: APP_PATH.BASE,
component: LayoutComponent,
canActivate: [authGuard],
- children: [...homeRoutes, ...recentsRoutes, ...searchRoutes, ...spacesRoutes, ...userRoutes, ...syncRoutes, ...adminRoutes]
+ children: [...homeRoutes, ...recentsRoutes, ...favoritesRoutes, ...searchRoutes, ...spacesRoutes, ...userRoutes, ...syncRoutes, ...adminRoutes]
},
...authRoutes,
...linksRoutes,
diff --git a/frontend/src/app/applications/favorites/components/favorites.component.html b/frontend/src/app/applications/favorites/components/favorites.component.html
new file mode 100644
index 00000000..9123833e
--- /dev/null
+++ b/frontend/src/app/applications/favorites/components/favorites.component.html
@@ -0,0 +1,194 @@
+<!--Start Top Menu-->
+<div class="app-top-menu">
+ <button (click)="loadFavorites()"
+ class="d-none d-sm-block btn btn-default me-1"
+ [tooltip]="'Refresh' | translate:locale.language"
+ type="button">
+ <fa-icon [icon]="icons.faArrowRotateRight" [animation]="loading ? 'spin' : null"></fa-icon>
+ </button>
+ <button (click)="goTo()"
+ [disabled]="!selected || selected.isDisabled"
+ class="btn btn-default me-1"
+ [tooltip]="'Go to' | translate:locale.language"
+ type="button">
+ <fa-icon [icon]="icons.faMapMarkerAlt"></fa-icon>
+ </button>
+ <button (click)="removeFavorite()"
+ [disabled]="!selected"
+ class="btn btn-default me-1"
+ [tooltip]="'Remove from favorites' | translate:locale.language"
+ type="button">
+ <fa-icon [icon]="icons.REMOVE_FAVORITE"></fa-icon>
+ </button>
+ <div class="ms-auto">
+ <div class="btn-group me-1">
+ <app-input-filter class="d-none d-sm-block"></app-input-filter>
+ </div>
+ <app-navigation-view (switchView)="galleryMode = $event"></app-navigation-view>
+ </div>
+</div>
+<!--End Top Menu-->
+@if (galleryMode?.enabled) {
+ <!--Start Gallery Content-->
+ <div [style.--gallery-card-size]="galleryMode.dimensions + 'px'"
+ [style.--gallery-image-size]="galleryMode.image + 'px'"
+ [style.--gallery-text-size]="galleryMode.textSize + 'px'"
+ class="app-gallery">
+ <app-virtual-scroll (contextmenu)="onContextMenu($event)"
+ [childHeight]="galleryMode.dimensions"
+ [childWidth]="galleryMode.dimensions"
+ [items]="favorites | searchFilter:inputFilter.search()"
+ [galleryMode]="true"
+ [resizeOffset]="110">
+ <div *ngTemplateOutlet="CommonMessages"></div>
+ <div class="row g-0" tabindex="-1">
+ @for (f of scrollView?.viewPortItems; track f.fileId) {
+ <div (click)="onSelect(f)"
+ (contextmenu)="onTargetContextMenu($event, f)"
+ (appTap)="goTo(f)"
+ [class.disabled]="f.isDisabled"
+ [class.selected]="f.fileId === selected?.fileId"
+ class="card">
+ <div [attr.rowIndex]="$index" class="card-body">
+ <img [src]="f.mimeUrl"
+ alt=""
+ class="gallery-image"
+ draggable="false"
+ (error)="f.fallBackMimeUrl()">
+ @if (f.newly) {
+ <span class="label-top-right">
+ <span class="badge bg-purple">{{ f.hTimeAgo }}</span>
+ </span>
+ }
+ @if (f.isDisabled) {
+ <span class="label-bottom-left">
+ <span class="badge bg-warning text-dark" l10nTranslate>
+ <fa-icon [icon]="icons.faTriangleExclamation"></fa-icon>
+ No longer accessible
+ </span>
+ </span>
+ }
+ </div>
+ <div class="card-footer text-center text-truncate p-1">
+ <span class="no-pointer-events text-file-name-preserve" draggable="false">{{ f.name }}</span>
+ </div>
+ </div>
+ }
+ </div>
+ </app-virtual-scroll>
+ </div>
+ <!--End Gallery Content-->
+} @else {
+ <!--Start Table Files Content-->
+ <table class="app-table">
+ <thead>
+ <tr>
+ @for (th of tableHeaders | keyvalue: originalOrderKeyValue; track th.key) {
+ @if (th.value.show) {
+ <th (click)="sortBy(th.key)"
+ [style.width.%]="th.value.width"
+ [class.text-align-center]="th.value.textCenter"
+ [class.cursor-pointer]="th.value.sortable"
+ class="{{th.value.class}}"
+ l10nTranslate>
+ {{ th.value.label }}
+ @if (sortTable.sortParam.column === th.key) {
+ <fa-icon [icon]="sortTable.sortParam.asc ? icons.faArrowDown : icons.faArrowUp"></fa-icon>
+ }
+ </th>
+ }
+ }
+ </tr>
+ </thead>
+ </table>
+ <app-virtual-scroll (contextmenu)="onContextMenu($event)"
+ [bufferAmount]="5"
+ [items]="favorites | searchFilter:inputFilter.search()">
+ <div *ngTemplateOutlet="CommonMessages"></div>
+ <table class="app-table">
+ <tbody tabindex="-1">
+ @for (f of scrollView?.viewPortItems; track f.fileId) {
+ <tr (click)="onSelect(f)"
+ (contextmenu)="onTargetContextMenu($event, f)"
+ (appTap)="goTo(f)"
+ [class.disabled]="f.isDisabled"
+ [class.selected]="f.fileId === selected?.fileId">
+ @for (th of tableHeaders | keyvalue: originalOrderKeyValue; track th.key) {
+ @if (th.value.show) {
+ <td [style.width.%]="th.value.width"
+ [class.text-align-center]="th.value.textCenter"
+ class="{{th.value.class}}">
+ @switch (th.key) {
+ @case ('name') {
+ <div class="d-flex align-items-center">
+ <img [src]="f.mimeUrl" alt="" draggable="false" height="30" width="30" (error)="f.fallBackMimeUrl()">
+ <div class="d-flex flex-column text-truncate">
+ <span class="no-pointer-events text-file-name-preserve" draggable="false">{{ f.name }}</span>
+ @if (f.isDisabled) {
+ <span class="text-warning fs-xs" l10nTranslate>No longer accessible</span>
+ }
+ </div>
+ </div>
+ }
+ @case ('location') {
+ @if (f.isDisabled) {
+ <span class="text-warning" l10nTranslate>
+ <fa-icon [icon]="icons.faTriangleExclamation"></fa-icon>
+ No longer accessible
+ </span>
+ } @else {
+ <app-file-location [location]="f" [displayAsRepository]="true"></app-file-location>
+ }
+ }
+ @case ('size') {
+ <span>{{ f.isDir && f.size === 0 ? '●' : (f.size | toBytes:0:true) }}</span>
+ }
+ @case ('modified') {
+ <span>{{ f.mtime | amLiveTimeAgo }}</span>
+ }
+ @case ('created') {
+ <span>{{ f.createdAt | amLiveTimeAgo }}</span>
+ }
+ }
+ </td>
+ }
+ }
+ </tr>
+ }
+ </tbody>
+ </table>
+ </app-virtual-scroll>
+ <!--End Table Files Content-->
+}
+<!--Start Foot Content-->
+<div class="app-foot-menu">
+ <span class="mx-auto">{{ favorites.length }} {{ 'favorites' | translate:locale.language }}</span>
+</div>
+<!--End Foot Content-->
+<!--Start Common Messages-->
+<ng-template #CommonMessages>
+ @if (!loading && !favorites.length) {
+ <div class="fs-base text-center text-gray fw-bold no-select p-4">
+ <span l10nTranslate>No favorites</span>
+ </div>
+ }
+</ng-template>
+<!--End Common Messages-->
+<!--Start Context Menu -->
+<context-menu #MainContextMenu>
+ <ng-template (execute)="loadFavorites()" contextMenuItem>
+ <span l10nTranslate><fa-icon [icon]="icons.faArrowRotateRight"></fa-icon>Refresh</span>
+ </ng-template>
+</context-menu>
+<context-menu #TargetContextMenu>
+ @if (!selected?.isDisabled) {
+ <ng-template (execute)="goTo()" contextMenuItem>
+ <span l10nTranslate><fa-icon [icon]="icons.faMapMarkerAlt"></fa-icon>Go to</span>
+ </ng-template>
+ <ng-template [divider]="true" contextMenuItem></ng-template>
+ }
+ <ng-template (execute)="removeFavorite()" contextMenuItem>
+ <span l10nTranslate><fa-icon [icon]="icons.REMOVE_FAVORITE"></fa-icon>Remove from favorites</span>
+ </ng-template>
+</context-menu>
+<!--End Context Menu-->
diff --git a/frontend/src/app/applications/favorites/components/favorites.component.ts b/frontend/src/app/applications/favorites/components/favorites.component.ts
new file mode 100644
index 00000000..f0206b2f
--- /dev/null
+++ b/frontend/src/app/applications/favorites/components/favorites.component.ts
@@ -0,0 +1,226 @@
+import { KeyValuePipe, NgTemplateOutlet } from '@angular/common'
+import { HttpErrorResponse } from '@angular/common/http'
+import { Component, ElementRef, inject, OnInit, ViewChild } from '@angular/core'
+import { ActivatedRoute, Router } from '@angular/router'
+import { FaIconComponent } from '@fortawesome/angular-fontawesome'
+import { faStar as faStarRegular } from '@fortawesome/free-regular-svg-icons'
+import { faArrowDown, faArrowRotateRight, faArrowUp, faMapMarkerAlt, faTriangleExclamation } from '@fortawesome/free-solid-svg-icons'
+import { ContextMenuComponent, ContextMenuModule } from '@perfectmemory/ngx-contextmenu'
+import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
+import { TooltipModule } from 'ngx-bootstrap/tooltip'
+import { take } from 'rxjs/operators'
+import { FilterComponent } from '../../../common/components/filter.component'
+import { NavigationViewComponent, ViewMode } from '../../../common/components/navigation-view/navigation-view.component'
+import { VirtualScrollComponent } from '../../../common/components/virtual-scroll.component'
+import { TapDirective } from '../../../common/directives/tap.directive'
+import { TableHeaderConfig } from '../../../common/interfaces/table.interface'
+import { SearchFilterPipe } from '../../../common/pipes/search.pipe'
+import { LiveTimeAgoPipe } from '../../../common/pipes/time-ago-live.pipe'
+import { ToBytesPipe } from '../../../common/pipes/to-bytes.pipe'
+import { originalOrderKeyValue } from '../../../common/utils/functions'
+import { SortSettings, SortTable } from '../../../common/utils/sort-table'
+import { LayoutService } from '../../../layout/layout.service'
+import { FileLocationComponent } from '../../files/components/utils/file-location.component'
+import { FileFavoriteModel } from '../../files/models/file-favorite.model'
+import { FilesService } from '../../files/services/files.service'
+import { SPACES_PATH } from '../../spaces/spaces.constants'
+import { FAVORITES_ICON, FAVORITES_PATH, FAVORITES_TITLE } from '../favorites.constants'
+
+@Component({
+ selector: 'app-favorites',
+ imports: [
+ FaIconComponent,
+ KeyValuePipe,
+ NgTemplateOutlet,
+ L10nTranslateDirective,
+ L10nTranslatePipe,
+ NavigationViewComponent,
+ FilterComponent,
+ SearchFilterPipe,
+ TooltipModule,
+ VirtualScrollComponent,
+ ContextMenuModule,
+ TapDirective,
+ LiveTimeAgoPipe,
+ ToBytesPipe,
+ FileLocationComponent
+ ],
+ templateUrl: './favorites.component.html'
+})
+export class FavoritesComponent implements OnInit {
+ @ViewChild(VirtualScrollComponent) scrollView: {
+ element: ElementRef
+ viewPortItems: FileFavoriteModel[]
+ scrollInto: (arg: FileFavoriteModel | number) => void
+ }
+ @ViewChild(FilterComponent, { static: true }) inputFilter: FilterComponent
+ @ViewChild(NavigationViewComponent, { static: true }) btnNavigationView: NavigationViewComponent
+ @ViewChild('MainContextMenu', { static: true }) mainContextMenu: ContextMenuComponent<any>
+ @ViewChild('TargetContextMenu', { static: true }) targetContextMenu: ContextMenuComponent<any>
+ protected readonly locale = inject<L10nLocale>(L10N_LOCALE)
+ protected readonly layout = inject(LayoutService)
+ protected readonly icons = {
+ FAVORITES: FAVORITES_ICON,
+ faArrowRotateRight,
+ faArrowDown,
+ faArrowUp,
+ faMapMarkerAlt,
+ faTriangleExclamation,
+ REMOVE_FAVORITE: faStarRegular
+ }
+ protected readonly originalOrderKeyValue = originalOrderKeyValue
+ protected loading = false
+ protected galleryMode: ViewMode
+ protected favorites: FileFavoriteModel[] = []
+ protected selected: FileFavoriteModel = null
+ protected tableHeaders: Record<'name' | 'location' | 'size' | 'modified' | 'created', TableHeaderConfig> = {
+ name: {
+ label: 'Name',
+ width: 35,
+ textCenter: false,
+ class: '',
+ show: true,
+ sortable: true
+ },
+ location: {
+ label: 'Location',
+ width: 35,
+ textCenter: false,
+ class: 'd-none d-md-table-cell fs-sm',
+ show: true,
+ sortable: true
+ },
+ size: {
+ label: 'Size',
+ width: 10,
+ textCenter: true,
+ class: 'd-none d-lg-table-cell',
+ show: true,
+ sortable: true
+ },
+ modified: {
+ label: 'Modified',
+ width: 12,
+ textCenter: true,
+ class: 'd-none d-sm-table-cell',
+ show: true,
+ sortable: true
+ },
+ created: {
+ label: 'Created',
+ width: 13,
+ textCenter: true,
+ class: 'd-none d-lg-table-cell',
+ show: true,
+ sortable: true
+ }
+ }
+ private readonly activatedRoute = inject(ActivatedRoute)
+ private readonly router = inject(Router)
+ private readonly filesService = inject(FilesService)
+ private focusOnSelect: string
+ private readonly sortSettings: SortSettings = {
+ default: [{ prop: 'createdAt', type: 'date' }],
+ name: [{ prop: 'name', type: 'string' }],
+ location: [{ prop: 'showedPath', type: 'string' }],
+ size: [{ prop: 'size', type: 'number' }],
+ modified: [{ prop: 'mtime', type: 'number' }],
+ created: [{ prop: 'createdAt', type: 'date' }]
+ }
+ protected sortTable = new SortTable(this.constructor.name, this.sortSettings)
+
+ constructor() {
+ this.activatedRoute.queryParams.subscribe((params) => (this.focusOnSelect = params.select))
+ this.layout.setBreadcrumbIcon(FAVORITES_ICON)
+ this.layout.setBreadcrumbNav({ url: `/${FAVORITES_PATH.BASE}/${FAVORITES_TITLE}`, translating: true, sameLink: true })
+ }
+
+ ngOnInit() {
+ this.galleryMode = this.btnNavigationView.currentView()
+ this.loadFavorites()
+ }
+
+ loadFavorites() {
+ this.loading = true
+ this.onSelect()
+ this.inputFilter.clear()
+ this.filesService
+ .listFavorites()
+ .pipe(take(1))
+ .subscribe({
+ next: (favorites: FileFavoriteModel[]) => {
+ this.sortBy(this.sortTable.sortParam.column, false, [...favorites])
+ this.loading = false
+ if (this.focusOnSelect) {
+ this.focusOn(this.focusOnSelect)
+ } else {
+ this.scrollView?.scrollInto(-1)
+ }
+ },
+ error: (e: HttpErrorResponse) => {
+ this.favorites = []
+ this.loading = false
+ this.layout.sendNotification('error', 'Favorites', 'Unable to load', e)
+ }
+ })
+ }
+
+ sortBy(column: string, toUpdate = true, collection?: FileFavoriteModel[]) {
+ this.favorites = this.sortTable.sortBy(column, toUpdate, collection || this.favorites)
+ }
+
+ onSelect(favorite: FileFavoriteModel = null) {
+ this.selected = favorite
+ }
+
+ onContextMenu(ev: Event) {
+ ev.preventDefault()
+ ev.stopPropagation()
+ this.layout.openContextMenu(ev, this.mainContextMenu)
+ }
+
+ onTargetContextMenu(ev: Event, favorite: FileFavoriteModel) {
+ ev.preventDefault()
+ if (ev.type === 'contextmenu') {
+ ev.stopPropagation()
+ }
+ this.onSelect(favorite)
+ this.layout.openContextMenu(ev, this.targetContextMenu)
+ }
+
+ goTo(favorite: FileFavoriteModel = this.selected) {
+ if (!favorite) return
+ if (favorite.isDisabled) {
+ this.layout.sendNotification('warning', favorite.name, 'No longer accessible')
+ return
+ }
+ this.router.navigate([SPACES_PATH.SPACES, ...favorite.path.split('/')], { queryParams: { select: favorite.name } }).catch(console.error)
+ }
+
+ removeFavorite(favorite: FileFavoriteModel = this.selected, ev?: Event) {
+ ev?.stopPropagation()
+ if (!favorite) return
+ this.filesService
+ .removeFavorite(favorite.fileId)
+ .pipe(take(1))
+ .subscribe({
+ next: () => {
+ if (this.selected?.fileId === favorite.fileId) this.onSelect()
+ this.sortBy(
+ this.sortTable.sortParam.column,
+ false,
+ this.favorites.filter((item) => item.fileId !== favorite.fileId)
+ )
+ },
+ error: (e: HttpErrorResponse) => this.layout.sendNotification('error', 'Favorites', favorite.name, e)
+ })
+ }
+
+ private focusOn(select: string) {
+ const favorite = this.favorites.find((item) => item.name.toLowerCase() === select.toLowerCase())
+ if (favorite) {
+ setTimeout(() => this.scrollView?.scrollInto(favorite), 100)
+ this.onSelect(favorite)
+ }
+ }
+}
diff --git a/frontend/src/app/applications/favorites/favorites.constants.ts b/frontend/src/app/applications/favorites/favorites.constants.ts
new file mode 100644
index 00000000..a45a8937
--- /dev/null
+++ b/frontend/src/app/applications/favorites/favorites.constants.ts
@@ -0,0 +1,10 @@
+import { IconDefinition } from '@fortawesome/fontawesome-svg-core'
+import { faStar } from '@fortawesome/free-solid-svg-icons'
+
+export const FAVORITES_PATH = {
+ BASE: 'favorites'
+} as const
+
+export const FAVORITES_TITLE = 'Favorites'
+
+export const FAVORITES_ICON: IconDefinition = faStar
diff --git a/frontend/src/app/applications/favorites/favorites.routes.ts b/frontend/src/app/applications/favorites/favorites.routes.ts
new file mode 100644
index 00000000..0c774a24
--- /dev/null
+++ b/frontend/src/app/applications/favorites/favorites.routes.ts
@@ -0,0 +1,6 @@
+import { Routes } from '@angular/router'
+import { noUserLinkGuard } from '../users/user.guards'
+import { FavoritesComponent } from './components/favorites.component'
+import { FAVORITES_PATH } from './favorites.constants'
+
+export const favoritesRoutes: Routes = [{ path: FAVORITES_PATH.BASE, component: FavoritesComponent, canActivate: [noUserLinkGuard] }]
diff --git a/frontend/src/app/applications/files/components/sidebar/files-selection.component.html b/frontend/src/app/applications/files/components/sidebar/files-selection.component.html
index 1d6bb91a..43852ab9 100644
--- a/frontend/src/app/applications/files/components/sidebar/files-selection.component.html
+++ b/frontend/src/app/applications/files/components/sidebar/files-selection.component.html
@@ -118,11 +118,25 @@
{{ (f.syncs.length ? 'yes' : 'no') | translate:locale.language }}
</span>
</div>
+ @if (canManageFavorite) {
+ <div class="d-flex align-items-center mb-1">
+ <div class="d-flex col-5 col-sm-5 text-bold" l10nTranslate>Favorites</div>
+ <button (click)="toggleFavorite(f)"
+ class="badge {{f.isFavorite ? 'bg-warning' : 'bg-default'}} cursor-pointer"
+ type="button"
+ [attr.aria-label]="(f.isFavorite ? 'Remove from favorites' : 'Add to favorites') | translate:locale.language">
+ <fa-icon [icon]="icons.FAVORITES"></fa-icon>
+ </button>
+ </div>
+ }
<div class="d-flex align-items-center mb-1">
<div class="d-flex col-5 col-sm-5 text-bold" l10nTranslate>Comments</div>
- <span (click)="goToComments()" class="badge {{f.hasComments ? 'bg-success' : 'bg-default'}} cursor-pointer">
- {{ (f.hasComments ? 'yes' : 'no') | translate:locale.language }}
- </span>
+ <button (click)="goToComments()"
+ class="badge {{f.hasComments ? 'bg-success' : 'bg-default'}} cursor-pointer"
+ type="button"
+ [attr.aria-label]="'Comments' | translate:locale.language">
+ <fa-icon [icon]="icons.faCommentDots"></fa-icon>
+ </button>
</div>
</div>
@if (f.root) {
diff --git a/frontend/src/app/applications/files/components/sidebar/files-selection.component.ts b/frontend/src/app/applications/files/components/sidebar/files-selection.component.ts
index 53112711..8f9dac0d 100755
--- a/frontend/src/app/applications/files/components/sidebar/files-selection.component.ts
+++ b/frontend/src/app/applications/files/components/sidebar/files-selection.component.ts
@@ -1,18 +1,22 @@
import { AsyncPipe } from '@angular/common'
+import { HttpErrorResponse } from '@angular/common/http'
import { ChangeDetectionStrategy, Component, inject, input } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { Router } from '@angular/router'
import { FaIconComponent } from '@fortawesome/angular-fontawesome'
-import { faLock, faSpinner, faTimes, faUnlock } from '@fortawesome/free-solid-svg-icons'
+import { faCommentDots, faLock, faSpinner, faTimes, faUnlock } from '@fortawesome/free-solid-svg-icons'
import { TAR_EXTENSION } from '@sync-in-server/backend/src/applications/files/constants/compress'
import type { CompressFileDto } from '@sync-in-server/backend/src/applications/files/dto/file-operations.dto'
import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
+import { take } from 'rxjs/operators'
import { BadgePermissionsComponent } from '../../../../common/components/badge-permissions.component'
import { AutoResizeDirective } from '../../../../common/directives/auto-resize.directive'
import { TimeDateFormatPipe } from '../../../../common/pipes/time-date-format.pipe'
import { defaultCardImageSize } from '../../../../layout/layout.constants'
import { TAB_MENU } from '../../../../layout/layout.interfaces'
import { LayoutService } from '../../../../layout/layout.service'
+import { StoreService } from '../../../../store/store.service'
+import { FAVORITES_ICON } from '../../../favorites/favorites.constants'
import { SPACES_ICON, SPACES_PATH } from '../../../spaces/spaces.constants'
import { SYNC_ICON } from '../../../sync/sync.constants'
import { UserAvatarComponent } from '../../../users/components/utils/user-avatar.component'
@@ -50,6 +54,7 @@ export class FilesSelectionComponent {
private readonly router = inject(Router)
private readonly layout = inject(LayoutService)
private readonly filesService = inject(FilesService)
+ private readonly store = inject(StoreService)
protected readonly locale = inject<L10nLocale>(L10N_LOCALE)
protected readonly cardImageSize = defaultCardImageSize
protected selectedAction: SelectionAction = 'clipboard'
@@ -58,6 +63,8 @@ export class FilesSelectionComponent {
SHARED: SPACES_ICON.SHARED_WITH_OTHERS,
LINKS: SPACES_ICON.LINKS,
SYNC: SYNC_ICON.SYNC,
+ FAVORITES: FAVORITES_ICON,
+ faCommentDots,
faLock,
faUnlock,
faSpinner,
@@ -78,6 +85,20 @@ export class FilesSelectionComponent {
this.layout.showRSideBarTab(TAB_MENU.COMMENTS, true)
}
+ protected get canManageFavorite(): boolean {
+ return !this.store.user.getValue()?.isLink && this.store.repository() !== SPACES_PATH.TRASH
+ }
+
+ toggleFavorite(file: FileModel) {
+ if (!this.canManageFavorite) return
+ this.filesService
+ .toggleFavorite(file)
+ .pipe(take(1))
+ .subscribe({
+ error: (e: HttpErrorResponse) => this.layout.sendNotification('error', 'Favorites', file.name, e)
+ })
+ }
+
addToClipboard() {
this.filesService.addToClipboard(this.files())
this.filesService.fileSelectionClear.next()
diff --git a/frontend/src/app/applications/files/models/file-favorite.model.ts b/frontend/src/app/applications/files/models/file-favorite.model.ts
new file mode 100644
index 00000000..f971cfe2
--- /dev/null
+++ b/frontend/src/app/applications/files/models/file-favorite.model.ts
@@ -0,0 +1,21 @@
+import type { FileFavorite } from '@sync-in-server/backend/src/applications/files/schemas/file-favorite.interface'
+import { getNewly } from '../../../common/utils/functions'
+import { dJs } from '../../../common/utils/time'
+import { FileLocationModel } from './file-location.model'
+
+export class FileFavoriteModel extends FileLocationModel implements FileFavorite {
+ fileId: number
+ isDir: boolean
+ size: number
+ ctime: number
+ createdAt: Date
+ isDisabled: boolean
+ hTimeAgo: string
+ newly = 0
+
+ constructor(props: FileFavorite) {
+ super(props, props.repository)
+ this.hTimeAgo = dJs(this.mtime).fromNow(true)
+ this.newly = getNewly(this.mtime)
+ }
+}
diff --git a/frontend/src/app/applications/files/models/file.model.ts b/frontend/src/app/applications/files/models/file.model.ts
index 4e871378..c83291a8 100644
--- a/frontend/src/app/applications/files/models/file.model.ts
+++ b/frontend/src/app/applications/files/models/file.model.ts
@@ -46,6 +46,7 @@ export class FileModel implements File {
// Extra properties
hasComments: boolean
+ isFavorite = false
root?: {
id: number
alias: string
@@ -70,7 +71,7 @@ export class FileModel implements File {
hTimeAgo: string
dirSize: Observable<number | undefined>
nbBadges = 0
- galleryBadges: ('lock' | 'shares' | 'spaces' | 'links' | 'syncs' | 'comments')[] = []
+ galleryBadges: ('lock' | 'favorites' | 'shares' | 'spaces' | 'links' | 'syncs' | 'comments')[] = []
// States
newly = 0
@@ -156,6 +157,7 @@ export class FileModel implements File {
updateNbBadges() {
this.galleryBadges = []
if (this.lock) this.galleryBadges.push('lock')
+ if (this.isFavorite) this.galleryBadges.push('favorites')
if (this.shares.length) this.galleryBadges.push('shares')
if (this.spaces.length) this.galleryBadges.push('spaces')
if (this.links.length) this.galleryBadges.push('links')
diff --git a/frontend/src/app/applications/files/services/files.service.ts b/frontend/src/app/applications/files/services/files.service.ts
index 975b1d96..d0baef9d 100644
--- a/frontend/src/app/applications/files/services/files.service.ts
+++ b/frontend/src/app/applications/files/services/files.service.ts
@@ -9,6 +9,7 @@ import {
SEND_FILE_ERROR_MSG
} from '@sync-in-server/backend/src/applications/files/constants/operations'
import {
+ API_FILES_FAVORITES,
API_FILES_OPERATION,
API_FILES_OPERATION_MAKE,
API_FILES_RECENTS,
@@ -18,6 +19,7 @@ import {
API_FILES_TASK_OPERATION_DOWNLOAD,
API_FILES_TASKS_DOWNLOAD
} from '@sync-in-server/backend/src/applications/files/constants/routes'
+import type { DeleteFileFavoriteDto, FileFavoriteDto } from '@sync-in-server/backend/src/applications/files/dto/file-favorite.dto'
import type {
CompressFileDto,
CopyMoveFileDto,
@@ -33,6 +35,7 @@ import { COLLABORA_ONLINE_EXTENSIONS } from '@sync-in-server/backend/src/applica
import type { FileEditorProviders } from '@sync-in-server/backend/src/applications/files/editors/file-editor-providers.interface'
import { ONLY_OFFICE_EXTENSIONS } from '@sync-in-server/backend/src/applications/files/editors/only-office/only-office.constants'
import type { FileContent } from '@sync-in-server/backend/src/applications/files/schemas/file-content.interface'
+import type { FileFavorite, FileFavoriteIdentity } from '@sync-in-server/backend/src/applications/files/schemas/file-favorite.interface'
import type { FileRecent } from '@sync-in-server/backend/src/applications/files/schemas/file-recent.interface'
import { API_SPACES_TREE } from '@sync-in-server/backend/src/applications/spaces/constants/routes'
import { SPACE_OPERATION } from '@sync-in-server/backend/src/applications/spaces/constants/spaces'
@@ -51,6 +54,7 @@ import { FilesViewerSelectDialog } from '../components/dialogs/files-viewer-sele
import { fileLockPropsToString } from '../components/utils/file-lock.utils'
import { MAX_TEXT_FILE_SIZE, SHORT_MIME } from '../files.constants'
import { FileContentModel } from '../models/file-content.model'
+import { FileFavoriteModel } from '../models/file-favorite.model'
import { FileRecentModel } from '../models/file-recent.model'
import { FileModel } from '../models/file.model'
import { FilesTasksService } from './files-tasks.service'
@@ -225,6 +229,44 @@ export class FilesService {
downloadWithAnchor(`${API_FILES_TASKS_DOWNLOAD}/${taskId}`)
}
+ listFavorites(): Observable<FileFavoriteModel[]> {
+ return this.http.get<FileFavorite[]>(API_FILES_FAVORITES).pipe(map((files) => files.map((file) => new FileFavoriteModel(file))))
+ }
+
+ addFavorite(file: FileModel): Observable<FileFavoriteIdentity> {
+ const body = { fileId: file.id } satisfies FileFavoriteDto
+ return this.http.post<FileFavoriteIdentity>(`${API_FILES_FAVORITES}/${file.encodedPath}`, body)
+ }
+
+ removeFavorite(fileId: number): Observable<void> {
+ const body = { fileId } satisfies DeleteFileFavoriteDto
+ return this.http.request<void>('delete', API_FILES_FAVORITES, { body })
+ }
+
+ toggleFavorite(file: FileModel): Observable<boolean> {
+ if (file.isFavorite) {
+ return this.removeFavorite(file.id).pipe(
+ tap(() => this.updateFavoriteState(file, false)),
+ map(() => false)
+ )
+ }
+ return this.addFavorite(file).pipe(
+ tap(({ fileId }) => {
+ if (file.id < 0) file.id = fileId
+ this.updateFavoriteState(file, true)
+ }),
+ map(() => true)
+ )
+ }
+
+ private updateFavoriteState(file: FileModel, isFavorite: boolean) {
+ file.isFavorite = isFavorite
+ file.updateNbBadges()
+ if (this.store.filesSelection().includes(file)) {
+ this.store.filesSelection.update((files) => [...files])
+ }
+ }
+
loadRecents(limit: number) {
this.http
.get<FileRecent[]>(API_FILES_RECENTS, { params: new HttpParams().set('limit', limit) })
diff --git a/frontend/src/app/applications/shares/components/sidebar/share-selection.component.html b/frontend/src/app/applications/shares/components/sidebar/share-selection.component.html
index 3bc93491..0864773d 100644
--- a/frontend/src/app/applications/shares/components/sidebar/share-selection.component.html
+++ b/frontend/src/app/applications/shares/components/sidebar/share-selection.component.html
@@ -40,9 +40,12 @@
</div>
<div class="d-flex align-items-center mb-1">
<div class="d-flex col-5 col-sm-5 text-bold" l10nTranslate>Comments</div>
- <span (click)="goToComments()" class="badge {{share().hasComments ? 'bg-success' : 'bg-default'}} cursor-pointer">
- {{ (share().hasComments ? 'yes' : 'no') | translate:locale.language }}
- </span>
+ <button (click)="goToComments()"
+ class="badge {{share().hasComments ? 'bg-success' : 'bg-default'}} cursor-pointer"
+ type="button"
+ [attr.aria-label]="'Comments' | translate:locale.language">
+ <fa-icon [icon]="faCommentDots"></fa-icon>
+ </button>
</div>
</div>
<hr class="my-1" />
@@ -56,4 +59,3 @@
}
-
diff --git a/frontend/src/app/applications/shares/components/sidebar/share-selection.component.ts b/frontend/src/app/applications/shares/components/sidebar/share-selection.component.ts
index 6e72e572..9784eb62 100755
--- a/frontend/src/app/applications/shares/components/sidebar/share-selection.component.ts
+++ b/frontend/src/app/applications/shares/components/sidebar/share-selection.component.ts
@@ -1,5 +1,6 @@
import { ChangeDetectionStrategy, Component, inject, input, InputSignal } from '@angular/core'
import { FaIconComponent } from '@fortawesome/angular-fontawesome'
+import { faCommentDots } from '@fortawesome/free-solid-svg-icons'
import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
import { BadgeMembersComponent } from '../../../../common/components/badge-members.component'
import { AutoResizeDirective } from '../../../../common/directives/auto-resize.directive'
@@ -32,6 +33,7 @@ export class ShareSelectionComponent {
share: InputSignal<ShareFileModel> = input.required<ShareFileModel>()
protected readonly locale = inject<L10nLocale>(L10N_LOCALE)
protected readonly iconShares = SPACES_ICON.SHARES
+ protected readonly faCommentDots = faCommentDots
protected readonly cardImageSize = defaultCardImageSize
protected readonly resizeOffset = defaultResizeOffset
private readonly layout = inject(LayoutService)
@@ -43,8 +45,6 @@ export class ShareSelectionComponent {
}
goToComments() {
- if (this.share().hasComments) {
- this.sharesService.goTo(this.share()).then(() => this.layout.showRSideBarTab(TAB_MENU.COMMENTS, true))
- }
+ this.sharesService.goTo(this.share()).then(() => this.layout.showRSideBarTab(TAB_MENU.COMMENTS, true))
}
}
diff --git a/frontend/src/app/applications/spaces/components/spaces-browser.component.html b/frontend/src/app/applications/spaces/components/spaces-browser.component.html
index ac9efce5..c4a40498 100644
--- a/frontend/src/app/applications/spaces/components/spaces-browser.component.html
+++ b/frontend/src/app/applications/spaces/components/spaces-browser.component.html
@@ -134,6 +134,17 @@
</a>
</li>
}
+ @if (selection.length === 1 && canManageFavorite) {
+ <li role="menuitem">
+ <a (click)="toggleFavorite(selection[0])" class="dropdown-item">
+ @if (selection[0].isFavorite) {
+ <span l10nTranslate><fa-icon [icon]="icons.FAVORITES"></fa-icon>Remove from favorites</span>
+ } @else {
+ <span l10nTranslate><fa-icon [icon]="icons.FAVORITES"></fa-icon>Add to favorites</span>
+ }
+ </a>
+ </li>
+ }
@if (!isTrashRepo && canCompress) {
<li role="menuitem">
<a (click)="openCompressionDialog()" class="dropdown-item">
@@ -264,6 +275,12 @@
<fa-icon [icon]="f.lock.isExclusive ? icons.faLock : icons.faLockOpen"></fa-icon>
</span>
}
+ @case ('favorites') {
+ <span (click)="layout.showRSideBarTab(TAB_MENU.SELECTION, true)"
+ class="badge bg-warning cursor-pointer">
+ <fa-icon [icon]="icons.FAVORITES"></fa-icon>
+ </span>
+ }
@case ('comments') {
<span (click)="layout.showRSideBarTab(TAB_MENU.COMMENTS, true)"
class="badge bg-success cursor-pointer">
@@ -451,6 +468,12 @@
<fa-icon [icon]="f.lock.isExclusive ? icons.faLock : icons.faLockOpen"></fa-icon>
</span>
}
+ @if (f.isFavorite) {
+ <span (click)="layout.showRSideBarTab(TAB_MENU.SELECTION, true)"
+ class="badge bg-warning cursor-pointer me-1">
+ <fa-icon [icon]="icons.FAVORITES"></fa-icon>
+ </span>
+ }
@if (f.hasComments) {
<span (click)="layout.showRSideBarTab(TAB_MENU.COMMENTS, true)"
class="badge bg-success cursor-pointer me-1">
@@ -600,6 +623,15 @@
<span l10nTranslate><fa-icon [icon]="icons.faRotate"></fa-icon>Synchronize</span>
</ng-template>
}
+ @if (selection.length === 1 && canManageFavorite) {
+ <ng-template (execute)="toggleFavorite(selection[0])" contextMenuItem>
+ @if (selection[0].isFavorite) {
+ <span l10nTranslate><fa-icon [icon]="icons.FAVORITES"></fa-icon>Remove from favorites</span>
+ } @else {
+ <span l10nTranslate><fa-icon [icon]="icons.FAVORITES"></fa-icon>Add to favorites</span>
+ }
+ </ng-template>
+ }
@if (selection.length === 1 && !isTrashRepo) {
<ng-template (execute)="layout.showRSideBarTab(TAB_MENU.COMMENTS, true)" contextMenuItem>
<span l10nTranslate><fa-icon [icon]="icons.faCommentDots"></fa-icon>Comment</span>
diff --git a/frontend/src/app/applications/spaces/components/spaces-browser.component.ts b/frontend/src/app/applications/spaces/components/spaces-browser.component.ts
index f0beebc4..5e98cc11 100644
--- a/frontend/src/app/applications/spaces/components/spaces-browser.component.ts
+++ b/frontend/src/app/applications/spaces/components/spaces-browser.component.ts
@@ -66,6 +66,7 @@ import { dragClass, tableTrSelectedClass } from '../../../layout/layout.constant
import { TAB_MENU } from '../../../layout/layout.interfaces'
import { LayoutService } from '../../../layout/layout.service'
import { StoreService } from '../../../store/store.service'
+import { FAVORITES_ICON } from '../../favorites/favorites.constants'
import { FilesCompressionDialogComponent } from '../../files/components/dialogs/files-compression-dialog.component'
import { FilesNewDialogComponent } from '../../files/components/dialogs/files-new-dialog.component'
import { FilesTrashDialogComponent } from '../../files/components/dialogs/files-trash-dialog.component'
@@ -133,6 +134,7 @@ export class SpacesBrowserComponent implements OnInit, AfterViewInit, OnDestroy
PERSONAL: SPACES_ICON.PERSONAL,
LINKS: SPACES_ICON.LINKS,
SYNC: SYNC_ICON.SYNC,
+ FAVORITES: FAVORITES_ICON,
faArrowRotateRight,
faPlus,
faCirclePlus,
@@ -179,6 +181,7 @@ export class SpacesBrowserComponent implements OnInit, AfterViewInit, OnDestroy
protected hasSelection = false
protected showSelectionChecks = false
protected hasDisabledItemsInSelection = false
+ protected canManageFavorite = false
protected canCompress = true
protected renamingInProgress = false
// Upload
@@ -314,6 +317,7 @@ export class SpacesBrowserComponent implements OnInit, AfterViewInit, OnDestroy
this.spacesBrowser.loadFiles().subscribe({
next: (spacesFiles: SpaceFiles) => {
this.spacePermissions = spacesFiles.permissions
+ this.canManageFavorite = !this.store.user.getValue()?.isLink && !this.isTrashRepo
this.canShare.outside = this.spacePermissions.indexOf(SPACE_OPERATION.SHARE_OUTSIDE) > -1
// todo: share inside is not used, this should allow the file anchor dialog to add a personal file to the current space (?)
this.canShare.inside = this.spacePermissions.indexOf(SPACE_OPERATION.SHARE_INSIDE) > -1
@@ -516,6 +520,16 @@ export class SpacesBrowserComponent implements OnInit, AfterViewInit, OnDestroy
this.filesService.addToClipboard(this.selection)
}
+ toggleFavorite(file: FileModel = this.selection[0]) {
+ if (!this.canManageFavorite || !file) return
+ this.filesService
+ .toggleFavorite(file)
+ .pipe(take(1))
+ .subscribe({
+ error: (e: HttpErrorResponse) => this.layout.sendNotification('error', 'Favorites', file.name, e)
+ })
+ }
+
openShareDialog() {
const f: Partial<FileSpace> = this.setFilePermissionsAndSpace()
if (f === null) return
diff --git a/frontend/src/app/applications/spaces/spaces.constants.ts b/frontend/src/app/applications/spaces/spaces.constants.ts
index a154ae6d..7647b260 100644
--- a/frontend/src/app/applications/spaces/spaces.constants.ts
+++ b/frontend/src/app/applications/spaces/spaces.constants.ts
@@ -107,6 +107,12 @@ export const SPACES_MENU: AppMenu = {
icon: RECENTS_ICON,
link: RECENTS_PATH.BASE
},
+ {
+ title: FAVORITES_TITLE,
+ icon: FAVORITES_ICON,
+ link: FAVORITES_PATH.BASE,
+ checks: [{ negate: true, prop: 'user', value: 'isLink' }]
+ },
SPACES_MENU_SECTION.SPACES,
{
id: USER_PERMISSION.PERSONAL_SPACE,
diff --git a/frontend/src/i18n/de.json b/frontend/src/i18n/de.json
index 0ab84272..a6d11b14 100644
--- a/frontend/src/i18n/de.json
+++ b/frontend/src/i18n/de.json
@@ -186,6 +186,13 @@
"Home": "Startseite",
"Recents": "Zuletzt verwendet",
"recents": "zuletzt",
+ "Favorites": "Favoriten",
+ "favorites": "Favoriten",
+ "No favorites": "Keine Favoriten",
+ "Add to favorites": "Zu Favoriten hinzufügen",
+ "Remove from favorites": "Aus Favoriten entfernen",
+ "No longer accessible": "Nicht mehr zugänglich",
+ "Not supported on this kind of location": "Für diese Art von Speicherort nicht unterstützt",
"Trash": "Papierkorb",
"trash bins": "Papierkörbe",
"Shares": "Freigaben",
diff --git a/frontend/src/i18n/es.json b/frontend/src/i18n/es.json
index 0da58ecf..2be1f8da 100644
--- a/frontend/src/i18n/es.json
+++ b/frontend/src/i18n/es.json
@@ -186,6 +186,13 @@
"Home": "Inicio",
"Recents": "Recientes",
"recents": "recientes",
+ "Favorites": "Favoritos",
+ "favorites": "favoritos",
+ "No favorites": "No hay favoritos",
+ "Add to favorites": "Añadir a favoritos",
+ "Remove from favorites": "Quitar de favoritos",
+ "No longer accessible": "Ya no es accesible",
+ "Not supported on this kind of location": "No compatible con este tipo de ubicación",
"Trash": "Papelera",
"trash bins": "papeleras",
"Shares": "Compartidos",
diff --git a/frontend/src/i18n/fr.json b/frontend/src/i18n/fr.json
index 8814bca5..199692db 100644
--- a/frontend/src/i18n/fr.json
+++ b/frontend/src/i18n/fr.json
@@ -186,6 +186,13 @@
"Home": "Accueil",
"Recents": "Récents",
"recents": "recents",
+ "Favorites": "Favoris",
+ "favorites": "favoris",
+ "No favorites": "Aucun favori",
+ "Add to favorites": "Ajouter aux favoris",
+ "Remove from favorites": "Retirer des favoris",
+ "No longer accessible": "N’est plus accessible",
+ "Not supported on this kind of location": "Non pris en charge pour ce type d’emplacement",
"Trash": "Corbeille",
"trash bins": "corbeilles",
"Shares": "Partages",
diff --git a/frontend/src/i18n/hi.json b/frontend/src/i18n/hi.json
index 029586a4..e8bcb27e 100644
--- a/frontend/src/i18n/hi.json
+++ b/frontend/src/i18n/hi.json
@@ -186,6 +186,13 @@
"Home": "होम",
"Recents": "हाल के",
"recents": "हाल के",
+ "Favorites": "पसंदीदा",
+ "favorites": "पसंदीदा",
+ "No favorites": "कोई पसंदीदा नहीं",
+ "Add to favorites": "पसंदीदा में जोड़ें",
+ "Remove from favorites": "पसंदीदा से हटाएँ",
+ "No longer accessible": "अब पहुँच योग्य नहीं",
+ "Not supported on this kind of location": "इस प्रकार के स्थान पर समर्थित नहीं है",
"Trash": "कचरा-पेटी",
"trash bins": "कचरा-पेटियाँ",
"Shares": "साझाकरण",
diff --git a/frontend/src/i18n/it.json b/frontend/src/i18n/it.json
index 21d3ffc6..84934a4f 100644
--- a/frontend/src/i18n/it.json
+++ b/frontend/src/i18n/it.json
@@ -186,6 +186,13 @@
"Home": "Home",
"Recents": "Recenti",
"recents": "recenti",
+ "Favorites": "Preferiti",
+ "favorites": "preferiti",
+ "No favorites": "Nessun preferito",
+ "Add to favorites": "Aggiungi ai preferiti",
+ "Remove from favorites": "Rimuovi dai preferiti",
+ "No longer accessible": "Non più accessibile",
+ "Not supported on this kind of location": "Non supportato per questo tipo di posizione",
"Trash": "Cestino",
"trash bins": "cestini",
"Shares": "Condivisioni",
diff --git a/frontend/src/i18n/ja.json b/frontend/src/i18n/ja.json
index ae447b67..2f0680c0 100644
--- a/frontend/src/i18n/ja.json
+++ b/frontend/src/i18n/ja.json
@@ -186,6 +186,13 @@
"Home": "ホーム",
"Recents": "最近",
"recents": "最近",
+ "Favorites": "お気に入り",
+ "favorites": "お気に入り",
+ "No favorites": "お気に入りはありません",
+ "Add to favorites": "お気に入りに追加",
+ "Remove from favorites": "お気に入りから削除",
+ "No longer accessible": "アクセスできなくなりました",
+ "Not supported on this kind of location": "この種類の場所ではサポートされていません",
"Trash": "ゴミ箱",
"trash bins": "ゴミ箱",
"Shares": "共有",
diff --git a/frontend/src/i18n/ko.json b/frontend/src/i18n/ko.json
index 521f0eff..41f986fd 100644
--- a/frontend/src/i18n/ko.json
+++ b/frontend/src/i18n/ko.json
@@ -186,6 +186,13 @@
"Home": "홈",
"Recents": "최근 항목",
"recents": "최근",
+ "Favorites": "즐겨찾기",
+ "favorites": "즐겨찾기",
+ "No favorites": "즐겨찾기 없음",
+ "Add to favorites": "즐겨찾기에 추가",
+ "Remove from favorites": "즐겨찾기에서 제거",
+ "No longer accessible": "더 이상 접근할 수 없음",
+ "Not supported on this kind of location": "이 유형의 위치에서는 지원되지 않습니다",
"Trash": "휴지통",
"trash bins": "휴지통",
"Shares": "공유",
diff --git a/frontend/src/i18n/nl.json b/frontend/src/i18n/nl.json
index 165be003..27323487 100644
--- a/frontend/src/i18n/nl.json
+++ b/frontend/src/i18n/nl.json
@@ -186,6 +186,13 @@
"Home": "Thuis",
"Recents": "Recente bestanden",
"recents": "recent",
+ "Favorites": "Favorieten",
+ "favorites": "favorieten",
+ "No favorites": "Geen favorieten",
+ "Add to favorites": "Toevoegen aan favorieten",
+ "Remove from favorites": "Verwijderen uit favorieten",
+ "No longer accessible": "Niet langer toegankelijk",
+ "Not supported on this kind of location": "Niet ondersteund voor dit type locatie",
"Trash": "Prullenmand",
"trash bins": "prullenmand",
"Shares": "Shares",
diff --git a/frontend/src/i18n/pl.json b/frontend/src/i18n/pl.json
index 73dfd7a3..79db89e5 100644
--- a/frontend/src/i18n/pl.json
+++ b/frontend/src/i18n/pl.json
@@ -186,6 +186,13 @@
"Home": "Strona główna",
"Recents": "Ostatnie",
"recents": "ostatnie",
+ "Favorites": "Ulubione",
+ "favorites": "ulubione",
+ "No favorites": "Brak ulubionych",
+ "Add to favorites": "Dodaj do ulubionych",
+ "Remove from favorites": "Usuń z ulubionych",
+ "No longer accessible": "Brak dostępu",
+ "Not supported on this kind of location": "Nieobsługiwane dla tego typu lokalizacji",
"Trash": "Kosz",
"trash bins": "kosze",
"Shares": "Udostępnienia",
diff --git a/frontend/src/i18n/pt-BR.json b/frontend/src/i18n/pt-BR.json
index c982ad0e..7a4d55dd 100644
--- a/frontend/src/i18n/pt-BR.json
+++ b/frontend/src/i18n/pt-BR.json
@@ -186,6 +186,13 @@
"Home": "Início",
"Recents": "Recentes",
"recents": "recentes",
+ "Favorites": "Favoritos",
+ "favorites": "favoritos",
+ "No favorites": "Nenhum favorito",
+ "Add to favorites": "Adicionar aos favoritos",
+ "Remove from favorites": "Remover dos favoritos",
+ "No longer accessible": "Não está mais acessível",
+ "Not supported on this kind of location": "Não há suporte para este tipo de local",
"Trash": "Lixeira",
"trash bins": "lixeiras",
"Shares": "Compartilhamentos",
diff --git a/frontend/src/i18n/pt.json b/frontend/src/i18n/pt.json
index 4fc8d3eb..861609fb 100644
--- a/frontend/src/i18n/pt.json
+++ b/frontend/src/i18n/pt.json
@@ -186,6 +186,13 @@
"Home": "Início",
"Recents": "Recentes",
"recents": "recentes",
+ "Favorites": "Favoritos",
+ "favorites": "favoritos",
+ "No favorites": "Nenhum favorito",
+ "Add to favorites": "Adicionar aos favoritos",
+ "Remove from favorites": "Remover dos favoritos",
+ "No longer accessible": "Já não está acessível",
+ "Not supported on this kind of location": "Não suportado para este tipo de localização",
"Trash": "Lixeira",
"trash bins": "lixeiras",
"Shares": "Compartilhamentos",
diff --git a/frontend/src/i18n/ru.json b/frontend/src/i18n/ru.json
index f7bdd92c..5e3d48a8 100644
--- a/frontend/src/i18n/ru.json
+++ b/frontend/src/i18n/ru.json
@@ -186,6 +186,13 @@
"Home": "Главная",
"Recents": "Недавние",
"recents": "недавние",
+ "Favorites": "Избранное",
+ "favorites": "избранное",
+ "No favorites": "Нет избранного",
+ "Add to favorites": "Добавить в избранное",
+ "Remove from favorites": "Удалить из избранного",
+ "No longer accessible": "Больше недоступно",
+ "Not supported on this kind of location": "Не поддерживается для этого типа расположения",
"Trash": "Корзина",
"trash bins": "корзины",
"Shares": "Общие ресурсы",
diff --git a/frontend/src/i18n/tr.json b/frontend/src/i18n/tr.json
index df8e1a7a..3b54ce96 100644
--- a/frontend/src/i18n/tr.json
+++ b/frontend/src/i18n/tr.json
@@ -186,6 +186,13 @@
"Home": "Ana sayfa",
"Recents": "Son kullanılanlar",
"recents": "son",
+ "Favorites": "Favoriler",
+ "favorites": "favoriler",
+ "No favorites": "Favori yok",
+ "Add to favorites": "Favorilere ekle",
+ "Remove from favorites": "Favorilerden kaldır",
+ "No longer accessible": "Artık erişilemiyor",
+ "Not supported on this kind of location": "Bu tür bir konumda desteklenmiyor",
"Trash": "Çöp kutusu",
"trash bins": "çöp kutuları",
"Shares": "Paylaşımlar",
diff --git a/frontend/src/i18n/zh.json b/frontend/src/i18n/zh.json
index 22e2871a..1b5eb11f 100644
--- a/frontend/src/i18n/zh.json
+++ b/frontend/src/i18n/zh.json
@@ -186,6 +186,13 @@
"Home": "首页",
"Recents": "最近",
"recents": "最近",
+ "Favorites": "收藏",
+ "favorites": "收藏",
+ "No favorites": "暂无收藏",
+ "Add to favorites": "添加到收藏",
+ "Remove from favorites": "从收藏中移除",
+ "No longer accessible": "无法再访问",
+ "Not supported on this kind of location": "不支持此类位置",
"Trash": "回收站",
"trash bins": "回收站",
"Shares": "共享",