Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(documents): prevent duplicate document uploads within an organization (#140)

Corentin Thomassetf78d42ca25ad
diff --git a/apps/papra-client/src/modules/documents/documents.composables.tsx b/apps/papra-client/src/modules/documents/documents.composables.tsx
index e03cf3f9..8da6a9e7 100644
--- a/apps/papra-client/src/modules/documents/documents.composables.tsx
+++ b/apps/papra-client/src/modules/documents/documents.composables.tsx
@@ -1,7 +1,9 @@
import type { Document } from './documents.types';
+import { safely } from '@corentinth/chisels';
import { createSignal } from 'solid-js';
import { useConfirmModal } from '../shared/confirm';
import { promptUploadFiles } from '../shared/files/upload';
+import { isHttpErrorWithCode } from '../shared/http/http-errors';
import { queryClient } from '../shared/query/query-client';
import { createToast } from '../ui/components/sonner';
import { deleteDocument, restoreDocument, uploadDocument } from './documents.services';
@@ -75,7 +77,15 @@ export function useRestoreDocument() {
export function useUploadDocuments({ organizationId }: { organizationId: string }) {
const uploadDocuments = async ({ files }: { files: File[] }) => {
for (const file of files) {
- await uploadDocument({ file, organizationId });
+ const [, error] = await safely(uploadDocument({ file, organizationId }));
+
+ if (isHttpErrorWithCode({ error, code: 'document.already_exists' })) {
+ createToast({
+ type: 'error',
+ message: 'Document already exists',
+ description: `The document ${file.name} already exists, it has not been uploaded.`,
+ });
+ }
}
queryClient.invalidateQueries({
diff --git a/apps/papra-server/migrations/0006_documents-hash.sql b/apps/papra-server/migrations/0006_documents-hash.sql
new file mode 100644
index 00000000..085f4deb
--- /dev/null
+++ b/apps/papra-server/migrations/0006_documents-hash.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `documents` ADD `original_sha256_hash` text NOT NULL;--> statement-breakpoint
+CREATE UNIQUE INDEX `documents_organization_id_original_sha256_hash_unique` ON `documents` (`organization_id`,`original_sha256_hash`);
\ No newline at end of file
diff --git a/apps/papra-server/migrations/meta/0006_snapshot.json b/apps/papra-server/migrations/meta/0006_snapshot.json
new file mode 100644
index 00000000..d00316a7
--- /dev/null
+++ b/apps/papra-server/migrations/meta/0006_snapshot.json
@@ -0,0 +1,957 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "b63753f1-78a4-4d56-bc18-52634b7f2401",
+ "prevId": "64c5c91e-42f1-45e8-bda0-934852ef45c9",
+ "tables": {
+ "documents": {
+ "name": "documents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_by": {
+ "name": "deleted_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_size": {
+ "name": "original_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "original_storage_key": {
+ "name": "original_storage_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_sha256_hash": {
+ "name": "original_sha256_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ }
+ },
+ "indexes": {
+ "documents_organization_id_is_deleted_created_at_index": {
+ "name": "documents_organization_id_is_deleted_created_at_index",
+ "columns": [
+ "organization_id",
+ "is_deleted",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "documents_organization_id_is_deleted_index": {
+ "name": "documents_organization_id_is_deleted_index",
+ "columns": [
+ "organization_id",
+ "is_deleted"
+ ],
+ "isUnique": false
+ },
+ "documents_organization_id_original_sha256_hash_unique": {
+ "name": "documents_organization_id_original_sha256_hash_unique",
+ "columns": [
+ "organization_id",
+ "original_sha256_hash"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "documents_organization_id_organizations_id_fk": {
+ "name": "documents_organization_id_organizations_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "documents_created_by_users_id_fk": {
+ "name": "documents_created_by_users_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ },
+ "documents_deleted_by_users_id_fk": {
+ "name": "documents_deleted_by_users_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "deleted_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organization_users": {
+ "name": "organization_users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "organization_users_user_id_users_id_fk": {
+ "name": "organization_users_user_id_users_id_fk",
+ "tableFrom": "organization_users",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "organization_users_organization_id_organizations_id_fk": {
+ "name": "organization_users_organization_id_organizations_id_fk",
+ "tableFrom": "organization_users",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organizations": {
+ "name": "organizations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_roles": {
+ "name": "user_roles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_roles_role_index": {
+ "name": "user_roles_role_index",
+ "columns": [
+ "role"
+ ],
+ "isUnique": false
+ },
+ "user_roles_user_id_role_unique_index": {
+ "name": "user_roles_user_id_role_unique_index",
+ "columns": [
+ "user_id",
+ "role"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "user_roles_user_id_users_id_fk": {
+ "name": "user_roles_user_id_users_id_fk",
+ "tableFrom": "user_roles",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "documents_tags": {
+ "name": "documents_tags",
+ "columns": {
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "documents_tags_document_id_documents_id_fk": {
+ "name": "documents_tags_document_id_documents_id_fk",
+ "tableFrom": "documents_tags",
+ "tableTo": "documents",
+ "columnsFrom": [
+ "document_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "documents_tags_tag_id_tags_id_fk": {
+ "name": "documents_tags_tag_id_tags_id_fk",
+ "tableFrom": "documents_tags",
+ "tableTo": "tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {
+ "documents_tags_pkey": {
+ "columns": [
+ "document_id",
+ "tag_id"
+ ],
+ "name": "documents_tags_pkey"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tags": {
+ "name": "tags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "tags_organization_id_name_unique": {
+ "name": "tags_organization_id_name_unique",
+ "columns": [
+ "organization_id",
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "tags_organization_id_organizations_id_fk": {
+ "name": "tags_organization_id_organizations_id_fk",
+ "tableFrom": "tags",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ },
+ "users_email_index": {
+ "name": "users_email_index",
+ "columns": [
+ "email"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "auth_accounts": {
+ "name": "auth_accounts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "auth_accounts_user_id_users_id_fk": {
+ "name": "auth_accounts_user_id_users_id_fk",
+ "tableFrom": "auth_accounts",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "auth_sessions": {
+ "name": "auth_sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "auth_sessions_token_index": {
+ "name": "auth_sessions_token_index",
+ "columns": [
+ "token"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "auth_sessions_user_id_users_id_fk": {
+ "name": "auth_sessions_user_id_users_id_fk",
+ "tableFrom": "auth_sessions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "auth_verifications": {
+ "name": "auth_verifications",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "auth_verifications_identifier_index": {
+ "name": "auth_verifications_identifier_index",
+ "columns": [
+ "identifier"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "intake_emails": {
+ "name": "intake_emails",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email_address": {
+ "name": "email_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "allowed_origins": {
+ "name": "allowed_origins",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "is_enabled": {
+ "name": "is_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ }
+ },
+ "indexes": {
+ "intake_emails_email_address_unique": {
+ "name": "intake_emails_email_address_unique",
+ "columns": [
+ "email_address"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "intake_emails_organization_id_organizations_id_fk": {
+ "name": "intake_emails_organization_id_organizations_id_fk",
+ "tableFrom": "intake_emails",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
diff --git a/apps/papra-server/migrations/meta/_journal.json b/apps/papra-server/migrations/meta/_journal.json
index 15495f34..7559f88b 100644
--- a/apps/papra-server/migrations/meta/_journal.json
+++ b/apps/papra-server/migrations/meta/_journal.json
@@ -43,6 +43,13 @@
"when": 1740570765157,
"tag": "0005_intake-emails-addresses",
"breakpoints": true
+ },
+ {
+ "idx": 6,
+ "version": "6",
+ "when": 1740775396113,
+ "tag": "0006_documents-hash",
+ "breakpoints": true
}
]
}
diff --git a/apps/papra-server/src/modules/documents/documents.errors.ts b/apps/papra-server/src/modules/documents/documents.errors.ts
index 088246d7..3b52b9cb 100644
--- a/apps/papra-server/src/modules/documents/documents.errors.ts
+++ b/apps/papra-server/src/modules/documents/documents.errors.ts
@@ -11,3 +11,9 @@ export const createDocumentIsNotDeletedError = createErrorFactory({
code: 'document.not_deleted',
statusCode: 400,
});
+
+export const createDocumentAlreadyExistsError = createErrorFactory({
+ message: 'Document already exists.',
+ code: 'document.already_exists',
+ statusCode: 409,
+});
diff --git a/apps/papra-server/src/modules/documents/documents.repository.test.ts b/apps/papra-server/src/modules/documents/documents.repository.test.ts
index 263a8e79..f4af44db 100644
--- a/apps/papra-server/src/modules/documents/documents.repository.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.repository.test.ts
@@ -1,6 +1,7 @@
import { map } from 'lodash-es';
import { describe, expect, test } from 'vitest';
import { createInMemoryDatabase } from '../app/database/database.test-utils';
+import { createDocumentAlreadyExistsError } from './documents.errors';
import { createDocumentsRepository } from './documents.repository';
describe('documents repository', () => {
@@ -21,6 +22,7 @@ describe('documents repository', () => {
name: 'Document 1',
originalName: 'document-1.pdf',
originalStorageKey: 'document-1.pdf',
+ originalSha256Hash: 'hash1',
});
expect(document).to.include({
@@ -30,6 +32,7 @@ describe('documents repository', () => {
name: 'Document 1',
originalName: 'document-1.pdf',
originalStorageKey: 'document-1.pdf',
+ originalSha256Hash: 'hash1',
isDeleted: false,
});
@@ -66,6 +69,41 @@ describe('documents repository', () => {
});
});
+ describe('saveOrganizationDocument', () => {
+ test('a document is unique by organization, an error is raised if a document with the same hash already exists', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'user-1', email: '[email protected]' }],
+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ });
+
+ const documentsRepository = createDocumentsRepository({ db });
+
+ await documentsRepository.saveOrganizationDocument({
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ name: 'Document 1',
+ originalName: 'document-1.pdf',
+ content: 'lorem ipsum',
+ originalStorageKey: '',
+ mimeType: 'application/pdf',
+ originalSha256Hash: 'hash1',
+ });
+
+ await expect(
+ documentsRepository.saveOrganizationDocument({
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ name: 'Document 1',
+ originalName: 'document-1.pdf',
+ content: 'lorem ipsum',
+ originalStorageKey: '',
+ mimeType: 'application/pdf',
+ originalSha256Hash: 'hash1',
+ }),
+ ).rejects.toThrow(createDocumentAlreadyExistsError());
+ });
+ });
+
describe('searchOrganizationDocuments', () => {
test('provides full text search on document name, original name, and content', async () => {
const { db } = await createInMemoryDatabase({
@@ -73,9 +111,9 @@ describe('documents repository', () => {
organizations: [{ id: 'organization-1', name: 'Organization 1' }],
organizationUsers: [{ organizationId: 'organization-1', userId: 'user-1' }],
documents: [
- { id: 'doc-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf' },
- { id: 'doc-2', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', originalStorageKey: '', mimeType: 'application/pdf' },
- { id: 'doc-3', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf' },
+ { id: 'doc-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1' },
+ { id: 'doc-2', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2' },
+ { id: 'doc-3', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3' },
],
});
@@ -112,10 +150,10 @@ describe('documents repository', () => {
{ organizationId: 'organization-2', userId: 'user-2' },
],
documents: [
- { id: 'doc-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 200 },
- { id: 'doc-2', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 10 },
- { id: 'doc-3', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 5 },
- { id: 'doc-4', organizationId: 'organization-2', createdBy: 'user-2', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 100 },
+ { id: 'doc-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 200, originalSha256Hash: 'hash1' },
+ { id: 'doc-2', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 10, originalSha256Hash: 'hash2' },
+ { id: 'doc-3', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 5, originalSha256Hash: 'hash3' },
+ { id: 'doc-4', organizationId: 'organization-2', createdBy: 'user-2', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 100, originalSha256Hash: 'hash4' },
],
});
diff --git a/apps/papra-server/src/modules/documents/documents.repository.ts b/apps/papra-server/src/modules/documents/documents.repository.ts
index ded72bc5..663eada5 100644
--- a/apps/papra-server/src/modules/documents/documents.repository.ts
+++ b/apps/papra-server/src/modules/documents/documents.repository.ts
@@ -1,11 +1,13 @@
import type { Database } from '../app/database/database.types';
import type { DbInsertableDocument } from './documents.types';
-import { injectArguments } from '@corentinth/chisels';
+import { injectArguments, safely } from '@corentinth/chisels';
import { subDays } from 'date-fns';
import { and, count, desc, eq, getTableColumns, lt, sql, sum } from 'drizzle-orm';
import { omit } from 'lodash-es';
+import { isUniqueConstraintError } from '../shared/db/constraints.models';
import { withPagination } from '../shared/db/pagination';
import { documentsTagsTable, tagsTable } from '../tags/tags.table';
+import { createDocumentAlreadyExistsError } from './documents.errors';
import { documentsTable } from './documents.table';
export type DocumentsRepository = ReturnType<typeof createDocumentsRepository>;
@@ -25,13 +27,34 @@ export function createDocumentsRepository({ db }: { db: Database }) {
hardDeleteDocument,
getExpiredDeletedDocuments,
getOrganizationStats,
+ getOrganizationDocumentBySha256Hash,
},
{ db },
);
}
+async function getOrganizationDocumentBySha256Hash({ sha256Hash, organizationId, db }: { sha256Hash: string; organizationId: string; db: Database }) {
+ const [document] = await db
+ .select()
+ .from(documentsTable)
+ .where(
+ and(
+ eq(documentsTable.originalSha256Hash, sha256Hash),
+ eq(documentsTable.organizationId, organizationId),
+ ),
+ );
+
+ return { document };
+}
+
async function saveOrganizationDocument({ db, ...documentToInsert }: { db: Database } & DbInsertableDocument) {
- const [document] = await db.insert(documentsTable).values(documentToInsert).returning();
+ const [documents, error] = await safely(db.insert(documentsTable).values(documentToInsert).returning());
+
+ if (isUniqueConstraintError({ error })) {
+ throw createDocumentAlreadyExistsError();
+ }
+
+ const [document] = documents ?? [];
return { document };
}
diff --git a/apps/papra-server/src/modules/documents/documents.services.test.ts b/apps/papra-server/src/modules/documents/documents.services.test.ts
new file mode 100644
index 00000000..d654036d
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/documents.services.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, test } from 'vitest';
+import { getFileSha256Hash } from './documents.services';
+
+describe('documents services', () => {
+ describe('getFileSha256Hash', () => {
+ test('computes the sha256 hash in hex format of a file content', async () => {
+ const file = new File(['lorem ipsum'], 'document.pdf', { type: 'application/pdf' });
+
+ const { hash } = await getFileSha256Hash({ file });
+
+ expect(hash).to.equal('5e2bf57d3f40c4b6df69daf1936cb766f832374b4fc0259a7cbff06e2f70f269');
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/documents.services.ts b/apps/papra-server/src/modules/documents/documents.services.ts
new file mode 100644
index 00000000..2da1835e
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/documents.services.ts
@@ -0,0 +1,11 @@
+export async function getFileSha256Hash({ file }: { file: File }) {
+ const arrayBuffer = await file.arrayBuffer();
+ const hash = await crypto.subtle.digest('SHA-256', arrayBuffer);
+ const hashHex = Array.from(new Uint8Array(hash))
+ .map(byte => byte.toString(16).padStart(2, '0'))
+ .join('');
+
+ return {
+ hash: hashHex,
+ };
+}
diff --git a/apps/papra-server/src/modules/documents/documents.table.test.ts b/apps/papra-server/src/modules/documents/documents.table.test.ts
index b3caa9bb..a45905eb 100644
--- a/apps/papra-server/src/modules/documents/documents.table.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.table.test.ts
@@ -23,6 +23,7 @@ describe('documents table', () => {
originalName: 'document-1.pdf',
originalStorageKey: 'document-1.pdf',
content: 'lorem ipsum',
+ originalSha256Hash: 'hash1',
},
{
id: 'document-2',
@@ -33,6 +34,7 @@ describe('documents table', () => {
originalName: 'photo-1.jpg',
originalStorageKey: 'photo-1.jpg',
content: 'dolor sit amet',
+ originalSha256Hash: 'hash2',
},
]);
@@ -82,6 +84,7 @@ describe('documents table', () => {
originalName: 'document-1.pdf',
originalStorageKey: 'document-1.pdf',
content: 'lorem ipsum',
+ originalSha256Hash: 'hash1',
},
{
id: 'document-2',
@@ -92,6 +95,7 @@ describe('documents table', () => {
originalName: 'photo-1.jpg',
originalStorageKey: 'photo-1.jpg',
content: 'dolor sit amet',
+ originalSha256Hash: 'hash2',
},
]);
@@ -143,6 +147,7 @@ describe('documents table', () => {
originalName: 'document-1.pdf',
originalStorageKey: 'document-1.pdf',
content: 'lorem ipsum',
+ originalSha256Hash: 'hash1',
},
{
id: 'document-2',
@@ -153,6 +158,7 @@ describe('documents table', () => {
originalName: 'photo-1.jpg',
originalStorageKey: 'photo-1.jpg',
content: 'dolor sit amet',
+ originalSha256Hash: 'hash2',
},
]);
diff --git a/apps/papra-server/src/modules/documents/documents.table.ts b/apps/papra-server/src/modules/documents/documents.table.ts
index 15f73919..49ac43f3 100644
--- a/apps/papra-server/src/modules/documents/documents.table.ts
+++ b/apps/papra-server/src/modules/documents/documents.table.ts
@@ -1,4 +1,4 @@
-import { index, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
+import { index, integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core';
import { organizationsTable } from '../organizations/organizations.table';
import { createPrimaryKeyField, createSoftDeleteColumns, createTimestampColumns } from '../shared/db/columns.helpers';
import { usersTable } from '../users/users.table';
@@ -16,6 +16,7 @@ export const documentsTable = sqliteTable('documents', {
originalName: text('original_name').notNull(),
originalSize: integer('original_size').notNull().default(0),
originalStorageKey: text('original_storage_key').notNull(),
+ originalSha256Hash: text('original_sha256_hash').notNull(),
name: text('name').notNull(),
mimeType: text('mime_type').notNull(),
@@ -25,4 +26,8 @@ export const documentsTable = sqliteTable('documents', {
index('documents_organization_id_is_deleted_created_at_index').on(table.organizationId, table.isDeleted, table.createdAt),
// To count/stats documents by organization
index('documents_organization_id_is_deleted_index').on(table.organizationId, table.isDeleted),
+ // Unique document by organization and hash
+ uniqueIndex('documents_organization_id_original_sha256_hash_unique').on(table.organizationId, table.originalSha256Hash),
+ // To select document by hash
+ index('documents_original_sha256_hash_index').on(table.originalSha256Hash),
]);
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.test.ts b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
index 72af13d5..10adc53d 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
@@ -2,6 +2,7 @@ import type { Config } from '../config/config.types';
import { describe, expect, test } from 'vitest';
import { createInMemoryDatabase } from '../app/database/database.test-utils';
import { collectReadableStreamToString } from '../shared/streams/readable-stream';
+import { createDocumentAlreadyExistsError } from './documents.errors';
import { createDocumentsRepository } from './documents.repository';
import { documentsTable } from './documents.table';
import { createDocument } from './documents.usecases';
@@ -57,5 +58,105 @@ describe('documents usecases', () => {
expect(documentRecords).to.eql([document]);
});
+
+ test('in the same organization, we should be able to have two documents with the same content, an error is raised if the document already exists', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'user-1', email: '[email protected]' }],
+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizationUsers: [{ organizationId: 'organization-1', userId: 'user-1' }],
+ });
+
+ const documentsRepository = createDocumentsRepository({ db });
+ const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });
+ let documentIdIndex = 1;
+ const generateDocumentId = () => `doc_${documentIdIndex++}`;
+
+ const file = new File(['content'], 'file.txt', { type: 'text/plain' });
+ const userId = 'user-1';
+ const organizationId = 'organization-1';
+
+ const { document: document1 } = await createDocument({
+ file,
+ userId,
+ organizationId,
+ documentsRepository,
+ documentsStorageService,
+ generateDocumentId,
+ });
+
+ expect(document1).to.include({
+ id: 'doc_1',
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ name: 'file.txt',
+ originalName: 'file.txt',
+ });
+
+ const { fileStream: fileStream1 } = await documentsStorageService.getFileStream({ storageKey: 'organization-1/originals/doc_1.txt' });
+ const content1 = await collectReadableStreamToString({ stream: fileStream1 });
+
+ expect(content1).to.eql('content');
+
+ await expect(
+ createDocument({
+ file,
+ userId,
+ organizationId,
+ documentsRepository,
+ documentsStorageService,
+ generateDocumentId,
+ }),
+ ).rejects.toThrow(
+ createDocumentAlreadyExistsError(),
+ );
+
+ const documentRecords = await db.select().from(documentsTable);
+
+ expect(documentRecords.map(({ id }) => id)).to.eql(['doc_1']);
+
+ await expect(
+ documentsStorageService.getFileStream({ storageKey: 'organization-1/originals/doc_2.txt' }),
+ ).rejects.toThrow('File not found');
+ });
+
+ test('when there is an issue when inserting the document in the db, the file should not be saved in the storage', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'user-1', email: '[email protected]' }],
+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizationUsers: [{ organizationId: 'organization-1', userId: 'user-1' }],
+ });
+
+ const documentsRepository = createDocumentsRepository({ db });
+ const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });
+ const generateDocumentId = () => 'doc_1';
+
+ const file = new File(['content'], 'file.txt', { type: 'text/plain' });
+ const userId = 'user-1';
+ const organizationId = 'organization-1';
+
+ expect(
+ createDocument({
+ file,
+ userId,
+ organizationId,
+ documentsRepository: {
+ ...documentsRepository,
+ saveOrganizationDocument: async () => {
+ throw new Error('Macron, explosion!');
+ },
+ },
+ documentsStorageService,
+ generateDocumentId,
+ }),
+ ).rejects.toThrow(new Error('Macron, explosion!'));
+
+ const documentRecords = await db.select().from(documentsTable);
+
+ expect(documentRecords).to.eql([]);
+
+ await expect(
+ documentsStorageService.getFileStream({ storageKey: 'organization-1/originals/doc_1.txt' }),
+ ).rejects.toThrow('File not found');
+ });
});
});
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.ts
index 92d7c460..a76d6691 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts
@@ -5,8 +5,9 @@ import type { DocumentStorageService } from './storage/documents.storage.service
import { safely } from '@corentinth/chisels';
import { extractTextFromFile } from '@papra/lecture';
import { createLogger } from '../shared/logger/logger';
-import { createDocumentNotFoundError } from './documents.errors';
+import { createDocumentAlreadyExistsError, createDocumentNotFoundError } from './documents.errors';
import { buildOriginalDocumentKey, generateDocumentId as generateDocumentIdImpl } from './documents.models';
+import { getFileSha256Hash } from './documents.services';
const logger = createLogger({ namespace: 'documents:usecases' });
@@ -43,6 +44,15 @@ export async function createDocument({
type: mimeType,
} = file;
+ const { hash } = await getFileSha256Hash({ file });
+
+ // Early check to avoid saving the file and then realizing it already exists with the db constraint
+ const { document: existingDocument } = await documentsRepository.getOrganizationDocumentBySha256Hash({ sha256Hash: hash, organizationId });
+
+ if (existingDocument) {
+ throw createDocumentAlreadyExistsError();
+ }
+
const documentId = generateDocumentId();
const { originalDocumentStorageKey } = buildOriginalDocumentKey({
@@ -58,7 +68,7 @@ export async function createDocument({
const { text } = await extractDocumentText({ file });
- const { document } = await documentsRepository.saveOrganizationDocument({
+ const [result, error] = await safely(documentsRepository.saveOrganizationDocument({
id: documentId,
name: fileName,
organizationId,
@@ -68,7 +78,18 @@ export async function createDocument({
originalStorageKey: storageKey,
mimeType,
content: text,
- });
+ originalSha256Hash: hash,
+ }),
+ );
+
+ if (error) {
+ // If the document is not saved, delete the file from the storage
+ await documentsStorageService.deleteFile({ storageKey: originalDocumentStorageKey });
+
+ throw error;
+ }
+
+ const { document } = result;
return { document };
}
diff --git a/apps/papra-server/src/modules/tags/tags.repository.test.ts b/apps/papra-server/src/modules/tags/tags.repository.test.ts
index 0bc0fc6e..f1d16fc1 100644
--- a/apps/papra-server/src/modules/tags/tags.repository.test.ts
+++ b/apps/papra-server/src/modules/tags/tags.repository.test.ts
@@ -72,7 +72,7 @@ describe('tags repository', () => {
organizations: [{ id: 'organization-1', name: 'Organization 1' }],
organizationUsers: [{ organizationId: 'organization-1', userId: 'user-1' }],
documents: [
- { id: 'document-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf' },
+ { id: 'document-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash' },
],
tags: [{ id: 'tag-1', organizationId: 'organization-1', name: 'Tag 1', color: '#aa0000' }],
});