Compare commits
156
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1901a2e56 | ||
|
|
09b0fbefcd | ||
|
|
3497ccd7bd | ||
|
|
5e27dc88f8 | ||
|
|
b276eb5b68 | ||
|
|
aec1f97ff8 | ||
|
|
fbe2dc2958 | ||
|
|
aaae81c68e | ||
|
|
3aa77819f2 | ||
|
|
28dab07870 | ||
|
|
ed6199de61 | ||
|
|
4d59ebfb2a | ||
|
|
ea4f37cccf | ||
|
|
c25131ae9b | ||
|
|
25df9410cd | ||
|
|
494f92421f | ||
|
|
eef5dce849 | ||
|
|
ddefe81082 | ||
|
|
be037b727f | ||
|
|
7a56f0504e | ||
|
|
f7c9855489 | ||
|
|
36a358f907 | ||
|
|
0bcb1810d6 | ||
|
|
aee535214d | ||
|
|
6d3154a7ae | ||
|
|
658ce2dab9 | ||
|
|
15df5cf168 | ||
|
|
23d7f38100 | ||
|
|
472fc2939e | ||
|
|
a21047e8b0 | ||
|
|
8ee03fa1c6 | ||
|
|
a22913e1e4 | ||
|
|
b3c0c69a7c | ||
|
|
2289080f9c | ||
|
|
a5ec62fa08 | ||
|
|
e7f7b7e201 | ||
|
|
74e8388bce | ||
|
|
e7c6db082c | ||
|
|
05a7161412 | ||
|
|
39267e795c | ||
|
|
6acce968a5 | ||
|
|
0722ecc6c4 | ||
|
|
3597a8b7bd | ||
|
|
c260394b95 | ||
|
|
93fcfb280a | ||
|
|
69cb8e7aec | ||
|
|
8e8e06628e | ||
|
|
5d3710260f | ||
|
|
ad8789d82a | ||
|
|
749966a197 | ||
|
|
d9e429aa3a | ||
|
|
ad0b6cf2d6 | ||
|
|
b63f2c16a2 | ||
|
|
edcc788d1a | ||
|
|
5b47ab5bbf | ||
|
|
fdba336c05 | ||
|
|
5db6b85fb9 | ||
|
|
70d941a400 | ||
|
|
13e88943b7 | ||
|
|
339e5cfb65 | ||
|
|
10944d9d57 | ||
|
|
0c9f460fb6 | ||
|
|
fa6e01b46e | ||
|
|
23f85d7267 | ||
|
|
f6290c0238 | ||
|
|
991be9ffa2 | ||
|
|
07bf79f3ee | ||
|
|
3a0acd0a21 | ||
|
|
fff637286f | ||
|
|
8f94c8f57e | ||
|
|
708a296f8d | ||
|
|
b486d1270e | ||
|
|
80faf0bc1e | ||
|
|
6555a9554a | ||
|
|
fdee719c89 | ||
|
|
1be48c276b | ||
|
|
2b6b7a8e1d | ||
|
|
fd9fb9b972 | ||
|
|
d8d6197008 | ||
|
|
1edd133e09 | ||
|
|
8685bf2a7c | ||
|
|
36475069de | ||
|
|
3aa8572c9e | ||
|
|
2e2d8477b9 | ||
|
|
90880eddf9 | ||
|
|
31fd6886dc | ||
|
|
3fdbf425b4 | ||
|
|
50e60d4972 | ||
|
|
a22330ebf4 | ||
|
|
172f622c5f | ||
|
|
cfd00b2c71 | ||
|
|
d82b958d9f | ||
|
|
c94ee388fc | ||
|
|
aa5333dcd9 | ||
|
|
a8265efff4 | ||
|
|
b9b425aba0 | ||
|
|
51caad636c | ||
|
|
023fd43b72 | ||
|
|
a8a0808274 | ||
|
|
3d2607f72a | ||
|
|
f9542a9257 | ||
|
|
963787316a | ||
|
|
a12e457577 | ||
|
|
bac61c7e9e | ||
|
|
fc2f34ee15 | ||
|
|
d9798badae | ||
|
|
efc0c1aab3 | ||
|
|
10672403c9 | ||
|
|
32fed96aa7 | ||
|
|
a70472b172 | ||
|
|
3b87ca0c3c | ||
|
|
0e1da982b6 | ||
|
|
6172351eed | ||
|
|
1174b6a4da | ||
|
|
a970c44d03 | ||
|
|
b574cef54a | ||
|
|
21a2433dd8 | ||
|
|
07cc250176 | ||
|
|
dc71b3007b | ||
|
|
1598057ed0 | ||
|
|
312fc2d615 | ||
|
|
72375d89d1 | ||
|
|
a990ecc02a | ||
|
|
da6ecc6619 | ||
|
|
dac176f0c6 | ||
|
|
41e5a7fbd6 | ||
|
|
b81ed9ec2e | ||
|
|
9b5c50db07 | ||
|
|
81c5d8ff46 | ||
|
|
a67f5199d3 | ||
|
|
3755bfde34 | ||
|
|
2834eec3be | ||
|
|
d89e1b5b1e | ||
|
|
19d7111cab | ||
|
|
ca9d7ef465 | ||
|
|
fad4f84c9c | ||
|
|
35863ac610 | ||
|
|
c17dd25069 | ||
|
|
5d7fb638af | ||
|
|
2fb4710dd7 | ||
|
|
85a74c1d46 | ||
|
|
21a93d6cac | ||
|
|
9599bca8a9 | ||
|
|
1709ca9049 | ||
|
|
18e4e03220 | ||
|
|
9901771572 | ||
|
|
514956570c | ||
|
|
423617db52 | ||
|
|
143f0c5031 | ||
|
|
368e9801a1 | ||
|
|
afc9ca5858 | ||
|
|
8815575124 | ||
|
|
fb9b01f53b | ||
|
|
93607937f6 | ||
|
|
687ab39286 | ||
|
|
83a3222cf6 |
+30
-37
@@ -31,15 +31,10 @@ jobs:
|
||||
project: ${{ steps.changes.outputs.project }}
|
||||
openapi: ${{ steps.changes.outputs.openapi }}
|
||||
steps:
|
||||
- name: Harden the runner (Audit all outbound calls)
|
||||
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- uses: actions/checkout@v4.3.0
|
||||
|
||||
- name: Check for file changes
|
||||
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
|
||||
uses: dorny/paths-filter@v3.0.2
|
||||
id: changes
|
||||
with:
|
||||
filters: .github/config/.files.yaml
|
||||
@@ -56,19 +51,19 @@ jobs:
|
||||
spring-security: [true, false]
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
|
||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
uses: actions/checkout@v4.3.0
|
||||
|
||||
- name: Set up JDK ${{ matrix.jdk-version }}
|
||||
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
uses: actions/setup-java@v4.7.1
|
||||
with:
|
||||
java-version: ${{ matrix.jdk-version }}
|
||||
distribution: "temurin"
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||
uses: gradle/actions/setup-gradle@v4.4.2
|
||||
with:
|
||||
gradle-version: 8.14
|
||||
- name: Build with Gradle and spring security ${{ matrix.spring-security }}
|
||||
@@ -94,7 +89,7 @@ jobs:
|
||||
done
|
||||
- name: Upload Test Reports
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: test-reports-jdk-${{ matrix.jdk-version }}-spring-security-${{ matrix.spring-security }}
|
||||
path: |
|
||||
@@ -111,26 +106,26 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
|
||||
uses: step-security/harden-runner@v2.13.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
uses: actions/checkout@v4.3.0
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
uses: actions/setup-java@v4.7.1
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: "temurin"
|
||||
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||
- uses: gradle/actions/setup-gradle@v4.4.2
|
||||
- name: Generate OpenAPI documentation
|
||||
run: ./gradlew :stirling-pdf:generateOpenApiDocs
|
||||
env:
|
||||
DISABLE_ADDITIONAL_FEATURES: true
|
||||
|
||||
- name: Upload OpenAPI Documentation
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: openapi-docs
|
||||
path: ./SwaggerDoc.json
|
||||
@@ -139,21 +134,19 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
|
||||
uses: step-security/harden-runner@v2.12.2
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
uses: actions/checkout@v4.2.2
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
uses: actions/setup-node@v4.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- name: Install frontend dependencies
|
||||
run: cd frontend && npm ci
|
||||
- name: Type-check frontend
|
||||
run: cd frontend && npm run prebuild && npm run typecheck:all
|
||||
- name: Lint frontend
|
||||
run: cd frontend && npm run lint
|
||||
- name: Build frontend
|
||||
@@ -161,7 +154,7 @@ jobs:
|
||||
- name: Run frontend tests
|
||||
run: cd frontend && npm run test -- --run
|
||||
- name: Upload frontend build artifacts
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: frontend-build
|
||||
path: frontend/dist/
|
||||
@@ -173,13 +166,13 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
|
||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
uses: actions/checkout@v4.3.0
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
uses: actions/setup-java@v4.7.1
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: "temurin"
|
||||
@@ -187,7 +180,7 @@ jobs:
|
||||
run: ./gradlew clean checkLicense
|
||||
- name: FAILED - check the licenses for compatibility
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: dependencies-without-allowed-license.json
|
||||
path: build/reports/dependency-license/dependencies-without-allowed-license.json
|
||||
@@ -214,15 +207,15 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
|
||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
|
||||
|
||||
- name: Set up Java 17
|
||||
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: "temurin"
|
||||
@@ -232,11 +225,11 @@ jobs:
|
||||
|
||||
- name: Install Docker Compose
|
||||
run: |
|
||||
sudo curl -SL "https://github.com/docker/compose/releases/download/v2.39.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
|
||||
sudo curl -SL "https://github.com/docker/compose/releases/download/v2.37.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
|
||||
sudo chmod +x /usr/local/bin/docker-compose
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c # v6.0.0
|
||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: 'pip' # caching pip dependencies
|
||||
@@ -263,21 +256,21 @@ jobs:
|
||||
docker-rev: ["Dockerfile", "Dockerfile.ultra-lite", "Dockerfile.fat"]
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
|
||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||
uses: gradle/actions/setup-gradle@017a9effdb900e5b5b2fddfb590a105619dca3c3 # v4.4.2
|
||||
with:
|
||||
gradle-version: 8.14
|
||||
|
||||
|
||||
@@ -115,46 +115,46 @@ Stirling-PDF currently supports 40 languages!
|
||||
|
||||
| Language | Progress |
|
||||
| -------------------------------------------- | -------------------------------------- |
|
||||
| Arabic (العربية) (ar_AR) |  |
|
||||
| Azerbaijani (Azərbaycan Dili) (az_AZ) |  |
|
||||
| Basque (Euskara) (eu_ES) |  |
|
||||
| Bulgarian (Български) (bg_BG) |  |
|
||||
| Catalan (Català) (ca_CA) |  |
|
||||
| Croatian (Hrvatski) (hr_HR) |  |
|
||||
| Czech (Česky) (cs_CZ) |  |
|
||||
| Danish (Dansk) (da_DK) |  |
|
||||
| Dutch (Nederlands) (nl_NL) |  |
|
||||
| Arabic (العربية) (ar_AR) |  |
|
||||
| Azerbaijani (Azərbaycan Dili) (az_AZ) |  |
|
||||
| Basque (Euskara) (eu_ES) |  |
|
||||
| Bulgarian (Български) (bg_BG) |  |
|
||||
| Catalan (Català) (ca_CA) |  |
|
||||
| Croatian (Hrvatski) (hr_HR) |  |
|
||||
| Czech (Česky) (cs_CZ) |  |
|
||||
| Danish (Dansk) (da_DK) |  |
|
||||
| Dutch (Nederlands) (nl_NL) |  |
|
||||
| English (English) (en_GB) |  |
|
||||
| English (US) (en_US) |  |
|
||||
| French (Français) (fr_FR) |  |
|
||||
| German (Deutsch) (de_DE) |  |
|
||||
| Greek (Ελληνικά) (el_GR) |  |
|
||||
| Hindi (हिंदी) (hi_IN) |  |
|
||||
| Hungarian (Magyar) (hu_HU) |  |
|
||||
| Indonesian (Bahasa Indonesia) (id_ID) |  |
|
||||
| Irish (Gaeilge) (ga_IE) |  |
|
||||
| Italian (Italiano) (it_IT) |  |
|
||||
| Japanese (日本語) (ja_JP) |  |
|
||||
| Korean (한국어) (ko_KR) |  |
|
||||
| Norwegian (Norsk) (no_NB) |  |
|
||||
| Persian (فارسی) (fa_IR) |  |
|
||||
| Polish (Polski) (pl_PL) |  |
|
||||
| Portuguese (Português) (pt_PT) |  |
|
||||
| Portuguese Brazilian (Português) (pt_BR) |  |
|
||||
| Romanian (Română) (ro_RO) |  |
|
||||
| Russian (Русский) (ru_RU) |  |
|
||||
| Serbian Latin alphabet (Srpski) (sr_LATN_RS) |  |
|
||||
| Simplified Chinese (简体中文) (zh_CN) |  |
|
||||
| Slovakian (Slovensky) (sk_SK) |  |
|
||||
| Slovenian (Slovenščina) (sl_SI) |  |
|
||||
| Spanish (Español) (es_ES) |  |
|
||||
| Swedish (Svenska) (sv_SE) |  |
|
||||
| Thai (ไทย) (th_TH) |  |
|
||||
| French (Français) (fr_FR) |  |
|
||||
| German (Deutsch) (de_DE) |  |
|
||||
| Greek (Ελληνικά) (el_GR) |  |
|
||||
| Hindi (हिंदी) (hi_IN) |  |
|
||||
| Hungarian (Magyar) (hu_HU) |  |
|
||||
| Indonesian (Bahasa Indonesia) (id_ID) |  |
|
||||
| Irish (Gaeilge) (ga_IE) |  |
|
||||
| Italian (Italiano) (it_IT) |  |
|
||||
| Japanese (日本語) (ja_JP) |  |
|
||||
| Korean (한국어) (ko_KR) |  |
|
||||
| Norwegian (Norsk) (no_NB) |  |
|
||||
| Persian (فارسی) (fa_IR) |  |
|
||||
| Polish (Polski) (pl_PL) |  |
|
||||
| Portuguese (Português) (pt_PT) |  |
|
||||
| Portuguese Brazilian (Português) (pt_BR) |  |
|
||||
| Romanian (Română) (ro_RO) |  |
|
||||
| Russian (Русский) (ru_RU) |  |
|
||||
| Serbian Latin alphabet (Srpski) (sr_LATN_RS) |  |
|
||||
| Simplified Chinese (简体中文) (zh_CN) |  |
|
||||
| Slovakian (Slovensky) (sk_SK) |  |
|
||||
| Slovenian (Slovenščina) (sl_SI) |  |
|
||||
| Spanish (Español) (es_ES) |  |
|
||||
| Swedish (Svenska) (sv_SE) |  |
|
||||
| Thai (ไทย) (th_TH) |  |
|
||||
| Tibetan (བོད་ཡིག་) (bo_CN) |  |
|
||||
| Traditional Chinese (繁體中文) (zh_TW) |  |
|
||||
| Turkish (Türkçe) (tr_TR) |  |
|
||||
| Ukrainian (Українська) (uk_UA) |  |
|
||||
| Vietnamese (Tiếng Việt) (vi_VN) |  |
|
||||
| Traditional Chinese (繁體中文) (zh_TW) |  |
|
||||
| Turkish (Türkçe) (tr_TR) |  |
|
||||
| Ukrainian (Українська) (uk_UA) |  |
|
||||
| Vietnamese (Tiếng Việt) (vi_VN) |  |
|
||||
| Malayalam (മലയാളം) (ml_IN) |  |
|
||||
|
||||
## Stirling PDF Enterprise
|
||||
|
||||
@@ -74,7 +74,8 @@ public class AppConfig {
|
||||
|
||||
@Bean(name = "appName")
|
||||
public String appName() {
|
||||
return "Stirling PDF";
|
||||
String homeTitle = applicationProperties.getUi().getAppName();
|
||||
return (homeTitle != null) ? homeTitle : "Stirling PDF";
|
||||
}
|
||||
|
||||
@Bean(name = "appVersion")
|
||||
@@ -92,7 +93,9 @@ public class AppConfig {
|
||||
|
||||
@Bean(name = "homeText")
|
||||
public String homeText() {
|
||||
return "null";
|
||||
return (applicationProperties.getUi().getHomeDescription() != null)
|
||||
? applicationProperties.getUi().getHomeDescription()
|
||||
: "null";
|
||||
}
|
||||
|
||||
@Bean(name = "languages")
|
||||
@@ -107,8 +110,11 @@ public class AppConfig {
|
||||
|
||||
@Bean(name = "navBarText")
|
||||
public String navBarText() {
|
||||
String navBar = applicationProperties.getUi().getAppNameNavbar();
|
||||
return (navBar != null) ? navBar : "Stirling PDF";
|
||||
String defaultNavBar =
|
||||
applicationProperties.getUi().getAppNameNavbar() != null
|
||||
? applicationProperties.getUi().getAppNameNavbar()
|
||||
: applicationProperties.getUi().getAppName();
|
||||
return (defaultNavBar != null) ? defaultNavBar : "Stirling PDF";
|
||||
}
|
||||
|
||||
@Bean(name = "enableAlphaFunctionality")
|
||||
|
||||
+12
-20
@@ -355,8 +355,6 @@ public class ApplicationProperties {
|
||||
private String tessdataDir;
|
||||
private Boolean enableAlphaFunctionality;
|
||||
private Boolean enableAnalytics;
|
||||
private Boolean enablePosthog;
|
||||
private Boolean enableScarf;
|
||||
private Datasource datasource;
|
||||
private Boolean disableSanitize;
|
||||
private int maxDPI;
|
||||
@@ -366,26 +364,10 @@ public class ApplicationProperties {
|
||||
private String fileUploadLimit;
|
||||
private TempFileManagement tempFileManagement = new TempFileManagement();
|
||||
private List<String> corsAllowedOrigins = new ArrayList<>();
|
||||
private String
|
||||
frontendUrl; // Base URL for frontend (used for invite links, etc.). If not set,
|
||||
|
||||
// falls back to backend URL.
|
||||
|
||||
public boolean isAnalyticsEnabled() {
|
||||
return this.getEnableAnalytics() != null && this.getEnableAnalytics();
|
||||
}
|
||||
|
||||
public boolean isPosthogEnabled() {
|
||||
// Treat null as enabled when analytics is enabled
|
||||
return this.isAnalyticsEnabled()
|
||||
&& (this.getEnablePosthog() == null || this.getEnablePosthog());
|
||||
}
|
||||
|
||||
public boolean isScarfEnabled() {
|
||||
// Treat null as enabled when analytics is enabled
|
||||
return this.isAnalyticsEnabled()
|
||||
&& (this.getEnableScarf() == null || this.getEnableScarf());
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
@@ -494,9 +476,21 @@ public class ApplicationProperties {
|
||||
|
||||
@Data
|
||||
public static class Ui {
|
||||
private String appName;
|
||||
private String homeDescription;
|
||||
private String appNameNavbar;
|
||||
private List<String> languages;
|
||||
|
||||
public String getAppName() {
|
||||
return appName != null && appName.trim().length() > 0 ? appName : null;
|
||||
}
|
||||
|
||||
public String getHomeDescription() {
|
||||
return homeDescription != null && homeDescription.trim().length() > 0
|
||||
? homeDescription
|
||||
: null;
|
||||
}
|
||||
|
||||
public String getAppNameNavbar() {
|
||||
return appNameNavbar != null && appNameNavbar.trim().length() > 0
|
||||
? appNameNavbar
|
||||
@@ -552,8 +546,6 @@ public class ApplicationProperties {
|
||||
@Data
|
||||
public static class Mail {
|
||||
private boolean enabled;
|
||||
private boolean enableInvites = false;
|
||||
private int inviteLinkExpiryHours = 72; // Default: 72 hours (3 days)
|
||||
private String host;
|
||||
private int port;
|
||||
private String username;
|
||||
|
||||
@@ -56,7 +56,7 @@ public class PostHogService {
|
||||
}
|
||||
|
||||
private void captureSystemInfo() {
|
||||
if (!applicationProperties.getSystem().isPosthogEnabled()) {
|
||||
if (!applicationProperties.getSystem().isAnalyticsEnabled()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -67,7 +67,7 @@ public class PostHogService {
|
||||
}
|
||||
|
||||
public void captureEvent(String eventName, Map<String, Object> properties) {
|
||||
if (!applicationProperties.getSystem().isPosthogEnabled()) {
|
||||
if (!applicationProperties.getSystem().isAnalyticsEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -325,16 +325,13 @@ public class PostHogService {
|
||||
properties,
|
||||
"system_enableAnalytics",
|
||||
applicationProperties.getSystem().isAnalyticsEnabled());
|
||||
addIfNotEmpty(
|
||||
properties,
|
||||
"system_enablePosthog",
|
||||
applicationProperties.getSystem().isPosthogEnabled());
|
||||
addIfNotEmpty(
|
||||
properties,
|
||||
"system_enableScarf",
|
||||
applicationProperties.getSystem().isScarfEnabled());
|
||||
|
||||
// Capture UI properties
|
||||
addIfNotEmpty(properties, "ui_appName", applicationProperties.getUi().getAppName());
|
||||
addIfNotEmpty(
|
||||
properties,
|
||||
"ui_homeDescription",
|
||||
applicationProperties.getUi().getHomeDescription());
|
||||
addIfNotEmpty(
|
||||
properties, "ui_appNameNavbar", applicationProperties.getUi().getAppNameNavbar());
|
||||
|
||||
|
||||
@@ -6,6 +6,4 @@ public interface UserServiceInterface {
|
||||
String getCurrentUsername();
|
||||
|
||||
long getTotalUsersCount();
|
||||
|
||||
boolean isCurrentUserAdmin();
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package stirling.software.common.util;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* Captures application command-line arguments at startup so they can be reused for restart
|
||||
* operations. This allows the application to restart with the same configuration.
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AppArgsCapture implements ApplicationRunner {
|
||||
|
||||
public static final AtomicReference<List<String>> APP_ARGS = new AtomicReference<>(List.of());
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
APP_ARGS.set(List.of(args.getSourceArgs()));
|
||||
log.debug(
|
||||
"Captured {} application arguments for restart capability",
|
||||
args.getSourceArgs().length);
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package stirling.software.common.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/** Utility class to locate JAR files at runtime for restart operations */
|
||||
@Slf4j
|
||||
public class JarPathUtil {
|
||||
|
||||
/**
|
||||
* Gets the path to the currently running JAR file
|
||||
*
|
||||
* @return Path to the current JAR, or null if not running from a JAR
|
||||
*/
|
||||
public static Path currentJar() {
|
||||
try {
|
||||
Path jar =
|
||||
Paths.get(
|
||||
JarPathUtil.class
|
||||
.getProtectionDomain()
|
||||
.getCodeSource()
|
||||
.getLocation()
|
||||
.toURI())
|
||||
.toAbsolutePath();
|
||||
|
||||
// Check if we're actually running from a JAR (not from IDE/classes directory)
|
||||
if (jar.toString().endsWith(".jar")) {
|
||||
log.debug("Current JAR located at: {}", jar);
|
||||
return jar;
|
||||
} else {
|
||||
log.warn("Not running from JAR, current location: {}", jar);
|
||||
return null;
|
||||
}
|
||||
} catch (URISyntaxException e) {
|
||||
log.error("Failed to determine current JAR location", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the path to the restart-helper.jar file Expected to be in the same directory as the main
|
||||
* JAR
|
||||
*
|
||||
* @return Path to restart-helper.jar, or null if not found
|
||||
*/
|
||||
public static Path restartHelperJar() {
|
||||
Path appJar = currentJar();
|
||||
if (appJar == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Path helperJar = appJar.getParent().resolve("restart-helper.jar");
|
||||
|
||||
if (Files.isRegularFile(helperJar)) {
|
||||
log.debug("Restart helper JAR located at: {}", helperJar);
|
||||
return helperJar;
|
||||
} else {
|
||||
log.warn("Restart helper JAR not found at: {}", helperJar);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the java binary path for the current JVM
|
||||
*
|
||||
* @return Path to java executable
|
||||
*/
|
||||
public static String javaExecutable() {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||
|
||||
// On Windows, add .exe extension
|
||||
if (System.getProperty("os.name").toLowerCase().contains("win")) {
|
||||
javaBin += ".exe";
|
||||
}
|
||||
|
||||
return javaBin;
|
||||
}
|
||||
}
|
||||
+8
@@ -112,11 +112,19 @@ class ApplicationPropertiesLogicTest {
|
||||
@Test
|
||||
void ui_getters_return_null_for_blank() {
|
||||
ApplicationProperties.Ui ui = new ApplicationProperties.Ui();
|
||||
ui.setAppName(" ");
|
||||
ui.setHomeDescription("");
|
||||
ui.setAppNameNavbar(null);
|
||||
|
||||
assertNull(ui.getAppName());
|
||||
assertNull(ui.getHomeDescription());
|
||||
assertNull(ui.getAppNameNavbar());
|
||||
|
||||
ui.setAppName("Stirling-PDF");
|
||||
ui.setHomeDescription("Home");
|
||||
ui.setAppNameNavbar("Nav");
|
||||
assertEquals("Stirling-PDF", ui.getAppName());
|
||||
assertEquals("Home", ui.getHomeDescription());
|
||||
assertEquals("Nav", ui.getAppNameNavbar());
|
||||
}
|
||||
|
||||
|
||||
+1
-392
@@ -1,15 +1,12 @@
|
||||
package stirling.software.SPDF.controller.api;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Hidden;
|
||||
|
||||
@@ -32,7 +29,7 @@ public class SettingsController {
|
||||
|
||||
@AutoJobPostMapping("/update-enable-analytics")
|
||||
@Hidden
|
||||
public ResponseEntity<String> updateApiKey(@RequestParam Boolean enabled) throws IOException {
|
||||
public ResponseEntity<String> updateApiKey(@RequestBody Boolean enabled) throws IOException {
|
||||
if (applicationProperties.getSystem().getEnableAnalytics() != null) {
|
||||
return ResponseEntity.status(HttpStatus.ALREADY_REPORTED)
|
||||
.body(
|
||||
@@ -49,392 +46,4 @@ public class SettingsController {
|
||||
public ResponseEntity<Map<String, Boolean>> getDisabledEndpoints() {
|
||||
return ResponseEntity.ok(endpointConfiguration.getEndpointStatuses());
|
||||
}
|
||||
|
||||
// ========== GENERAL SETTINGS ==========
|
||||
|
||||
@GetMapping("/admin/settings/general")
|
||||
@Hidden
|
||||
public ResponseEntity<Map<String, Object>> getGeneralSettings() {
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
settings.put("ui", applicationProperties.getUi());
|
||||
settings.put(
|
||||
"system",
|
||||
Map.of(
|
||||
"defaultLocale", applicationProperties.getSystem().getDefaultLocale(),
|
||||
"showUpdate", applicationProperties.getSystem().isShowUpdate(),
|
||||
"showUpdateOnlyAdmin",
|
||||
applicationProperties.getSystem().getShowUpdateOnlyAdmin(),
|
||||
"customHTMLFiles", applicationProperties.getSystem().isCustomHTMLFiles(),
|
||||
"fileUploadLimit", applicationProperties.getSystem().getFileUploadLimit()));
|
||||
return ResponseEntity.ok(settings);
|
||||
}
|
||||
|
||||
@PostMapping("/admin/settings/general")
|
||||
@Hidden
|
||||
public ResponseEntity<String> updateGeneralSettings(@RequestBody Map<String, Object> settings)
|
||||
throws IOException {
|
||||
// Update UI settings
|
||||
if (settings.containsKey("ui")) {
|
||||
Map<String, String> ui = (Map<String, String>) settings.get("ui");
|
||||
if (ui.containsKey("appNameNavbar")) {
|
||||
GeneralUtils.saveKeyToSettings("ui.appNameNavbar", ui.get("appNameNavbar"));
|
||||
applicationProperties.getUi().setAppNameNavbar(ui.get("appNameNavbar"));
|
||||
}
|
||||
}
|
||||
|
||||
// Update System settings
|
||||
if (settings.containsKey("system")) {
|
||||
Map<String, Object> system = (Map<String, Object>) settings.get("system");
|
||||
if (system.containsKey("defaultLocale")) {
|
||||
GeneralUtils.saveKeyToSettings("system.defaultLocale", system.get("defaultLocale"));
|
||||
applicationProperties
|
||||
.getSystem()
|
||||
.setDefaultLocale((String) system.get("defaultLocale"));
|
||||
}
|
||||
if (system.containsKey("showUpdate")) {
|
||||
GeneralUtils.saveKeyToSettings("system.showUpdate", system.get("showUpdate"));
|
||||
applicationProperties.getSystem().setShowUpdate((Boolean) system.get("showUpdate"));
|
||||
}
|
||||
if (system.containsKey("showUpdateOnlyAdmin")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"system.showUpdateOnlyAdmin", system.get("showUpdateOnlyAdmin"));
|
||||
applicationProperties
|
||||
.getSystem()
|
||||
.setShowUpdateOnlyAdmin((Boolean) system.get("showUpdateOnlyAdmin"));
|
||||
}
|
||||
if (system.containsKey("fileUploadLimit")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"system.fileUploadLimit", system.get("fileUploadLimit"));
|
||||
applicationProperties
|
||||
.getSystem()
|
||||
.setFileUploadLimit((String) system.get("fileUploadLimit"));
|
||||
}
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(
|
||||
"General settings updated. Restart required for changes to take effect.");
|
||||
}
|
||||
|
||||
// ========== SECURITY SETTINGS ==========
|
||||
|
||||
@GetMapping("/admin/settings/security")
|
||||
@Hidden
|
||||
public ResponseEntity<Map<String, Object>> getSecuritySettings() {
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
ApplicationProperties.Security security = applicationProperties.getSecurity();
|
||||
|
||||
settings.put("enableLogin", security.getEnableLogin());
|
||||
settings.put("csrfDisabled", security.getCsrfDisabled());
|
||||
settings.put("loginMethod", security.getLoginMethod());
|
||||
settings.put("loginAttemptCount", security.getLoginAttemptCount());
|
||||
settings.put("loginResetTimeMinutes", security.getLoginResetTimeMinutes());
|
||||
settings.put(
|
||||
"initialLogin",
|
||||
Map.of(
|
||||
"username",
|
||||
security.getInitialLogin().getUsername() != null
|
||||
? security.getInitialLogin().getUsername()
|
||||
: ""));
|
||||
|
||||
// JWT settings
|
||||
ApplicationProperties.Security.Jwt jwt = security.getJwt();
|
||||
settings.put(
|
||||
"jwt",
|
||||
Map.of(
|
||||
"enableKeystore", jwt.isEnableKeystore(),
|
||||
"enableKeyRotation", jwt.isEnableKeyRotation(),
|
||||
"enableKeyCleanup", jwt.isEnableKeyCleanup(),
|
||||
"keyRetentionDays", jwt.getKeyRetentionDays()));
|
||||
|
||||
return ResponseEntity.ok(settings);
|
||||
}
|
||||
|
||||
@PostMapping("/admin/settings/security")
|
||||
@Hidden
|
||||
public ResponseEntity<String> updateSecuritySettings(@RequestBody Map<String, Object> settings)
|
||||
throws IOException {
|
||||
if (settings.containsKey("enableLogin")) {
|
||||
GeneralUtils.saveKeyToSettings("security.enableLogin", settings.get("enableLogin"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.setEnableLogin((Boolean) settings.get("enableLogin"));
|
||||
}
|
||||
if (settings.containsKey("csrfDisabled")) {
|
||||
GeneralUtils.saveKeyToSettings("security.csrfDisabled", settings.get("csrfDisabled"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.setCsrfDisabled((Boolean) settings.get("csrfDisabled"));
|
||||
}
|
||||
if (settings.containsKey("loginMethod")) {
|
||||
GeneralUtils.saveKeyToSettings("security.loginMethod", settings.get("loginMethod"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.setLoginMethod((String) settings.get("loginMethod"));
|
||||
}
|
||||
if (settings.containsKey("loginAttemptCount")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"security.loginAttemptCount", settings.get("loginAttemptCount"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.setLoginAttemptCount((Integer) settings.get("loginAttemptCount"));
|
||||
}
|
||||
if (settings.containsKey("loginResetTimeMinutes")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"security.loginResetTimeMinutes", settings.get("loginResetTimeMinutes"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.setLoginResetTimeMinutes(
|
||||
((Number) settings.get("loginResetTimeMinutes")).longValue());
|
||||
}
|
||||
|
||||
// JWT settings
|
||||
if (settings.containsKey("jwt")) {
|
||||
Map<String, Object> jwt = (Map<String, Object>) settings.get("jwt");
|
||||
if (jwt.containsKey("keyRetentionDays")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"security.jwt.keyRetentionDays", jwt.get("keyRetentionDays"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getJwt()
|
||||
.setKeyRetentionDays((Integer) jwt.get("keyRetentionDays"));
|
||||
}
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(
|
||||
"Security settings updated. Restart required for changes to take effect.");
|
||||
}
|
||||
|
||||
// ========== CONNECTIONS SETTINGS (OAuth/SAML) ==========
|
||||
|
||||
@GetMapping("/admin/settings/connections")
|
||||
@Hidden
|
||||
public ResponseEntity<Map<String, Object>> getConnectionsSettings() {
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
ApplicationProperties.Security security = applicationProperties.getSecurity();
|
||||
|
||||
// OAuth2 settings
|
||||
ApplicationProperties.Security.OAUTH2 oauth2 = security.getOauth2();
|
||||
settings.put(
|
||||
"oauth2",
|
||||
Map.of(
|
||||
"enabled", oauth2.getEnabled(),
|
||||
"issuer", oauth2.getIssuer() != null ? oauth2.getIssuer() : "",
|
||||
"clientId", oauth2.getClientId() != null ? oauth2.getClientId() : "",
|
||||
"provider", oauth2.getProvider() != null ? oauth2.getProvider() : "",
|
||||
"autoCreateUser", oauth2.getAutoCreateUser(),
|
||||
"blockRegistration", oauth2.getBlockRegistration(),
|
||||
"useAsUsername",
|
||||
oauth2.getUseAsUsername() != null
|
||||
? oauth2.getUseAsUsername()
|
||||
: ""));
|
||||
|
||||
// SAML2 settings
|
||||
ApplicationProperties.Security.SAML2 saml2 = security.getSaml2();
|
||||
settings.put(
|
||||
"saml2",
|
||||
Map.of(
|
||||
"enabled", saml2.getEnabled(),
|
||||
"provider", saml2.getProvider() != null ? saml2.getProvider() : "",
|
||||
"autoCreateUser", saml2.getAutoCreateUser(),
|
||||
"blockRegistration", saml2.getBlockRegistration(),
|
||||
"registrationId", saml2.getRegistrationId()));
|
||||
|
||||
return ResponseEntity.ok(settings);
|
||||
}
|
||||
|
||||
@PostMapping("/admin/settings/connections")
|
||||
@Hidden
|
||||
public ResponseEntity<String> updateConnectionsSettings(
|
||||
@RequestBody Map<String, Object> settings) throws IOException {
|
||||
// OAuth2 settings
|
||||
if (settings.containsKey("oauth2")) {
|
||||
Map<String, Object> oauth2 = (Map<String, Object>) settings.get("oauth2");
|
||||
if (oauth2.containsKey("enabled")) {
|
||||
GeneralUtils.saveKeyToSettings("security.oauth2.enabled", oauth2.get("enabled"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getOauth2()
|
||||
.setEnabled((Boolean) oauth2.get("enabled"));
|
||||
}
|
||||
if (oauth2.containsKey("issuer")) {
|
||||
GeneralUtils.saveKeyToSettings("security.oauth2.issuer", oauth2.get("issuer"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getOauth2()
|
||||
.setIssuer((String) oauth2.get("issuer"));
|
||||
}
|
||||
if (oauth2.containsKey("clientId")) {
|
||||
GeneralUtils.saveKeyToSettings("security.oauth2.clientId", oauth2.get("clientId"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getOauth2()
|
||||
.setClientId((String) oauth2.get("clientId"));
|
||||
}
|
||||
if (oauth2.containsKey("clientSecret")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"security.oauth2.clientSecret", oauth2.get("clientSecret"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getOauth2()
|
||||
.setClientSecret((String) oauth2.get("clientSecret"));
|
||||
}
|
||||
if (oauth2.containsKey("provider")) {
|
||||
GeneralUtils.saveKeyToSettings("security.oauth2.provider", oauth2.get("provider"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getOauth2()
|
||||
.setProvider((String) oauth2.get("provider"));
|
||||
}
|
||||
if (oauth2.containsKey("autoCreateUser")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"security.oauth2.autoCreateUser", oauth2.get("autoCreateUser"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getOauth2()
|
||||
.setAutoCreateUser((Boolean) oauth2.get("autoCreateUser"));
|
||||
}
|
||||
if (oauth2.containsKey("blockRegistration")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"security.oauth2.blockRegistration", oauth2.get("blockRegistration"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getOauth2()
|
||||
.setBlockRegistration((Boolean) oauth2.get("blockRegistration"));
|
||||
}
|
||||
if (oauth2.containsKey("useAsUsername")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"security.oauth2.useAsUsername", oauth2.get("useAsUsername"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getOauth2()
|
||||
.setUseAsUsername((String) oauth2.get("useAsUsername"));
|
||||
}
|
||||
}
|
||||
|
||||
// SAML2 settings
|
||||
if (settings.containsKey("saml2")) {
|
||||
Map<String, Object> saml2 = (Map<String, Object>) settings.get("saml2");
|
||||
if (saml2.containsKey("enabled")) {
|
||||
GeneralUtils.saveKeyToSettings("security.saml2.enabled", saml2.get("enabled"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getSaml2()
|
||||
.setEnabled((Boolean) saml2.get("enabled"));
|
||||
}
|
||||
if (saml2.containsKey("provider")) {
|
||||
GeneralUtils.saveKeyToSettings("security.saml2.provider", saml2.get("provider"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getSaml2()
|
||||
.setProvider((String) saml2.get("provider"));
|
||||
}
|
||||
if (saml2.containsKey("autoCreateUser")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"security.saml2.autoCreateUser", saml2.get("autoCreateUser"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getSaml2()
|
||||
.setAutoCreateUser((Boolean) saml2.get("autoCreateUser"));
|
||||
}
|
||||
if (saml2.containsKey("blockRegistration")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"security.saml2.blockRegistration", saml2.get("blockRegistration"));
|
||||
applicationProperties
|
||||
.getSecurity()
|
||||
.getSaml2()
|
||||
.setBlockRegistration((Boolean) saml2.get("blockRegistration"));
|
||||
}
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(
|
||||
"Connection settings updated. Restart required for changes to take effect.");
|
||||
}
|
||||
|
||||
// ========== PRIVACY SETTINGS ==========
|
||||
|
||||
@GetMapping("/admin/settings/privacy")
|
||||
@Hidden
|
||||
public ResponseEntity<Map<String, Object>> getPrivacySettings() {
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
|
||||
settings.put("enableAnalytics", applicationProperties.getSystem().getEnableAnalytics());
|
||||
settings.put("googleVisibility", applicationProperties.getSystem().getGooglevisibility());
|
||||
settings.put("metricsEnabled", applicationProperties.getMetrics().getEnabled());
|
||||
|
||||
return ResponseEntity.ok(settings);
|
||||
}
|
||||
|
||||
@PostMapping("/admin/settings/privacy")
|
||||
@Hidden
|
||||
public ResponseEntity<String> updatePrivacySettings(@RequestBody Map<String, Object> settings)
|
||||
throws IOException {
|
||||
if (settings.containsKey("enableAnalytics")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"system.enableAnalytics", settings.get("enableAnalytics"));
|
||||
applicationProperties
|
||||
.getSystem()
|
||||
.setEnableAnalytics((Boolean) settings.get("enableAnalytics"));
|
||||
}
|
||||
if (settings.containsKey("googleVisibility")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"system.googlevisibility", settings.get("googleVisibility"));
|
||||
applicationProperties
|
||||
.getSystem()
|
||||
.setGooglevisibility((Boolean) settings.get("googleVisibility"));
|
||||
}
|
||||
if (settings.containsKey("metricsEnabled")) {
|
||||
GeneralUtils.saveKeyToSettings("metrics.enabled", settings.get("metricsEnabled"));
|
||||
applicationProperties.getMetrics().setEnabled((Boolean) settings.get("metricsEnabled"));
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(
|
||||
"Privacy settings updated. Restart required for changes to take effect.");
|
||||
}
|
||||
|
||||
// ========== ADVANCED SETTINGS ==========
|
||||
|
||||
@GetMapping("/admin/settings/advanced")
|
||||
@Hidden
|
||||
public ResponseEntity<Map<String, Object>> getAdvancedSettings() {
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
|
||||
settings.put("endpoints", applicationProperties.getEndpoints());
|
||||
settings.put(
|
||||
"enableAlphaFunctionality",
|
||||
applicationProperties.getSystem().getEnableAlphaFunctionality());
|
||||
settings.put("maxDPI", applicationProperties.getSystem().getMaxDPI());
|
||||
settings.put("enableUrlToPDF", applicationProperties.getSystem().getEnableUrlToPDF());
|
||||
settings.put("customPaths", applicationProperties.getSystem().getCustomPaths());
|
||||
settings.put(
|
||||
"tempFileManagement", applicationProperties.getSystem().getTempFileManagement());
|
||||
|
||||
return ResponseEntity.ok(settings);
|
||||
}
|
||||
|
||||
@PostMapping("/admin/settings/advanced")
|
||||
@Hidden
|
||||
public ResponseEntity<String> updateAdvancedSettings(@RequestBody Map<String, Object> settings)
|
||||
throws IOException {
|
||||
if (settings.containsKey("enableAlphaFunctionality")) {
|
||||
GeneralUtils.saveKeyToSettings(
|
||||
"system.enableAlphaFunctionality", settings.get("enableAlphaFunctionality"));
|
||||
applicationProperties
|
||||
.getSystem()
|
||||
.setEnableAlphaFunctionality(
|
||||
(Boolean) settings.get("enableAlphaFunctionality"));
|
||||
}
|
||||
if (settings.containsKey("maxDPI")) {
|
||||
GeneralUtils.saveKeyToSettings("system.maxDPI", settings.get("maxDPI"));
|
||||
applicationProperties.getSystem().setMaxDPI((Integer) settings.get("maxDPI"));
|
||||
}
|
||||
if (settings.containsKey("enableUrlToPDF")) {
|
||||
GeneralUtils.saveKeyToSettings("system.enableUrlToPDF", settings.get("enableUrlToPDF"));
|
||||
applicationProperties
|
||||
.getSystem()
|
||||
.setEnableUrlToPDF((Boolean) settings.get("enableUrlToPDF"));
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(
|
||||
"Advanced settings updated. Restart required for changes to take effect.");
|
||||
}
|
||||
}
|
||||
|
||||
+3
-24
@@ -15,7 +15,6 @@ import stirling.software.common.annotations.api.ConfigApi;
|
||||
import stirling.software.common.configuration.AppConfig;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.service.ServerCertificateServiceInterface;
|
||||
import stirling.software.common.service.UserServiceInterface;
|
||||
|
||||
@ConfigApi
|
||||
@Hidden
|
||||
@@ -25,21 +24,17 @@ public class ConfigController {
|
||||
private final ApplicationContext applicationContext;
|
||||
private final EndpointConfiguration endpointConfiguration;
|
||||
private final ServerCertificateServiceInterface serverCertificateService;
|
||||
private final UserServiceInterface userService;
|
||||
|
||||
public ConfigController(
|
||||
ApplicationProperties applicationProperties,
|
||||
ApplicationContext applicationContext,
|
||||
EndpointConfiguration endpointConfiguration,
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
ServerCertificateServiceInterface serverCertificateService,
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
UserServiceInterface userService) {
|
||||
ServerCertificateServiceInterface serverCertificateService) {
|
||||
this.applicationProperties = applicationProperties;
|
||||
this.applicationContext = applicationContext;
|
||||
this.endpointConfiguration = endpointConfiguration;
|
||||
this.serverCertificateService = serverCertificateService;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping("/app-config")
|
||||
@@ -56,36 +51,20 @@ public class ConfigController {
|
||||
configData.put("serverPort", appConfig.getServerPort());
|
||||
|
||||
// Extract values from ApplicationProperties
|
||||
configData.put("appName", applicationProperties.getUi().getAppName());
|
||||
configData.put("appNameNavbar", applicationProperties.getUi().getAppNameNavbar());
|
||||
configData.put("homeDescription", applicationProperties.getUi().getHomeDescription());
|
||||
configData.put("languages", applicationProperties.getUi().getLanguages());
|
||||
|
||||
// Security settings
|
||||
configData.put("enableLogin", applicationProperties.getSecurity().getEnableLogin());
|
||||
|
||||
// Mail settings - check both SMTP enabled AND invites enabled
|
||||
boolean smtpEnabled = applicationProperties.getMail().isEnabled();
|
||||
boolean invitesEnabled = applicationProperties.getMail().isEnableInvites();
|
||||
configData.put("enableEmailInvites", smtpEnabled && invitesEnabled);
|
||||
|
||||
// Check if user is admin using UserServiceInterface
|
||||
boolean isAdmin = false;
|
||||
if (userService != null) {
|
||||
try {
|
||||
isAdmin = userService.isCurrentUserAdmin();
|
||||
} catch (Exception e) {
|
||||
// If there's an error, isAdmin remains false
|
||||
}
|
||||
}
|
||||
configData.put("isAdmin", isAdmin);
|
||||
|
||||
// System settings
|
||||
configData.put(
|
||||
"enableAlphaFunctionality",
|
||||
applicationProperties.getSystem().getEnableAlphaFunctionality());
|
||||
configData.put(
|
||||
"enableAnalytics", applicationProperties.getSystem().getEnableAnalytics());
|
||||
configData.put("enablePosthog", applicationProperties.getSystem().getEnablePosthog());
|
||||
configData.put("enableScarf", applicationProperties.getSystem().getEnableScarf());
|
||||
|
||||
// Premium/Enterprise settings
|
||||
configData.put("premiumEnabled", applicationProperties.getPremium().isEnabled());
|
||||
|
||||
@@ -99,7 +99,6 @@ premium:
|
||||
|
||||
mail:
|
||||
enabled: false # set to 'true' to enable sending emails
|
||||
enableInvites: false # set to 'true' to enable email invites for user management (requires mail.enabled and security.enableLogin)
|
||||
host: smtp.example.com # SMTP server hostname
|
||||
port: 587 # SMTP server port
|
||||
username: '' # SMTP server username
|
||||
@@ -107,8 +106,8 @@ mail:
|
||||
from: '' # sender email address
|
||||
|
||||
legal:
|
||||
termsAndConditions: https://www.stirling.com/legal/terms-of-service # URL to the terms and conditions of your application (e.g. https://example.com/terms). Empty string to disable or filename to load from local file in static folder
|
||||
privacyPolicy: https://www.stirling.com/legal/privacy-policy # URL to the privacy policy of your application (e.g. https://example.com/privacy). Empty string to disable or filename to load from local file in static folder
|
||||
termsAndConditions: https://www.stirlingpdf.com/terms # URL to the terms and conditions of your application (e.g. https://example.com/terms). Empty string to disable or filename to load from local file in static folder
|
||||
privacyPolicy: https://www.stirlingpdf.com/privacy-policy # URL to the privacy policy of your application (e.g. https://example.com/privacy). Empty string to disable or filename to load from local file in static folder
|
||||
accessibilityStatement: '' # URL to the accessibility statement of your application (e.g. https://example.com/accessibility). Empty string to disable or filename to load from local file in static folder
|
||||
cookiePolicy: '' # URL to the cookie policy of your application (e.g. https://example.com/cookie). Empty string to disable or filename to load from local file in static folder
|
||||
impressum: '' # URL to the impressum of your application (e.g. https://example.com/impressum). Empty string to disable or filename to load from local file in static folder
|
||||
@@ -121,9 +120,7 @@ system:
|
||||
showUpdateOnlyAdmin: false # only admins can see when a new update is available, depending on showUpdate it must be set to 'true'
|
||||
customHTMLFiles: false # enable to have files placed in /customFiles/templates override the existing template HTML files
|
||||
tessdataDir: /usr/share/tessdata # path to the directory containing the Tessdata files. This setting is relevant for Windows systems. For Windows users, this path should be adjusted to point to the appropriate directory where the Tessdata files are stored.
|
||||
enableAnalytics: null # Master toggle for analytics: set to 'true' to enable all analytics, 'false' to disable all analytics, or leave as 'null' to prompt admin on first launch
|
||||
enablePosthog: null # Enable PostHog analytics (open-source product analytics): set to 'true' to enable, 'false' to disable, or 'null' to enable by default when analytics is enabled
|
||||
enableScarf: null # Enable Scarf tracking pixel: set to 'true' to enable, 'false' to disable, or 'null' to enable by default when analytics is enabled
|
||||
enableAnalytics: null # set to 'true' to enable analytics, set to 'false' to disable analytics; for enterprise users, this is set to true
|
||||
enableUrlToPDF: false # Set to 'true' to enable URL to PDF, INTERNAL ONLY, known security issues, should not be used externally
|
||||
disableSanitize: false # set to true to disable Sanitize HTML; (can lead to injections in HTML)
|
||||
maxDPI: 500 # Maximum allowed DPI for PDF to image conversion
|
||||
@@ -172,6 +169,8 @@ system:
|
||||
cleanupSystemTemp: false # Whether to clean broader system temp directory
|
||||
|
||||
ui:
|
||||
appName: '' # application's visible name
|
||||
homeDescription: '' # short description or tagline shown on the homepage
|
||||
appNameNavbar: '' # name displayed on the navigation bar
|
||||
languages: [] # If empty, all languages are enabled. To display only German and Polish ["de_DE", "pl_PL"]. British English is always enabled.
|
||||
|
||||
|
||||
+5
-3
@@ -1,15 +1,17 @@
|
||||
package stirling.software.proprietary.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
/** Configuration to enable scheduling for the audit system. */
|
||||
/** Configuration to explicitly enable JPA repositories and scheduling for the audit system. */
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(basePackages = "stirling.software.proprietary.repository")
|
||||
@EnableScheduling
|
||||
public class AuditJpaConfig {
|
||||
// This configuration enables scheduling for audit cleanup tasks
|
||||
// JPA repositories are now managed by DatabaseConfig to avoid conflicts
|
||||
// This configuration enables JPA repositories in the specified package
|
||||
// and enables scheduling for audit cleanup tasks
|
||||
// No additional beans or methods needed
|
||||
}
|
||||
|
||||
-434
@@ -1,434 +0,0 @@
|
||||
package stirling.software.proprietary.controller.api;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.annotations.api.ProprietaryUiDataApi;
|
||||
import stirling.software.proprietary.audit.AuditEventType;
|
||||
import stirling.software.proprietary.model.security.PersistentAuditEvent;
|
||||
import stirling.software.proprietary.repository.PersistentAuditEventRepository;
|
||||
import stirling.software.proprietary.security.config.EnterpriseEndpoint;
|
||||
|
||||
/** REST API controller for audit data used by React frontend. */
|
||||
@Slf4j
|
||||
@ProprietaryUiDataApi
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@RequiredArgsConstructor
|
||||
@EnterpriseEndpoint
|
||||
public class AuditRestController {
|
||||
|
||||
private final PersistentAuditEventRepository auditRepository;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* Get audit events with pagination and filters. Maps to frontend's getEvents() call.
|
||||
*
|
||||
* @param page Page number (0-indexed)
|
||||
* @param pageSize Number of items per page
|
||||
* @param eventType Filter by event type
|
||||
* @param username Filter by username (principal)
|
||||
* @param startDate Filter start date
|
||||
* @param endDate Filter end date
|
||||
* @return Paginated audit events response
|
||||
*/
|
||||
@GetMapping("/audit-events")
|
||||
public ResponseEntity<AuditEventsResponse> getAuditEvents(
|
||||
@RequestParam(value = "page", defaultValue = "0") int page,
|
||||
@RequestParam(value = "pageSize", defaultValue = "30") int pageSize,
|
||||
@RequestParam(value = "eventType", required = false) String eventType,
|
||||
@RequestParam(value = "username", required = false) String username,
|
||||
@RequestParam(value = "startDate", required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
LocalDate startDate,
|
||||
@RequestParam(value = "endDate", required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
LocalDate endDate) {
|
||||
|
||||
Pageable pageable = PageRequest.of(page, pageSize, Sort.by("timestamp").descending());
|
||||
Page<PersistentAuditEvent> events;
|
||||
|
||||
// Apply filters based on provided parameters
|
||||
if (eventType != null && username != null && startDate != null && endDate != null) {
|
||||
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
events =
|
||||
auditRepository.findByPrincipalAndTypeAndTimestampBetween(
|
||||
username, eventType, start, end, pageable);
|
||||
} else if (eventType != null && username != null) {
|
||||
events = auditRepository.findByPrincipalAndType(username, eventType, pageable);
|
||||
} else if (eventType != null && startDate != null && endDate != null) {
|
||||
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
events = auditRepository.findByTypeAndTimestampBetween(eventType, start, end, pageable);
|
||||
} else if (username != null && startDate != null && endDate != null) {
|
||||
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
events =
|
||||
auditRepository.findByPrincipalAndTimestampBetween(
|
||||
username, start, end, pageable);
|
||||
} else if (startDate != null && endDate != null) {
|
||||
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
events = auditRepository.findByTimestampBetween(start, end, pageable);
|
||||
} else if (eventType != null) {
|
||||
events = auditRepository.findByType(eventType, pageable);
|
||||
} else if (username != null) {
|
||||
events = auditRepository.findByPrincipal(username, pageable);
|
||||
} else {
|
||||
events = auditRepository.findAll(pageable);
|
||||
}
|
||||
|
||||
// Convert to response format expected by frontend
|
||||
List<AuditEventDto> eventDtos =
|
||||
events.getContent().stream().map(this::convertToDto).collect(Collectors.toList());
|
||||
|
||||
AuditEventsResponse response =
|
||||
AuditEventsResponse.builder()
|
||||
.events(eventDtos)
|
||||
.totalEvents((int) events.getTotalElements())
|
||||
.page(events.getNumber())
|
||||
.pageSize(events.getSize())
|
||||
.totalPages(events.getTotalPages())
|
||||
.build();
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get chart data for dashboard. Maps to frontend's getChartsData() call.
|
||||
*
|
||||
* @param period Time period for charts (day/week/month)
|
||||
* @return Chart data for events by type, user, and over time
|
||||
*/
|
||||
@GetMapping("/audit-charts")
|
||||
public ResponseEntity<AuditChartsData> getAuditCharts(
|
||||
@RequestParam(value = "period", defaultValue = "week") String period) {
|
||||
|
||||
// Calculate days based on period
|
||||
int days;
|
||||
switch (period.toLowerCase()) {
|
||||
case "day":
|
||||
days = 1;
|
||||
break;
|
||||
case "month":
|
||||
days = 30;
|
||||
break;
|
||||
case "week":
|
||||
default:
|
||||
days = 7;
|
||||
break;
|
||||
}
|
||||
|
||||
// Get events from the specified period
|
||||
Instant startDate = Instant.now().minus(java.time.Duration.ofDays(days));
|
||||
List<PersistentAuditEvent> events = auditRepository.findByTimestampAfter(startDate);
|
||||
|
||||
// Count events by type
|
||||
Map<String, Long> eventsByType =
|
||||
events.stream()
|
||||
.collect(
|
||||
Collectors.groupingBy(
|
||||
PersistentAuditEvent::getType, Collectors.counting()));
|
||||
|
||||
// Count events by principal (user)
|
||||
Map<String, Long> eventsByUser =
|
||||
events.stream()
|
||||
.collect(
|
||||
Collectors.groupingBy(
|
||||
PersistentAuditEvent::getPrincipal, Collectors.counting()));
|
||||
|
||||
// Count events by day
|
||||
Map<String, Long> eventsByDay =
|
||||
events.stream()
|
||||
.collect(
|
||||
Collectors.groupingBy(
|
||||
e ->
|
||||
LocalDateTime.ofInstant(
|
||||
e.getTimestamp(),
|
||||
ZoneId.systemDefault())
|
||||
.format(DateTimeFormatter.ISO_LOCAL_DATE),
|
||||
Collectors.counting()));
|
||||
|
||||
// Convert to ChartData format
|
||||
ChartData eventsByTypeChart =
|
||||
ChartData.builder()
|
||||
.labels(new ArrayList<>(eventsByType.keySet()))
|
||||
.values(
|
||||
eventsByType.values().stream()
|
||||
.map(Long::intValue)
|
||||
.collect(Collectors.toList()))
|
||||
.build();
|
||||
|
||||
ChartData eventsByUserChart =
|
||||
ChartData.builder()
|
||||
.labels(new ArrayList<>(eventsByUser.keySet()))
|
||||
.values(
|
||||
eventsByUser.values().stream()
|
||||
.map(Long::intValue)
|
||||
.collect(Collectors.toList()))
|
||||
.build();
|
||||
|
||||
// Sort events by day for time series
|
||||
TreeMap<String, Long> sortedEventsByDay = new TreeMap<>(eventsByDay);
|
||||
ChartData eventsOverTimeChart =
|
||||
ChartData.builder()
|
||||
.labels(new ArrayList<>(sortedEventsByDay.keySet()))
|
||||
.values(
|
||||
sortedEventsByDay.values().stream()
|
||||
.map(Long::intValue)
|
||||
.collect(Collectors.toList()))
|
||||
.build();
|
||||
|
||||
AuditChartsData chartsData =
|
||||
AuditChartsData.builder()
|
||||
.eventsByType(eventsByTypeChart)
|
||||
.eventsByUser(eventsByUserChart)
|
||||
.eventsOverTime(eventsOverTimeChart)
|
||||
.build();
|
||||
|
||||
return ResponseEntity.ok(chartsData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available event types for filtering. Maps to frontend's getEventTypes() call.
|
||||
*
|
||||
* @return List of unique event types
|
||||
*/
|
||||
@GetMapping("/audit-event-types")
|
||||
public ResponseEntity<List<String>> getEventTypes() {
|
||||
// Get distinct event types from the database
|
||||
List<String> dbTypes = auditRepository.findDistinctEventTypes();
|
||||
|
||||
// Include standard enum types in case they're not in the database yet
|
||||
List<String> enumTypes =
|
||||
Arrays.stream(AuditEventType.values())
|
||||
.map(AuditEventType::name)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Combine both sources, remove duplicates, and sort
|
||||
Set<String> combinedTypes = new HashSet<>();
|
||||
combinedTypes.addAll(dbTypes);
|
||||
combinedTypes.addAll(enumTypes);
|
||||
|
||||
List<String> result = combinedTypes.stream().sorted().collect(Collectors.toList());
|
||||
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of users for filtering. Maps to frontend's getUsers() call.
|
||||
*
|
||||
* @return List of unique usernames
|
||||
*/
|
||||
@GetMapping("/audit-users")
|
||||
public ResponseEntity<List<String>> getUsers() {
|
||||
// Use the countByPrincipal query to get unique principals
|
||||
List<Object[]> principalCounts = auditRepository.countByPrincipal();
|
||||
|
||||
List<String> users =
|
||||
principalCounts.stream()
|
||||
.map(arr -> (String) arr[0])
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return ResponseEntity.ok(users);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export audit data in CSV or JSON format. Maps to frontend's exportData() call.
|
||||
*
|
||||
* @param format Export format (csv or json)
|
||||
* @param eventType Filter by event type
|
||||
* @param username Filter by username
|
||||
* @param startDate Filter start date
|
||||
* @param endDate Filter end date
|
||||
* @return File download response
|
||||
*/
|
||||
@GetMapping("/audit-export")
|
||||
public ResponseEntity<byte[]> exportAuditData(
|
||||
@RequestParam(value = "format", defaultValue = "csv") String format,
|
||||
@RequestParam(value = "eventType", required = false) String eventType,
|
||||
@RequestParam(value = "username", required = false) String username,
|
||||
@RequestParam(value = "startDate", required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
LocalDate startDate,
|
||||
@RequestParam(value = "endDate", required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
LocalDate endDate) {
|
||||
|
||||
// Get data with same filtering as getAuditEvents
|
||||
List<PersistentAuditEvent> events;
|
||||
|
||||
if (eventType != null && username != null && startDate != null && endDate != null) {
|
||||
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
events =
|
||||
auditRepository.findAllByPrincipalAndTypeAndTimestampBetweenForExport(
|
||||
username, eventType, start, end);
|
||||
} else if (eventType != null && username != null) {
|
||||
events = auditRepository.findAllByPrincipalAndTypeForExport(username, eventType);
|
||||
} else if (eventType != null && startDate != null && endDate != null) {
|
||||
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
events =
|
||||
auditRepository.findAllByTypeAndTimestampBetweenForExport(
|
||||
eventType, start, end);
|
||||
} else if (username != null && startDate != null && endDate != null) {
|
||||
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
events =
|
||||
auditRepository.findAllByPrincipalAndTimestampBetweenForExport(
|
||||
username, start, end);
|
||||
} else if (startDate != null && endDate != null) {
|
||||
Instant start = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
Instant end = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
events = auditRepository.findAllByTimestampBetweenForExport(start, end);
|
||||
} else if (eventType != null) {
|
||||
events = auditRepository.findByTypeForExport(eventType);
|
||||
} else if (username != null) {
|
||||
events = auditRepository.findAllByPrincipalForExport(username);
|
||||
} else {
|
||||
events = auditRepository.findAll();
|
||||
}
|
||||
|
||||
// Export based on format
|
||||
if ("json".equalsIgnoreCase(format)) {
|
||||
return exportAsJson(events);
|
||||
} else {
|
||||
return exportAsCsv(events);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
|
||||
private AuditEventDto convertToDto(PersistentAuditEvent event) {
|
||||
// Parse the JSON data field if present
|
||||
Map<String, Object> details = new HashMap<>();
|
||||
if (event.getData() != null && !event.getData().isEmpty()) {
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> parsed = objectMapper.readValue(event.getData(), Map.class);
|
||||
details = parsed;
|
||||
} catch (JsonProcessingException e) {
|
||||
log.warn("Failed to parse audit event data as JSON: {}", event.getData());
|
||||
details.put("rawData", event.getData());
|
||||
}
|
||||
}
|
||||
|
||||
return AuditEventDto.builder()
|
||||
.id(String.valueOf(event.getId()))
|
||||
.timestamp(event.getTimestamp().toString())
|
||||
.eventType(event.getType())
|
||||
.username(event.getPrincipal())
|
||||
.ipAddress((String) details.getOrDefault("ipAddress", "")) // Extract if available
|
||||
.details(details)
|
||||
.build();
|
||||
}
|
||||
|
||||
private ResponseEntity<byte[]> exportAsCsv(List<PersistentAuditEvent> events) {
|
||||
StringBuilder csv = new StringBuilder();
|
||||
csv.append("ID,Principal,Type,Timestamp,Data\n");
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
|
||||
|
||||
for (PersistentAuditEvent event : events) {
|
||||
csv.append(event.getId()).append(",");
|
||||
csv.append(escapeCSV(event.getPrincipal())).append(",");
|
||||
csv.append(escapeCSV(event.getType())).append(",");
|
||||
csv.append(formatter.format(event.getTimestamp())).append(",");
|
||||
csv.append(escapeCSV(event.getData())).append("\n");
|
||||
}
|
||||
|
||||
byte[] csvBytes = csv.toString().getBytes();
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
|
||||
headers.setContentDispositionFormData("attachment", "audit_export.csv");
|
||||
|
||||
return ResponseEntity.ok().headers(headers).body(csvBytes);
|
||||
}
|
||||
|
||||
private ResponseEntity<byte[]> exportAsJson(List<PersistentAuditEvent> events) {
|
||||
try {
|
||||
byte[] jsonBytes = objectMapper.writeValueAsBytes(events);
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.setContentDispositionFormData("attachment", "audit_export.json");
|
||||
|
||||
return ResponseEntity.ok().headers(headers).body(jsonBytes);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.error("Error serializing audit events to JSON", e);
|
||||
return ResponseEntity.internalServerError().build();
|
||||
}
|
||||
}
|
||||
|
||||
private String escapeCSV(String field) {
|
||||
if (field == null) {
|
||||
return "";
|
||||
}
|
||||
// Replace double quotes with two double quotes and wrap in quotes
|
||||
return "\"" + field.replace("\"", "\"\"") + "\"";
|
||||
}
|
||||
|
||||
// DTOs for response formatting
|
||||
|
||||
@lombok.Data
|
||||
@lombok.Builder
|
||||
public static class AuditEventsResponse {
|
||||
private List<AuditEventDto> events;
|
||||
private int totalEvents;
|
||||
private int page;
|
||||
private int pageSize;
|
||||
private int totalPages;
|
||||
}
|
||||
|
||||
@lombok.Data
|
||||
@lombok.Builder
|
||||
public static class AuditEventDto {
|
||||
private String id;
|
||||
private String timestamp;
|
||||
private String eventType;
|
||||
private String username;
|
||||
private String ipAddress;
|
||||
private Map<String, Object> details;
|
||||
}
|
||||
|
||||
@lombok.Data
|
||||
@lombok.Builder
|
||||
public static class AuditChartsData {
|
||||
private ChartData eventsByType;
|
||||
private ChartData eventsByUser;
|
||||
private ChartData eventsOverTime;
|
||||
}
|
||||
|
||||
@lombok.Data
|
||||
@lombok.Builder
|
||||
public static class ChartData {
|
||||
private List<String> labels;
|
||||
private List<Integer> values;
|
||||
}
|
||||
}
|
||||
+2
-27
@@ -39,7 +39,6 @@ import stirling.software.proprietary.audit.AuditLevel;
|
||||
import stirling.software.proprietary.config.AuditConfigurationProperties;
|
||||
import stirling.software.proprietary.model.Team;
|
||||
import stirling.software.proprietary.model.dto.TeamWithUserCountDTO;
|
||||
import stirling.software.proprietary.repository.PersistentAuditEventRepository;
|
||||
import stirling.software.proprietary.security.config.EnterpriseEndpoint;
|
||||
import stirling.software.proprietary.security.database.repository.SessionRepository;
|
||||
import stirling.software.proprietary.security.database.repository.UserRepository;
|
||||
@@ -51,10 +50,10 @@ import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrin
|
||||
import stirling.software.proprietary.security.service.DatabaseService;
|
||||
import stirling.software.proprietary.security.service.TeamService;
|
||||
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
|
||||
import stirling.software.proprietary.service.UserLicenseSettingsService;
|
||||
|
||||
@Slf4j
|
||||
@ProprietaryUiDataApi
|
||||
@EnterpriseEndpoint
|
||||
public class ProprietaryUIDataController {
|
||||
|
||||
private final ApplicationProperties applicationProperties;
|
||||
@@ -66,8 +65,6 @@ public class ProprietaryUIDataController {
|
||||
private final DatabaseService databaseService;
|
||||
private final boolean runningEE;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final UserLicenseSettingsService licenseSettingsService;
|
||||
private final PersistentAuditEventRepository auditRepository;
|
||||
|
||||
public ProprietaryUIDataController(
|
||||
ApplicationProperties applicationProperties,
|
||||
@@ -78,9 +75,7 @@ public class ProprietaryUIDataController {
|
||||
SessionRepository sessionRepository,
|
||||
DatabaseService databaseService,
|
||||
ObjectMapper objectMapper,
|
||||
@Qualifier("runningEE") boolean runningEE,
|
||||
UserLicenseSettingsService licenseSettingsService,
|
||||
PersistentAuditEventRepository auditRepository) {
|
||||
@Qualifier("runningEE") boolean runningEE) {
|
||||
this.applicationProperties = applicationProperties;
|
||||
this.auditConfig = auditConfig;
|
||||
this.sessionPersistentRegistry = sessionPersistentRegistry;
|
||||
@@ -90,13 +85,10 @@ public class ProprietaryUIDataController {
|
||||
this.databaseService = databaseService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.runningEE = runningEE;
|
||||
this.licenseSettingsService = licenseSettingsService;
|
||||
this.auditRepository = auditRepository;
|
||||
}
|
||||
|
||||
@GetMapping("/audit-dashboard")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@EnterpriseEndpoint
|
||||
@Operation(summary = "Get audit dashboard data")
|
||||
public ResponseEntity<AuditDashboardData> getAuditDashboardData() {
|
||||
AuditDashboardData data = new AuditDashboardData();
|
||||
@@ -270,13 +262,6 @@ public class ProprietaryUIDataController {
|
||||
.filter(team -> !team.getName().equals(TeamService.INTERNAL_TEAM_NAME))
|
||||
.toList();
|
||||
|
||||
// Calculate license limits
|
||||
int maxAllowedUsers = licenseSettingsService.calculateMaxAllowedUsers();
|
||||
long availableSlots = licenseSettingsService.getAvailableUserSlots();
|
||||
int grandfatheredCount = licenseSettingsService.getDisplayGrandfatheredCount();
|
||||
int licenseMaxUsers = licenseSettingsService.getSettings().getLicenseMaxUsers();
|
||||
boolean premiumEnabled = applicationProperties.getPremium().isEnabled();
|
||||
|
||||
AdminSettingsData data = new AdminSettingsData();
|
||||
data.setUsers(sortedUsers);
|
||||
data.setCurrentUsername(authentication.getName());
|
||||
@@ -288,11 +273,6 @@ public class ProprietaryUIDataController {
|
||||
data.setDisabledUsers(disabledUsers);
|
||||
data.setTeams(allTeams);
|
||||
data.setMaxPaidUsers(applicationProperties.getPremium().getMaxUsers());
|
||||
data.setMaxAllowedUsers(maxAllowedUsers);
|
||||
data.setAvailableSlots(availableSlots);
|
||||
data.setGrandfatheredUserCount(grandfatheredCount);
|
||||
data.setLicenseMaxUsers(licenseMaxUsers);
|
||||
data.setPremiumEnabled(premiumEnabled);
|
||||
|
||||
return ResponseEntity.ok(data);
|
||||
}
|
||||
@@ -465,11 +445,6 @@ public class ProprietaryUIDataController {
|
||||
private int disabledUsers;
|
||||
private List<Team> teams;
|
||||
private int maxPaidUsers;
|
||||
private int maxAllowedUsers;
|
||||
private long availableSlots;
|
||||
private int grandfatheredUserCount;
|
||||
private int licenseMaxUsers;
|
||||
private boolean premiumEnabled;
|
||||
}
|
||||
|
||||
@Data
|
||||
|
||||
-236
@@ -1,236 +0,0 @@
|
||||
package stirling.software.proprietary.controller.api;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.annotations.api.ProprietaryUiDataApi;
|
||||
import stirling.software.proprietary.audit.AuditEventType;
|
||||
import stirling.software.proprietary.model.security.PersistentAuditEvent;
|
||||
import stirling.software.proprietary.repository.PersistentAuditEventRepository;
|
||||
import stirling.software.proprietary.security.config.EnterpriseEndpoint;
|
||||
|
||||
/** REST API controller for usage analytics data used by React frontend. */
|
||||
@Slf4j
|
||||
@ProprietaryUiDataApi
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@RequiredArgsConstructor
|
||||
@EnterpriseEndpoint
|
||||
public class UsageRestController {
|
||||
|
||||
private final PersistentAuditEventRepository auditRepository;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* Get endpoint statistics derived from audit events. This endpoint analyzes HTTP_REQUEST audit
|
||||
* events to generate usage statistics.
|
||||
*
|
||||
* @param limit Optional limit on number of endpoints to return
|
||||
* @param dataType Type of data to include: "all" (default), "api" (API endpoints excluding
|
||||
* auth), or "ui" (non-API endpoints)
|
||||
* @return Endpoint statistics response
|
||||
*/
|
||||
@GetMapping("/usage-endpoint-statistics")
|
||||
public ResponseEntity<EndpointStatisticsResponse> getEndpointStatistics(
|
||||
@RequestParam(value = "limit", required = false) Integer limit,
|
||||
@RequestParam(value = "dataType", defaultValue = "all") String dataType) {
|
||||
|
||||
// Get all HTTP_REQUEST audit events
|
||||
List<PersistentAuditEvent> httpEvents =
|
||||
auditRepository.findByTypeForExport(AuditEventType.HTTP_REQUEST.name());
|
||||
|
||||
// Count visits per endpoint
|
||||
Map<String, Long> endpointCounts = new HashMap<>();
|
||||
|
||||
for (PersistentAuditEvent event : httpEvents) {
|
||||
String endpoint = extractEndpointFromAuditData(event.getData());
|
||||
if (endpoint != null) {
|
||||
// Apply data type filter
|
||||
if (!shouldIncludeEndpoint(endpoint, dataType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
endpointCounts.merge(endpoint, 1L, Long::sum);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate totals
|
||||
long totalVisits = endpointCounts.values().stream().mapToLong(Long::longValue).sum();
|
||||
int totalEndpoints = endpointCounts.size();
|
||||
|
||||
// Convert to list and sort by visit count (descending)
|
||||
List<EndpointStatistic> statistics =
|
||||
endpointCounts.entrySet().stream()
|
||||
.map(
|
||||
entry -> {
|
||||
String endpoint = entry.getKey();
|
||||
long visits = entry.getValue();
|
||||
double percentage =
|
||||
totalVisits > 0 ? (visits * 100.0 / totalVisits) : 0.0;
|
||||
|
||||
return EndpointStatistic.builder()
|
||||
.endpoint(endpoint)
|
||||
.visits((int) visits)
|
||||
.percentage(Math.round(percentage * 10.0) / 10.0)
|
||||
.build();
|
||||
})
|
||||
.sorted(Comparator.comparingInt(EndpointStatistic::getVisits).reversed())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Apply limit if specified
|
||||
if (limit != null && limit > 0 && statistics.size() > limit) {
|
||||
statistics = statistics.subList(0, limit);
|
||||
}
|
||||
|
||||
EndpointStatisticsResponse response =
|
||||
EndpointStatisticsResponse.builder()
|
||||
.endpoints(statistics)
|
||||
.totalEndpoints(totalEndpoints)
|
||||
.totalVisits((int) totalVisits)
|
||||
.build();
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the endpoint path from the audit event's data field. The data field contains JSON
|
||||
* with an "endpoint" or "path" key.
|
||||
*
|
||||
* @param dataJson JSON string from audit event
|
||||
* @return Endpoint path or null if not found
|
||||
*/
|
||||
private String extractEndpointFromAuditData(String dataJson) {
|
||||
if (dataJson == null || dataJson.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> data = objectMapper.readValue(dataJson, Map.class);
|
||||
|
||||
// Try common keys for endpoint path
|
||||
Object endpoint = data.get("endpoint");
|
||||
if (endpoint != null) {
|
||||
return normalizeEndpoint(endpoint.toString());
|
||||
}
|
||||
|
||||
Object path = data.get("path");
|
||||
if (path != null) {
|
||||
return normalizeEndpoint(path.toString());
|
||||
}
|
||||
|
||||
// Fallback: check if there's a request-related key
|
||||
Object requestUri = data.get("requestUri");
|
||||
if (requestUri != null) {
|
||||
return normalizeEndpoint(requestUri.toString());
|
||||
}
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
log.debug("Failed to parse audit data JSON: {}", dataJson, e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize endpoint paths by removing query strings and standardizing format.
|
||||
*
|
||||
* @param endpoint Raw endpoint path
|
||||
* @return Normalized endpoint path
|
||||
*/
|
||||
private String normalizeEndpoint(String endpoint) {
|
||||
if (endpoint == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Remove query string
|
||||
int queryIndex = endpoint.indexOf('?');
|
||||
if (queryIndex != -1) {
|
||||
endpoint = endpoint.substring(0, queryIndex);
|
||||
}
|
||||
|
||||
// Ensure it starts with /
|
||||
if (!endpoint.startsWith("/")) {
|
||||
endpoint = "/" + endpoint;
|
||||
}
|
||||
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if an endpoint should be included based on the data type filter.
|
||||
*
|
||||
* @param endpoint The endpoint path to check
|
||||
* @param dataType The filter type: "all", "api", or "ui"
|
||||
* @return true if the endpoint should be included, false otherwise
|
||||
*/
|
||||
private boolean shouldIncludeEndpoint(String endpoint, String dataType) {
|
||||
if ("all".equalsIgnoreCase(dataType)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isApiEndpoint = isApiEndpoint(endpoint);
|
||||
|
||||
if ("api".equalsIgnoreCase(dataType)) {
|
||||
return isApiEndpoint;
|
||||
} else if ("ui".equalsIgnoreCase(dataType)) {
|
||||
return !isApiEndpoint;
|
||||
}
|
||||
|
||||
// Default to including all if unrecognized type
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an endpoint is an API endpoint. API endpoints match /api/v1/* pattern but exclude
|
||||
* /api/v1/auth/* paths.
|
||||
*
|
||||
* @param endpoint The endpoint path to check
|
||||
* @return true if this is an API endpoint (excluding auth endpoints), false otherwise
|
||||
*/
|
||||
private boolean isApiEndpoint(String endpoint) {
|
||||
if (endpoint == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if it starts with /api/v1/
|
||||
if (!endpoint.startsWith("/api/v1/")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Exclude auth endpoints
|
||||
if (endpoint.startsWith("/api/v1/auth/")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// DTOs for response formatting
|
||||
|
||||
@lombok.Data
|
||||
@lombok.Builder
|
||||
public static class EndpointStatisticsResponse {
|
||||
private List<EndpointStatistic> endpoints;
|
||||
private int totalEndpoints;
|
||||
private int totalVisits;
|
||||
}
|
||||
|
||||
@lombok.Data
|
||||
@lombok.Builder
|
||||
public static class EndpointStatistic {
|
||||
private String endpoint;
|
||||
private int visits;
|
||||
private double percentage;
|
||||
}
|
||||
}
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
package stirling.software.proprietary.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import lombok.*;
|
||||
|
||||
/**
|
||||
* Entity to store user license settings in the database. This is a singleton entity (only one row
|
||||
* should exist). Tracks grandfathered user counts and license limits.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "user_license_settings")
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
public class UserLicenseSettings implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final Long SINGLETON_ID = 1L;
|
||||
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private Long id = SINGLETON_ID;
|
||||
|
||||
/**
|
||||
* The number of users that existed in the database when grandfathering was initialized. This
|
||||
* value is set once during initial setup and should NEVER be modified afterwards.
|
||||
*/
|
||||
@Column(name = "grandfathered_user_count", nullable = false)
|
||||
private int grandfatheredUserCount = 0;
|
||||
|
||||
/**
|
||||
* Flag to indicate that grandfathering has been initialized and locked. Once true, the
|
||||
* grandfatheredUserCount should never change. This prevents manipulation by deleting/recreating
|
||||
* the table.
|
||||
*/
|
||||
@Column(name = "grandfathering_locked", nullable = false)
|
||||
private boolean grandfatheringLocked = false;
|
||||
|
||||
/**
|
||||
* Maximum number of users allowed by the current license. This is updated when the license key
|
||||
* is validated.
|
||||
*/
|
||||
@Column(name = "license_max_users", nullable = false)
|
||||
private int licenseMaxUsers = 0;
|
||||
|
||||
/**
|
||||
* Random salt used when generating signatures. Makes it harder to recompute the signature when
|
||||
* manually editing the table.
|
||||
*/
|
||||
@Column(name = "integrity_salt", nullable = false, length = 64)
|
||||
private String integritySalt = "";
|
||||
|
||||
/**
|
||||
* Signed representation of {@code grandfatheredUserCount}. Stores the original value alongside
|
||||
* a secret-backed HMAC so we can detect tampering and restore the correct count.
|
||||
*/
|
||||
@Column(name = "grandfathered_user_signature", nullable = false, length = 256)
|
||||
private String grandfatheredUserSignature = "";
|
||||
}
|
||||
-8
@@ -20,7 +20,6 @@ import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.service.DatabaseServiceInterface;
|
||||
import stirling.software.proprietary.security.service.TeamService;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.proprietary.service.UserLicenseSettingsService;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -31,7 +30,6 @@ public class InitialSecuritySetup {
|
||||
private final TeamService teamService;
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final DatabaseServiceInterface databaseService;
|
||||
private final UserLicenseSettingsService licenseSettingsService;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
@@ -47,18 +45,12 @@ public class InitialSecuritySetup {
|
||||
|
||||
assignUsersToDefaultTeamIfMissing();
|
||||
initializeInternalApiUser();
|
||||
initializeUserLicenseSettings();
|
||||
} catch (IllegalArgumentException | SQLException | UnsupportedProviderException e) {
|
||||
log.error("Failed to initialize security setup.", e);
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private void initializeUserLicenseSettings() {
|
||||
licenseSettingsService.initializeGrandfatheredCount();
|
||||
licenseSettingsService.updateLicenseMaxUsers();
|
||||
}
|
||||
|
||||
private void assignUsersToDefaultTeamIfMissing() {
|
||||
Team defaultTeam = teamService.getOrCreateDefaultTeam();
|
||||
Team internalTeam = teamService.getOrCreateInternalTeam();
|
||||
|
||||
+1
-2
@@ -25,8 +25,7 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
|
||||
@EnableJpaRepositories(
|
||||
basePackages = {
|
||||
"stirling.software.proprietary.security.database.repository",
|
||||
"stirling.software.proprietary.security.repository",
|
||||
"stirling.software.proprietary.repository"
|
||||
"stirling.software.proprietary.security.repository"
|
||||
})
|
||||
@EntityScan({"stirling.software.proprietary.security.model", "stirling.software.proprietary.model"})
|
||||
public class DatabaseConfig {
|
||||
|
||||
+6
-6
@@ -39,6 +39,7 @@ import stirling.software.proprietary.security.CustomLogoutSuccessHandler;
|
||||
import stirling.software.proprietary.security.JwtAuthenticationEntryPoint;
|
||||
import stirling.software.proprietary.security.database.repository.JPATokenRepositoryImpl;
|
||||
import stirling.software.proprietary.security.database.repository.PersistentLoginRepository;
|
||||
import stirling.software.proprietary.security.filter.FirstLoginFilter;
|
||||
import stirling.software.proprietary.security.filter.IPRateLimitingFilter;
|
||||
import stirling.software.proprietary.security.filter.JwtAuthenticationFilter;
|
||||
import stirling.software.proprietary.security.filter.UserAuthenticationFilter;
|
||||
@@ -73,6 +74,7 @@ public class SecurityConfiguration {
|
||||
private final JwtServiceInterface jwtService;
|
||||
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||
private final LoginAttemptService loginAttemptService;
|
||||
private final FirstLoginFilter firstLoginFilter;
|
||||
private final SessionPersistentRegistry sessionRegistry;
|
||||
private final PersistentLoginRepository persistentLoginRepository;
|
||||
private final GrantedAuthoritiesMapper oAuth2userAuthoritiesMapper;
|
||||
@@ -91,6 +93,7 @@ public class SecurityConfiguration {
|
||||
JwtServiceInterface jwtService,
|
||||
JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint,
|
||||
LoginAttemptService loginAttemptService,
|
||||
FirstLoginFilter firstLoginFilter,
|
||||
SessionPersistentRegistry sessionRegistry,
|
||||
@Autowired(required = false) GrantedAuthoritiesMapper oAuth2userAuthoritiesMapper,
|
||||
@Autowired(required = false)
|
||||
@@ -107,6 +110,7 @@ public class SecurityConfiguration {
|
||||
this.jwtService = jwtService;
|
||||
this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
|
||||
this.loginAttemptService = loginAttemptService;
|
||||
this.firstLoginFilter = firstLoginFilter;
|
||||
this.sessionRegistry = sessionRegistry;
|
||||
this.persistentLoginRepository = persistentLoginRepository;
|
||||
this.oAuth2userAuthoritiesMapper = oAuth2userAuthoritiesMapper;
|
||||
@@ -131,7 +135,8 @@ public class SecurityConfiguration {
|
||||
http.addFilterBefore(
|
||||
userAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(
|
||||
rateLimitingFilter(), UsernamePasswordAuthenticationFilter.class);
|
||||
rateLimitingFilter(), UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(firstLoginFilter, IPRateLimitingFilter.class);
|
||||
|
||||
if (v2Enabled) {
|
||||
http.addFilterBefore(jwtAuthenticationFilter(), UserAuthenticationFilter.class);
|
||||
@@ -241,7 +246,6 @@ public class SecurityConfiguration {
|
||||
|| trimmedUri.endsWith(".svg")
|
||||
|| trimmedUri.startsWith("/register")
|
||||
|| trimmedUri.startsWith("/signup")
|
||||
|| trimmedUri.startsWith("/invite")
|
||||
|| trimmedUri.startsWith("/auth/callback")
|
||||
|| trimmedUri.startsWith("/error")
|
||||
|| trimmedUri.startsWith("/images/")
|
||||
@@ -264,10 +268,6 @@ public class SecurityConfiguration {
|
||||
|| trimmedUri.startsWith(
|
||||
"/api/v1/auth/refresh")
|
||||
|| trimmedUri.startsWith("/api/v1/auth/me")
|
||||
|| trimmedUri.startsWith(
|
||||
"/api/v1/invite/validate")
|
||||
|| trimmedUri.startsWith(
|
||||
"/api/v1/invite/accept")
|
||||
|| trimmedUri.startsWith("/v1/api-docs")
|
||||
|| uri.contains("/v1/api-docs");
|
||||
})
|
||||
|
||||
+5
-31
@@ -5,20 +5,14 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.util.GeneralUtils;
|
||||
import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
|
||||
import stirling.software.proprietary.service.UserLicenseSettingsService;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -30,36 +24,21 @@ public class LicenseKeyChecker {
|
||||
|
||||
private final ApplicationProperties applicationProperties;
|
||||
|
||||
private final UserLicenseSettingsService licenseSettingsService;
|
||||
|
||||
private License premiumEnabledResult = License.NORMAL;
|
||||
|
||||
public LicenseKeyChecker(
|
||||
KeygenLicenseVerifier licenseService,
|
||||
ApplicationProperties applicationProperties,
|
||||
@Lazy UserLicenseSettingsService licenseSettingsService) {
|
||||
KeygenLicenseVerifier licenseService, ApplicationProperties applicationProperties) {
|
||||
this.licenseService = licenseService;
|
||||
this.applicationProperties = applicationProperties;
|
||||
this.licenseSettingsService = licenseSettingsService;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
evaluateLicense();
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void onApplicationReady() {
|
||||
synchronizeLicenseSettings();
|
||||
this.checkLicense();
|
||||
}
|
||||
|
||||
@Scheduled(initialDelay = 604800000, fixedRate = 604800000) // 7 days in milliseconds
|
||||
public void checkLicensePeriodically() {
|
||||
evaluateLicense();
|
||||
synchronizeLicenseSettings();
|
||||
checkLicense();
|
||||
}
|
||||
|
||||
private void evaluateLicense() {
|
||||
private void checkLicense() {
|
||||
if (!applicationProperties.getPremium().isEnabled()) {
|
||||
premiumEnabledResult = License.NORMAL;
|
||||
} else {
|
||||
@@ -80,10 +59,6 @@ public class LicenseKeyChecker {
|
||||
}
|
||||
}
|
||||
|
||||
private void synchronizeLicenseSettings() {
|
||||
licenseSettingsService.updateLicenseMaxUsers();
|
||||
}
|
||||
|
||||
private String getLicenseKeyContent(String keyOrFilePath) {
|
||||
if (keyOrFilePath == null || keyOrFilePath.trim().isEmpty()) {
|
||||
log.error("License key is not specified");
|
||||
@@ -114,8 +89,7 @@ public class LicenseKeyChecker {
|
||||
public void updateLicenseKey(String newKey) throws IOException {
|
||||
applicationProperties.getPremium().setKey(newKey);
|
||||
GeneralUtils.saveKeyToSettings("EnterpriseEdition.key", newKey);
|
||||
evaluateLicense();
|
||||
synchronizeLicenseSettings();
|
||||
checkLicense();
|
||||
}
|
||||
|
||||
public License getPremiumLicenseEnabledResult() {
|
||||
|
||||
+4
-187
@@ -1,27 +1,19 @@
|
||||
package stirling.software.proprietary.security.controller.api;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
@@ -40,9 +32,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.annotations.api.AdminApi;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.util.AppArgsCapture;
|
||||
import stirling.software.common.util.GeneralUtils;
|
||||
import stirling.software.common.util.JarPathUtil;
|
||||
import stirling.software.proprietary.security.model.api.admin.SettingValueResponse;
|
||||
import stirling.software.proprietary.security.model.api.admin.UpdateSettingValueRequest;
|
||||
import stirling.software.proprietary.security.model.api.admin.UpdateSettingsRequest;
|
||||
@@ -55,7 +45,6 @@ public class AdminSettingsController {
|
||||
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ApplicationContext applicationContext;
|
||||
|
||||
// Track settings that have been modified but not yet applied (require restart)
|
||||
private static final ConcurrentHashMap<String, Object> pendingChanges =
|
||||
@@ -206,8 +195,7 @@ public class AdminSettingsController {
|
||||
@Operation(
|
||||
summary = "Get specific settings section",
|
||||
description =
|
||||
"Retrieve settings for a specific section (e.g., security, system, ui). "
|
||||
+ "By default includes pending changes with awaitingRestart flags. Admin access required.")
|
||||
"Retrieve settings for a specific section (e.g., security, system, ui). Admin access required.")
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
@@ -218,9 +206,7 @@ public class AdminSettingsController {
|
||||
responseCode = "403",
|
||||
description = "Access denied - Admin role required")
|
||||
})
|
||||
public ResponseEntity<?> getSettingsSection(
|
||||
@PathVariable String sectionName,
|
||||
@RequestParam(defaultValue = "true") boolean includePending) {
|
||||
public ResponseEntity<?> getSettingsSection(@PathVariable String sectionName) {
|
||||
try {
|
||||
Object sectionData = getSectionData(sectionName);
|
||||
if (sectionData == null) {
|
||||
@@ -231,24 +217,8 @@ public class AdminSettingsController {
|
||||
+ ". Valid sections: "
|
||||
+ String.join(", ", VALID_SECTION_NAMES));
|
||||
}
|
||||
|
||||
// Convert to Map for manipulation
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> sectionMap = objectMapper.convertValue(sectionData, Map.class);
|
||||
|
||||
if (includePending && !pendingChanges.isEmpty()) {
|
||||
// Add pending changes block for this section
|
||||
Map<String, Object> sectionPending = extractPendingForSection(sectionName);
|
||||
if (!sectionPending.isEmpty()) {
|
||||
sectionMap.put("_pending", sectionPending);
|
||||
}
|
||||
}
|
||||
|
||||
log.debug(
|
||||
"Admin requested settings section: {} (includePending={})",
|
||||
sectionName,
|
||||
includePending);
|
||||
return ResponseEntity.ok(sectionMap);
|
||||
log.debug("Admin requested settings section: {}", sectionName);
|
||||
return ResponseEntity.ok(sectionData);
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.error("Invalid section name {}: {}", sectionName, e.getMessage(), e);
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
@@ -418,101 +388,6 @@ public class AdminSettingsController {
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/restart")
|
||||
@Operation(
|
||||
summary = "Restart the application",
|
||||
description =
|
||||
"Triggers a graceful restart of the Spring Boot application to apply pending settings changes. Uses a restart helper to ensure proper restart. Admin access required.")
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(responseCode = "200", description = "Restart initiated successfully"),
|
||||
@ApiResponse(
|
||||
responseCode = "403",
|
||||
description = "Access denied - Admin role required"),
|
||||
@ApiResponse(responseCode = "500", description = "Failed to initiate restart")
|
||||
})
|
||||
public ResponseEntity<String> restartApplication() {
|
||||
try {
|
||||
log.warn("Admin initiated application restart");
|
||||
|
||||
// Get paths to current JAR and restart helper
|
||||
Path appJar = JarPathUtil.currentJar();
|
||||
Path helperJar = JarPathUtil.restartHelperJar();
|
||||
|
||||
if (appJar == null) {
|
||||
log.error("Cannot restart: not running from JAR (likely development mode)");
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body(
|
||||
"Restart not available in development mode. Please restart the application manually.");
|
||||
}
|
||||
|
||||
if (helperJar == null || !Files.isRegularFile(helperJar)) {
|
||||
log.error("Cannot restart: restart-helper.jar not found at expected location");
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body("Restart helper not found. Please restart the application manually.");
|
||||
}
|
||||
|
||||
// Get current application arguments
|
||||
List<String> appArgs = AppArgsCapture.APP_ARGS.get();
|
||||
|
||||
// Write args to temp file to avoid command-line quoting issues
|
||||
Path argsFile = Files.createTempFile("stirling-app-args-", ".txt");
|
||||
Files.write(argsFile, appArgs, StandardCharsets.UTF_8);
|
||||
|
||||
// Get current process PID and java executable
|
||||
long pid = ProcessHandle.current().pid();
|
||||
String javaBin = JarPathUtil.javaExecutable();
|
||||
|
||||
// Build command to launch restart helper
|
||||
List<String> cmd = new ArrayList<>();
|
||||
cmd.add(javaBin);
|
||||
cmd.add("-jar");
|
||||
cmd.add(helperJar.toString());
|
||||
cmd.add("--pid");
|
||||
cmd.add(Long.toString(pid));
|
||||
cmd.add("--app");
|
||||
cmd.add(appJar.toString());
|
||||
cmd.add("--argsFile");
|
||||
cmd.add(argsFile.toString());
|
||||
cmd.add("--backoffMs");
|
||||
cmd.add("1000");
|
||||
|
||||
log.info("Launching restart helper: {}", String.join(" ", cmd));
|
||||
|
||||
// Launch restart helper process
|
||||
new ProcessBuilder(cmd)
|
||||
.directory(appJar.getParent().toFile())
|
||||
.inheritIO() // Forward logs
|
||||
.start();
|
||||
|
||||
// Clear pending changes since we're restarting
|
||||
pendingChanges.clear();
|
||||
|
||||
// Give the HTTP response time to complete, then exit
|
||||
new Thread(
|
||||
() -> {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
log.info("Shutting down for restart...");
|
||||
SpringApplication.exit(applicationContext, () -> 0);
|
||||
System.exit(0);
|
||||
} catch (InterruptedException e) {
|
||||
log.error("Restart interrupted: {}", e.getMessage(), e);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
})
|
||||
.start();
|
||||
|
||||
return ResponseEntity.ok(
|
||||
"Application restart initiated. The server will be back online shortly.");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to initiate restart: {}", e.getMessage(), e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body("Failed to initiate application restart: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Object getSectionData(String sectionName) {
|
||||
if (sectionName == null || sectionName.trim().isEmpty()) {
|
||||
return null;
|
||||
@@ -751,62 +626,4 @@ public class AdminSettingsController {
|
||||
|
||||
return mergedSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract pending changes for a specific section
|
||||
*
|
||||
* @param sectionName The section name (e.g., "security", "system")
|
||||
* @return Map of pending changes with nested structure for this section
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> extractPendingForSection(String sectionName) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
String sectionPrefix = sectionName.toLowerCase() + ".";
|
||||
|
||||
// Find all pending changes for this section
|
||||
for (Map.Entry<String, Object> entry : pendingChanges.entrySet()) {
|
||||
String pendingKey = entry.getKey();
|
||||
|
||||
if (pendingKey.toLowerCase().startsWith(sectionPrefix)) {
|
||||
// Extract the path within the section (e.g., "security.enableLogin" ->
|
||||
// "enableLogin")
|
||||
String pathInSection = pendingKey.substring(sectionPrefix.length());
|
||||
Object pendingValue = entry.getValue();
|
||||
|
||||
// Build nested structure from dot notation
|
||||
setNestedValue(result, pathInSection, pendingValue);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a value in a nested map using dot notation
|
||||
*
|
||||
* @param map The root map
|
||||
* @param dotPath The dot notation path (e.g., "oauth2.clientSecret")
|
||||
* @param value The value to set
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private void setNestedValue(Map<String, Object> map, String dotPath, Object value) {
|
||||
String[] parts = dotPath.split("\\.");
|
||||
Map<String, Object> current = map;
|
||||
|
||||
// Navigate/create nested maps for all parts except the last
|
||||
for (int i = 0; i < parts.length - 1; i++) {
|
||||
String part = parts[i];
|
||||
Object nested = current.get(part);
|
||||
|
||||
if (!(nested instanceof Map)) {
|
||||
nested = new HashMap<String, Object>();
|
||||
current.put(part, nested);
|
||||
}
|
||||
|
||||
current = (Map<String, Object>) nested;
|
||||
}
|
||||
|
||||
// Set the final value
|
||||
current.put(parts[parts.length - 1], value);
|
||||
}
|
||||
}
|
||||
|
||||
+30
-96
@@ -2,19 +2,21 @@ package stirling.software.proprietary.security.controller.api;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
import org.eclipse.jetty.http.HttpStatus;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.core.io.InputStreamResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Hidden;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -40,19 +42,15 @@ public class DatabaseController {
|
||||
summary = "Import a database backup file",
|
||||
description = "Uploads and imports a database backup SQL file.")
|
||||
@PostMapping(consumes = "multipart/form-data", value = "import-database")
|
||||
public ResponseEntity<?> importDatabase(
|
||||
public String importDatabase(
|
||||
@Parameter(description = "SQL file to import", required = true)
|
||||
@RequestParam("fileInput")
|
||||
MultipartFile file)
|
||||
MultipartFile file,
|
||||
RedirectAttributes redirectAttributes)
|
||||
throws IOException {
|
||||
if (file == null || file.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(
|
||||
java.util.Map.of(
|
||||
"error",
|
||||
"fileNullOrEmpty",
|
||||
"message",
|
||||
"File is null or empty"));
|
||||
redirectAttributes.addAttribute("error", "fileNullOrEmpty");
|
||||
return "redirect:/database";
|
||||
}
|
||||
log.info("Received file: {}", file.getOriginalFilename());
|
||||
Path tempTemplatePath = Files.createTempFile("backup_", ".sql");
|
||||
@@ -60,31 +58,15 @@ public class DatabaseController {
|
||||
Files.copy(in, tempTemplatePath, StandardCopyOption.REPLACE_EXISTING);
|
||||
boolean importSuccess = databaseService.importDatabaseFromUI(tempTemplatePath);
|
||||
if (importSuccess) {
|
||||
return ResponseEntity.ok(
|
||||
java.util.Map.of(
|
||||
"message",
|
||||
"importIntoDatabaseSuccessed",
|
||||
"description",
|
||||
"Database imported successfully"));
|
||||
redirectAttributes.addAttribute("infoMessage", "importIntoDatabaseSuccessed");
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(
|
||||
java.util.Map.of(
|
||||
"error",
|
||||
"failedImportFile",
|
||||
"message",
|
||||
"Failed to import database file"));
|
||||
redirectAttributes.addAttribute("error", "failedImportFile");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error importing database: {}", e.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(
|
||||
java.util.Map.of(
|
||||
"error",
|
||||
"failedImportFile",
|
||||
"message",
|
||||
"Failed to import database: " + e.getMessage()));
|
||||
redirectAttributes.addAttribute("error", "failedImportFile");
|
||||
}
|
||||
return "redirect:/database";
|
||||
}
|
||||
|
||||
@Hidden
|
||||
@@ -92,17 +74,11 @@ public class DatabaseController {
|
||||
summary = "Import database backup by filename",
|
||||
description = "Imports a database backup file from the server using its file name.")
|
||||
@GetMapping("/import-database-file/{fileName}")
|
||||
public ResponseEntity<?> importDatabaseFromBackupUI(
|
||||
public String importDatabaseFromBackupUI(
|
||||
@Parameter(description = "Name of the file to import", required = true) @PathVariable
|
||||
String fileName) {
|
||||
if (fileName == null || fileName.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(
|
||||
java.util.Map.of(
|
||||
"error",
|
||||
"fileNullOrEmpty",
|
||||
"message",
|
||||
"File name is null or empty"));
|
||||
return "redirect:/database?error=fileNullOrEmpty";
|
||||
}
|
||||
// Check if the file exists in the backup list
|
||||
boolean fileExists =
|
||||
@@ -110,31 +86,14 @@ public class DatabaseController {
|
||||
.anyMatch(backup -> backup.getFileName().equals(fileName));
|
||||
if (!fileExists) {
|
||||
log.error("File {} not found in backup list", fileName);
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(
|
||||
java.util.Map.of(
|
||||
"error",
|
||||
"fileNotFound",
|
||||
"message",
|
||||
"File not found in backup list"));
|
||||
return "redirect:/database?error=fileNotFound";
|
||||
}
|
||||
log.info("Received file: {}", fileName);
|
||||
if (databaseService.importDatabaseFromUI(fileName)) {
|
||||
log.info("File {} imported to database", fileName);
|
||||
return ResponseEntity.ok(
|
||||
java.util.Map.of(
|
||||
"message",
|
||||
"importIntoDatabaseSuccessed",
|
||||
"description",
|
||||
"Database backup imported successfully"));
|
||||
return "redirect:/database?infoMessage=importIntoDatabaseSuccessed";
|
||||
}
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(
|
||||
java.util.Map.of(
|
||||
"error",
|
||||
"failedImportFile",
|
||||
"message",
|
||||
"Failed to import database file"));
|
||||
return "redirect:/database?error=failedImportFile";
|
||||
}
|
||||
|
||||
@Hidden
|
||||
@@ -142,42 +101,24 @@ public class DatabaseController {
|
||||
summary = "Delete a database backup file",
|
||||
description = "Deletes a specified database backup file from the server.")
|
||||
@GetMapping("/delete/{fileName}")
|
||||
public ResponseEntity<?> deleteFile(
|
||||
public String deleteFile(
|
||||
@Parameter(description = "Name of the file to delete", required = true) @PathVariable
|
||||
String fileName) {
|
||||
if (fileName == null || fileName.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(
|
||||
java.util.Map.of(
|
||||
"error",
|
||||
"invalidFileName",
|
||||
"message",
|
||||
"File must not be null or empty"));
|
||||
throw new IllegalArgumentException("File must not be null or empty");
|
||||
}
|
||||
try {
|
||||
if (databaseService.deleteBackupFile(fileName)) {
|
||||
log.info("Deleted file: {}", fileName);
|
||||
return ResponseEntity.ok(java.util.Map.of("message", "File deleted successfully"));
|
||||
} else {
|
||||
log.error("Failed to delete file: {}", fileName);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(
|
||||
java.util.Map.of(
|
||||
"error",
|
||||
"failedToDeleteFile",
|
||||
"message",
|
||||
"Failed to delete backup file"));
|
||||
return "redirect:/database?error=failedToDeleteFile";
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error deleting file: {}", e.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(
|
||||
java.util.Map.of(
|
||||
"error",
|
||||
"deleteError",
|
||||
"message",
|
||||
"Error deleting file: " + e.getMessage()));
|
||||
return "redirect:/database?error=" + e.getMessage();
|
||||
}
|
||||
return "redirect:/database";
|
||||
}
|
||||
|
||||
@Hidden
|
||||
@@ -201,29 +142,22 @@ public class DatabaseController {
|
||||
.body(resource);
|
||||
} catch (IOException e) {
|
||||
log.error("Error downloading file: {}", e.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(
|
||||
java.util.Map.of(
|
||||
"error",
|
||||
"downloadFailed",
|
||||
"message",
|
||||
"Failed to download file: " + e.getMessage()));
|
||||
return ResponseEntity.status(HttpStatus.SEE_OTHER_303)
|
||||
.location(URI.create("/database?error=downloadFailed"))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Create a database backup",
|
||||
description = "This endpoint triggers the creation of a database backup.")
|
||||
description =
|
||||
"This endpoint triggers the creation of a database backup and redirects to the"
|
||||
+ " database management page.")
|
||||
@GetMapping("/createDatabaseBackup")
|
||||
public ResponseEntity<?> createDatabaseBackup() {
|
||||
public String createDatabaseBackup() {
|
||||
log.info("Starting database backup creation...");
|
||||
databaseService.exportDatabase();
|
||||
log.info("Database backup successfully created.");
|
||||
return ResponseEntity.ok(
|
||||
java.util.Map.of(
|
||||
"message",
|
||||
"backupCreated",
|
||||
"description",
|
||||
"Database backup created successfully"));
|
||||
return "redirect:/database?infoMessage=backupCreated";
|
||||
}
|
||||
}
|
||||
|
||||
-484
@@ -1,484 +0,0 @@
|
||||
package stirling.software.proprietary.security.controller.api;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.annotations.api.UserApi;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.enumeration.Role;
|
||||
import stirling.software.proprietary.model.Team;
|
||||
import stirling.software.proprietary.security.model.InviteToken;
|
||||
import stirling.software.proprietary.security.repository.InviteTokenRepository;
|
||||
import stirling.software.proprietary.security.repository.TeamRepository;
|
||||
import stirling.software.proprietary.security.service.EmailService;
|
||||
import stirling.software.proprietary.security.service.TeamService;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
|
||||
@UserApi
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/invite")
|
||||
public class InviteLinkController {
|
||||
|
||||
private final InviteTokenRepository inviteTokenRepository;
|
||||
private final TeamRepository teamRepository;
|
||||
private final UserService userService;
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final Optional<EmailService> emailService;
|
||||
|
||||
/**
|
||||
* Generate a new invite link (admin only)
|
||||
*
|
||||
* @param email The email address to invite
|
||||
* @param role The role to assign (default: ROLE_USER)
|
||||
* @param teamId The team to assign (optional, uses default team if not provided)
|
||||
* @param expiryHours Custom expiry hours (optional, uses default from config)
|
||||
* @param sendEmail Whether to send the invite link via email (default: false)
|
||||
* @param principal The authenticated admin user
|
||||
* @param request The HTTP request
|
||||
* @return ResponseEntity with the invite link or error
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/generate")
|
||||
public ResponseEntity<?> generateInviteLink(
|
||||
@RequestParam(name = "email", required = false) String email,
|
||||
@RequestParam(name = "role", defaultValue = "ROLE_USER") String role,
|
||||
@RequestParam(name = "teamId", required = false) Long teamId,
|
||||
@RequestParam(name = "expiryHours", required = false) Integer expiryHours,
|
||||
@RequestParam(name = "sendEmail", defaultValue = "false") boolean sendEmail,
|
||||
Principal principal,
|
||||
HttpServletRequest request) {
|
||||
|
||||
try {
|
||||
// Check if email invites are enabled
|
||||
if (!applicationProperties.getMail().isEnableInvites()) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Email invites are not enabled"));
|
||||
}
|
||||
|
||||
// If email is provided, validate and check for conflicts
|
||||
if (email != null && !email.trim().isEmpty()) {
|
||||
// Validate email format
|
||||
if (!email.contains("@")) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Invalid email address"));
|
||||
}
|
||||
|
||||
email = email.trim().toLowerCase();
|
||||
|
||||
// Check if user already exists
|
||||
if (userService.usernameExistsIgnoreCase(email)) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", "User already exists"));
|
||||
}
|
||||
|
||||
// Check if there's already an active invite for this email
|
||||
Optional<InviteToken> existingInvite = inviteTokenRepository.findByEmail(email);
|
||||
if (existingInvite.isPresent() && existingInvite.get().isValid()) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"An active invite already exists for this email address"));
|
||||
}
|
||||
|
||||
// If sendEmail is requested but no email provided, reject
|
||||
if (sendEmail) {
|
||||
// Email will be sent
|
||||
}
|
||||
} else {
|
||||
// No email provided - this is a general invite link
|
||||
email = null; // Ensure it's null, not empty string
|
||||
|
||||
// Cannot send email if no email address provided
|
||||
if (sendEmail) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot send email without an email address"));
|
||||
}
|
||||
}
|
||||
|
||||
// Check license limits
|
||||
if (applicationProperties.getPremium().isEnabled()) {
|
||||
long currentUserCount = userService.getTotalUsersCount();
|
||||
long activeInvites = inviteTokenRepository.countActiveInvites(LocalDateTime.now());
|
||||
int maxUsers = applicationProperties.getPremium().getMaxUsers();
|
||||
|
||||
if (currentUserCount + activeInvites >= maxUsers) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"Maximum number of users reached for your license"));
|
||||
}
|
||||
}
|
||||
|
||||
// Validate role
|
||||
try {
|
||||
Role roleEnum = Role.fromString(role);
|
||||
if (roleEnum == Role.INTERNAL_API_USER) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot assign INTERNAL_API_USER role"));
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Invalid role specified"));
|
||||
}
|
||||
|
||||
// Determine team
|
||||
Long effectiveTeamId = teamId;
|
||||
if (effectiveTeamId == null) {
|
||||
Team defaultTeam =
|
||||
teamRepository.findByName(TeamService.DEFAULT_TEAM_NAME).orElse(null);
|
||||
if (defaultTeam != null) {
|
||||
effectiveTeamId = defaultTeam.getId();
|
||||
}
|
||||
} else {
|
||||
Team selectedTeam = teamRepository.findById(effectiveTeamId).orElse(null);
|
||||
if (selectedTeam != null
|
||||
&& TeamService.INTERNAL_TEAM_NAME.equals(selectedTeam.getName())) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot assign users to Internal team"));
|
||||
}
|
||||
}
|
||||
|
||||
// Generate token
|
||||
String token = UUID.randomUUID().toString();
|
||||
|
||||
// Determine expiry time
|
||||
int effectiveExpiryHours =
|
||||
(expiryHours != null && expiryHours > 0)
|
||||
? expiryHours
|
||||
: applicationProperties.getMail().getInviteLinkExpiryHours();
|
||||
LocalDateTime expiresAt = LocalDateTime.now().plusHours(effectiveExpiryHours);
|
||||
|
||||
// Create invite token
|
||||
InviteToken inviteToken = new InviteToken();
|
||||
inviteToken.setToken(token);
|
||||
inviteToken.setEmail(email);
|
||||
inviteToken.setRole(role);
|
||||
inviteToken.setTeamId(effectiveTeamId);
|
||||
inviteToken.setExpiresAt(expiresAt);
|
||||
inviteToken.setCreatedBy(principal.getName());
|
||||
|
||||
inviteTokenRepository.save(inviteToken);
|
||||
|
||||
// Build invite URL
|
||||
// Use configured frontend URL if available, otherwise fall back to backend URL
|
||||
String baseUrl;
|
||||
String configuredFrontendUrl = applicationProperties.getSystem().getFrontendUrl();
|
||||
if (configuredFrontendUrl != null && !configuredFrontendUrl.trim().isEmpty()) {
|
||||
// Use configured frontend URL (remove trailing slash if present)
|
||||
baseUrl =
|
||||
configuredFrontendUrl.endsWith("/")
|
||||
? configuredFrontendUrl.substring(
|
||||
0, configuredFrontendUrl.length() - 1)
|
||||
: configuredFrontendUrl;
|
||||
} else {
|
||||
// Fall back to backend URL from request
|
||||
baseUrl =
|
||||
request.getScheme()
|
||||
+ "://"
|
||||
+ request.getServerName()
|
||||
+ (request.getServerPort() != 80 && request.getServerPort() != 443
|
||||
? ":" + request.getServerPort()
|
||||
: "");
|
||||
}
|
||||
String inviteUrl = baseUrl + "/invite?token=" + token;
|
||||
|
||||
log.info("Generated invite link for {} by {}", email, principal.getName());
|
||||
|
||||
// Optionally send email
|
||||
boolean emailSent = false;
|
||||
String emailError = null;
|
||||
if (sendEmail) {
|
||||
if (!emailService.isPresent()) {
|
||||
emailError = "Email service is not configured";
|
||||
log.warn("Cannot send invite email: Email service not configured");
|
||||
} else {
|
||||
try {
|
||||
emailService
|
||||
.get()
|
||||
.sendInviteLinkEmail(email, inviteUrl, expiresAt.toString());
|
||||
emailSent = true;
|
||||
log.info("Sent invite link email to: {}", email);
|
||||
} catch (Exception emailEx) {
|
||||
emailError = emailEx.getMessage();
|
||||
log.error(
|
||||
"Failed to send invite email to {}: {}",
|
||||
email,
|
||||
emailEx.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("token", token);
|
||||
response.put("inviteUrl", inviteUrl);
|
||||
response.put("email", email);
|
||||
response.put("expiresAt", expiresAt.toString());
|
||||
response.put("expiryHours", effectiveExpiryHours);
|
||||
if (sendEmail) {
|
||||
response.put("emailSent", emailSent);
|
||||
if (emailError != null) {
|
||||
response.put("emailError", emailError);
|
||||
}
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to generate invite link: {}", e.getMessage(), e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(Map.of("error", "Failed to generate invite link: " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List all active invite links (admin only)
|
||||
*
|
||||
* @return List of active invite tokens
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping("/list")
|
||||
public ResponseEntity<?> listInviteLinks() {
|
||||
try {
|
||||
List<InviteToken> activeInvites =
|
||||
inviteTokenRepository.findByUsedFalseAndExpiresAtAfter(LocalDateTime.now());
|
||||
|
||||
List<Map<String, Object>> inviteList =
|
||||
activeInvites.stream()
|
||||
.map(
|
||||
invite -> {
|
||||
Map<String, Object> inviteMap = new HashMap<>();
|
||||
inviteMap.put("id", invite.getId());
|
||||
inviteMap.put("email", invite.getEmail());
|
||||
inviteMap.put("role", invite.getRole());
|
||||
inviteMap.put("teamId", invite.getTeamId());
|
||||
inviteMap.put("createdBy", invite.getCreatedBy());
|
||||
inviteMap.put(
|
||||
"createdAt", invite.getCreatedAt().toString());
|
||||
inviteMap.put(
|
||||
"expiresAt", invite.getExpiresAt().toString());
|
||||
return inviteMap;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return ResponseEntity.ok(Map.of("invites", inviteList));
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to list invite links: {}", e.getMessage(), e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(Map.of("error", "Failed to list invite links"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke an invite link (admin only)
|
||||
*
|
||||
* @param inviteId The invite token ID to revoke
|
||||
* @return Success or error response
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@DeleteMapping("/revoke/{inviteId}")
|
||||
public ResponseEntity<?> revokeInviteLink(@PathVariable Long inviteId) {
|
||||
try {
|
||||
Optional<InviteToken> inviteOpt = inviteTokenRepository.findById(inviteId);
|
||||
if (inviteOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "Invite not found"));
|
||||
}
|
||||
|
||||
inviteTokenRepository.deleteById(inviteId);
|
||||
log.info("Revoked invite link ID: {}", inviteId);
|
||||
|
||||
return ResponseEntity.ok(Map.of("message", "Invite link revoked successfully"));
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to revoke invite link: {}", e.getMessage(), e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(Map.of("error", "Failed to revoke invite link"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up expired invite tokens (admin only)
|
||||
*
|
||||
* @return Number of deleted tokens
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/cleanup")
|
||||
public ResponseEntity<?> cleanupExpiredInvites() {
|
||||
try {
|
||||
List<InviteToken> expiredInvites =
|
||||
inviteTokenRepository.findAll().stream()
|
||||
.filter(invite -> !invite.isValid())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
int count = expiredInvites.size();
|
||||
inviteTokenRepository.deleteAll(expiredInvites);
|
||||
|
||||
log.info("Cleaned up {} expired invite tokens", count);
|
||||
|
||||
return ResponseEntity.ok(Map.of("deletedCount", count));
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to cleanup expired invites: {}", e.getMessage(), e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(Map.of("error", "Failed to cleanup expired invites"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an invite token (public endpoint)
|
||||
*
|
||||
* @param token The invite token to validate
|
||||
* @return Invite details if valid, error otherwise
|
||||
*/
|
||||
@GetMapping("/validate/{token}")
|
||||
public ResponseEntity<?> validateInviteToken(@PathVariable String token) {
|
||||
try {
|
||||
Optional<InviteToken> inviteOpt = inviteTokenRepository.findByToken(token);
|
||||
|
||||
if (inviteOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "Invalid invite link"));
|
||||
}
|
||||
|
||||
InviteToken invite = inviteOpt.get();
|
||||
|
||||
if (invite.isUsed()) {
|
||||
return ResponseEntity.status(HttpStatus.GONE)
|
||||
.body(Map.of("error", "This invite link has already been used"));
|
||||
}
|
||||
|
||||
if (invite.isExpired()) {
|
||||
return ResponseEntity.status(HttpStatus.GONE)
|
||||
.body(Map.of("error", "This invite link has expired"));
|
||||
}
|
||||
|
||||
// Check if user already exists (only if email is pre-set)
|
||||
if (invite.getEmail() != null
|
||||
&& userService.usernameExistsIgnoreCase(invite.getEmail())) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", "User already exists"));
|
||||
}
|
||||
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("email", invite.getEmail());
|
||||
response.put("role", invite.getRole());
|
||||
response.put("expiresAt", invite.getExpiresAt().toString());
|
||||
response.put("emailRequired", invite.getEmail() == null);
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to validate invite token: {}", e.getMessage(), e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(Map.of("error", "Failed to validate invite link"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept an invite and create user account (public endpoint)
|
||||
*
|
||||
* @param token The invite token
|
||||
* @param email The email address (required if not pre-set in invite)
|
||||
* @param password The password to set for the new account
|
||||
* @return Success or error response
|
||||
*/
|
||||
@PostMapping("/accept/{token}")
|
||||
public ResponseEntity<?> acceptInvite(
|
||||
@PathVariable String token,
|
||||
@RequestParam(name = "email", required = false) String email,
|
||||
@RequestParam(name = "password") String password) {
|
||||
try {
|
||||
// Validate password
|
||||
if (password == null || password.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Password is required"));
|
||||
}
|
||||
|
||||
Optional<InviteToken> inviteOpt = inviteTokenRepository.findByToken(token);
|
||||
|
||||
if (inviteOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "Invalid invite link"));
|
||||
}
|
||||
|
||||
InviteToken invite = inviteOpt.get();
|
||||
|
||||
if (invite.isUsed()) {
|
||||
return ResponseEntity.status(HttpStatus.GONE)
|
||||
.body(Map.of("error", "This invite link has already been used"));
|
||||
}
|
||||
|
||||
if (invite.isExpired()) {
|
||||
return ResponseEntity.status(HttpStatus.GONE)
|
||||
.body(Map.of("error", "This invite link has expired"));
|
||||
}
|
||||
|
||||
// Determine the email to use
|
||||
String effectiveEmail = invite.getEmail();
|
||||
if (effectiveEmail == null) {
|
||||
// Email not pre-set, must be provided by user
|
||||
if (email == null || email.trim().isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Email address is required"));
|
||||
}
|
||||
|
||||
// Validate email format
|
||||
if (!email.contains("@")) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Invalid email address"));
|
||||
}
|
||||
|
||||
effectiveEmail = email.trim().toLowerCase();
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
if (userService.usernameExistsIgnoreCase(effectiveEmail)) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", "User already exists"));
|
||||
}
|
||||
|
||||
// Create the user account
|
||||
userService.saveUser(
|
||||
effectiveEmail,
|
||||
password,
|
||||
invite.getTeamId(),
|
||||
invite.getRole(),
|
||||
false); // Don't force password change
|
||||
|
||||
// Mark invite as used
|
||||
invite.setUsed(true);
|
||||
invite.setUsedAt(LocalDateTime.now());
|
||||
inviteTokenRepository.save(invite);
|
||||
|
||||
log.info(
|
||||
"User account created via invite link: {} with role: {}",
|
||||
effectiveEmail,
|
||||
invite.getRole());
|
||||
|
||||
return ResponseEntity.ok(
|
||||
Map.of("message", "Account created successfully", "username", effectiveEmail));
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to accept invite: {}", e.getMessage(), e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(Map.of("error", "Failed to create account: " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
-44
@@ -1,12 +1,10 @@
|
||||
package stirling.software.proprietary.security.controller.api;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.view.RedirectView;
|
||||
|
||||
import jakarta.transaction.Transactional;
|
||||
|
||||
@@ -32,113 +30,98 @@ public class TeamController {
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/create")
|
||||
public ResponseEntity<?> createTeam(@RequestParam("name") String name) {
|
||||
public RedirectView createTeam(@RequestParam("name") String name) {
|
||||
if (teamRepository.existsByNameIgnoreCase(name)) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", "Team name already exists."));
|
||||
return new RedirectView("/teams?messageType=teamExists");
|
||||
}
|
||||
Team team = new Team();
|
||||
team.setName(name);
|
||||
teamRepository.save(team);
|
||||
return ResponseEntity.ok(Map.of("message", "Team created successfully"));
|
||||
return new RedirectView("/teams?messageType=teamCreated");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/rename")
|
||||
public ResponseEntity<?> renameTeam(
|
||||
public RedirectView renameTeam(
|
||||
@RequestParam("teamId") Long teamId, @RequestParam("newName") String newName) {
|
||||
Optional<Team> existing = teamRepository.findById(teamId);
|
||||
if (existing.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "Team not found."));
|
||||
return new RedirectView("/teams?messageType=teamNotFound");
|
||||
}
|
||||
if (teamRepository.existsByNameIgnoreCase(newName)) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", "Team name already exists."));
|
||||
return new RedirectView("/teams?messageType=teamNameExists");
|
||||
}
|
||||
Team team = existing.get();
|
||||
|
||||
// Prevent renaming the Internal team
|
||||
if (team.getName().equals(TeamService.INTERNAL_TEAM_NAME)) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot rename Internal team."));
|
||||
return new RedirectView("/teams?messageType=internalTeamNotAccessible");
|
||||
}
|
||||
|
||||
team.setName(newName);
|
||||
teamRepository.save(team);
|
||||
return ResponseEntity.ok(Map.of("message", "Team renamed successfully"));
|
||||
return new RedirectView("/teams?messageType=teamRenamed");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/delete")
|
||||
@Transactional
|
||||
public ResponseEntity<?> deleteTeam(@RequestParam("teamId") Long teamId) {
|
||||
public RedirectView deleteTeam(@RequestParam("teamId") Long teamId) {
|
||||
Optional<Team> teamOpt = teamRepository.findById(teamId);
|
||||
if (teamOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "Team not found."));
|
||||
return new RedirectView("/teams?messageType=teamNotFound");
|
||||
}
|
||||
|
||||
Team team = teamOpt.get();
|
||||
|
||||
// Prevent deleting the Internal team
|
||||
if (team.getName().equals(TeamService.INTERNAL_TEAM_NAME)) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot delete Internal team."));
|
||||
return new RedirectView("/teams?messageType=internalTeamNotAccessible");
|
||||
}
|
||||
|
||||
long memberCount = userRepository.countByTeam(team);
|
||||
if (memberCount > 0) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"Team must be empty before deletion. Please remove all members first."));
|
||||
return new RedirectView("/teams?messageType=teamHasUsers");
|
||||
}
|
||||
|
||||
teamRepository.delete(team);
|
||||
return ResponseEntity.ok(Map.of("message", "Team deleted successfully"));
|
||||
return new RedirectView("/teams?messageType=teamDeleted");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/addUser")
|
||||
@Transactional
|
||||
public ResponseEntity<?> addUserToTeam(
|
||||
public RedirectView addUserToTeam(
|
||||
@RequestParam("teamId") Long teamId, @RequestParam("userId") Long userId) {
|
||||
|
||||
// Find the team
|
||||
Optional<Team> teamOpt = teamRepository.findById(teamId);
|
||||
if (teamOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "Team not found."));
|
||||
}
|
||||
Team team = teamOpt.get();
|
||||
Team team =
|
||||
teamRepository
|
||||
.findById(teamId)
|
||||
.orElseThrow(() -> new RuntimeException("Team not found"));
|
||||
|
||||
// Prevent adding users to the Internal team
|
||||
if (team.getName().equals(TeamService.INTERNAL_TEAM_NAME)) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot add users to Internal team."));
|
||||
return new RedirectView("/teams?error=internalTeamNotAccessible");
|
||||
}
|
||||
|
||||
// Find the user
|
||||
Optional<User> userOpt = userRepository.findById(userId);
|
||||
if (userOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "User not found."));
|
||||
}
|
||||
User user = userOpt.get();
|
||||
User user =
|
||||
userRepository
|
||||
.findById(userId)
|
||||
.orElseThrow(() -> new RuntimeException("User not found"));
|
||||
|
||||
// Check if user is in the Internal team - prevent moving them
|
||||
if (user.getTeam() != null
|
||||
&& user.getTeam().getName().equals(TeamService.INTERNAL_TEAM_NAME)) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot move users from Internal team."));
|
||||
return new RedirectView("/teams/" + teamId + "?error=cannotMoveInternalUsers");
|
||||
}
|
||||
|
||||
// Assign user to team
|
||||
user.setTeam(team);
|
||||
userRepository.save(user);
|
||||
|
||||
return ResponseEntity.ok(Map.of("message", "User added to team successfully"));
|
||||
// Redirect back to team details page
|
||||
return new RedirectView("/teams/" + teamId + "?messageType=userAdded");
|
||||
}
|
||||
}
|
||||
|
||||
+77
-314
@@ -17,6 +17,8 @@ import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.oauth2.core.user.OAuth2User;
|
||||
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
import org.springframework.web.servlet.view.RedirectView;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
@@ -36,11 +38,9 @@ import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.model.api.user.UsernameAndPass;
|
||||
import stirling.software.proprietary.security.repository.TeamRepository;
|
||||
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
|
||||
import stirling.software.proprietary.security.service.EmailService;
|
||||
import stirling.software.proprietary.security.service.TeamService;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
|
||||
import stirling.software.proprietary.service.UserLicenseSettingsService;
|
||||
|
||||
@UserApi
|
||||
@Slf4j
|
||||
@@ -53,8 +53,6 @@ public class UserController {
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final TeamRepository teamRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final Optional<EmailService> emailService;
|
||||
private final UserLicenseSettingsService licenseSettingsService;
|
||||
|
||||
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
|
||||
@PostMapping("/register")
|
||||
@@ -79,9 +77,10 @@ public class UserController {
|
||||
.body(Map.of("error", "Invalid username format"));
|
||||
}
|
||||
|
||||
if (usernameAndPass.getPassword() == null || usernameAndPass.getPassword().isEmpty()) {
|
||||
if (usernameAndPass.getPassword() == null
|
||||
|| usernameAndPass.getPassword().length() < 6) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Password is required"));
|
||||
.body(Map.of("error", "Password must be at least 6 characters"));
|
||||
}
|
||||
|
||||
Team team = teamRepository.findByName(TeamService.DEFAULT_TEAM_NAME).orElse(null);
|
||||
@@ -138,130 +137,100 @@ public class UserController {
|
||||
|
||||
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
|
||||
@PostMapping("/change-username")
|
||||
public ResponseEntity<?> changeUsername(
|
||||
public RedirectView changeUsername(
|
||||
Principal principal,
|
||||
@RequestParam(name = "currentPasswordChangeUsername") String currentPassword,
|
||||
@RequestParam(name = "newUsername") String newUsername,
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response)
|
||||
HttpServletResponse response,
|
||||
RedirectAttributes redirectAttributes)
|
||||
throws IOException, SQLException, UnsupportedProviderException {
|
||||
if (!userService.isUsernameValid(newUsername)) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "invalidUsername", "message", "Invalid username format"));
|
||||
return new RedirectView("/account?messageType=invalidUsername", true);
|
||||
}
|
||||
if (principal == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(Map.of("error", "notAuthenticated", "message", "User not authenticated"));
|
||||
return new RedirectView("/account?messageType=notAuthenticated", true);
|
||||
}
|
||||
// The username MUST be unique when renaming
|
||||
Optional<User> userOpt = userService.findByUsername(principal.getName());
|
||||
if (userOpt == null || userOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "userNotFound", "message", "User not found"));
|
||||
return new RedirectView("/account?messageType=userNotFound", true);
|
||||
}
|
||||
User user = userOpt.get();
|
||||
if (user.getUsername().equals(newUsername)) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", "usernameExists", "message", "Username already in use"));
|
||||
return new RedirectView("/account?messageType=usernameExists", true);
|
||||
}
|
||||
if (!userService.isPasswordCorrect(user, currentPassword)) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(Map.of("error", "incorrectPassword", "message", "Incorrect password"));
|
||||
return new RedirectView("/account?messageType=incorrectPassword", true);
|
||||
}
|
||||
if (!user.getUsername().equals(newUsername) && userService.usernameExists(newUsername)) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", "usernameExists", "message", "Username already exists"));
|
||||
return new RedirectView("/account?messageType=usernameExists", true);
|
||||
}
|
||||
if (newUsername != null && newUsername.length() > 0) {
|
||||
try {
|
||||
userService.changeUsername(user, newUsername);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"invalidUsername",
|
||||
"message",
|
||||
"Invalid username format"));
|
||||
return new RedirectView("/account?messageType=invalidUsername", true);
|
||||
}
|
||||
}
|
||||
// Logout using Spring's utility
|
||||
new SecurityContextLogoutHandler().logout(request, response, null);
|
||||
return ResponseEntity.ok(
|
||||
Map.of(
|
||||
"message",
|
||||
"credsUpdated",
|
||||
"description",
|
||||
"Username changed successfully. Please log in again."));
|
||||
return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED, true);
|
||||
}
|
||||
|
||||
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
|
||||
@PostMapping("/change-password-on-login")
|
||||
public ResponseEntity<?> changePasswordOnLogin(
|
||||
public RedirectView changePasswordOnLogin(
|
||||
Principal principal,
|
||||
@RequestParam(name = "currentPassword") String currentPassword,
|
||||
@RequestParam(name = "newPassword") String newPassword,
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response)
|
||||
HttpServletResponse response,
|
||||
RedirectAttributes redirectAttributes)
|
||||
throws SQLException, UnsupportedProviderException {
|
||||
if (principal == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(Map.of("error", "notAuthenticated", "message", "User not authenticated"));
|
||||
return new RedirectView("/change-creds?messageType=notAuthenticated", true);
|
||||
}
|
||||
Optional<User> userOpt = userService.findByUsernameIgnoreCase(principal.getName());
|
||||
if (userOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "userNotFound", "message", "User not found"));
|
||||
return new RedirectView("/change-creds?messageType=userNotFound", true);
|
||||
}
|
||||
User user = userOpt.get();
|
||||
if (!userService.isPasswordCorrect(user, currentPassword)) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(Map.of("error", "incorrectPassword", "message", "Incorrect password"));
|
||||
return new RedirectView("/change-creds?messageType=incorrectPassword", true);
|
||||
}
|
||||
userService.changePassword(user, newPassword);
|
||||
userService.changeFirstUse(user, false);
|
||||
// Logout using Spring's utility
|
||||
new SecurityContextLogoutHandler().logout(request, response, null);
|
||||
return ResponseEntity.ok(
|
||||
Map.of(
|
||||
"message",
|
||||
"credsUpdated",
|
||||
"description",
|
||||
"Password changed successfully. Please log in again."));
|
||||
return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED, true);
|
||||
}
|
||||
|
||||
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
|
||||
@PostMapping("/change-password")
|
||||
public ResponseEntity<?> changePassword(
|
||||
public RedirectView changePassword(
|
||||
Principal principal,
|
||||
@RequestParam(name = "currentPassword") String currentPassword,
|
||||
@RequestParam(name = "newPassword") String newPassword,
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response)
|
||||
HttpServletResponse response,
|
||||
RedirectAttributes redirectAttributes)
|
||||
throws SQLException, UnsupportedProviderException {
|
||||
if (principal == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(Map.of("error", "notAuthenticated", "message", "User not authenticated"));
|
||||
return new RedirectView("/account?messageType=notAuthenticated", true);
|
||||
}
|
||||
Optional<User> userOpt = userService.findByUsernameIgnoreCase(principal.getName());
|
||||
if (userOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "userNotFound", "message", "User not found"));
|
||||
return new RedirectView("/account?messageType=userNotFound", true);
|
||||
}
|
||||
User user = userOpt.get();
|
||||
if (!userService.isPasswordCorrect(user, currentPassword)) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(Map.of("error", "incorrectPassword", "message", "Incorrect password"));
|
||||
return new RedirectView("/account?messageType=incorrectPassword", true);
|
||||
}
|
||||
userService.changePassword(user, newPassword);
|
||||
// Logout using Spring's utility
|
||||
new SecurityContextLogoutHandler().logout(request, response, null);
|
||||
return ResponseEntity.ok(
|
||||
Map.of(
|
||||
"message",
|
||||
"credsUpdated",
|
||||
"description",
|
||||
"Password changed successfully. Please log in again."));
|
||||
return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED, true);
|
||||
}
|
||||
|
||||
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
|
||||
@@ -279,23 +248,23 @@ public class UserController {
|
||||
* </ul>
|
||||
* Keys not listed above will be ignored.
|
||||
* @param principal The currently authenticated user.
|
||||
* @return A ResponseEntity with success or error information.
|
||||
* @return A redirect string to the account page after updating the settings.
|
||||
* @throws SQLException If a database error occurs.
|
||||
* @throws UnsupportedProviderException If the operation is not supported for the user's
|
||||
* provider.
|
||||
*/
|
||||
public ResponseEntity<?> updateUserSettings(
|
||||
@RequestBody Map<String, String> updates, Principal principal)
|
||||
public String updateUserSettings(@RequestBody Map<String, String> updates, Principal principal)
|
||||
throws SQLException, UnsupportedProviderException {
|
||||
log.debug("Processed updates: {}", updates);
|
||||
// Assuming you have a method in userService to update the settings for a user
|
||||
userService.updateUserSettings(principal.getName(), updates);
|
||||
return ResponseEntity.ok(Map.of("message", "Settings updated successfully"));
|
||||
// Redirect to a page of your choice after updating
|
||||
return "redirect:/account";
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/admin/saveUser")
|
||||
public ResponseEntity<?> saveUser(
|
||||
public RedirectView saveUser(
|
||||
@RequestParam(name = "username", required = true) String username,
|
||||
@RequestParam(name = "password", required = false) String password,
|
||||
@RequestParam(name = "role") String role,
|
||||
@@ -305,48 +274,33 @@ public class UserController {
|
||||
boolean forceChange)
|
||||
throws IllegalArgumentException, SQLException, UnsupportedProviderException {
|
||||
if (!userService.isUsernameValid(username)) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"Invalid username format. Username must be 3-50 characters."));
|
||||
return new RedirectView("/adminSettings?messageType=invalidUsername", true);
|
||||
}
|
||||
if (licenseSettingsService.wouldExceedLimit(1)) {
|
||||
long availableSlots = licenseSettingsService.getAvailableUserSlots();
|
||||
int maxAllowed = licenseSettingsService.calculateMaxAllowedUsers();
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"Maximum number of users reached. Allowed: "
|
||||
+ maxAllowed
|
||||
+ ", Available slots: "
|
||||
+ availableSlots));
|
||||
if (applicationProperties.getPremium().isEnabled()
|
||||
&& applicationProperties.getPremium().getMaxUsers()
|
||||
<= userService.getTotalUsersCount()) {
|
||||
return new RedirectView("/adminSettings?messageType=maxUsersReached", true);
|
||||
}
|
||||
Optional<User> userOpt = userService.findByUsernameIgnoreCase(username);
|
||||
if (userOpt.isPresent()) {
|
||||
User user = userOpt.get();
|
||||
if (user.getUsername().equalsIgnoreCase(username)) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", "Username already exists."));
|
||||
return new RedirectView("/adminSettings?messageType=usernameExists", true);
|
||||
}
|
||||
}
|
||||
if (userService.usernameExistsIgnoreCase(username)) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", "Username already exists."));
|
||||
return new RedirectView("/adminSettings?messageType=usernameExists", true);
|
||||
}
|
||||
try {
|
||||
// Validate the role
|
||||
Role roleEnum = Role.fromString(role);
|
||||
if (roleEnum == Role.INTERNAL_API_USER) {
|
||||
// If the role is INTERNAL_API_USER, reject the request
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot assign INTERNAL_API_USER role."));
|
||||
return new RedirectView("/adminSettings?messageType=invalidRole", true);
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
// If the role ID is not valid, return error
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Invalid role specified."));
|
||||
// If the role ID is not valid, redirect with an error message
|
||||
return new RedirectView("/adminSettings?messageType=invalidRole", true);
|
||||
}
|
||||
|
||||
// Use teamId if provided, otherwise use default team
|
||||
@@ -362,143 +316,28 @@ public class UserController {
|
||||
Team selectedTeam = teamRepository.findById(effectiveTeamId).orElse(null);
|
||||
if (selectedTeam != null
|
||||
&& TeamService.INTERNAL_TEAM_NAME.equals(selectedTeam.getName())) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot assign users to Internal team."));
|
||||
return new RedirectView(
|
||||
"/adminSettings?messageType=internalTeamNotAccessible", true);
|
||||
}
|
||||
}
|
||||
|
||||
if (authType.equalsIgnoreCase(AuthenticationType.SSO.toString())) {
|
||||
userService.saveUser(username, AuthenticationType.SSO, effectiveTeamId, role);
|
||||
} else {
|
||||
if (password == null || password.isBlank()) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Password is required."));
|
||||
}
|
||||
if (password.length() < 6) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Password must be at least 6 characters."));
|
||||
if (password.isBlank()) {
|
||||
return new RedirectView("/adminSettings?messageType=invalidPassword", true);
|
||||
}
|
||||
userService.saveUser(username, password, effectiveTeamId, role, forceChange);
|
||||
}
|
||||
return ResponseEntity.ok(Map.of("message", "User created successfully"));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/admin/inviteUsers")
|
||||
public ResponseEntity<?> inviteUsers(
|
||||
@RequestParam(name = "emails", required = true) String emails,
|
||||
@RequestParam(name = "role", defaultValue = "ROLE_USER") String role,
|
||||
@RequestParam(name = "teamId", required = false) Long teamId)
|
||||
throws SQLException, UnsupportedProviderException {
|
||||
|
||||
// Check if email invites are enabled
|
||||
if (!applicationProperties.getMail().isEnableInvites()) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Email invites are not enabled"));
|
||||
}
|
||||
|
||||
// Check if email service is available
|
||||
if (!emailService.isPresent()) {
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"Email service is not configured. Please configure SMTP settings."));
|
||||
}
|
||||
|
||||
// Parse comma-separated email addresses
|
||||
String[] emailArray = emails.split(",");
|
||||
if (emailArray.length == 0) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "At least one email address is required"));
|
||||
}
|
||||
|
||||
// Check license limits
|
||||
if (licenseSettingsService.wouldExceedLimit(emailArray.length)) {
|
||||
long availableSlots = licenseSettingsService.getAvailableUserSlots();
|
||||
int maxAllowed = licenseSettingsService.calculateMaxAllowedUsers();
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"Not enough user slots available. Allowed: "
|
||||
+ maxAllowed
|
||||
+ ", Available: "
|
||||
+ availableSlots
|
||||
+ ", Requested: "
|
||||
+ emailArray.length));
|
||||
}
|
||||
|
||||
// Validate role
|
||||
try {
|
||||
Role roleEnum = Role.fromString(role);
|
||||
if (roleEnum == Role.INTERNAL_API_USER) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot assign INTERNAL_API_USER role"));
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Invalid role specified"));
|
||||
}
|
||||
|
||||
// Determine team
|
||||
Long effectiveTeamId = teamId;
|
||||
if (effectiveTeamId == null) {
|
||||
Team defaultTeam =
|
||||
teamRepository.findByName(TeamService.DEFAULT_TEAM_NAME).orElse(null);
|
||||
if (defaultTeam != null) {
|
||||
effectiveTeamId = defaultTeam.getId();
|
||||
}
|
||||
} else {
|
||||
Team selectedTeam = teamRepository.findById(effectiveTeamId).orElse(null);
|
||||
if (selectedTeam != null
|
||||
&& TeamService.INTERNAL_TEAM_NAME.equals(selectedTeam.getName())) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot assign users to Internal team"));
|
||||
}
|
||||
}
|
||||
|
||||
int successCount = 0;
|
||||
int failureCount = 0;
|
||||
StringBuilder errors = new StringBuilder();
|
||||
|
||||
// Process each email
|
||||
for (String email : emailArray) {
|
||||
email = email.trim();
|
||||
if (email.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
InviteResult result = processEmailInvite(email, effectiveTeamId, role);
|
||||
if (result.isSuccess()) {
|
||||
successCount++;
|
||||
} else {
|
||||
failureCount++;
|
||||
errors.append(result.getErrorMessage()).append("; ");
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("successCount", successCount);
|
||||
response.put("failureCount", failureCount);
|
||||
|
||||
if (failureCount > 0) {
|
||||
response.put("errors", errors.toString());
|
||||
}
|
||||
|
||||
if (successCount > 0) {
|
||||
response.put("message", successCount + " user(s) invited successfully");
|
||||
return ResponseEntity.ok(response);
|
||||
} else {
|
||||
response.put("error", "Failed to invite any users");
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
|
||||
}
|
||||
return new RedirectView(
|
||||
"/adminSettings", // Redirect to account page after adding the user
|
||||
true);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/admin/changeRole")
|
||||
@Transactional
|
||||
public ResponseEntity<?> changeRole(
|
||||
public RedirectView changeRole(
|
||||
@RequestParam(name = "username") String username,
|
||||
@RequestParam(name = "role") String role,
|
||||
@RequestParam(name = "teamId", required = false) Long teamId,
|
||||
@@ -506,32 +345,27 @@ public class UserController {
|
||||
throws SQLException, UnsupportedProviderException {
|
||||
Optional<User> userOpt = userService.findByUsernameIgnoreCase(username);
|
||||
if (!userOpt.isPresent()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "User not found."));
|
||||
return new RedirectView("/adminSettings?messageType=userNotFound", true);
|
||||
}
|
||||
if (!userService.usernameExistsIgnoreCase(username)) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "User not found."));
|
||||
return new RedirectView("/adminSettings?messageType=userNotFound", true);
|
||||
}
|
||||
// Get the currently authenticated username
|
||||
String currentUsername = authentication.getName();
|
||||
// Check if the provided username matches the current session's username
|
||||
if (currentUsername.equalsIgnoreCase(username)) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot change your own role."));
|
||||
return new RedirectView("/adminSettings?messageType=downgradeCurrentUser", true);
|
||||
}
|
||||
try {
|
||||
// Validate the role
|
||||
Role roleEnum = Role.fromString(role);
|
||||
if (roleEnum == Role.INTERNAL_API_USER) {
|
||||
// If the role is INTERNAL_API_USER, reject the request
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot assign INTERNAL_API_USER role."));
|
||||
return new RedirectView("/adminSettings?messageType=invalidRole", true);
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
// If the role ID is not valid, return error
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Invalid role specified."));
|
||||
// If the role ID is not valid, redirect with an error message
|
||||
return new RedirectView("/adminSettings?messageType=invalidRole", true);
|
||||
}
|
||||
User user = userOpt.get();
|
||||
|
||||
@@ -541,15 +375,15 @@ public class UserController {
|
||||
if (team != null) {
|
||||
// Prevent assigning to Internal team
|
||||
if (TeamService.INTERNAL_TEAM_NAME.equals(team.getName())) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot assign users to Internal team."));
|
||||
return new RedirectView(
|
||||
"/adminSettings?messageType=internalTeamNotAccessible", true);
|
||||
}
|
||||
|
||||
// Prevent moving users from Internal team
|
||||
if (user.getTeam() != null
|
||||
&& TeamService.INTERNAL_TEAM_NAME.equals(user.getTeam().getName())) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot move users from Internal team."));
|
||||
return new RedirectView(
|
||||
"/adminSettings?messageType=cannotMoveInternalUsers", true);
|
||||
}
|
||||
|
||||
user.setTeam(team);
|
||||
@@ -558,31 +392,30 @@ public class UserController {
|
||||
}
|
||||
|
||||
userService.changeRole(user, role);
|
||||
return ResponseEntity.ok(Map.of("message", "User role updated successfully"));
|
||||
return new RedirectView(
|
||||
"/adminSettings", // Redirect to account page after adding the user
|
||||
true);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/admin/changeUserEnabled/{username}")
|
||||
public ResponseEntity<?> changeUserEnabled(
|
||||
public RedirectView changeUserEnabled(
|
||||
@PathVariable("username") String username,
|
||||
@RequestParam("enabled") boolean enabled,
|
||||
Authentication authentication)
|
||||
throws SQLException, UnsupportedProviderException {
|
||||
Optional<User> userOpt = userService.findByUsernameIgnoreCase(username);
|
||||
if (userOpt.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "User not found."));
|
||||
return new RedirectView("/adminSettings?messageType=userNotFound", true);
|
||||
}
|
||||
if (!userService.usernameExistsIgnoreCase(username)) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "User not found."));
|
||||
return new RedirectView("/adminSettings?messageType=userNotFound", true);
|
||||
}
|
||||
// Get the currently authenticated username
|
||||
String currentUsername = authentication.getName();
|
||||
// Check if the provided username matches the current session's username
|
||||
if (currentUsername.equalsIgnoreCase(username)) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot disable your own account."));
|
||||
return new RedirectView("/adminSettings?messageType=disabledCurrentUser", true);
|
||||
}
|
||||
User user = userOpt.get();
|
||||
userService.changeUserEnabled(user, enabled);
|
||||
@@ -609,24 +442,23 @@ public class UserController {
|
||||
}
|
||||
}
|
||||
}
|
||||
return ResponseEntity.ok(
|
||||
Map.of("message", "User " + (enabled ? "enabled" : "disabled") + " successfully"));
|
||||
return new RedirectView(
|
||||
"/adminSettings", // Redirect to account page after adding the user
|
||||
true);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/admin/deleteUser/{username}")
|
||||
public ResponseEntity<?> deleteUser(
|
||||
public RedirectView deleteUser(
|
||||
@PathVariable("username") String username, Authentication authentication) {
|
||||
if (!userService.usernameExistsIgnoreCase(username)) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("error", "User not found."));
|
||||
return new RedirectView("/adminSettings?messageType=deleteUsernameExists", true);
|
||||
}
|
||||
// Get the currently authenticated username
|
||||
String currentUsername = authentication.getName();
|
||||
// Check if the provided username matches the current session's username
|
||||
if (currentUsername.equalsIgnoreCase(username)) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("error", "Cannot delete your own account."));
|
||||
return new RedirectView("/adminSettings?messageType=deleteCurrentUser", true);
|
||||
}
|
||||
// Invalidate all sessions before deleting the user
|
||||
List<SessionInformation> sessionsInformations =
|
||||
@@ -636,7 +468,7 @@ public class UserController {
|
||||
sessionRegistry.removeSessionInformation(sessionsInformation.getSessionId());
|
||||
}
|
||||
userService.deleteUser(username);
|
||||
return ResponseEntity.ok(Map.of("message", "User deleted successfully"));
|
||||
return new RedirectView("/adminSettings", true);
|
||||
}
|
||||
|
||||
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
|
||||
@@ -667,73 +499,4 @@ public class UserController {
|
||||
}
|
||||
return ResponseEntity.ok(apiKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to process a single email invitation.
|
||||
*
|
||||
* @param email The email address to invite
|
||||
* @param teamId The team ID to assign the user to
|
||||
* @param role The role to assign to the user
|
||||
* @return InviteResult containing success status and optional error message
|
||||
*/
|
||||
private InviteResult processEmailInvite(String email, Long teamId, String role) {
|
||||
try {
|
||||
// Validate email format (basic check)
|
||||
if (!email.contains("@") || !email.contains(".")) {
|
||||
return InviteResult.failure(email + ": Invalid email format");
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
if (userService.usernameExistsIgnoreCase(email)) {
|
||||
return InviteResult.failure(email + ": User already exists");
|
||||
}
|
||||
|
||||
// Generate random password
|
||||
String temporaryPassword = java.util.UUID.randomUUID().toString().substring(0, 12);
|
||||
|
||||
// Create user with forceChange=true
|
||||
userService.saveUser(email, temporaryPassword, teamId, role, true);
|
||||
|
||||
// Send invite email
|
||||
try {
|
||||
emailService.get().sendInviteEmail(email, email, temporaryPassword);
|
||||
log.info("Sent invite email to: {}", email);
|
||||
return InviteResult.success();
|
||||
} catch (Exception emailEx) {
|
||||
log.error("Failed to send invite email to {}: {}", email, emailEx.getMessage());
|
||||
return InviteResult.failure(email + ": User created but email failed to send");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to invite user {}: {}", email, e.getMessage());
|
||||
return InviteResult.failure(email + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Result object for individual email invite processing. */
|
||||
private static class InviteResult {
|
||||
private final boolean success;
|
||||
private final String errorMessage;
|
||||
|
||||
private InviteResult(boolean success, String errorMessage) {
|
||||
this.success = success;
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
static InviteResult success() {
|
||||
return new InviteResult(true, null);
|
||||
}
|
||||
|
||||
static InviteResult failure(String errorMessage) {
|
||||
return new InviteResult(false, errorMessage);
|
||||
}
|
||||
|
||||
boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package stirling.software.proprietary.security.filter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.util.RequestUriUtils;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class FirstLoginFilter extends OncePerRequestFilter {
|
||||
|
||||
@Lazy private final UserService userService;
|
||||
|
||||
public FirstLoginFilter(@Lazy UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
String method = request.getMethod();
|
||||
String requestURI = request.getRequestURI();
|
||||
String contextPath = request.getContextPath();
|
||||
// Check if the request is for static resources
|
||||
boolean isStaticResource = RequestUriUtils.isStaticResource(contextPath, requestURI);
|
||||
// If it's a static resource, just continue the filter chain and skip the logic below
|
||||
if (isStaticResource) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.isAuthenticated()) {
|
||||
Optional<User> user = userService.findByUsernameIgnoreCase(authentication.getName());
|
||||
if ("GET".equalsIgnoreCase(method)
|
||||
&& user.isPresent()
|
||||
&& user.get().isFirstLogin()
|
||||
&& !(contextPath + "/change-creds").equals(requestURI)) {
|
||||
response.sendRedirect(contextPath + "/change-creds");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
HttpSession session = request.getSession(true);
|
||||
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
|
||||
String creationTime = timeFormat.format(new Date(session.getCreationTime()));
|
||||
log.debug(
|
||||
"Request Info - New: {}, creationTimeSession {}, ID: {}, IP: {}, User-Agent: {}, Referer: {}, Request URL: {}",
|
||||
session.isNew(),
|
||||
creationTime,
|
||||
session.getId(),
|
||||
request.getRemoteAddr(),
|
||||
request.getHeader("User-Agent"),
|
||||
request.getHeader("Referer"),
|
||||
request.getRequestURL().toString());
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
+1
-4
@@ -84,14 +84,11 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
boolean isPublicAuthEndpoint =
|
||||
requestURI.startsWith(contextPath + "/login")
|
||||
|| requestURI.startsWith(contextPath + "/signup")
|
||||
|| requestURI.startsWith(contextPath + "/invite")
|
||||
|| requestURI.startsWith(contextPath + "/auth/")
|
||||
|| requestURI.startsWith(contextPath + "/oauth2")
|
||||
|| requestURI.startsWith(contextPath + "/api/v1/auth/login")
|
||||
|| requestURI.startsWith(contextPath + "/api/v1/auth/register")
|
||||
|| requestURI.startsWith(contextPath + "/api/v1/auth/refresh")
|
||||
|| requestURI.startsWith(contextPath + "/api/v1/invite/validate")
|
||||
|| requestURI.startsWith(contextPath + "/api/v1/invite/accept");
|
||||
|| requestURI.startsWith(contextPath + "/api/v1/auth/refresh");
|
||||
|
||||
if (!isPublicAuthEndpoint) {
|
||||
// For API requests, return 401 JSON
|
||||
|
||||
-3
@@ -227,7 +227,6 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
|
||||
contextPath + "/login",
|
||||
contextPath + "/signup",
|
||||
contextPath + "/register",
|
||||
contextPath + "/invite",
|
||||
contextPath + "/error",
|
||||
contextPath + "/images/",
|
||||
contextPath + "/public/",
|
||||
@@ -241,8 +240,6 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
|
||||
contextPath + "/api/v1/auth/register",
|
||||
contextPath + "/api/v1/auth/refresh",
|
||||
contextPath + "/api/v1/auth/me",
|
||||
contextPath + "/api/v1/invite/validate",
|
||||
contextPath + "/api/v1/invite/accept",
|
||||
contextPath + "/site.webmanifest"
|
||||
};
|
||||
|
||||
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
package stirling.software.proprietary.security.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
@Table(name = "invite_tokens")
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class InviteToken implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "token", unique = true, nullable = false, length = 100)
|
||||
private String token;
|
||||
|
||||
@Column(name = "email", nullable = true, length = 255)
|
||||
private String email; // Optional - if not set, user can provide their own email
|
||||
|
||||
@Column(name = "role", nullable = false, length = 50)
|
||||
private String role;
|
||||
|
||||
@Column(name = "team_id")
|
||||
private Long teamId;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private LocalDateTime expiresAt;
|
||||
|
||||
@Column(name = "used", nullable = false)
|
||||
private boolean used = false;
|
||||
|
||||
@Column(name = "created_by", nullable = false, length = 255)
|
||||
private String createdBy;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(name = "used_at")
|
||||
private LocalDateTime usedAt;
|
||||
|
||||
public boolean isExpired() {
|
||||
return LocalDateTime.now().isAfter(expiresAt);
|
||||
}
|
||||
|
||||
public boolean isValid() {
|
||||
return !used && !isExpired();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -73,6 +73,7 @@ public class User implements UserDetails, Serializable {
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "team_id")
|
||||
@JsonIgnore
|
||||
private Team team;
|
||||
|
||||
@ElementCollection
|
||||
@@ -80,7 +81,6 @@ public class User implements UserDetails, Serializable {
|
||||
@Lob
|
||||
@Column(name = "setting_value", columnDefinition = "text")
|
||||
@CollectionTable(name = "user_settings", joinColumns = @JoinColumn(name = "user_id"))
|
||||
@JsonIgnore
|
||||
private Map<String, String> settings = new HashMap<>(); // Key-value pairs of settings.
|
||||
|
||||
@CreationTimestamp
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package stirling.software.proprietary.security.repository;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import stirling.software.proprietary.security.model.InviteToken;
|
||||
|
||||
@Repository
|
||||
public interface InviteTokenRepository extends JpaRepository<InviteToken, Long> {
|
||||
|
||||
Optional<InviteToken> findByToken(String token);
|
||||
|
||||
Optional<InviteToken> findByEmail(String email);
|
||||
|
||||
List<InviteToken> findByUsedFalseAndExpiresAtAfter(LocalDateTime now);
|
||||
|
||||
List<InviteToken> findByCreatedBy(String createdBy);
|
||||
|
||||
@Modifying
|
||||
@Query("DELETE FROM InviteToken it WHERE it.expiresAt < :now")
|
||||
void deleteExpiredTokens(@Param("now") LocalDateTime now);
|
||||
|
||||
@Query("SELECT COUNT(it) FROM InviteToken it WHERE it.used = false AND it.expiresAt > :now")
|
||||
long countActiveInvites(@Param("now") LocalDateTime now);
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package stirling.software.proprietary.security.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import stirling.software.proprietary.model.UserLicenseSettings;
|
||||
|
||||
@Repository
|
||||
public interface UserLicenseSettingsRepository extends JpaRepository<UserLicenseSettings, Long> {
|
||||
|
||||
/**
|
||||
* Finds the singleton UserLicenseSettings record.
|
||||
*
|
||||
* @return Optional containing the settings if they exist
|
||||
*/
|
||||
default Optional<UserLicenseSettings> findSettings() {
|
||||
return findById(UserLicenseSettings.SINGLETON_ID);
|
||||
}
|
||||
}
|
||||
-140
@@ -73,144 +73,4 @@ public class EmailService {
|
||||
// Sends the email via the configured mail sender
|
||||
mailSender.send(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a plain text/HTML email without attachments asynchronously.
|
||||
*
|
||||
* @param to The recipient email address
|
||||
* @param subject The email subject
|
||||
* @param body The email body (can contain HTML)
|
||||
* @param isHtml Whether the body contains HTML content
|
||||
* @throws MessagingException If there is an issue with creating or sending the email.
|
||||
*/
|
||||
@Async
|
||||
public void sendPlainEmail(String to, String subject, String body, boolean isHtml)
|
||||
throws MessagingException {
|
||||
// Validate recipient email address
|
||||
if (to == null || to.trim().isEmpty()) {
|
||||
throw new MessagingException("Invalid recipient email address");
|
||||
}
|
||||
|
||||
ApplicationProperties.Mail mailProperties = applicationProperties.getMail();
|
||||
|
||||
// Creates a MimeMessage to represent the email
|
||||
MimeMessage message = mailSender.createMimeMessage();
|
||||
|
||||
// Helper class to set up the message content
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, false);
|
||||
|
||||
// Sets the recipient, subject, body, and sender email
|
||||
helper.addTo(to);
|
||||
helper.setSubject(subject);
|
||||
helper.setText(body, isHtml);
|
||||
helper.setFrom(mailProperties.getFrom());
|
||||
|
||||
// Sends the email via the configured mail sender
|
||||
mailSender.send(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an invitation email to a new user with their credentials.
|
||||
*
|
||||
* @param to The recipient email address
|
||||
* @param username The username for the new account
|
||||
* @param temporaryPassword The temporary password
|
||||
* @throws MessagingException If there is an issue with creating or sending the email.
|
||||
*/
|
||||
@Async
|
||||
public void sendInviteEmail(String to, String username, String temporaryPassword)
|
||||
throws MessagingException {
|
||||
String subject = "Welcome to Stirling PDF";
|
||||
|
||||
String body =
|
||||
"""
|
||||
<html><body style="margin: 0; padding: 0;">
|
||||
<div style="font-family: Arial, sans-serif; background-color: #f8f9fa; padding: 20px;">
|
||||
<div style="max-width: 600px; margin: auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;">
|
||||
<!-- Logo -->
|
||||
<div style="text-align: center; padding: 20px; background-color: #222;">
|
||||
<img src="https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/main/docs/stirling-transparent.svg" alt="Stirling PDF" style="max-height: 60px;">
|
||||
</div>
|
||||
<!-- Content -->
|
||||
<div style="padding: 30px; color: #333;">
|
||||
<h2 style="color: #222; margin-top: 0;">Welcome to Stirling PDF!</h2>
|
||||
<p>Hi there,</p>
|
||||
<p>You have been invited to join the workspace. Below are your login credentials:</p>
|
||||
<!-- Credentials Box -->
|
||||
<div style="background-color: #f8f9fa; border-left: 4px solid #007bff; padding: 15px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0 0 10px 0;"><strong>Username:</strong> %s</p>
|
||||
<p style="margin: 0;"><strong>Temporary Password:</strong> %s</p>
|
||||
</div>
|
||||
<div style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0; color: #856404;"><strong>⚠️ Important:</strong> You will be required to change your password upon first login for security reasons.</p>
|
||||
</div>
|
||||
<p>Please keep these credentials secure and do not share them with anyone.</p>
|
||||
<p style="margin-bottom: 0;">— The Stirling PDF Team</p>
|
||||
</div>
|
||||
<!-- Footer -->
|
||||
<div style="text-align: center; padding: 15px; font-size: 12px; color: #777; background-color: #f0f0f0;">
|
||||
© 2025 Stirling PDF. All rights reserved.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body></html>
|
||||
"""
|
||||
.formatted(username, temporaryPassword);
|
||||
|
||||
sendPlainEmail(to, subject, body, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an invitation link email to a new user.
|
||||
*
|
||||
* @param to The recipient email address
|
||||
* @param inviteUrl The full URL for accepting the invite
|
||||
* @param expiresAt The expiration timestamp
|
||||
* @throws MessagingException If there is an issue with creating or sending the email.
|
||||
*/
|
||||
@Async
|
||||
public void sendInviteLinkEmail(String to, String inviteUrl, String expiresAt)
|
||||
throws MessagingException {
|
||||
String subject = "You've been invited to Stirling PDF";
|
||||
|
||||
String body =
|
||||
"""
|
||||
<html><body style="margin: 0; padding: 0;">
|
||||
<div style="font-family: Arial, sans-serif; background-color: #f8f9fa; padding: 20px;">
|
||||
<div style="max-width: 600px; margin: auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;">
|
||||
<!-- Logo -->
|
||||
<div style="text-align: center; padding: 20px; background-color: #222;">
|
||||
<img src="https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/main/docs/stirling-transparent.svg" alt="Stirling PDF" style="max-height: 60px;">
|
||||
</div>
|
||||
<!-- Content -->
|
||||
<div style="padding: 30px; color: #333;">
|
||||
<h2 style="color: #222; margin-top: 0;">Welcome to Stirling PDF!</h2>
|
||||
<p>Hi there,</p>
|
||||
<p>You have been invited to join the Stirling PDF workspace. Click the button below to set up your account:</p>
|
||||
<!-- CTA Button -->
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="%s" style="display: inline-block; background-color: #007bff; color: #ffffff; padding: 14px 28px; text-decoration: none; border-radius: 5px; font-weight: bold;">Accept Invitation</a>
|
||||
</div>
|
||||
<p style="font-size: 14px; color: #666;">Or copy and paste this link in your browser:</p>
|
||||
<div style="background-color: #f8f9fa; padding: 12px; margin: 15px 0; border-radius: 4px; word-break: break-all; font-size: 13px; color: #555;">
|
||||
%s
|
||||
</div>
|
||||
<div style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0; color: #856404; font-size: 14px;"><strong>⚠️ Important:</strong> This invitation link will expire on %s. Please complete your registration before then.</p>
|
||||
</div>
|
||||
<p>If you didn't expect this invitation, you can safely ignore this email.</p>
|
||||
<p style="margin-bottom: 0;">— The Stirling PDF Team</p>
|
||||
</div>
|
||||
<!-- Footer -->
|
||||
<div style="text-align: center; padding: 15px; font-size: 12px; color: #777; background-color: #f0f0f0;">
|
||||
© 2025 Stirling PDF. All rights reserved.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body></html>
|
||||
"""
|
||||
.formatted(inviteUrl, inviteUrl, expiresAt);
|
||||
|
||||
sendPlainEmail(to, subject, body, true);
|
||||
}
|
||||
}
|
||||
|
||||
-15
@@ -642,21 +642,6 @@ public class UserService implements UserServiceInterface {
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isCurrentUserAdmin() {
|
||||
try {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null
|
||||
&& authentication.isAuthenticated()
|
||||
&& !"anonymousUser".equals(authentication.getPrincipal())) {
|
||||
return authentication.getAuthorities().stream()
|
||||
.anyMatch(auth -> Role.ADMIN.getRoleId().equals(auth.getAuthority()));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Error checking admin status", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void syncCustomApiUser(String customApiKey) {
|
||||
if (customApiKey == null || customApiKey.trim().isBlank()) {
|
||||
|
||||
+1
-34
@@ -30,8 +30,6 @@ import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.configuration.InstallationPathConfig;
|
||||
import stirling.software.common.service.ServerCertificateServiceInterface;
|
||||
import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
|
||||
import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@@ -53,12 +51,6 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa
|
||||
@Value("${system.serverCertificate.regenerateOnStartup:false}")
|
||||
private boolean regenerateOnStartup;
|
||||
|
||||
private final LicenseKeyChecker licenseKeyChecker;
|
||||
|
||||
public ServerCertificateService(LicenseKeyChecker licenseKeyChecker) {
|
||||
this.licenseKeyChecker = licenseKeyChecker;
|
||||
}
|
||||
|
||||
static {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
@@ -67,13 +59,8 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa
|
||||
return Paths.get(InstallationPathConfig.getConfigPath(), KEYSTORE_FILENAME);
|
||||
}
|
||||
|
||||
private boolean hasProOrEnterpriseAccess() {
|
||||
License license = licenseKeyChecker.getPremiumLicenseEnabledResult();
|
||||
return license == License.PRO || license == License.ENTERPRISE;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled && hasProOrEnterpriseAccess();
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public boolean hasServerCertificate() {
|
||||
@@ -86,11 +73,6 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasProOrEnterpriseAccess()) {
|
||||
log.info("Server certificate feature requires Pro or Enterprise license");
|
||||
return;
|
||||
}
|
||||
|
||||
Path keystorePath = getKeystorePath();
|
||||
|
||||
if (!Files.exists(keystorePath) || regenerateOnStartup) {
|
||||
@@ -106,11 +88,6 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa
|
||||
}
|
||||
|
||||
public KeyStore getServerKeyStore() throws Exception {
|
||||
if (!hasProOrEnterpriseAccess()) {
|
||||
throw new IllegalStateException(
|
||||
"Server certificate feature requires Pro or Enterprise license");
|
||||
}
|
||||
|
||||
if (!enabled || !hasServerCertificate()) {
|
||||
throw new IllegalStateException("Server certificate is not available");
|
||||
}
|
||||
@@ -137,11 +114,6 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa
|
||||
}
|
||||
|
||||
public void uploadServerCertificate(InputStream p12Stream, String password) throws Exception {
|
||||
if (!hasProOrEnterpriseAccess()) {
|
||||
throw new IllegalStateException(
|
||||
"Server certificate feature requires Pro or Enterprise license");
|
||||
}
|
||||
|
||||
// Validate the uploaded certificate
|
||||
KeyStore uploadedKeyStore = KeyStore.getInstance("PKCS12");
|
||||
uploadedKeyStore.load(p12Stream, password.toCharArray());
|
||||
@@ -202,11 +174,6 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa
|
||||
}
|
||||
|
||||
private void generateServerCertificate() throws Exception {
|
||||
if (!hasProOrEnterpriseAccess()) {
|
||||
throw new IllegalStateException(
|
||||
"Server certificate feature requires Pro or Enterprise license");
|
||||
}
|
||||
|
||||
// Generate key pair
|
||||
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
|
||||
keyPairGenerator.initialize(2048, new SecureRandom());
|
||||
|
||||
-411
@@ -1,411 +0,0 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.model.UserLicenseSettings;
|
||||
import stirling.software.proprietary.security.repository.UserLicenseSettingsRepository;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
|
||||
/**
|
||||
* Service for managing user license settings and grandfathering logic.
|
||||
*
|
||||
* <p>User limit calculation:
|
||||
*
|
||||
* <ul>
|
||||
* <li>Default limit: 5 users
|
||||
* <li>Grandfathered limit: max(5, existing user count at initialization)
|
||||
* <li>With pro license: grandfathered limit + license maxUsers
|
||||
* <li>Without pro license: grandfathered limit
|
||||
* </ul>
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class UserLicenseSettingsService {
|
||||
|
||||
private static final int DEFAULT_USER_LIMIT = 5;
|
||||
private static final String SIGNATURE_SEPARATOR = ":";
|
||||
private static final String DEFAULT_INTEGRITY_SECRET = "stirling-pdf-user-license-guard";
|
||||
|
||||
private final UserLicenseSettingsRepository settingsRepository;
|
||||
private final UserService userService;
|
||||
private final ApplicationProperties applicationProperties;
|
||||
|
||||
/**
|
||||
* Gets the current user license settings, creating them if they don't exist.
|
||||
*
|
||||
* @return The current settings
|
||||
*/
|
||||
@Transactional
|
||||
public UserLicenseSettings getOrCreateSettings() {
|
||||
return settingsRepository
|
||||
.findSettings()
|
||||
.orElseGet(
|
||||
() -> {
|
||||
log.info("Initializing user license settings");
|
||||
UserLicenseSettings settings = new UserLicenseSettings();
|
||||
settings.setId(UserLicenseSettings.SINGLETON_ID);
|
||||
settings.setGrandfatheredUserCount(0);
|
||||
settings.setLicenseMaxUsers(0);
|
||||
settings.setGrandfatheringLocked(false);
|
||||
settings.setIntegritySalt(UUID.randomUUID().toString());
|
||||
settings.setGrandfatheredUserSignature("");
|
||||
return settingsRepository.save(settings);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the grandfathered user count if not already set. This should be called on
|
||||
* application startup.
|
||||
*
|
||||
* <p>IMPORTANT: Once grandfathering is locked, this value can NEVER be changed. This prevents
|
||||
* manipulation by deleting the settings table.
|
||||
*
|
||||
* <p>Logic:
|
||||
*
|
||||
* <ul>
|
||||
* <li>If grandfatheringLocked is true: Skip initialization (already set permanently)
|
||||
* <li>If users exist in database: Set to max(5, current user count) - this is an existing
|
||||
* installation
|
||||
* <li>If no users exist: Set to 5 (default) - this is a fresh installation
|
||||
* <li>Lock grandfathering immediately after setting
|
||||
* </ul>
|
||||
*/
|
||||
@Transactional
|
||||
public void initializeGrandfatheredCount() {
|
||||
UserLicenseSettings settings = getOrCreateSettings();
|
||||
|
||||
boolean changed = ensureIntegritySalt(settings);
|
||||
|
||||
// CRITICAL: Never change grandfathering once it's locked
|
||||
if (settings.isGrandfatheringLocked()) {
|
||||
if (settings.getGrandfatheredUserSignature() == null
|
||||
|| settings.getGrandfatheredUserSignature().isBlank()) {
|
||||
settings.setGrandfatheredUserSignature(
|
||||
generateSignature(settings.getGrandfatheredUserCount(), settings));
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
settingsRepository.save(settings);
|
||||
}
|
||||
log.debug(
|
||||
"Grandfathering is locked. Current grandfathered count: {}",
|
||||
settings.getGrandfatheredUserCount());
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine if this is an existing installation or fresh install
|
||||
long currentUserCount = userService.getTotalUsersCount();
|
||||
boolean isExistingInstallation = currentUserCount > 0;
|
||||
|
||||
int grandfatheredCount;
|
||||
if (isExistingInstallation) {
|
||||
// Existing installation (v2.0+ or has users) - grandfather current user count
|
||||
grandfatheredCount = Math.max(DEFAULT_USER_LIMIT, (int) currentUserCount);
|
||||
log.info(
|
||||
"Existing installation detected. Grandfathering {} users (current: {}, minimum:"
|
||||
+ " {})",
|
||||
grandfatheredCount,
|
||||
currentUserCount,
|
||||
DEFAULT_USER_LIMIT);
|
||||
} else {
|
||||
// Fresh installation - set to default
|
||||
grandfatheredCount = DEFAULT_USER_LIMIT;
|
||||
log.info(
|
||||
"Fresh installation detected. Setting default grandfathered limit: {}",
|
||||
grandfatheredCount);
|
||||
}
|
||||
|
||||
// Set and LOCK the grandfathering permanently
|
||||
settings.setGrandfatheredUserCount(grandfatheredCount);
|
||||
settings.setGrandfatheringLocked(true);
|
||||
settings.setGrandfatheredUserSignature(generateSignature(grandfatheredCount, settings));
|
||||
settingsRepository.save(settings);
|
||||
|
||||
log.warn(
|
||||
"GRANDFATHERING LOCKED: {} users. This value can never be changed.",
|
||||
grandfatheredCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the license max users from the application properties. This should be called when the
|
||||
* license is validated.
|
||||
*/
|
||||
@Transactional
|
||||
public void updateLicenseMaxUsers() {
|
||||
UserLicenseSettings settings = getOrCreateSettings();
|
||||
|
||||
int licenseMaxUsers = 0;
|
||||
if (applicationProperties.getPremium().isEnabled()) {
|
||||
licenseMaxUsers = applicationProperties.getPremium().getMaxUsers();
|
||||
}
|
||||
|
||||
if (settings.getLicenseMaxUsers() != licenseMaxUsers) {
|
||||
settings.setLicenseMaxUsers(licenseMaxUsers);
|
||||
settingsRepository.save(settings);
|
||||
log.info("Updated license max users to: {}", licenseMaxUsers);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates and enforces the integrity of license settings. This ensures that even if someone
|
||||
* manually modifies the database, the grandfathering rules are still enforced.
|
||||
*/
|
||||
@Transactional
|
||||
public void validateSettingsIntegrity() {
|
||||
UserLicenseSettings settings = getOrCreateSettings();
|
||||
boolean changed = ensureIntegritySalt(settings);
|
||||
|
||||
Optional<Integer> signedCountOpt = extractSignedCount(settings);
|
||||
boolean signatureValid =
|
||||
signedCountOpt.isPresent()
|
||||
&& signatureMatches(
|
||||
signedCountOpt.get(),
|
||||
settings.getGrandfatheredUserSignature(),
|
||||
settings);
|
||||
|
||||
int targetCount = settings.getGrandfatheredUserCount();
|
||||
String targetSignature = settings.getGrandfatheredUserSignature();
|
||||
|
||||
if (!signatureValid) {
|
||||
int restoredCount =
|
||||
signedCountOpt.orElseGet(
|
||||
() ->
|
||||
Math.max(
|
||||
DEFAULT_USER_LIMIT,
|
||||
(int) userService.getTotalUsersCount()));
|
||||
log.error(
|
||||
"Grandfathered user signature invalid or missing. Restoring locked count to {}.",
|
||||
restoredCount);
|
||||
targetCount = restoredCount;
|
||||
targetSignature = generateSignature(targetCount, settings);
|
||||
changed = true;
|
||||
} else {
|
||||
int signedCount = signedCountOpt.get();
|
||||
if (targetCount != signedCount) {
|
||||
log.error(
|
||||
"Grandfathered user count ({}) was modified without signature update. Restoring to {}.",
|
||||
targetCount,
|
||||
signedCount);
|
||||
targetCount = signedCount;
|
||||
targetSignature = generateSignature(targetCount, settings);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (targetCount < DEFAULT_USER_LIMIT) {
|
||||
if (targetCount != DEFAULT_USER_LIMIT) {
|
||||
log.warn(
|
||||
"Grandfathered count ({}) is below minimum ({}). Enforcing minimum.",
|
||||
targetCount,
|
||||
DEFAULT_USER_LIMIT);
|
||||
}
|
||||
targetCount = DEFAULT_USER_LIMIT;
|
||||
targetSignature = generateSignature(targetCount, settings);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (targetSignature == null || targetSignature.isBlank()) {
|
||||
targetSignature = generateSignature(targetCount, settings);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed
|
||||
|| settings.getGrandfatheredUserCount() != targetCount
|
||||
|| (targetSignature != null
|
||||
&& !targetSignature.equals(settings.getGrandfatheredUserSignature()))) {
|
||||
settings.setGrandfatheredUserCount(targetCount);
|
||||
settings.setGrandfatheredUserSignature(targetSignature);
|
||||
settingsRepository.save(settings);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the maximum allowed users based on grandfathering rules.
|
||||
*
|
||||
* <p>Logic:
|
||||
*
|
||||
* <ul>
|
||||
* <li>Grandfathered limit = max(5, existing user count at initialization)
|
||||
* <li>If premium enabled: total limit = grandfathered limit + license maxUsers
|
||||
* <li>If premium disabled: total limit = grandfathered limit
|
||||
* </ul>
|
||||
*
|
||||
* @return Maximum number of users allowed
|
||||
*/
|
||||
public int calculateMaxAllowedUsers() {
|
||||
validateSettingsIntegrity();
|
||||
UserLicenseSettings settings = getOrCreateSettings();
|
||||
|
||||
int grandfatheredLimit = settings.getGrandfatheredUserCount();
|
||||
if (grandfatheredLimit == 0) {
|
||||
// Fallback if not initialized yet - should not happen with validation
|
||||
log.warn("Grandfathered limit is 0, using default: {}", DEFAULT_USER_LIMIT);
|
||||
grandfatheredLimit = DEFAULT_USER_LIMIT;
|
||||
}
|
||||
|
||||
int totalLimit = grandfatheredLimit;
|
||||
|
||||
if (applicationProperties.getPremium().isEnabled()) {
|
||||
totalLimit = grandfatheredLimit + settings.getLicenseMaxUsers();
|
||||
}
|
||||
|
||||
log.debug(
|
||||
"Calculated max allowed users: {} (grandfathered: {}, license: {}, premium enabled: {})",
|
||||
totalLimit,
|
||||
grandfatheredLimit,
|
||||
settings.getLicenseMaxUsers(),
|
||||
applicationProperties.getPremium().isEnabled());
|
||||
|
||||
return totalLimit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if adding new users would exceed the limit.
|
||||
*
|
||||
* @param newUsersCount Number of new users to add
|
||||
* @return true if the addition would exceed the limit
|
||||
*/
|
||||
public boolean wouldExceedLimit(int newUsersCount) {
|
||||
long currentUserCount = userService.getTotalUsersCount();
|
||||
int maxAllowed = calculateMaxAllowedUsers();
|
||||
return (currentUserCount + newUsersCount) > maxAllowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the number of available user slots.
|
||||
*
|
||||
* @return Number of users that can still be added
|
||||
*/
|
||||
public long getAvailableUserSlots() {
|
||||
long currentUserCount = userService.getTotalUsersCount();
|
||||
int maxAllowed = calculateMaxAllowedUsers();
|
||||
return Math.max(0, maxAllowed - currentUserCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the grandfathered user count for display purposes. Returns only the excess users beyond
|
||||
* the base limit (5).
|
||||
*
|
||||
* <p>Examples:
|
||||
*
|
||||
* <ul>
|
||||
* <li>If grandfathered = 5: returns 0 (base amount, nothing special)
|
||||
* <li>If grandfathered = 10: returns 5 (5 extra users)
|
||||
* <li>If grandfathered = 15: returns 10 (10 extra users)
|
||||
* </ul>
|
||||
*
|
||||
* @return Number of grandfathered users beyond the base limit
|
||||
*/
|
||||
public int getDisplayGrandfatheredCount() {
|
||||
UserLicenseSettings settings = getOrCreateSettings();
|
||||
int totalGrandfathered = settings.getGrandfatheredUserCount();
|
||||
return Math.max(0, totalGrandfathered - DEFAULT_USER_LIMIT);
|
||||
}
|
||||
|
||||
/** Gets the current settings. */
|
||||
public UserLicenseSettings getSettings() {
|
||||
return getOrCreateSettings();
|
||||
}
|
||||
|
||||
private boolean ensureIntegritySalt(UserLicenseSettings settings) {
|
||||
if (settings.getIntegritySalt() == null || settings.getIntegritySalt().isBlank()) {
|
||||
settings.setIntegritySalt(UUID.randomUUID().toString());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private Optional<Integer> extractSignedCount(UserLicenseSettings settings) {
|
||||
String signature = settings.getGrandfatheredUserSignature();
|
||||
if (signature == null || signature.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
String[] parts = signature.split(SIGNATURE_SEPARATOR, 2);
|
||||
if (parts.length != 2) {
|
||||
log.warn("Invalid grandfathered user signature format detected");
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
try {
|
||||
return Optional.of(Integer.parseInt(parts[0]));
|
||||
} catch (NumberFormatException ex) {
|
||||
log.warn("Unable to parse grandfathered user signature count", ex);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean signatureMatches(int count, String signature, UserLicenseSettings settings) {
|
||||
if (signature == null || signature.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
return generateSignature(count, settings).equals(signature);
|
||||
}
|
||||
|
||||
private String generateSignature(int count, UserLicenseSettings settings) {
|
||||
if (settings.getIntegritySalt() == null || settings.getIntegritySalt().isBlank()) {
|
||||
throw new IllegalStateException("Integrity salt must be initialized before signing.");
|
||||
}
|
||||
String payload = buildSignaturePayload(count, settings.getIntegritySalt());
|
||||
String secret = deriveIntegritySecret();
|
||||
String digest = computeHmac(payload, secret);
|
||||
return count + SIGNATURE_SEPARATOR + digest;
|
||||
}
|
||||
|
||||
private String buildSignaturePayload(int count, String salt) {
|
||||
return count + SIGNATURE_SEPARATOR + salt;
|
||||
}
|
||||
|
||||
private String deriveIntegritySecret() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
appendIfPresent(builder, applicationProperties.getAutomaticallyGenerated().getKey());
|
||||
appendIfPresent(builder, applicationProperties.getAutomaticallyGenerated().getUUID());
|
||||
appendIfPresent(builder, applicationProperties.getPremium().getKey());
|
||||
|
||||
if (builder.length() == 0) {
|
||||
builder.append(DEFAULT_INTEGRITY_SECRET);
|
||||
}
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private void appendIfPresent(StringBuilder builder, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
if (builder.length() > 0) {
|
||||
builder.append(SIGNATURE_SEPARATOR);
|
||||
}
|
||||
builder.append(value);
|
||||
}
|
||||
}
|
||||
|
||||
private String computeHmac(String payload, String secret) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
SecretKeySpec keySpec =
|
||||
new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
|
||||
mac.init(keySpec);
|
||||
byte[] digest = mac.doFinal(payload.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("Failed to compute grandfathered user signature", e);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new IllegalStateException("Invalid key for grandfathered user signature", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-32
@@ -629,40 +629,9 @@ tasks.named('bootRun') {
|
||||
tasks.named('build') {
|
||||
group = 'build'
|
||||
description = 'Delegates to :stirling-pdf:bootJar'
|
||||
dependsOn ':stirling-pdf:bootJar', 'buildRestartHelper'
|
||||
dependsOn ':stirling-pdf:bootJar'
|
||||
|
||||
doFirst {
|
||||
println "Delegating to :stirling-pdf:bootJar"
|
||||
}
|
||||
}
|
||||
|
||||
// Task to compile RestartHelper.java
|
||||
tasks.register('compileRestartHelper', JavaCompile) {
|
||||
group = 'build'
|
||||
description = 'Compiles the RestartHelper utility'
|
||||
|
||||
source = fileTree(dir: 'scripts', include: 'RestartHelper.java')
|
||||
classpath = files()
|
||||
destinationDirectory = file("${buildDir}/restart-helper-classes")
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
// Task to create restart-helper.jar
|
||||
tasks.register('buildRestartHelper', Jar) {
|
||||
group = 'build'
|
||||
description = 'Builds the restart-helper.jar'
|
||||
dependsOn 'compileRestartHelper'
|
||||
|
||||
from "${buildDir}/restart-helper-classes"
|
||||
archiveFileName = 'restart-helper.jar'
|
||||
destinationDirectory = file("${buildDir}/libs")
|
||||
|
||||
manifest {
|
||||
attributes 'Main-Class': 'RestartHelper'
|
||||
}
|
||||
|
||||
doLast {
|
||||
println "restart-helper.jar created at: ${destinationDirectory.get()}/restart-helper.jar"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
# Unified Dockerfile - Frontend + Backend in single container
|
||||
# Supports MODE parameter: BOTH (default), FRONTEND, BACKEND
|
||||
|
||||
# Stage 1: Build Frontend
|
||||
FROM node:20-alpine AS frontend-build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY frontend/package.json frontend/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY frontend .
|
||||
RUN npm run build
|
||||
|
||||
# Stage 2: Build Backend
|
||||
FROM gradle:8.14-jdk21 AS backend-build
|
||||
|
||||
COPY build.gradle .
|
||||
COPY settings.gradle .
|
||||
COPY gradlew .
|
||||
COPY gradle gradle/
|
||||
COPY app/core/build.gradle core/.
|
||||
COPY app/common/build.gradle common/.
|
||||
COPY app/proprietary/build.gradle proprietary/.
|
||||
RUN ./gradlew build -x spotlessApply -x spotlessCheck -x test -x sonarqube || return 0
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
|
||||
RUN DISABLE_ADDITIONAL_FEATURES=false \
|
||||
STIRLING_PDF_DESKTOP_UI=false \
|
||||
./gradlew clean build -x spotlessApply -x spotlessCheck -x test -x sonarqube
|
||||
|
||||
# Stage 3: Final unified image
|
||||
FROM alpine:3.22.1
|
||||
|
||||
ARG VERSION_TAG
|
||||
|
||||
# Labels
|
||||
LABEL org.opencontainers.image.title="Stirling-PDF Unified"
|
||||
LABEL org.opencontainers.image.description="Unified container for Stirling-PDF - Frontend + Backend with MODE parameter"
|
||||
LABEL org.opencontainers.image.source="https://github.com/Stirling-Tools/Stirling-PDF"
|
||||
LABEL org.opencontainers.image.licenses="MIT"
|
||||
LABEL org.opencontainers.image.vendor="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.url="https://www.stirlingpdf.com"
|
||||
LABEL org.opencontainers.image.documentation="https://docs.stirlingpdf.com"
|
||||
LABEL maintainer="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.authors="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.version="${VERSION_TAG}"
|
||||
LABEL org.opencontainers.image.keywords="PDF, manipulation, unified, API, Spring Boot, React"
|
||||
|
||||
# Copy backend files
|
||||
COPY scripts /scripts
|
||||
COPY app/core/src/main/resources/static/fonts/*.ttf /usr/share/fonts/opentype/noto/
|
||||
COPY --from=backend-build /app/app/core/build/libs/*.jar app.jar
|
||||
|
||||
# Copy frontend files
|
||||
COPY --from=frontend-build /app/dist /usr/share/nginx/html
|
||||
|
||||
# Copy nginx configuration
|
||||
COPY docker/unified/nginx.conf /etc/nginx/nginx.conf
|
||||
COPY docker/unified/entrypoint.sh /entrypoint.sh
|
||||
|
||||
# Environment Variables
|
||||
ENV DISABLE_ADDITIONAL_FEATURES=false \
|
||||
VERSION_TAG=$VERSION_TAG \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_CUSTOM_OPTS="" \
|
||||
HOME=/home/stirlingpdfuser \
|
||||
PUID=1000 \
|
||||
PGID=1000 \
|
||||
UMASK=022 \
|
||||
PYTHONPATH=/usr/lib/libreoffice/program:/opt/venv/lib/python3.12/site-packages \
|
||||
UNO_PATH=/usr/lib/libreoffice/program \
|
||||
URE_BOOTSTRAP=file:///usr/lib/libreoffice/program/fundamentalrc \
|
||||
PATH=$PATH:/opt/venv/bin \
|
||||
STIRLING_TEMPFILES_DIRECTORY=/tmp/stirling-pdf \
|
||||
TMPDIR=/tmp/stirling-pdf \
|
||||
TEMP=/tmp/stirling-pdf \
|
||||
TMP=/tmp/stirling-pdf \
|
||||
MODE=BOTH \
|
||||
BACKEND_INTERNAL_PORT=8081 \
|
||||
VITE_API_BASE_URL=http://localhost:8080
|
||||
|
||||
# Install all dependencies
|
||||
RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/apk/repositories && \
|
||||
echo "@community https://dl-cdn.alpinelinux.org/alpine/edge/community" | tee -a /etc/apk/repositories && \
|
||||
echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/testing" | tee -a /etc/apk/repositories && \
|
||||
apk upgrade --no-cache -a && \
|
||||
apk add --no-cache \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
tini \
|
||||
bash \
|
||||
curl \
|
||||
shadow \
|
||||
su-exec \
|
||||
openssl \
|
||||
openssl-dev \
|
||||
openjdk21-jre \
|
||||
nginx \
|
||||
# Doc conversion
|
||||
gcompat \
|
||||
libc6-compat \
|
||||
libreoffice \
|
||||
# pdftohtml
|
||||
poppler-utils \
|
||||
# OCR MY PDF
|
||||
unpaper \
|
||||
tesseract-ocr-data-eng \
|
||||
tesseract-ocr-data-chi_sim \
|
||||
tesseract-ocr-data-deu \
|
||||
tesseract-ocr-data-fra \
|
||||
tesseract-ocr-data-por \
|
||||
ocrmypdf \
|
||||
# CV
|
||||
py3-opencv \
|
||||
python3 \
|
||||
py3-pip \
|
||||
py3-pillow@testing \
|
||||
py3-pdf2image@testing && \
|
||||
python3 -m venv /opt/venv && \
|
||||
/opt/venv/bin/pip install --upgrade pip setuptools && \
|
||||
/opt/venv/bin/pip install --no-cache-dir --upgrade unoserver weasyprint && \
|
||||
ln -s /usr/lib/libreoffice/program/uno.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||
ln -s /usr/lib/libreoffice/program/unohelper.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||
ln -s /usr/lib/libreoffice/program /opt/venv/lib/python3.12/site-packages/LibreOffice && \
|
||||
mv /usr/share/tessdata /usr/share/tessdata-original && \
|
||||
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf /pipeline/watchedFolders /pipeline/finishedFolders && \
|
||||
mkdir -p /var/lib/nginx/tmp /var/log/nginx && \
|
||||
fc-cache -f -v && \
|
||||
chmod +x /scripts/* && \
|
||||
chmod +x /entrypoint.sh && \
|
||||
# User permissions
|
||||
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /pipeline /usr/share/fonts/opentype/noto /configs /customFiles /pipeline /tmp/stirling-pdf /var/lib/nginx /var/log/nginx /usr/share/nginx && \
|
||||
chown stirlingpdfuser:stirlingpdfgroup /app.jar
|
||||
|
||||
EXPOSE 8080/tcp
|
||||
|
||||
ENTRYPOINT ["tini", "--", "/entrypoint.sh"]
|
||||
@@ -30,7 +30,6 @@ COPY scripts /scripts
|
||||
COPY app/core/src/main/resources/static/fonts/*.ttf /usr/share/fonts/opentype/noto/
|
||||
# first /app directory is for the build stage, second is for the final image
|
||||
COPY --from=build /app/app/core/build/libs/*.jar app.jar
|
||||
COPY --from=build /app/build/libs/restart-helper.jar restart-helper.jar
|
||||
|
||||
ARG VERSION_TAG
|
||||
|
||||
@@ -114,7 +113,7 @@ RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/a
|
||||
# User permissions
|
||||
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /pipeline /usr/share/fonts/opentype/noto /configs /customFiles /pipeline /tmp/stirling-pdf && \
|
||||
chown stirlingpdfuser:stirlingpdfgroup /app.jar /restart-helper.jar
|
||||
chown stirlingpdfuser:stirlingpdfgroup /app.jar
|
||||
|
||||
EXPOSE 8080/tcp
|
||||
|
||||
|
||||
@@ -30,7 +30,6 @@ COPY scripts /scripts
|
||||
COPY app/core/src/main/resources/static/fonts/*.ttf /usr/share/fonts/opentype/noto/
|
||||
# first /app directory is for the build stage, second is for the final image
|
||||
COPY --from=build /app/app/core/build/libs/*.jar app.jar
|
||||
COPY --from=build /app/build/libs/restart-helper.jar restart-helper.jar
|
||||
|
||||
ARG VERSION_TAG
|
||||
|
||||
@@ -105,7 +104,7 @@ RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/a
|
||||
# User permissions
|
||||
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /pipeline /usr/share/fonts/opentype/noto /configs /customFiles /pipeline /tmp/stirling-pdf && \
|
||||
chown stirlingpdfuser:stirlingpdfgroup /app.jar /restart-helper.jar
|
||||
chown stirlingpdfuser:stirlingpdfgroup /app.jar
|
||||
|
||||
EXPOSE 8080/tcp
|
||||
# Set user and run command
|
||||
|
||||
@@ -45,7 +45,6 @@ ENV DISABLE_ADDITIONAL_FEATURES=true \
|
||||
COPY scripts/init-without-ocr.sh /scripts/init-without-ocr.sh
|
||||
COPY scripts/installFonts.sh /scripts/installFonts.sh
|
||||
COPY --from=build /app/app/core/build/libs/*.jar app.jar
|
||||
COPY --from=build /app/build/libs/restart-helper.jar restart-helper.jar
|
||||
|
||||
# Set up necessary directories and permissions
|
||||
RUN echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/apk/repositories && \
|
||||
@@ -66,7 +65,7 @@ RUN echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /et
|
||||
chmod +x /scripts/*.sh && \
|
||||
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /pipeline /configs /customFiles /pipeline /tmp/stirling-pdf && \
|
||||
chown stirlingpdfuser:stirlingpdfgroup /app.jar /restart-helper.jar
|
||||
chown stirlingpdfuser:stirlingpdfgroup /app.jar
|
||||
|
||||
# Set environment variables
|
||||
ENV ENDPOINTS_GROUPS_TO_REMOVE=CLI
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
# Example Docker Compose for Unified Stirling-PDF Container
|
||||
# MODE=BACKEND: Backend API only (no frontend)
|
||||
|
||||
services:
|
||||
stirling-pdf-backend-only:
|
||||
container_name: Stirling-PDF-Backend-Only
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: docker/Dockerfile.unified
|
||||
ports:
|
||||
- "8080:8080"
|
||||
volumes:
|
||||
- ./stirling/data:/usr/share/tessdata:rw
|
||||
- ./stirling/config:/configs:rw
|
||||
- ./stirling/logs:/logs:rw
|
||||
- ./stirling/customFiles:/customFiles:rw
|
||||
- ./stirling/pipeline:/pipeline:rw
|
||||
environment:
|
||||
# MODE parameter: BACKEND only
|
||||
MODE: BACKEND
|
||||
|
||||
# Standard Stirling-PDF configuration
|
||||
DISABLE_ADDITIONAL_FEATURES: "false"
|
||||
DOCKER_ENABLE_SECURITY: "false"
|
||||
PUID: 1000
|
||||
PGID: 1000
|
||||
UMASK: "022"
|
||||
|
||||
# Application settings
|
||||
SYSTEM_DEFAULTLOCALE: en-US
|
||||
UI_APPNAME: Stirling-PDF
|
||||
SYSTEM_MAXFILESIZE: "100"
|
||||
METRICS_ENABLED: "true"
|
||||
|
||||
# Optional: Add OCR languages (comma-separated)
|
||||
# TESSERACT_LANGS: "deu,fra,spa"
|
||||
|
||||
# Optional: Java memory settings
|
||||
# JAVA_CUSTOM_OPTS: "-Xmx4g"
|
||||
|
||||
restart: unless-stopped
|
||||
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -f http://localhost:8080/api/v1/info/status || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 4G
|
||||
reservations:
|
||||
memory: 2G
|
||||
|
||||
# Access the API at: http://localhost:8080/api
|
||||
# Swagger UI at: http://localhost:8080/swagger-ui/index.html
|
||||
@@ -1,59 +0,0 @@
|
||||
# Example Docker Compose for Unified Stirling-PDF Container
|
||||
# MODE=BOTH (default): Frontend + Backend in single container on port 8080
|
||||
|
||||
services:
|
||||
stirling-pdf-unified:
|
||||
container_name: Stirling-PDF-Unified-Both
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: docker/Dockerfile.unified
|
||||
ports:
|
||||
- "8080:8080"
|
||||
volumes:
|
||||
- ./stirling/data:/usr/share/tessdata:rw
|
||||
- ./stirling/config:/configs:rw
|
||||
- ./stirling/logs:/logs:rw
|
||||
- ./stirling/customFiles:/customFiles:rw
|
||||
- ./stirling/pipeline:/pipeline:rw
|
||||
environment:
|
||||
# MODE parameter: BOTH (default), FRONTEND, or BACKEND
|
||||
MODE: BOTH
|
||||
|
||||
# Backend runs internally on this port when MODE=BOTH
|
||||
BACKEND_INTERNAL_PORT: 8081
|
||||
|
||||
# Standard Stirling-PDF configuration
|
||||
DISABLE_ADDITIONAL_FEATURES: "false"
|
||||
DOCKER_ENABLE_SECURITY: "false"
|
||||
PUID: 1000
|
||||
PGID: 1000
|
||||
UMASK: "022"
|
||||
|
||||
# Application settings
|
||||
SYSTEM_DEFAULTLOCALE: en-US
|
||||
UI_APPNAME: Stirling-PDF
|
||||
UI_HOMEDESCRIPTION: Your locally hosted one-stop-shop for all your PDF needs
|
||||
SYSTEM_MAXFILESIZE: "100"
|
||||
METRICS_ENABLED: "true"
|
||||
|
||||
# Optional: Add OCR languages (comma-separated)
|
||||
# TESSERACT_LANGS: "deu,fra,spa"
|
||||
|
||||
# Optional: Java memory settings
|
||||
# JAVA_CUSTOM_OPTS: "-Xmx4g"
|
||||
|
||||
restart: unless-stopped
|
||||
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -f http://localhost:8080/api/v1/info/status || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 4G
|
||||
reservations:
|
||||
memory: 2G
|
||||
@@ -1,63 +0,0 @@
|
||||
# Example Docker Compose for Unified Stirling-PDF Container
|
||||
# MODE=FRONTEND: Frontend only, connects to separate backend
|
||||
|
||||
services:
|
||||
stirling-pdf-backend:
|
||||
container_name: Stirling-PDF-Backend
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: docker/Dockerfile.unified
|
||||
ports:
|
||||
- "8081:8080"
|
||||
volumes:
|
||||
- ./stirling/data:/usr/share/tessdata:rw
|
||||
- ./stirling/config:/configs:rw
|
||||
- ./stirling/logs:/logs:rw
|
||||
- ./stirling/customFiles:/customFiles:rw
|
||||
- ./stirling/pipeline:/pipeline:rw
|
||||
environment:
|
||||
MODE: BACKEND
|
||||
DISABLE_ADDITIONAL_FEATURES: "false"
|
||||
DOCKER_ENABLE_SECURITY: "false"
|
||||
PUID: 1000
|
||||
PGID: 1000
|
||||
UMASK: "022"
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -f http://localhost:8080/api/v1/info/status || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 4G
|
||||
|
||||
stirling-pdf-frontend:
|
||||
container_name: Stirling-PDF-Frontend
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: docker/Dockerfile.unified
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
MODE: FRONTEND
|
||||
|
||||
# Point to the backend service
|
||||
VITE_API_BASE_URL: http://stirling-pdf-backend:8080
|
||||
|
||||
# Minimal config needed for frontend
|
||||
PUID: 1000
|
||||
PGID: 1000
|
||||
depends_on:
|
||||
- stirling-pdf-backend
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -f http://localhost:8080/ || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 512M
|
||||
@@ -1,458 +0,0 @@
|
||||
# Stirling-PDF Unified Container
|
||||
|
||||
Single Docker container that can run as **frontend + backend**, **frontend only**, or **backend only** using the `MODE` environment variable.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### MODE=BOTH (Default)
|
||||
Single container with both frontend and backend on port 8080:
|
||||
|
||||
```bash
|
||||
docker run -p 8080:8080 \
|
||||
-e MODE=BOTH \
|
||||
stirlingtools/stirling-pdf:unified
|
||||
```
|
||||
|
||||
Access at: `http://localhost:8080`
|
||||
|
||||
### MODE=FRONTEND
|
||||
Frontend only, connecting to separate backend:
|
||||
|
||||
```bash
|
||||
docker run -p 8080:8080 \
|
||||
-e MODE=FRONTEND \
|
||||
-e VITE_API_BASE_URL=http://backend:8080 \
|
||||
stirlingtools/stirling-pdf:unified
|
||||
```
|
||||
|
||||
### MODE=BACKEND
|
||||
Backend API only:
|
||||
|
||||
```bash
|
||||
docker run -p 8080:8080 \
|
||||
-e MODE=BACKEND \
|
||||
stirlingtools/stirling-pdf:unified
|
||||
```
|
||||
|
||||
Access API at: `http://localhost:8080/api`
|
||||
Swagger UI at: `http://localhost:8080/swagger-ui/index.html`
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
### MODE=BOTH (Default)
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Port 8080 (External) │
|
||||
│ ┌───────────────────────────────┐ │
|
||||
│ │ Nginx │ │
|
||||
│ │ • Serves frontend (/) │ │
|
||||
│ │ • Proxies /api/* → backend │ │
|
||||
│ └───────────┬───────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌───────────▼───────────────────┐ │
|
||||
│ │ Backend (Internal 8081) │ │
|
||||
│ │ • Spring Boot │ │
|
||||
│ │ • PDF Processing │ │
|
||||
│ │ • UnoServer │ │
|
||||
│ └───────────────────────────────┘ │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### MODE=FRONTEND
|
||||
```
|
||||
┌─────────────────────────────┐ ┌──────────────────┐
|
||||
│ Frontend Container │ │ Backend │
|
||||
│ Port 8080 │ │ (External) │
|
||||
│ ┌───────────────────────┐ │ │ │
|
||||
│ │ Nginx │ │──────▶ :8080/api │
|
||||
│ │ • Serves frontend │ │ │ │
|
||||
│ │ • Proxies to backend │ │ │ │
|
||||
│ └───────────────────────┘ │ └──────────────────┘
|
||||
└─────────────────────────────┘
|
||||
```
|
||||
|
||||
### MODE=BACKEND
|
||||
```
|
||||
┌─────────────────────────────┐
|
||||
│ Backend Container │
|
||||
│ Port 8080 │
|
||||
│ ┌───────────────────────┐ │
|
||||
│ │ Spring Boot │ │
|
||||
│ │ • API Endpoints │ │
|
||||
│ │ • PDF Processing │ │
|
||||
│ │ • UnoServer │ │
|
||||
│ └───────────────────────┘ │
|
||||
└─────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables
|
||||
|
||||
### MODE Configuration
|
||||
|
||||
| Variable | Values | Default | Description |
|
||||
|----------|--------|---------|-------------|
|
||||
| `MODE` | `BOTH`, `FRONTEND`, `BACKEND` | `BOTH` | Container operation mode |
|
||||
|
||||
### MODE=BOTH Specific
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `BACKEND_INTERNAL_PORT` | `8081` | Internal port for backend when MODE=BOTH |
|
||||
|
||||
### MODE=FRONTEND Specific
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `VITE_API_BASE_URL` | `http://backend:8080` | Backend URL for API proxying |
|
||||
|
||||
### Standard Configuration
|
||||
|
||||
All modes support standard Stirling-PDF environment variables:
|
||||
|
||||
- `DISABLE_ADDITIONAL_FEATURES` - Enable/disable OCR and LibreOffice features
|
||||
- `DOCKER_ENABLE_SECURITY` - Enable authentication
|
||||
- `PUID` / `PGID` - User/Group IDs
|
||||
- `SYSTEM_MAXFILESIZE` - Max upload size (MB)
|
||||
- `TESSERACT_LANGS` - Comma-separated OCR language codes
|
||||
- `JAVA_CUSTOM_OPTS` - Additional JVM options
|
||||
|
||||
See full configuration docs at: https://docs.stirlingpdf.com
|
||||
|
||||
---
|
||||
|
||||
## Docker Compose Examples
|
||||
|
||||
### Example 1: All-in-One (MODE=BOTH)
|
||||
|
||||
**File:** `docker/compose/docker-compose-unified-both.yml`
|
||||
|
||||
```yaml
|
||||
services:
|
||||
stirling-pdf:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
ports:
|
||||
- "8080:8080"
|
||||
volumes:
|
||||
- ./data:/usr/share/tessdata:rw
|
||||
- ./config:/configs:rw
|
||||
environment:
|
||||
MODE: BOTH
|
||||
restart: unless-stopped
|
||||
```
|
||||
|
||||
### Example 2: Separate Frontend & Backend
|
||||
|
||||
**File:** `docker/compose/docker-compose-unified-frontend.yml`
|
||||
|
||||
```yaml
|
||||
services:
|
||||
backend:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
ports:
|
||||
- "8081:8080"
|
||||
environment:
|
||||
MODE: BACKEND
|
||||
volumes:
|
||||
- ./data:/usr/share/tessdata:rw
|
||||
- ./config:/configs:rw
|
||||
|
||||
frontend:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
MODE: FRONTEND
|
||||
VITE_API_BASE_URL: http://backend:8080
|
||||
depends_on:
|
||||
- backend
|
||||
```
|
||||
|
||||
### Example 3: Backend API Only
|
||||
|
||||
**File:** `docker/compose/docker-compose-unified-backend.yml`
|
||||
|
||||
```yaml
|
||||
services:
|
||||
stirling-pdf-api:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
MODE: BACKEND
|
||||
volumes:
|
||||
- ./data:/usr/share/tessdata:rw
|
||||
- ./config:/configs:rw
|
||||
restart: unless-stopped
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Building the Image
|
||||
|
||||
```bash
|
||||
# From repository root
|
||||
docker build -t stirlingtools/stirling-pdf:unified -f docker/Dockerfile.unified .
|
||||
```
|
||||
|
||||
### Build Arguments
|
||||
|
||||
| Argument | Description |
|
||||
|----------|-------------|
|
||||
| `VERSION_TAG` | Version tag for the image |
|
||||
|
||||
Example:
|
||||
```bash
|
||||
docker build \
|
||||
--build-arg VERSION_TAG=v1.0.0 \
|
||||
-t stirlingtools/stirling-pdf:unified \
|
||||
-f docker/Dockerfile.unified .
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
### 1. Simple Deployment (MODE=BOTH)
|
||||
- **Best for:** Personal use, small teams, simple deployments
|
||||
- **Pros:** Single container, easy setup, minimal configuration
|
||||
- **Cons:** Frontend and backend scale together
|
||||
|
||||
### 2. Scaled Frontend (MODE=FRONTEND + BACKEND)
|
||||
- **Best for:** High traffic, need to scale frontend independently
|
||||
- **Pros:** Scale frontend containers separately, CDN-friendly
|
||||
- **Example:**
|
||||
```yaml
|
||||
services:
|
||||
backend:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
environment:
|
||||
MODE: BACKEND
|
||||
deploy:
|
||||
replicas: 1
|
||||
|
||||
frontend:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
environment:
|
||||
MODE: FRONTEND
|
||||
VITE_API_BASE_URL: http://backend:8080
|
||||
deploy:
|
||||
replicas: 5 # Scale frontend independently
|
||||
```
|
||||
|
||||
### 3. API-Only (MODE=BACKEND)
|
||||
- **Best for:** Headless deployments, custom frontends, API integrations
|
||||
- **Pros:** Minimal resources, no nginx overhead
|
||||
- **Example:** Use with external frontend or API consumers
|
||||
|
||||
### 4. Multi-Backend Setup
|
||||
- **Best for:** Load balancing, high availability
|
||||
- **Example:**
|
||||
```yaml
|
||||
services:
|
||||
backend-1:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
environment:
|
||||
MODE: BACKEND
|
||||
|
||||
backend-2:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
environment:
|
||||
MODE: BACKEND
|
||||
|
||||
frontend:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
environment:
|
||||
MODE: FRONTEND
|
||||
VITE_API_BASE_URL: http://load-balancer:8080
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Port Configuration
|
||||
|
||||
All modes use **port 8080** by default:
|
||||
|
||||
- **MODE=BOTH**: Nginx listens on 8080, proxies to backend on internal 8081
|
||||
- **MODE=FRONTEND**: Nginx listens on 8080
|
||||
- **MODE=BACKEND**: Spring Boot listens on 8080
|
||||
|
||||
**Expose port 8080** in all configurations:
|
||||
```yaml
|
||||
ports:
|
||||
- "8080:8080"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Health Checks
|
||||
|
||||
### MODE=BOTH and MODE=BACKEND
|
||||
```yaml
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -f http://localhost:8080/api/v1/info/status || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
```
|
||||
|
||||
### MODE=FRONTEND
|
||||
```yaml
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -f http://localhost:8080/ || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Check logs
|
||||
```bash
|
||||
docker logs stirling-pdf-container
|
||||
```
|
||||
|
||||
Look for the startup banner:
|
||||
```
|
||||
===================================
|
||||
Stirling-PDF Unified Container
|
||||
MODE: BOTH
|
||||
===================================
|
||||
```
|
||||
|
||||
### Invalid MODE error
|
||||
```
|
||||
ERROR: Invalid MODE 'XYZ'. Must be BOTH, FRONTEND, or BACKEND
|
||||
```
|
||||
**Fix:** Set `MODE` to one of the three valid values.
|
||||
|
||||
### Frontend can't connect to backend (MODE=FRONTEND)
|
||||
**Check:**
|
||||
1. `VITE_API_BASE_URL` points to correct backend URL
|
||||
2. Backend container is running and accessible
|
||||
3. Network connectivity between containers
|
||||
|
||||
### Backend not starting (MODE=BOTH or BACKEND)
|
||||
**Check:**
|
||||
1. Sufficient memory allocated (4GB recommended)
|
||||
2. Java heap size (`JAVA_CUSTOM_OPTS`)
|
||||
3. Volume permissions for `/tmp/stirling-pdf`
|
||||
|
||||
---
|
||||
|
||||
## Migration Guide
|
||||
|
||||
### From Separate Containers → MODE=BOTH
|
||||
|
||||
**Before:**
|
||||
```yaml
|
||||
services:
|
||||
frontend:
|
||||
image: stirlingtools/stirling-pdf:frontend
|
||||
ports: ["80:80"]
|
||||
|
||||
backend:
|
||||
image: stirlingtools/stirling-pdf:backend
|
||||
ports: ["8080:8080"]
|
||||
```
|
||||
|
||||
**After:**
|
||||
```yaml
|
||||
services:
|
||||
stirling-pdf:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
ports: ["8080:8080"]
|
||||
environment:
|
||||
MODE: BOTH
|
||||
```
|
||||
|
||||
### From Legacy → MODE=BACKEND
|
||||
```yaml
|
||||
services:
|
||||
stirling-pdf:
|
||||
image: stirlingtools/stirling-pdf:latest
|
||||
ports: ["8080:8080"]
|
||||
```
|
||||
|
||||
**Becomes:**
|
||||
```yaml
|
||||
services:
|
||||
stirling-pdf:
|
||||
image: stirlingtools/stirling-pdf:unified
|
||||
ports: ["8080:8080"]
|
||||
environment:
|
||||
MODE: BACKEND
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Tuning
|
||||
|
||||
### MODE=BOTH
|
||||
```yaml
|
||||
environment:
|
||||
JAVA_CUSTOM_OPTS: "-Xmx4g -XX:MaxRAMPercentage=75"
|
||||
BACKEND_INTERNAL_PORT: 8081
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 4G
|
||||
reservations:
|
||||
memory: 2G
|
||||
```
|
||||
|
||||
### MODE=FRONTEND (Lightweight)
|
||||
```yaml
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 512M
|
||||
reservations:
|
||||
memory: 256M
|
||||
```
|
||||
|
||||
### MODE=BACKEND (Heavy Processing)
|
||||
```yaml
|
||||
environment:
|
||||
JAVA_CUSTOM_OPTS: "-Xmx8g"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 10G
|
||||
reservations:
|
||||
memory: 4G
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **MODE=BOTH**: Backend not exposed externally (runs on internal port)
|
||||
2. **MODE=BACKEND**: API exposed directly - consider API authentication
|
||||
3. **MODE=FRONTEND**: Only serves static files - minimal attack surface
|
||||
|
||||
Enable security features:
|
||||
```yaml
|
||||
environment:
|
||||
DOCKER_ENABLE_SECURITY: "true"
|
||||
SECURITY_ENABLELOGIN: "true"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Support
|
||||
|
||||
- Documentation: https://docs.stirlingpdf.com
|
||||
- GitHub Issues: https://github.com/Stirling-Tools/Stirling-PDF/issues
|
||||
- Docker Hub: https://hub.docker.com/r/stirlingtools/stirling-pdf
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT License - See repository for full details
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Build script for Stirling-PDF Unified Container
|
||||
# Usage: ./build.sh [version-tag]
|
||||
|
||||
set -e
|
||||
|
||||
VERSION_TAG=${1:-latest}
|
||||
IMAGE_NAME="stirlingtools/stirling-pdf:unified-${VERSION_TAG}"
|
||||
|
||||
echo "==================================="
|
||||
echo "Building Stirling-PDF Unified Container"
|
||||
echo "Version: $VERSION_TAG"
|
||||
echo "Image: $IMAGE_NAME"
|
||||
echo "==================================="
|
||||
|
||||
# Navigate to repository root (assuming script is in docker/unified/)
|
||||
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
REPO_ROOT="$SCRIPT_DIR/../.."
|
||||
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
# Build the image
|
||||
docker build \
|
||||
--build-arg VERSION_TAG="$VERSION_TAG" \
|
||||
-t "$IMAGE_NAME" \
|
||||
-f docker/Dockerfile.unified \
|
||||
.
|
||||
|
||||
echo "==================================="
|
||||
echo "✓ Build complete!"
|
||||
echo "Image: $IMAGE_NAME"
|
||||
echo ""
|
||||
echo "Test the image:"
|
||||
echo " MODE=BOTH: docker run -p 8080:8080 -e MODE=BOTH $IMAGE_NAME"
|
||||
echo " MODE=FRONTEND: docker run -p 8080:8080 -e MODE=FRONTEND $IMAGE_NAME"
|
||||
echo " MODE=BACKEND: docker run -p 8080:8080 -e MODE=BACKEND $IMAGE_NAME"
|
||||
echo "==================================="
|
||||
@@ -1,176 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
# Default MODE to BOTH if not set
|
||||
MODE=${MODE:-BOTH}
|
||||
|
||||
echo "==================================="
|
||||
echo "Stirling-PDF Unified Container"
|
||||
echo "MODE: $MODE"
|
||||
echo "==================================="
|
||||
|
||||
# Function to setup OCR (from init.sh)
|
||||
setup_ocr() {
|
||||
echo "Setting up OCR languages..."
|
||||
|
||||
# Copy tessdata
|
||||
mkdir -p /usr/share/tessdata
|
||||
cp -rn /usr/share/tessdata-original/* /usr/share/tessdata 2>/dev/null || true
|
||||
|
||||
if [ -d /usr/share/tesseract-ocr/4.00/tessdata ]; then
|
||||
cp -r /usr/share/tesseract-ocr/4.00/tessdata/* /usr/share/tessdata 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if [ -d /usr/share/tesseract-ocr/5/tessdata ]; then
|
||||
cp -r /usr/share/tesseract-ocr/5/tessdata/* /usr/share/tessdata 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Install additional languages if specified
|
||||
if [[ -n "$TESSERACT_LANGS" ]]; then
|
||||
SPACE_SEPARATED_LANGS=$(echo $TESSERACT_LANGS | tr ',' ' ')
|
||||
pattern='^[a-zA-Z]{2,4}(_[a-zA-Z]{2,4})?$'
|
||||
for LANG in $SPACE_SEPARATED_LANGS; do
|
||||
if [[ $LANG =~ $pattern ]]; then
|
||||
apk add --no-cache "tesseract-ocr-data-$LANG" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to setup user permissions (from init-without-ocr.sh)
|
||||
setup_permissions() {
|
||||
echo "Setting up user permissions..."
|
||||
|
||||
export JAVA_TOOL_OPTIONS="${JAVA_BASE_OPTS} ${JAVA_CUSTOM_OPTS}"
|
||||
|
||||
# Update user and group IDs
|
||||
if [ ! -z "$PUID" ] && [ "$PUID" != "$(id -u stirlingpdfuser)" ]; then
|
||||
usermod -o -u "$PUID" stirlingpdfuser || true
|
||||
fi
|
||||
|
||||
if [ ! -z "$PGID" ] && [ "$PGID" != "$(getent group stirlingpdfgroup | cut -d: -f3)" ]; then
|
||||
groupmod -o -g "$PGID" stirlingpdfgroup || true
|
||||
fi
|
||||
|
||||
umask "$UMASK" || true
|
||||
|
||||
# Install fonts if needed
|
||||
if [[ -n "$LANGS" ]]; then
|
||||
/scripts/installFonts.sh $LANGS
|
||||
fi
|
||||
|
||||
# Ensure directories exist with correct permissions
|
||||
mkdir -p /tmp/stirling-pdf || true
|
||||
|
||||
# Set ownership and permissions
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup \
|
||||
$HOME /logs /scripts /usr/share/fonts/opentype/noto \
|
||||
/configs /customFiles /pipeline /tmp/stirling-pdf \
|
||||
/var/lib/nginx /var/log/nginx /usr/share/nginx \
|
||||
/app.jar 2>/dev/null || echo "[WARN] Some chown operations failed, may run as host user"
|
||||
|
||||
chmod -R 755 /logs /scripts /usr/share/fonts/opentype/noto \
|
||||
/configs /customFiles /pipeline /tmp/stirling-pdf 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Function to configure nginx
|
||||
configure_nginx() {
|
||||
local backend_url=$1
|
||||
echo "Configuring nginx with backend URL: $backend_url"
|
||||
sed -i "s|\${BACKEND_URL}|${backend_url}|g" /etc/nginx/nginx.conf
|
||||
}
|
||||
|
||||
# Function to run as user or root depending on permissions
|
||||
run_as_user() {
|
||||
if [ "$(id -u)" = "0" ]; then
|
||||
# Running as root, use su-exec
|
||||
su-exec stirlingpdfuser "$@"
|
||||
else
|
||||
# Already running as non-root
|
||||
exec "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
# Setup OCR and permissions
|
||||
setup_ocr
|
||||
setup_permissions
|
||||
|
||||
# Handle different modes
|
||||
case "$MODE" in
|
||||
BOTH)
|
||||
echo "Starting in BOTH mode: Frontend + Backend on port 8080"
|
||||
|
||||
# Configure nginx to proxy to internal backend
|
||||
configure_nginx "http://localhost:${BACKEND_INTERNAL_PORT:-8081}"
|
||||
|
||||
# Start backend on internal port
|
||||
echo "Starting backend on port ${BACKEND_INTERNAL_PORT:-8081}..."
|
||||
run_as_user sh -c "java -Dfile.encoding=UTF-8 \
|
||||
-Djava.io.tmpdir=/tmp/stirling-pdf \
|
||||
-Dserver.port=${BACKEND_INTERNAL_PORT:-8081} \
|
||||
-jar /app.jar" &
|
||||
BACKEND_PID=$!
|
||||
|
||||
# Start unoserver for document conversion
|
||||
run_as_user /opt/venv/bin/unoserver --port 2003 --interface 127.0.0.1 &
|
||||
UNO_PID=$!
|
||||
|
||||
# Wait for backend to start
|
||||
sleep 3
|
||||
|
||||
# Start nginx on port 8080
|
||||
echo "Starting nginx on port 8080..."
|
||||
run_as_user nginx -g "daemon off;" &
|
||||
NGINX_PID=$!
|
||||
|
||||
echo "==================================="
|
||||
echo "✓ Frontend available at: http://localhost:8080"
|
||||
echo "✓ Backend API at: http://localhost:8080/api"
|
||||
echo "✓ Backend running internally on port ${BACKEND_INTERNAL_PORT:-8081}"
|
||||
echo "==================================="
|
||||
;;
|
||||
|
||||
FRONTEND)
|
||||
echo "Starting in FRONTEND mode: Frontend only on port 8080"
|
||||
|
||||
# Configure nginx with external backend URL
|
||||
BACKEND_URL=${VITE_API_BASE_URL:-http://backend:8080}
|
||||
configure_nginx "$BACKEND_URL"
|
||||
|
||||
# Start nginx on port 8080
|
||||
echo "Starting nginx on port 8080..."
|
||||
run_as_user nginx -g "daemon off;" &
|
||||
NGINX_PID=$!
|
||||
|
||||
echo "==================================="
|
||||
echo "✓ Frontend available at: http://localhost:8080"
|
||||
echo "✓ Proxying API calls to: $BACKEND_URL"
|
||||
echo "==================================="
|
||||
;;
|
||||
|
||||
BACKEND)
|
||||
echo "Starting in BACKEND mode: Backend only on port 8080"
|
||||
|
||||
# Start backend on port 8080
|
||||
echo "Starting backend on port 8080..."
|
||||
run_as_user sh -c "java -Dfile.encoding=UTF-8 \
|
||||
-Djava.io.tmpdir=/tmp/stirling-pdf \
|
||||
-Dserver.port=8080 \
|
||||
-jar /app.jar & /opt/venv/bin/unoserver --port 2003 --interface 127.0.0.1" &
|
||||
BACKEND_PID=$!
|
||||
|
||||
echo "==================================="
|
||||
echo "✓ Backend API available at: http://localhost:8080/api"
|
||||
echo "✓ Swagger UI at: http://localhost:8080/swagger-ui/index.html"
|
||||
echo "==================================="
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "ERROR: Invalid MODE '$MODE'. Must be BOTH, FRONTEND, or BACKEND"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
# Wait for all background processes
|
||||
wait
|
||||
@@ -1,118 +0,0 @@
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
# Add .mjs MIME type mapping
|
||||
types {
|
||||
text/javascript mjs;
|
||||
}
|
||||
|
||||
# Gzip compression
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html index.htm;
|
||||
|
||||
# Global settings for file uploads
|
||||
client_max_body_size 100m;
|
||||
|
||||
# Handle client-side routing - support subpaths
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# Proxy API calls to backend
|
||||
location /api/ {
|
||||
proxy_pass ${BACKEND_URL}/api/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
|
||||
# Additional headers for proper API proxying
|
||||
proxy_set_header Connection '';
|
||||
proxy_http_version 1.1;
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
|
||||
# Timeout settings for large file uploads
|
||||
proxy_connect_timeout 60s;
|
||||
proxy_send_timeout 60s;
|
||||
proxy_read_timeout 60s;
|
||||
|
||||
# Request size limits for file uploads
|
||||
client_max_body_size 100m;
|
||||
proxy_request_buffering off;
|
||||
}
|
||||
|
||||
# Proxy Swagger UI to backend (including versioned paths)
|
||||
location ~ ^/swagger-ui(.*)$ {
|
||||
proxy_pass ${BACKEND_URL}/swagger-ui$1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
|
||||
proxy_set_header Connection '';
|
||||
proxy_http_version 1.1;
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
}
|
||||
|
||||
# Proxy API docs to backend (with query parameters and sub-paths)
|
||||
location ~ ^/v3/api-docs(.*)$ {
|
||||
proxy_pass ${BACKEND_URL}/v3/api-docs$1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
}
|
||||
|
||||
# Proxy v1 API docs to backend (with query parameters and sub-paths)
|
||||
location ~ ^/v1/api-docs(.*)$ {
|
||||
proxy_pass ${BACKEND_URL}/v1/api-docs$1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
}
|
||||
|
||||
# Serve .mjs files with correct MIME type (must come before general static assets)
|
||||
location ~* \.mjs$ {
|
||||
try_files $uri =404;
|
||||
add_header Content-Type "text/javascript; charset=utf-8" always;
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# Cache static assets
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# Security headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import eslint from '@eslint/js';
|
||||
import globals from 'globals';
|
||||
import { defineConfig } from 'eslint/config';
|
||||
import tseslint from 'typescript-eslint';
|
||||
// @ts-expect-error - plugin has no types
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
// @ts-expect-error - plugin has no types
|
||||
import importPlugin from 'eslint-plugin-import';
|
||||
|
||||
const srcGlobs = [
|
||||
@@ -26,7 +29,13 @@ export default defineConfig(
|
||||
eslint.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
{
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
},
|
||||
rules: {
|
||||
// React Hooks rules
|
||||
...reactHooks.configs.recommended.rules,
|
||||
// TypeScript rules
|
||||
'@typescript-eslint/no-empty-object-type': [
|
||||
'error',
|
||||
{
|
||||
@@ -39,13 +48,13 @@ export default defineConfig(
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{
|
||||
'args': 'all', // All function args must be used (or explicitly ignored)
|
||||
'argsIgnorePattern': '^_', // Allow unused variables beginning with an underscore
|
||||
'caughtErrors': 'all', // Caught errors must be used (or explicitly ignored)
|
||||
'caughtErrorsIgnorePattern': '^_', // Allow unused variables beginning with an underscore
|
||||
'destructuredArrayIgnorePattern': '^_', // Allow unused variables beginning with an underscore
|
||||
'varsIgnorePattern': '^_', // Allow unused variables beginning with an underscore
|
||||
'ignoreRestSiblings': true, // Allow unused variables when removing attributes from objects (otherwise this requires explicit renaming like `({ x: _x, ...y }) => y`, which is clunky)
|
||||
args: 'all', // All function args must be used (or explicitly ignored)
|
||||
argsIgnorePattern: '^_', // Allow unused variables beginning with an underscore
|
||||
caughtErrors: 'all', // Caught errors must be used (or explicitly ignored)
|
||||
caughtErrorsIgnorePattern: '^_', // Allow unused variables beginning with an underscore
|
||||
destructuredArrayIgnorePattern: '^_', // Allow unused variables beginning with an underscore
|
||||
varsIgnorePattern: '^_', // Allow unused variables beginning with an underscore
|
||||
ignoreRestSiblings: true, // Allow unused variables when removing attributes from objects (otherwise this requires explicit renaming like `({ x: _x, ...y }) => y`, which is clunky)
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
+1
-1
@@ -18,6 +18,6 @@
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/index.tsx"></script>
|
||||
<script type="module" src="/src/index.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Generated
+76
-92
@@ -10,24 +10,25 @@
|
||||
"license": "SEE LICENSE IN https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/refs/heads/main/proprietary/LICENSE",
|
||||
"dependencies": {
|
||||
"@atlaskit/pragmatic-drag-and-drop": "^1.7.7",
|
||||
"@embedpdf/core": "^1.3.14",
|
||||
"@embedpdf/engines": "^1.3.14",
|
||||
"@embedpdf/plugin-annotation": "^1.3.14",
|
||||
"@embedpdf/plugin-export": "^1.3.14",
|
||||
"@embedpdf/plugin-history": "^1.3.14",
|
||||
"@embedpdf/plugin-interaction-manager": "^1.3.14",
|
||||
"@embedpdf/plugin-loader": "^1.3.14",
|
||||
"@embedpdf/plugin-pan": "^1.3.14",
|
||||
"@embedpdf/plugin-render": "^1.3.14",
|
||||
"@embedpdf/plugin-rotate": "^1.3.14",
|
||||
"@embedpdf/plugin-scroll": "^1.3.14",
|
||||
"@embedpdf/plugin-search": "^1.3.14",
|
||||
"@embedpdf/plugin-selection": "^1.3.14",
|
||||
"@embedpdf/plugin-spread": "^1.3.14",
|
||||
"@embedpdf/plugin-thumbnail": "^1.3.14",
|
||||
"@embedpdf/plugin-tiling": "^1.3.14",
|
||||
"@embedpdf/plugin-viewport": "^1.3.14",
|
||||
"@embedpdf/plugin-zoom": "^1.3.14",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@embedpdf/core": "^1.3.1",
|
||||
"@embedpdf/engines": "^1.3.1",
|
||||
"@embedpdf/plugin-annotation": "^1.3.1",
|
||||
"@embedpdf/plugin-export": "^1.3.1",
|
||||
"@embedpdf/plugin-history": "^1.3.1",
|
||||
"@embedpdf/plugin-interaction-manager": "^1.3.1",
|
||||
"@embedpdf/plugin-loader": "^1.3.1",
|
||||
"@embedpdf/plugin-pan": "^1.3.1",
|
||||
"@embedpdf/plugin-render": "^1.3.1",
|
||||
"@embedpdf/plugin-rotate": "^1.3.1",
|
||||
"@embedpdf/plugin-scroll": "^1.3.1",
|
||||
"@embedpdf/plugin-search": "^1.3.1",
|
||||
"@embedpdf/plugin-selection": "^1.3.1",
|
||||
"@embedpdf/plugin-spread": "^1.3.1",
|
||||
"@embedpdf/plugin-thumbnail": "^1.3.1",
|
||||
"@embedpdf/plugin-tiling": "^1.3.1",
|
||||
"@embedpdf/plugin-viewport": "^1.3.1",
|
||||
"@embedpdf/plugin-zoom": "^1.3.1",
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.1",
|
||||
"@iconify/react": "^6.0.2",
|
||||
@@ -38,8 +39,6 @@
|
||||
"@mui/icons-material": "^7.3.2",
|
||||
"@mui/material": "^7.3.2",
|
||||
"@reactour/tour": "^3.8.0",
|
||||
"@stripe/react-stripe-js": "^4.0.2",
|
||||
"@stripe/stripe-js": "^7.9.0",
|
||||
"@tailwindcss/postcss": "^4.1.13",
|
||||
"@tanstack/react-virtual": "^3.13.12",
|
||||
"autoprefixer": "^10.4.21",
|
||||
@@ -96,7 +95,6 @@
|
||||
"typescript": "^5.9.2",
|
||||
"typescript-eslint": "^8.44.1",
|
||||
"vite": "^7.1.7",
|
||||
"vite-tsconfig-paths": "^5.1.4",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
},
|
||||
@@ -503,6 +501,63 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility/node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/@dnd-kit/core": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/core/node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/@dnd-kit/utilities": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
||||
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/utilities/node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/@embedpdf/core": {
|
||||
"version": "1.3.14",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/core/-/core-1.3.14.tgz",
|
||||
@@ -3047,29 +3102,6 @@
|
||||
"url": "https://github.com/sindresorhus/is?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/@stripe/react-stripe-js": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@stripe/react-stripe-js/-/react-stripe-js-4.0.2.tgz",
|
||||
"integrity": "sha512-l2wau+8/LOlHl+Sz8wQ1oDuLJvyw51nQCsu6/ljT6smqzTszcMHifjAJoXlnMfcou3+jK/kQyVe04u/ufyTXgg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prop-types": "^15.7.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@stripe/stripe-js": ">=1.44.1 <8.0.0",
|
||||
"react": ">=16.8.0 <20.0.0",
|
||||
"react-dom": ">=16.8.0 <20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@stripe/stripe-js": {
|
||||
"version": "7.9.0",
|
||||
"resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-7.9.0.tgz",
|
||||
"integrity": "sha512-ggs5k+/0FUJcIgNY08aZTqpBTtbExkJMYMLSMwyucrhtWexVOEY1KJmhBsxf+E/Q15f5rbwBpj+t0t2AW2oCsQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.16"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core": {
|
||||
"version": "1.13.5",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.13.5.tgz",
|
||||
@@ -8003,13 +8035,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/globrex": {
|
||||
"version": "0.1.2",
|
||||
"resolved": "https://registry.npmjs.org/globrex/-/globrex-0.1.2.tgz",
|
||||
"integrity": "sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/gonzales-pe": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/gonzales-pe/-/gonzales-pe-4.3.0.tgz",
|
||||
@@ -13331,27 +13356,6 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/tsconfck": {
|
||||
"version": "3.1.6",
|
||||
"resolved": "https://registry.npmjs.org/tsconfck/-/tsconfck-3.1.6.tgz",
|
||||
"integrity": "sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"tsconfck": "bin/tsconfck.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18 || >=20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/tsconfig-paths": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-4.2.0.tgz",
|
||||
@@ -13882,26 +13886,6 @@
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/vite-tsconfig-paths": {
|
||||
"version": "5.1.4",
|
||||
"resolved": "https://registry.npmjs.org/vite-tsconfig-paths/-/vite-tsconfig-paths-5.1.4.tgz",
|
||||
"integrity": "sha512-cYj0LRuLV2c2sMqhqhGpaO3LretdtMn/BVX4cPLanIZuwwrkVl+lK84E/miEXkCHWXuq65rhNN4rXsBcOB3S4w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "^4.1.1",
|
||||
"globrex": "^0.1.2",
|
||||
"tsconfck": "^3.0.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vite": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"vite": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
|
||||
+23
-28
@@ -6,24 +6,25 @@
|
||||
"proxy": "http://localhost:8080",
|
||||
"dependencies": {
|
||||
"@atlaskit/pragmatic-drag-and-drop": "^1.7.7",
|
||||
"@embedpdf/core": "^1.3.14",
|
||||
"@embedpdf/engines": "^1.3.14",
|
||||
"@embedpdf/plugin-annotation": "^1.3.14",
|
||||
"@embedpdf/plugin-export": "^1.3.14",
|
||||
"@embedpdf/plugin-history": "^1.3.14",
|
||||
"@embedpdf/plugin-interaction-manager": "^1.3.14",
|
||||
"@embedpdf/plugin-loader": "^1.3.14",
|
||||
"@embedpdf/plugin-pan": "^1.3.14",
|
||||
"@embedpdf/plugin-render": "^1.3.14",
|
||||
"@embedpdf/plugin-rotate": "^1.3.14",
|
||||
"@embedpdf/plugin-scroll": "^1.3.14",
|
||||
"@embedpdf/plugin-search": "^1.3.14",
|
||||
"@embedpdf/plugin-selection": "^1.3.14",
|
||||
"@embedpdf/plugin-spread": "^1.3.14",
|
||||
"@embedpdf/plugin-thumbnail": "^1.3.14",
|
||||
"@embedpdf/plugin-tiling": "^1.3.14",
|
||||
"@embedpdf/plugin-viewport": "^1.3.14",
|
||||
"@embedpdf/plugin-zoom": "^1.3.14",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@embedpdf/core": "^1.3.1",
|
||||
"@embedpdf/engines": "^1.3.1",
|
||||
"@embedpdf/plugin-annotation": "^1.3.1",
|
||||
"@embedpdf/plugin-export": "^1.3.1",
|
||||
"@embedpdf/plugin-history": "^1.3.1",
|
||||
"@embedpdf/plugin-interaction-manager": "^1.3.1",
|
||||
"@embedpdf/plugin-loader": "^1.3.1",
|
||||
"@embedpdf/plugin-pan": "^1.3.1",
|
||||
"@embedpdf/plugin-render": "^1.3.1",
|
||||
"@embedpdf/plugin-rotate": "^1.3.1",
|
||||
"@embedpdf/plugin-scroll": "^1.3.1",
|
||||
"@embedpdf/plugin-search": "^1.3.1",
|
||||
"@embedpdf/plugin-selection": "^1.3.1",
|
||||
"@embedpdf/plugin-spread": "^1.3.1",
|
||||
"@embedpdf/plugin-thumbnail": "^1.3.1",
|
||||
"@embedpdf/plugin-tiling": "^1.3.1",
|
||||
"@embedpdf/plugin-viewport": "^1.3.1",
|
||||
"@embedpdf/plugin-zoom": "^1.3.1",
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.1",
|
||||
"@iconify/react": "^6.0.2",
|
||||
@@ -31,8 +32,6 @@
|
||||
"@mantine/dates": "^8.3.1",
|
||||
"@mantine/dropzone": "^8.3.1",
|
||||
"@mantine/hooks": "^8.3.1",
|
||||
"@stripe/react-stripe-js": "^4.0.2",
|
||||
"@stripe/stripe-js": "^7.9.0",
|
||||
"@mui/icons-material": "^7.3.2",
|
||||
"@mui/material": "^7.3.2",
|
||||
"@reactour/tour": "^3.8.0",
|
||||
@@ -59,15 +58,12 @@
|
||||
},
|
||||
"scripts": {
|
||||
"predev": "npm run generate-icons",
|
||||
"dev": "vite",
|
||||
"dev": "npm run typecheck && vite",
|
||||
"prebuild": "npm run generate-icons",
|
||||
"lint": "eslint --max-warnings=0",
|
||||
"build": "vite build",
|
||||
"lint": "eslint",
|
||||
"build": "npm run typecheck && vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck:core": "tsc --noEmit --project tsconfig.core.json",
|
||||
"typecheck:proprietary": "tsc --noEmit --project tsconfig.proprietary.json",
|
||||
"typecheck:all": "npm run typecheck:core && npm run typecheck:proprietary",
|
||||
"check": "npm run typecheck && npm run lint && npm run test:run",
|
||||
"generate-licenses": "node scripts/generate-licenses.js",
|
||||
"generate-icons": "node scripts/generate-icons.js",
|
||||
@@ -125,9 +121,9 @@
|
||||
"@vitejs/plugin-react-swc": "^4.1.0",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"eslint": "^9.36.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-import-resolver-typescript": "^4.4.4",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"jsdom": "^27.0.0",
|
||||
"license-checker": "^25.0.1",
|
||||
"madge": "^8.0.0",
|
||||
@@ -139,7 +135,6 @@
|
||||
"typescript": "^5.9.2",
|
||||
"typescript-eslint": "^8.44.1",
|
||||
"vite": "^7.1.7",
|
||||
"vite-tsconfig-paths": "^5.1.4",
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"depcheck": {
|
||||
|
||||
@@ -250,7 +250,6 @@
|
||||
"title": "Do you want make Stirling PDF better?",
|
||||
"paragraph1": "Stirling PDF has opt in analytics to help us improve the product. We do not track any personal information or file contents.",
|
||||
"paragraph2": "Please consider enabling analytics to help Stirling-PDF grow and to allow us to understand our users better.",
|
||||
"learnMore": "Learn more",
|
||||
"enable": "Enable analytics",
|
||||
"disable": "Disable analytics",
|
||||
"settings": "You can change the settings for analytics in the config/settings.yml file"
|
||||
@@ -298,20 +297,6 @@
|
||||
"general": {
|
||||
"title": "General",
|
||||
"description": "Configure general application preferences.",
|
||||
"account": "Account",
|
||||
"accountDescription": "Manage your account settings",
|
||||
"user": "User",
|
||||
"signedInAs": "Signed in as",
|
||||
"logout": "Log out",
|
||||
"enableFeatures": {
|
||||
"title": "For System Administrators",
|
||||
"intro": "Enable user authentication, team management, and workspace features for your organization.",
|
||||
"action": "Configure",
|
||||
"and": "and",
|
||||
"benefit": "Enables user roles, team collaboration, admin controls, and enterprise features.",
|
||||
"learnMore": "Learn more in documentation",
|
||||
"dismiss": "Dismiss"
|
||||
},
|
||||
"autoUnzip": "Auto-unzip API responses",
|
||||
"autoUnzipDescription": "Automatically extract files from ZIP responses",
|
||||
"autoUnzipTooltip": "Automatically extract ZIP files returned from API operations. Disable to keep ZIP files intact. This does not affect automation workflows.",
|
||||
@@ -413,10 +398,8 @@
|
||||
"top20": "Top 20",
|
||||
"all": "All",
|
||||
"refresh": "Refresh",
|
||||
"dataTypeLabel": "Data Type:",
|
||||
"dataTypeAll": "All",
|
||||
"dataTypeApi": "API",
|
||||
"dataTypeUi": "UI",
|
||||
"includeHomepage": "Include Homepage ('/')",
|
||||
"includeLoginPage": "Include Login Page ('/login')",
|
||||
"totalEndpoints": "Total Endpoints",
|
||||
"totalVisits": "Total Visits",
|
||||
"showing": "Showing",
|
||||
@@ -1001,7 +984,8 @@
|
||||
"title": "Choose Your Split Method"
|
||||
}
|
||||
},
|
||||
"selectMethod": "Select a split method"
|
||||
"selectMethod": "Select a split method",
|
||||
"resultsTitle": "Split Results"
|
||||
},
|
||||
"rotate": {
|
||||
"title": "Rotate PDF",
|
||||
@@ -3077,10 +3061,7 @@
|
||||
"magicLinkSent": "Magic link sent to {{email}}! Check your email and click the link to sign in.",
|
||||
"passwordResetSent": "Password reset link sent to {{email}}! Check your email and follow the instructions.",
|
||||
"failedToSignIn": "Failed to sign in with {{provider}}: {{message}}",
|
||||
"unexpectedError": "Unexpected error: {{message}}",
|
||||
"accountCreatedSuccess": "Account created successfully! You can now sign in.",
|
||||
"passwordChangedSuccess": "Password changed successfully! Please sign in with your new password.",
|
||||
"credentialsUpdated": "Your credentials have been updated. Please sign in again."
|
||||
"unexpectedError": "Unexpected error: {{message}}"
|
||||
},
|
||||
"signup": {
|
||||
"title": "Create an account",
|
||||
@@ -3391,10 +3372,6 @@
|
||||
"title": "Analytics",
|
||||
"description": "These cookies help us understand how our tools are being used, so we can focus on building the features our community values most. Rest assured—Stirling PDF cannot and will never track the content of the documents you work with."
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"posthog": "PostHog Analytics",
|
||||
"scarf": "Scarf Pixel"
|
||||
}
|
||||
},
|
||||
"removeMetadata": {
|
||||
@@ -3461,7 +3438,8 @@
|
||||
"toggleAnnotations": "Toggle Annotations Visibility",
|
||||
"annotationMode": "Toggle Annotation Mode",
|
||||
"draw": "Draw",
|
||||
"save": "Save"
|
||||
"save": "Save",
|
||||
"saveChanges": "Save Changes"
|
||||
},
|
||||
"search": {
|
||||
"title": "Search PDF",
|
||||
@@ -3508,358 +3486,8 @@
|
||||
"help": "Help",
|
||||
"account": "Account",
|
||||
"config": "Config",
|
||||
"adminSettings": "Admin Settings",
|
||||
"allTools": "All Tools"
|
||||
},
|
||||
"admin": {
|
||||
"error": "Error",
|
||||
"success": "Success",
|
||||
"expand": "Expand",
|
||||
"close": "Close",
|
||||
"status": {
|
||||
"active": "Active",
|
||||
"inactive": "Inactive"
|
||||
},
|
||||
"settings": {
|
||||
"title": "Admin Settings",
|
||||
"workspace": "Workspace",
|
||||
"fetchError": "Failed to load settings",
|
||||
"saveError": "Failed to save settings",
|
||||
"saved": "Settings saved successfully",
|
||||
"saveSuccess": "Settings saved successfully",
|
||||
"save": "Save Changes",
|
||||
"restartRequired": "Restart Required",
|
||||
"restart": {
|
||||
"title": "Restart Required",
|
||||
"message": "Settings have been saved successfully. A server restart is required for the changes to take effect.",
|
||||
"question": "Would you like to restart the server now or later?",
|
||||
"now": "Restart Now",
|
||||
"later": "Restart Later"
|
||||
},
|
||||
"restarting": "Restarting Server",
|
||||
"restartingMessage": "The server is restarting. Please wait a moment...",
|
||||
"restartError": "Failed to restart server. Please restart manually.",
|
||||
"general": {
|
||||
"title": "System Settings",
|
||||
"description": "Configure system-wide application settings including branding and default behaviour.",
|
||||
"ui": "User Interface",
|
||||
"system": "System",
|
||||
"appName": "Application Name",
|
||||
"appName.description": "The name displayed in the browser tab and home page",
|
||||
"appNameNavbar": "Navbar Brand",
|
||||
"appNameNavbar.description": "The name displayed in the navigation bar",
|
||||
"homeDescription": "Home Description",
|
||||
"homeDescription.description": "The description text shown on the home page",
|
||||
"defaultLocale": "Default Locale",
|
||||
"defaultLocale.description": "The default language for new users (e.g., en_US, es_ES)",
|
||||
"fileUploadLimit": "File Upload Limit",
|
||||
"fileUploadLimit.description": "Maximum file upload size (e.g., 100MB, 1GB)",
|
||||
"showUpdate": "Show Update Notifications",
|
||||
"showUpdate.description": "Display notifications when a new version is available",
|
||||
"showUpdateOnlyAdmin": "Show Updates to Admins Only",
|
||||
"showUpdateOnlyAdmin.description": "Restrict update notifications to admin users only",
|
||||
"customHTMLFiles": "Custom HTML Files",
|
||||
"customHTMLFiles.description": "Allow serving custom HTML files from the customFiles directory",
|
||||
"languages": "Available Languages",
|
||||
"languages.description": "Languages that users can select from (leave empty to enable all languages)",
|
||||
"customMetadata": "Custom Metadata",
|
||||
"customMetadata.autoUpdate": "Auto Update Metadata",
|
||||
"customMetadata.autoUpdate.description": "Automatically update PDF metadata on all processed documents",
|
||||
"customMetadata.author": "Default Author",
|
||||
"customMetadata.author.description": "Default author for PDF metadata (e.g., username)",
|
||||
"customMetadata.creator": "Default Creator",
|
||||
"customMetadata.creator.description": "Default creator for PDF metadata",
|
||||
"customMetadata.producer": "Default Producer",
|
||||
"customMetadata.producer.description": "Default producer for PDF metadata",
|
||||
"customPaths": "Custom Paths",
|
||||
"customPaths.description": "Configure custom file system paths for pipeline processing and external tools",
|
||||
"customPaths.pipeline": "Pipeline Directories",
|
||||
"customPaths.pipeline.watchedFoldersDir": "Watched Folders Directory",
|
||||
"customPaths.pipeline.watchedFoldersDir.description": "Directory where pipeline monitors for incoming PDFs (leave empty for default: /pipeline/watchedFolders)",
|
||||
"customPaths.pipeline.finishedFoldersDir": "Finished Folders Directory",
|
||||
"customPaths.pipeline.finishedFoldersDir.description": "Directory where processed PDFs are outputted (leave empty for default: /pipeline/finishedFolders)",
|
||||
"customPaths.operations": "External Tool Paths",
|
||||
"customPaths.operations.weasyprint": "WeasyPrint Executable",
|
||||
"customPaths.operations.weasyprint.description": "Path to WeasyPrint executable for HTML to PDF conversion (leave empty for default: /opt/venv/bin/weasyprint)",
|
||||
"customPaths.operations.unoconvert": "Unoconvert Executable",
|
||||
"customPaths.operations.unoconvert.description": "Path to LibreOffice unoconvert for document conversions (leave empty for default: /opt/venv/bin/unoconvert)"
|
||||
},
|
||||
"security": {
|
||||
"title": "Security",
|
||||
"description": "Configure authentication, login behaviour, and security policies.",
|
||||
"ssoNotice": {
|
||||
"title": "Looking for SSO/SAML settings?",
|
||||
"message": "OAuth2 and SAML2 authentication providers have been moved to the Connections menu for easier management."
|
||||
},
|
||||
"authentication": "Authentication",
|
||||
"enableLogin": "Enable Login",
|
||||
"enableLogin.description": "Require users to log in before accessing the application",
|
||||
"loginMethod": "Login Method",
|
||||
"loginMethod.description": "The authentication method to use for user login",
|
||||
"loginMethod.all": "All Methods",
|
||||
"loginMethod.normal": "Username/Password Only",
|
||||
"loginMethod.oauth2": "OAuth2 Only",
|
||||
"loginMethod.saml2": "SAML2 Only",
|
||||
"loginAttemptCount": "Login Attempt Limit",
|
||||
"loginAttemptCount.description": "Maximum number of failed login attempts before account lockout",
|
||||
"loginResetTimeMinutes": "Login Reset Time (minutes)",
|
||||
"loginResetTimeMinutes.description": "Time before failed login attempts are reset",
|
||||
"csrfDisabled": "Disable CSRF Protection",
|
||||
"csrfDisabled.description": "Disable Cross-Site Request Forgery protection (not recommended)",
|
||||
"initialLogin": "Initial Login",
|
||||
"initialLogin.username": "Initial Username",
|
||||
"initialLogin.username.description": "The username for the initial admin account",
|
||||
"initialLogin.password": "Initial Password",
|
||||
"initialLogin.password.description": "The password for the initial admin account",
|
||||
"jwt": "JWT Configuration",
|
||||
"jwt.secureCookie": "Secure Cookie",
|
||||
"jwt.secureCookie.description": "Require HTTPS for JWT cookies (recommended for production)",
|
||||
"jwt.keyRetentionDays": "Key Retention Days",
|
||||
"jwt.keyRetentionDays.description": "Number of days to retain old JWT keys for verification",
|
||||
"jwt.persistence": "Enable Key Persistence",
|
||||
"jwt.persistence.description": "Store JWT keys persistently to survive server restarts",
|
||||
"jwt.enableKeyRotation": "Enable Key Rotation",
|
||||
"jwt.enableKeyRotation.description": "Automatically rotate JWT signing keys periodically",
|
||||
"jwt.enableKeyCleanup": "Enable Key Cleanup",
|
||||
"jwt.enableKeyCleanup.description": "Automatically remove expired JWT keys",
|
||||
"audit": "Audit Logging",
|
||||
"audit.enabled": "Enable Audit Logging",
|
||||
"audit.enabled.description": "Track user actions and system events for compliance and security monitoring",
|
||||
"audit.level": "Audit Level",
|
||||
"audit.level.description": "0=OFF, 1=BASIC, 2=STANDARD, 3=VERBOSE",
|
||||
"audit.retentionDays": "Audit Retention (days)",
|
||||
"audit.retentionDays.description": "Number of days to retain audit logs",
|
||||
"htmlUrlSecurity": "HTML URL Security",
|
||||
"htmlUrlSecurity.description": "Configure URL access restrictions for HTML processing to prevent SSRF attacks",
|
||||
"htmlUrlSecurity.enabled": "Enable URL Security",
|
||||
"htmlUrlSecurity.enabled.description": "Enable URL security restrictions for HTML to PDF conversions",
|
||||
"htmlUrlSecurity.level": "Security Level",
|
||||
"htmlUrlSecurity.level.description": "MAX: whitelist only, MEDIUM: block internal networks, OFF: no restrictions",
|
||||
"htmlUrlSecurity.level.max": "Maximum (Whitelist Only)",
|
||||
"htmlUrlSecurity.level.medium": "Medium (Block Internal)",
|
||||
"htmlUrlSecurity.level.off": "Off (No Restrictions)",
|
||||
"htmlUrlSecurity.advanced": "Advanced Settings",
|
||||
"htmlUrlSecurity.allowedDomains": "Allowed Domains (Whitelist)",
|
||||
"htmlUrlSecurity.allowedDomains.description": "One domain per line (e.g., cdn.example.com). Only these domains allowed when level is MAX",
|
||||
"htmlUrlSecurity.blockedDomains": "Blocked Domains (Blacklist)",
|
||||
"htmlUrlSecurity.blockedDomains.description": "One domain per line (e.g., malicious.com). Additional domains to block",
|
||||
"htmlUrlSecurity.internalTlds": "Internal TLDs",
|
||||
"htmlUrlSecurity.internalTlds.description": "One TLD per line (e.g., .local, .internal). Block domains with these TLD patterns",
|
||||
"htmlUrlSecurity.networkBlocking": "Network Blocking",
|
||||
"htmlUrlSecurity.blockPrivateNetworks": "Block Private Networks",
|
||||
"htmlUrlSecurity.blockPrivateNetworks.description": "Block RFC 1918 private networks (10.x.x.x, 192.168.x.x, 172.16-31.x.x)",
|
||||
"htmlUrlSecurity.blockLocalhost": "Block Localhost",
|
||||
"htmlUrlSecurity.blockLocalhost.description": "Block localhost and loopback addresses (127.x.x.x, ::1)",
|
||||
"htmlUrlSecurity.blockLinkLocal": "Block Link-Local Addresses",
|
||||
"htmlUrlSecurity.blockLinkLocal.description": "Block link-local addresses (169.254.x.x, fe80::/10)",
|
||||
"htmlUrlSecurity.blockCloudMetadata": "Block Cloud Metadata Endpoints",
|
||||
"htmlUrlSecurity.blockCloudMetadata.description": "Block cloud provider metadata endpoints (169.254.169.254)"
|
||||
},
|
||||
"connections": {
|
||||
"title": "Connections",
|
||||
"description": "Configure external authentication providers like OAuth2 and SAML.",
|
||||
"linkedServices": "Linked Services",
|
||||
"unlinkedServices": "Unlinked Services",
|
||||
"connect": "Connect",
|
||||
"disconnect": "Disconnect",
|
||||
"disconnected": "Provider disconnected successfully",
|
||||
"disconnectError": "Failed to disconnect provider",
|
||||
"ssoAutoLogin": "SSO Auto Login",
|
||||
"ssoAutoLogin.enable": "Enable SSO Auto Login",
|
||||
"ssoAutoLogin.description": "Automatically redirect to SSO login when authentication is required",
|
||||
"oauth2": "OAuth2",
|
||||
"oauth2.enabled": "Enable OAuth2",
|
||||
"oauth2.enabled.description": "Allow users to authenticate using OAuth2 providers",
|
||||
"oauth2.provider": "Provider",
|
||||
"oauth2.provider.description": "The OAuth2 provider to use for authentication",
|
||||
"oauth2.issuer": "Issuer URL",
|
||||
"oauth2.issuer.description": "The OAuth2 provider issuer URL",
|
||||
"oauth2.clientId": "Client ID",
|
||||
"oauth2.clientId.description": "The OAuth2 client ID from your provider",
|
||||
"oauth2.clientSecret": "Client Secret",
|
||||
"oauth2.clientSecret.description": "The OAuth2 client secret from your provider",
|
||||
"oauth2.useAsUsername": "Use as Username",
|
||||
"oauth2.useAsUsername.description": "The OAuth2 claim to use as the username (e.g., email, sub)",
|
||||
"oauth2.autoCreateUser": "Auto Create Users",
|
||||
"oauth2.autoCreateUser.description": "Automatically create user accounts on first OAuth2 login",
|
||||
"oauth2.blockRegistration": "Block Registration",
|
||||
"oauth2.blockRegistration.description": "Prevent new user registration via OAuth2",
|
||||
"oauth2.scopes": "OAuth2 Scopes",
|
||||
"oauth2.scopes.description": "Comma-separated list of OAuth2 scopes to request (e.g., openid, profile, email)",
|
||||
"saml2": "SAML2",
|
||||
"saml2.enabled": "Enable SAML2",
|
||||
"saml2.enabled.description": "Allow users to authenticate using SAML2 providers",
|
||||
"saml2.provider": "Provider",
|
||||
"saml2.provider.description": "The SAML2 provider name",
|
||||
"saml2.registrationId": "Registration ID",
|
||||
"saml2.registrationId.description": "The SAML2 registration identifier",
|
||||
"saml2.autoCreateUser": "Auto Create Users",
|
||||
"saml2.autoCreateUser.description": "Automatically create user accounts on first SAML2 login",
|
||||
"saml2.blockRegistration": "Block Registration",
|
||||
"saml2.blockRegistration.description": "Prevent new user registration via SAML2"
|
||||
},
|
||||
"database": {
|
||||
"title": "Database",
|
||||
"description": "Configure custom database connection settings for enterprise deployments.",
|
||||
"configuration": "Database Configuration",
|
||||
"enableCustom": "Enable Custom Database",
|
||||
"enableCustom.description": "Use your own custom database configuration instead of the default embedded database",
|
||||
"customUrl": "Custom Database URL",
|
||||
"customUrl.description": "Full JDBC connection string (e.g., jdbc:postgresql://localhost:5432/postgres). If provided, individual connection settings below are not used.",
|
||||
"type": "Database Type",
|
||||
"type.description": "Type of database (not used if custom URL is provided)",
|
||||
"hostName": "Host Name",
|
||||
"hostName.description": "Database server hostname (not used if custom URL is provided)",
|
||||
"port": "Port",
|
||||
"port.description": "Database server port (not used if custom URL is provided)",
|
||||
"name": "Database Name",
|
||||
"name.description": "Name of the database (not used if custom URL is provided)",
|
||||
"username": "Username",
|
||||
"username.description": "Database authentication username",
|
||||
"password": "Password",
|
||||
"password.description": "Database authentication password"
|
||||
},
|
||||
"privacy": {
|
||||
"title": "Privacy",
|
||||
"description": "Configure privacy and data collection settings.",
|
||||
"analytics": "Analytics & Tracking",
|
||||
"enableAnalytics": "Enable Analytics",
|
||||
"enableAnalytics.description": "Collect anonymous usage analytics to help improve the application",
|
||||
"metricsEnabled": "Enable Metrics",
|
||||
"metricsEnabled.description": "Enable collection of performance and usage metrics",
|
||||
"searchEngine": "Search Engine Visibility",
|
||||
"googleVisibility": "Google Visibility",
|
||||
"googleVisibility.description": "Allow search engines to index this application"
|
||||
},
|
||||
"advanced": {
|
||||
"title": "Advanced",
|
||||
"description": "Configure advanced features and experimental functionality.",
|
||||
"features": "Feature Flags",
|
||||
"processing": "Processing",
|
||||
"endpoints": "Endpoints",
|
||||
"endpoints.manage": "Manage API Endpoints",
|
||||
"endpoints.description": "Endpoint management is configured via YAML. See documentation for details on enabling/disabling specific endpoints.",
|
||||
"enableAlphaFunctionality": "Enable Alpha Features",
|
||||
"enableAlphaFunctionality.description": "Enable experimental and alpha-stage features (may be unstable)",
|
||||
"enableUrlToPDF": "Enable URL to PDF",
|
||||
"enableUrlToPDF.description": "Allow conversion of web pages to PDF documents",
|
||||
"maxDPI": "Maximum DPI",
|
||||
"maxDPI.description": "Maximum DPI for image processing (0 = unlimited)",
|
||||
"tessdataDir": "Tessdata Directory",
|
||||
"tessdataDir.description": "Path to the tessdata directory for OCR language files",
|
||||
"disableSanitize": "Disable HTML Sanitization",
|
||||
"disableSanitize.description": "WARNING: Security risk - disabling HTML sanitization can lead to XSS vulnerabilities",
|
||||
"tempFileManagement": "Temp File Management",
|
||||
"tempFileManagement.description": "Configure temporary file storage and cleanup behavior",
|
||||
"tempFileManagement.baseTmpDir": "Base Temp Directory",
|
||||
"tempFileManagement.baseTmpDir.description": "Base directory for temporary files (leave empty for default: java.io.tmpdir/stirling-pdf)",
|
||||
"tempFileManagement.libreofficeDir": "LibreOffice Temp Directory",
|
||||
"tempFileManagement.libreofficeDir.description": "Directory for LibreOffice temp files (leave empty for default: baseTmpDir/libreoffice)",
|
||||
"tempFileManagement.systemTempDir": "System Temp Directory",
|
||||
"tempFileManagement.systemTempDir.description": "System temp directory to clean (only used if cleanupSystemTemp is enabled)",
|
||||
"tempFileManagement.prefix": "Temp File Prefix",
|
||||
"tempFileManagement.prefix.description": "Prefix for temp file names",
|
||||
"tempFileManagement.maxAgeHours": "Max Age (hours)",
|
||||
"tempFileManagement.maxAgeHours.description": "Maximum age in hours before temp files are cleaned up",
|
||||
"tempFileManagement.cleanupIntervalMinutes": "Cleanup Interval (minutes)",
|
||||
"tempFileManagement.cleanupIntervalMinutes.description": "How often to run cleanup (in minutes)",
|
||||
"tempFileManagement.startupCleanup": "Startup Cleanup",
|
||||
"tempFileManagement.startupCleanup.description": "Clean up old temp files on application startup",
|
||||
"tempFileManagement.cleanupSystemTemp": "Cleanup System Temp",
|
||||
"tempFileManagement.cleanupSystemTemp.description": "Whether to clean broader system temp directory (use with caution)",
|
||||
"processExecutor": "Process Executor Limits",
|
||||
"processExecutor.description": "Configure session limits and timeouts for each process executor",
|
||||
"processExecutor.sessionLimit": "Session Limit",
|
||||
"processExecutor.sessionLimit.description": "Maximum concurrent instances",
|
||||
"processExecutor.timeout": "Timeout (minutes)",
|
||||
"processExecutor.timeout.description": "Maximum execution time",
|
||||
"processExecutor.libreOffice": "LibreOffice",
|
||||
"processExecutor.pdfToHtml": "PDF to HTML",
|
||||
"processExecutor.qpdf": "QPDF",
|
||||
"processExecutor.tesseract": "Tesseract OCR",
|
||||
"processExecutor.pythonOpenCv": "Python OpenCV",
|
||||
"processExecutor.weasyPrint": "WeasyPrint",
|
||||
"processExecutor.installApp": "Install App",
|
||||
"processExecutor.calibre": "Calibre",
|
||||
"processExecutor.ghostscript": "Ghostscript",
|
||||
"processExecutor.ocrMyPdf": "OCRmyPDF"
|
||||
},
|
||||
"mail": {
|
||||
"title": "Mail Server",
|
||||
"description": "Configure SMTP settings for sending email notifications.",
|
||||
"smtp": "SMTP Configuration",
|
||||
"enabled": "Enable Mail",
|
||||
"enabled.description": "Enable email notifications and SMTP functionality",
|
||||
"host": "SMTP Host",
|
||||
"host.description": "The hostname or IP address of your SMTP server",
|
||||
"port": "SMTP Port",
|
||||
"port.description": "The port number for SMTP connection (typically 25, 465, or 587)",
|
||||
"username": "SMTP Username",
|
||||
"username.description": "Username for SMTP authentication",
|
||||
"password": "SMTP Password",
|
||||
"password.description": "Password for SMTP authentication",
|
||||
"from": "From Address",
|
||||
"from.description": "The email address to use as the sender",
|
||||
"enableInvites": "Enable Email Invites",
|
||||
"enableInvites.description": "Allow admins to invite users via email with auto-generated passwords"
|
||||
},
|
||||
"legal": {
|
||||
"title": "Legal Documents",
|
||||
"description": "Configure links to legal documents and policies.",
|
||||
"disclaimer": {
|
||||
"title": "Legal Responsibility Warning",
|
||||
"message": "By customizing these legal documents, you assume full responsibility for ensuring compliance with all applicable laws and regulations, including but not limited to GDPR and other EU data protection requirements. Only modify these settings if: (1) you are operating a personal/private instance, (2) you are outside EU jurisdiction and understand your local legal obligations, or (3) you have obtained proper legal counsel and accept sole responsibility for all user data and legal compliance. Stirling-PDF and its developers assume no liability for your legal obligations."
|
||||
},
|
||||
"termsAndConditions": "Terms and Conditions",
|
||||
"termsAndConditions.description": "URL or filename to terms and conditions",
|
||||
"privacyPolicy": "Privacy Policy",
|
||||
"privacyPolicy.description": "URL or filename to privacy policy",
|
||||
"accessibilityStatement": "Accessibility Statement",
|
||||
"accessibilityStatement.description": "URL or filename to accessibility statement",
|
||||
"cookiePolicy": "Cookie Policy",
|
||||
"cookiePolicy.description": "URL or filename to cookie policy",
|
||||
"impressum": "Impressum",
|
||||
"impressum.description": "URL or filename to impressum (required in some jurisdictions)"
|
||||
},
|
||||
"premium": {
|
||||
"title": "Premium & Enterprise",
|
||||
"description": "Configure your premium or enterprise license key.",
|
||||
"license": "License Configuration",
|
||||
"key": "License Key",
|
||||
"key.description": "Enter your premium or enterprise license key",
|
||||
"enabled": "Enable Premium Features",
|
||||
"enabled.description": "Enable license key checks for pro/enterprise features",
|
||||
"movedFeatures": {
|
||||
"title": "Premium Features Distributed",
|
||||
"message": "Premium and Enterprise features are now organized in their respective sections:"
|
||||
}
|
||||
},
|
||||
"features": {
|
||||
"title": "Features",
|
||||
"description": "Configure optional features and functionality.",
|
||||
"serverCertificate": "Server Certificate",
|
||||
"serverCertificate.description": "Configure server-side certificate generation for \"Sign with Stirling-PDF\" functionality",
|
||||
"serverCertificate.enabled": "Enable Server Certificate",
|
||||
"serverCertificate.enabled.description": "Enable server-side certificate for \"Sign with Stirling-PDF\" option",
|
||||
"serverCertificate.organizationName": "Organization Name",
|
||||
"serverCertificate.organizationName.description": "Organization name for generated certificates",
|
||||
"serverCertificate.validity": "Certificate Validity (days)",
|
||||
"serverCertificate.validity.description": "Number of days the certificate will be valid",
|
||||
"serverCertificate.regenerateOnStartup": "Regenerate on Startup",
|
||||
"serverCertificate.regenerateOnStartup.description": "Generate new certificate on each application startup"
|
||||
},
|
||||
"endpoints": {
|
||||
"title": "API Endpoints",
|
||||
"description": "Control which API endpoints and endpoint groups are available.",
|
||||
"management": "Endpoint Management",
|
||||
"toRemove": "Disabled Endpoints",
|
||||
"toRemove.description": "Select individual endpoints to disable",
|
||||
"groupsToRemove": "Disabled Endpoint Groups",
|
||||
"groupsToRemove.description": "Select endpoint groups to disable",
|
||||
"note": "Note: Disabling endpoints restricts API access but does not remove UI components. Restart required for changes to take effect."
|
||||
}
|
||||
}
|
||||
},
|
||||
"fileUpload": {
|
||||
"selectFile": "Select a file",
|
||||
"selectFiles": "Select files",
|
||||
@@ -4217,10 +3845,6 @@
|
||||
"preview": "Preview"
|
||||
},
|
||||
"config": {
|
||||
"overview": {
|
||||
"title": "Application Configuration",
|
||||
"description": "Current application settings and configuration details."
|
||||
},
|
||||
"account": {
|
||||
"overview": {
|
||||
"title": "Account Settings",
|
||||
@@ -4421,440 +4045,5 @@
|
||||
"finish": "Finish",
|
||||
"startTour": "Start Tour",
|
||||
"startTourDescription": "Take a guided tour of Stirling PDF's key features"
|
||||
},
|
||||
"workspace": {
|
||||
"title": "Workspace",
|
||||
"people": {
|
||||
"title": "People",
|
||||
"description": "Manage workspace members and their permissions",
|
||||
"loading": "Loading people...",
|
||||
"searchMembers": "Search members...",
|
||||
"addMembers": "Add Members",
|
||||
"inviteMembers": "Invite Members",
|
||||
"inviteMembers.subtitle": "Type or paste in emails below, separated by commas. Your workspace will be billed by members.",
|
||||
"user": "User",
|
||||
"role": "Role",
|
||||
"team": "Team",
|
||||
"status": "Status",
|
||||
"actions": "Actions",
|
||||
"noMembersFound": "No members found",
|
||||
"active": "Active",
|
||||
"disabled": "Disabled",
|
||||
"activeSession": "Active session",
|
||||
"member": "Member",
|
||||
"admin": "Admin",
|
||||
"roleDescriptions": {
|
||||
"admin": "Can manage settings and invite members, with full administrative access.",
|
||||
"member": "Can view and edit shared files, but cannot manage workspace settings or members."
|
||||
},
|
||||
"editRole": "Edit Role",
|
||||
"enable": "Enable",
|
||||
"disable": "Disable",
|
||||
"deleteUser": "Delete User",
|
||||
"deleteUserSuccess": "User deleted successfully",
|
||||
"deleteUserError": "Failed to delete user",
|
||||
"confirmDelete": "Are you sure you want to delete this user? This action cannot be undone.",
|
||||
"addMember": {
|
||||
"title": "Add Member",
|
||||
"username": "Username (Email)",
|
||||
"usernamePlaceholder": "user@example.com",
|
||||
"password": "Password",
|
||||
"passwordPlaceholder": "Enter password",
|
||||
"role": "Role",
|
||||
"team": "Team (Optional)",
|
||||
"teamPlaceholder": "Select a team",
|
||||
"forcePasswordChange": "Force password change on first login",
|
||||
"cancel": "Cancel",
|
||||
"submit": "Add Member",
|
||||
"usernameRequired": "Username and password are required",
|
||||
"passwordTooShort": "Password must be at least 6 characters",
|
||||
"success": "User created successfully",
|
||||
"error": "Failed to create user"
|
||||
},
|
||||
"editMember": {
|
||||
"title": "Edit Member",
|
||||
"editing": "Editing:",
|
||||
"role": "Role",
|
||||
"team": "Team (Optional)",
|
||||
"teamPlaceholder": "Select a team",
|
||||
"cancel": "Cancel",
|
||||
"submit": "Update Member",
|
||||
"success": "User updated successfully",
|
||||
"error": "Failed to update user"
|
||||
},
|
||||
"toggleEnabled": {
|
||||
"success": "User status updated successfully",
|
||||
"error": "Failed to update user status"
|
||||
},
|
||||
"delete": {
|
||||
"success": "User deleted successfully",
|
||||
"error": "Failed to delete user"
|
||||
},
|
||||
"emailInvite": {
|
||||
"tab": "Email Invite",
|
||||
"description": "Type or paste in emails below, separated by commas. Users will receive login credentials via email.",
|
||||
"emails": "Email Addresses",
|
||||
"emailsPlaceholder": "user1@example.com, user2@example.com",
|
||||
"emailsRequired": "At least one email address is required",
|
||||
"submit": "Send Invites",
|
||||
"success": "user(s) invited successfully",
|
||||
"partialSuccess": "Some invites failed",
|
||||
"allFailed": "Failed to invite users",
|
||||
"error": "Failed to send invites"
|
||||
},
|
||||
"directInvite": {
|
||||
"tab": "Direct Create"
|
||||
},
|
||||
"inviteLinkTab": {
|
||||
"tab": "Invite Link"
|
||||
},
|
||||
"inviteLink": {
|
||||
"description": "Generate a secure link that allows the user to set their own password",
|
||||
"email": "Email Address",
|
||||
"emailRequired": "Email address is required",
|
||||
"emailOptional": "Optional - leave blank for a general invite link",
|
||||
"emailRequiredForSend": "Email address is required to send email notification",
|
||||
"expiryHours": "Expiry Hours",
|
||||
"expiryDescription": "How many hours until the link expires",
|
||||
"sendEmail": "Send invite link via email",
|
||||
"smtpRequired": "SMTP not configured",
|
||||
"generate": "Generate Link",
|
||||
"generated": "Invite Link Generated",
|
||||
"copied": "Link copied to clipboard",
|
||||
"success": "Invite link generated successfully",
|
||||
"successWithEmail": "Invite link generated and sent via email",
|
||||
"emailFailed": "Email failed to send",
|
||||
"error": "Failed to generate invite link"
|
||||
},
|
||||
"inviteMode": {
|
||||
"username": "Username",
|
||||
"email": "Email",
|
||||
"emailDisabled": "Email invites require SMTP configuration and mail.enableInvites=true in settings"
|
||||
},
|
||||
"license": {
|
||||
"users": "users",
|
||||
"availableSlots": "Available Slots",
|
||||
"grandfathered": "Grandfathered",
|
||||
"grandfatheredShort": "{{count}} grandfathered",
|
||||
"fromLicense": "from license",
|
||||
"slotsAvailable": "{{count}} user slot(s) available",
|
||||
"noSlotsAvailable": "No slots available",
|
||||
"currentUsage": "Currently using {{current}} of {{max}} user licences"
|
||||
}
|
||||
},
|
||||
"teams": {
|
||||
"title": "Teams",
|
||||
"description": "Manage teams and organize workspace members",
|
||||
"loading": "Loading teams...",
|
||||
"loadingDetails": "Loading team details...",
|
||||
"createNewTeam": "Create New Team",
|
||||
"teamName": "Team Name",
|
||||
"totalMembers": "Total Members",
|
||||
"actions": "Actions",
|
||||
"noTeamsFound": "No teams found",
|
||||
"noMembers": "No members in this team",
|
||||
"system": "System",
|
||||
"addMember": "Add Member",
|
||||
"viewTeam": "View Team",
|
||||
"removeMember": "Remove from team",
|
||||
"cannotRemoveFromSystemTeam": "Cannot remove from system team",
|
||||
"renameTeamLabel": "Rename Team",
|
||||
"deleteTeamLabel": "Delete Team",
|
||||
"cannotDeleteInternal": "Cannot delete the Internal team",
|
||||
"confirmDelete": "Are you sure you want to delete this team? This team must be empty to delete.",
|
||||
"confirmRemove": "Remove user from this team?",
|
||||
"cannotRenameInternal": "Cannot rename the Internal team",
|
||||
"cannotAddToInternal": "Cannot add members to the Internal team",
|
||||
"teamNotFound": "Team not found",
|
||||
"backToTeams": "Back to Teams",
|
||||
"memberCount": "{{count}} members",
|
||||
"removeMemberSuccess": "User removed from team",
|
||||
"removeMemberError": "Failed to remove user from team",
|
||||
"createTeam": {
|
||||
"title": "Create New Team",
|
||||
"teamName": "Team Name",
|
||||
"teamNamePlaceholder": "Enter team name",
|
||||
"cancel": "Cancel",
|
||||
"submit": "Create Team",
|
||||
"nameRequired": "Team name is required",
|
||||
"success": "Team created successfully",
|
||||
"error": "Failed to create team"
|
||||
},
|
||||
"renameTeam": {
|
||||
"title": "Rename Team",
|
||||
"renaming": "Renaming:",
|
||||
"newTeamName": "New Team Name",
|
||||
"newTeamNamePlaceholder": "Enter new team name",
|
||||
"cancel": "Cancel",
|
||||
"submit": "Rename Team",
|
||||
"nameRequired": "Team name is required",
|
||||
"success": "Team renamed successfully",
|
||||
"error": "Failed to rename team"
|
||||
},
|
||||
"deleteTeam": {
|
||||
"success": "Team deleted successfully",
|
||||
"error": "Failed to delete team. Make sure the team is empty.",
|
||||
"teamMustBeEmpty": "Team must be empty before deletion"
|
||||
},
|
||||
"addMemberToTeam": {
|
||||
"title": "Add Member to Team",
|
||||
"addingTo": "Adding to",
|
||||
"selectUser": "Select User",
|
||||
"selectUserPlaceholder": "Choose a user",
|
||||
"selectUserRequired": "Please select a user",
|
||||
"currentlyIn": "currently in",
|
||||
"willBeMoved": "Note: This user will be moved from their current team to this team.",
|
||||
"cancel": "Cancel",
|
||||
"submit": "Add Member",
|
||||
"userRequired": "Please select a user",
|
||||
"success": "Member added to team successfully",
|
||||
"error": "Failed to add member to team"
|
||||
},
|
||||
"changeTeam": {
|
||||
"label": "Change Team",
|
||||
"title": "Change Team",
|
||||
"changing": "Moving",
|
||||
"selectTeam": "Select Team",
|
||||
"selectTeamPlaceholder": "Choose a team",
|
||||
"selectTeamRequired": "Please select a team",
|
||||
"success": "Team changed successfully",
|
||||
"error": "Failed to change team",
|
||||
"submit": "Change Team"
|
||||
}
|
||||
}
|
||||
},
|
||||
"plan": {
|
||||
"currency": "Currency",
|
||||
"popular": "Popular",
|
||||
"current": "Current Plan",
|
||||
"upgrade": "Upgrade",
|
||||
"contact": "Contact Us",
|
||||
"customPricing": "Custom",
|
||||
"showComparison": "Compare All Features",
|
||||
"hideComparison": "Hide Feature Comparison",
|
||||
"featureComparison": "Feature Comparison",
|
||||
"activePlan": {
|
||||
"title": "Active Plan",
|
||||
"subtitle": "Your current subscription details"
|
||||
},
|
||||
"availablePlans": {
|
||||
"title": "Available Plans",
|
||||
"subtitle": "Choose the plan that fits your needs"
|
||||
},
|
||||
"static": {
|
||||
"title": "Billing Information",
|
||||
"message": "Online billing is not currently configured. To upgrade your plan or manage subscriptions, please contact us directly.",
|
||||
"contactSales": "Contact Sales",
|
||||
"contactToUpgrade": "Contact us to upgrade or customize your plan",
|
||||
"maxUsers": "Max Users",
|
||||
"upTo": "Up to"
|
||||
},
|
||||
"period": {
|
||||
"month": "month"
|
||||
},
|
||||
"free": {
|
||||
"name": "Free",
|
||||
"highlight1": "Limited Tool Usage Per week",
|
||||
"highlight2": "Access to all tools",
|
||||
"highlight3": "Community support"
|
||||
},
|
||||
"pro": {
|
||||
"name": "Pro",
|
||||
"highlight1": "Unlimited Tool Usage",
|
||||
"highlight2": "Advanced PDF tools",
|
||||
"highlight3": "No watermarks"
|
||||
},
|
||||
"enterprise": {
|
||||
"name": "Enterprise",
|
||||
"highlight1": "Custom pricing",
|
||||
"highlight2": "Dedicated support",
|
||||
"highlight3": "Latest features"
|
||||
},
|
||||
"feature": {
|
||||
"title": "Feature",
|
||||
"pdfTools": "Basic PDF Tools",
|
||||
"fileSize": "File Size Limit",
|
||||
"automation": "Automate tool workflows",
|
||||
"api": "API Access",
|
||||
"priority": "Priority Support",
|
||||
"customPricing": "Custom Pricing"
|
||||
}
|
||||
},
|
||||
"subscription": {
|
||||
"status": {
|
||||
"active": "Active",
|
||||
"pastDue": "Past Due",
|
||||
"canceled": "Canceled",
|
||||
"incomplete": "Incomplete",
|
||||
"trialing": "Trial",
|
||||
"none": "No Subscription"
|
||||
},
|
||||
"renewsOn": "Renews on {{date}}",
|
||||
"cancelsOn": "Cancels on {{date}}"
|
||||
},
|
||||
"billing": {
|
||||
"manageBilling": "Manage Billing",
|
||||
"portal": {
|
||||
"error": "Failed to open billing portal"
|
||||
}
|
||||
},
|
||||
"payment": {
|
||||
"preparing": "Preparing your checkout...",
|
||||
"upgradeTitle": "Upgrade to {{planName}}",
|
||||
"success": "Payment Successful!",
|
||||
"successMessage": "Your subscription has been activated successfully. You will receive a confirmation email shortly.",
|
||||
"autoClose": "This window will close automatically...",
|
||||
"error": "Payment Error"
|
||||
},
|
||||
"firstLogin": {
|
||||
"title": "First Time Login",
|
||||
"welcomeTitle": "Welcome!",
|
||||
"welcomeMessage": "For security reasons, you must change your password on your first login.",
|
||||
"loggedInAs": "Logged in as",
|
||||
"error": "Error",
|
||||
"currentPassword": "Current Password",
|
||||
"enterCurrentPassword": "Enter your current password",
|
||||
"newPassword": "New Password",
|
||||
"enterNewPassword": "Enter new password (min 8 characters)",
|
||||
"confirmPassword": "Confirm New Password",
|
||||
"reEnterNewPassword": "Re-enter new password",
|
||||
"changePassword": "Change Password",
|
||||
"allFieldsRequired": "All fields are required",
|
||||
"passwordsDoNotMatch": "New passwords do not match",
|
||||
"passwordTooShort": "Password must be at least 8 characters",
|
||||
"passwordMustBeDifferent": "New password must be different from current password",
|
||||
"passwordChangedSuccess": "Password changed successfully! Please log in again.",
|
||||
"passwordChangeFailed": "Failed to change password. Please check your current password."
|
||||
},
|
||||
"invite": {
|
||||
"welcome": "Welcome to Stirling PDF",
|
||||
"invalidToken": "Invalid invitation link",
|
||||
"validationError": "Failed to validate invitation link",
|
||||
"passwordRequired": "Password is required",
|
||||
"passwordTooShort": "Password must be at least 6 characters",
|
||||
"passwordMismatch": "Passwords do not match",
|
||||
"acceptError": "Failed to create account",
|
||||
"validating": "Validating invitation...",
|
||||
"invalidInvitation": "Invalid Invitation",
|
||||
"goToLogin": "Go to Login",
|
||||
"welcomeTitle": "You've been invited!",
|
||||
"welcomeSubtitle": "Complete your account setup to get started",
|
||||
"accountFor": "Creating account for",
|
||||
"linkExpires": "Link expires",
|
||||
"email": "Email address",
|
||||
"emailPlaceholder": "Enter your email address",
|
||||
"emailRequired": "Email address is required",
|
||||
"invalidEmail": "Invalid email address",
|
||||
"choosePassword": "Choose a password",
|
||||
"passwordPlaceholder": "Enter your password",
|
||||
"confirmPassword": "Confirm password",
|
||||
"confirmPasswordPlaceholder": "Re-enter your password",
|
||||
"createAccount": "Create Account",
|
||||
"creating": "Creating Account...",
|
||||
"alreadyHaveAccount": "Already have an account?",
|
||||
"signIn": "Sign in"
|
||||
},
|
||||
"audit": {
|
||||
"error": {
|
||||
"title": "Error loading audit system"
|
||||
},
|
||||
"notAvailable": "Audit system not available",
|
||||
"notAvailableMessage": "The audit system is not configured or not available.",
|
||||
"disabled": "Audit logging is disabled",
|
||||
"disabledMessage": "Enable audit logging in your application configuration to track system events.",
|
||||
"systemStatus": {
|
||||
"title": "System Status",
|
||||
"status": "Audit Logging",
|
||||
"enabled": "Enabled",
|
||||
"disabled": "Disabled",
|
||||
"level": "Audit Level",
|
||||
"retention": "Retention Period",
|
||||
"days": "days",
|
||||
"totalEvents": "Total Events"
|
||||
},
|
||||
"tabs": {
|
||||
"dashboard": "Dashboard",
|
||||
"events": "Audit Events",
|
||||
"export": "Export"
|
||||
},
|
||||
"charts": {
|
||||
"title": "Audit Dashboard",
|
||||
"error": "Error loading charts",
|
||||
"day": "Day",
|
||||
"week": "Week",
|
||||
"month": "Month",
|
||||
"byType": "Events by Type",
|
||||
"byUser": "Events by User",
|
||||
"overTime": "Events Over Time"
|
||||
},
|
||||
"events": {
|
||||
"title": "Audit Events",
|
||||
"filterByType": "Filter by type",
|
||||
"filterByUser": "Filter by user",
|
||||
"startDate": "Start date",
|
||||
"endDate": "End date",
|
||||
"clearFilters": "Clear",
|
||||
"error": "Error loading events",
|
||||
"noEvents": "No events found",
|
||||
"timestamp": "Timestamp",
|
||||
"type": "Type",
|
||||
"user": "User",
|
||||
"ipAddress": "IP Address",
|
||||
"actions": "Actions",
|
||||
"viewDetails": "View Details",
|
||||
"eventDetails": "Event Details",
|
||||
"details": "Details"
|
||||
},
|
||||
"export": {
|
||||
"title": "Export Audit Data",
|
||||
"description": "Export audit events to CSV or JSON format. Use filters to limit the exported data.",
|
||||
"format": "Export Format",
|
||||
"filters": "Filters (Optional)",
|
||||
"filterByType": "Filter by type",
|
||||
"filterByUser": "Filter by user",
|
||||
"startDate": "Start date",
|
||||
"endDate": "End date",
|
||||
"clearFilters": "Clear",
|
||||
"exportButton": "Export Data",
|
||||
"error": "Failed to export data"
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"noData": "No data available",
|
||||
"error": "Error loading usage statistics",
|
||||
"noDataMessage": "No usage statistics are currently available.",
|
||||
"controls": {
|
||||
"top10": "Top 10",
|
||||
"top20": "Top 20",
|
||||
"all": "All",
|
||||
"refresh": "Refresh",
|
||||
"dataTypeLabel": "Data Type:",
|
||||
"dataType": {
|
||||
"all": "All",
|
||||
"api": "API",
|
||||
"ui": "UI"
|
||||
}
|
||||
},
|
||||
"showing": {
|
||||
"top10": "Top 10",
|
||||
"top20": "Top 20",
|
||||
"all": "All"
|
||||
},
|
||||
"stats": {
|
||||
"totalEndpoints": "Total Endpoints",
|
||||
"totalVisits": "Total Visits",
|
||||
"showing": "Showing",
|
||||
"selectedVisits": "Selected Visits"
|
||||
},
|
||||
"chart": {
|
||||
"title": "Endpoint Usage Chart"
|
||||
},
|
||||
"table": {
|
||||
"title": "Detailed Statistics",
|
||||
"endpoint": "Endpoint",
|
||||
"visits": "Visits",
|
||||
"percentage": "Percentage",
|
||||
"noData": "No data available"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
.App {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.App-logo {
|
||||
height: 40vmin;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.App-logo {
|
||||
animation: App-logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.App-header {
|
||||
background-color: #282c34;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: calc(10px + 2vmin);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.App-link {
|
||||
color: #61dafb;
|
||||
}
|
||||
|
||||
@keyframes App-logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { Suspense } from "react";
|
||||
import { Routes, Route } from "react-router-dom";
|
||||
import { RainbowThemeProvider } from "./components/shared/RainbowThemeProvider";
|
||||
import { FileContextProvider } from "./contexts/FileContext";
|
||||
import { NavigationProvider } from "./contexts/NavigationContext";
|
||||
import { ToolRegistryProvider } from "./contexts/ToolRegistryProvider";
|
||||
import { FilesModalProvider } from "./contexts/FilesModalContext";
|
||||
import { ToolWorkflowProvider } from "./contexts/ToolWorkflowContext";
|
||||
import { HotkeyProvider } from "./contexts/HotkeyContext";
|
||||
import { SidebarProvider } from "./contexts/SidebarContext";
|
||||
import { PreferencesProvider } from "./contexts/PreferencesContext";
|
||||
import { OnboardingProvider } from "./contexts/OnboardingContext";
|
||||
import { TourOrchestrationProvider } from "./contexts/TourOrchestrationContext";
|
||||
import ErrorBoundary from "./components/shared/ErrorBoundary";
|
||||
import OnboardingTour from "./components/onboarding/OnboardingTour";
|
||||
|
||||
// Import auth components
|
||||
import { AuthProvider } from "./auth/UseSession";
|
||||
import Landing from "./routes/Landing";
|
||||
import Login from "./routes/Login";
|
||||
import Signup from "./routes/Signup";
|
||||
import AuthCallback from "./routes/AuthCallback";
|
||||
|
||||
// Import global styles
|
||||
import "./styles/tailwind.css";
|
||||
import "./styles/cookieconsent.css";
|
||||
import "./index.css";
|
||||
import { RightRailProvider } from "./contexts/RightRailContext";
|
||||
import { ViewerProvider } from "./contexts/ViewerContext";
|
||||
import { SignatureProvider } from "./contexts/SignatureContext";
|
||||
|
||||
// Import file ID debugging helpers (development only)
|
||||
import "./utils/fileIdSafety";
|
||||
|
||||
// Loading component for i18next suspense
|
||||
const LoadingFallback = () => (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
height: "100vh",
|
||||
fontSize: "18px",
|
||||
color: "#666",
|
||||
}}
|
||||
>
|
||||
Loading...
|
||||
</div>
|
||||
);
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Suspense fallback={<LoadingFallback />}>
|
||||
<PreferencesProvider>
|
||||
<RainbowThemeProvider>
|
||||
<ErrorBoundary>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
{/* Auth routes - no FileContext or other providers needed */}
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/signup" element={<Signup />} />
|
||||
<Route path="/auth/callback" element={<AuthCallback />} />
|
||||
|
||||
{/* Main app routes - wrapped with all providers */}
|
||||
<Route
|
||||
path="/*"
|
||||
element={
|
||||
<OnboardingProvider>
|
||||
<FileContextProvider enableUrlSync={true} enablePersistence={true}>
|
||||
<ToolRegistryProvider>
|
||||
<NavigationProvider>
|
||||
<FilesModalProvider>
|
||||
<ToolWorkflowProvider>
|
||||
<HotkeyProvider>
|
||||
<SidebarProvider>
|
||||
<ViewerProvider>
|
||||
<SignatureProvider>
|
||||
<RightRailProvider>
|
||||
<TourOrchestrationProvider>
|
||||
<Landing />
|
||||
<OnboardingTour />
|
||||
</TourOrchestrationProvider>
|
||||
</RightRailProvider>
|
||||
</SignatureProvider>
|
||||
</ViewerProvider>
|
||||
</SidebarProvider>
|
||||
</HotkeyProvider>
|
||||
</ToolWorkflowProvider>
|
||||
</FilesModalProvider>
|
||||
</NavigationProvider>
|
||||
</ToolRegistryProvider>
|
||||
</FileContextProvider>
|
||||
</OnboardingProvider>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</ErrorBoundary>
|
||||
</RainbowThemeProvider>
|
||||
</PreferencesProvider>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createContext, useContext, useEffect, useState, ReactNode, useCallback } from 'react';
|
||||
import { springAuth } from '@app/auth/springAuthClient';
|
||||
import type { Session, User, AuthError } from '@app/auth/springAuthClient';
|
||||
import { springAuth } from './springAuthClient';
|
||||
import type { Session, User, AuthError } from './springAuthClient';
|
||||
|
||||
/**
|
||||
* Auth Context Type
|
||||
-1
@@ -15,7 +15,6 @@ export interface User {
|
||||
role: string;
|
||||
enabled?: boolean;
|
||||
is_anonymous?: boolean;
|
||||
isFirstLogin?: boolean;
|
||||
app_metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
+11
-11
@@ -1,17 +1,17 @@
|
||||
import React, { useState, useCallback, useEffect } from 'react';
|
||||
import { Modal } from '@mantine/core';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { StirlingFileStub } from '@app/types/fileContext';
|
||||
import { useFileManager } from '@app/hooks/useFileManager';
|
||||
import { useFilesModalContext } from '@app/contexts/FilesModalContext';
|
||||
import { Tool } from '@app/types/tool';
|
||||
import MobileLayout from '@app/components/fileManager/MobileLayout';
|
||||
import DesktopLayout from '@app/components/fileManager/DesktopLayout';
|
||||
import DragOverlay from '@app/components/fileManager/DragOverlay';
|
||||
import { FileManagerProvider } from '@app/contexts/FileManagerContext';
|
||||
import { Z_INDEX_FILE_MANAGER_MODAL } from '@app/styles/zIndex';
|
||||
import { isGoogleDriveConfigured } from '@app/services/googleDrivePickerService';
|
||||
import { loadScript } from '@app/utils/scriptLoader';
|
||||
import { StirlingFileStub } from '../types/fileContext';
|
||||
import { useFileManager } from '../hooks/useFileManager';
|
||||
import { useFilesModalContext } from '../contexts/FilesModalContext';
|
||||
import { Tool } from '../types/tool';
|
||||
import MobileLayout from './fileManager/MobileLayout';
|
||||
import DesktopLayout from './fileManager/DesktopLayout';
|
||||
import DragOverlay from './fileManager/DragOverlay';
|
||||
import { FileManagerProvider } from '../contexts/FileManagerContext';
|
||||
import { Z_INDEX_FILE_MANAGER_MODAL } from '../styles/zIndex';
|
||||
import { isGoogleDriveConfigured } from '../services/googleDrivePickerService';
|
||||
import { loadScript } from '../utils/scriptLoader';
|
||||
|
||||
interface FileManagerProps {
|
||||
selectedTool?: Tool | null;
|
||||
+3
-3
@@ -3,9 +3,9 @@ import { Card, Group, Text, Button, Progress } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import StorageIcon from "@mui/icons-material/Storage";
|
||||
import DeleteIcon from "@mui/icons-material/Delete";
|
||||
import { StorageStats } from "@app/services/fileStorage";
|
||||
import { formatFileSize } from "@app/utils/fileUtils";
|
||||
import { getStorageUsagePercent } from "@app/utils/storageUtils";
|
||||
import { StorageStats } from "../services/fileStorage";
|
||||
import { formatFileSize } from "../utils/fileUtils";
|
||||
import { getStorageUsagePercent } from "../utils/storageUtils";
|
||||
|
||||
interface StorageStatsCardProps {
|
||||
storageStats: StorageStats | null;
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Stack, Alert, Text } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { DrawingControls } from '@app/components/annotation/shared/DrawingControls';
|
||||
import { ColorPicker } from '@app/components/annotation/shared/ColorPicker';
|
||||
import { usePDFAnnotation } from '@app/components/annotation/providers/PDFAnnotationProvider';
|
||||
import { DrawingControls } from './DrawingControls';
|
||||
import { ColorPicker } from './ColorPicker';
|
||||
import { usePDFAnnotation } from '../providers/PDFAnnotationProvider';
|
||||
|
||||
export interface AnnotationToolConfig {
|
||||
enableDrawing?: boolean;
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import React, { useRef, useState } from 'react';
|
||||
import { Paper, Button, Modal, Stack, Text, Popover, ColorPicker as MantineColorPicker } from '@mantine/core';
|
||||
import { ColorSwatchButton } from '@app/components/annotation/shared/ColorPicker';
|
||||
import PenSizeSelector from '@app/components/tools/sign/PenSizeSelector';
|
||||
import { ColorSwatchButton } from './ColorPicker';
|
||||
import PenSizeSelector from '../../tools/sign/PenSizeSelector';
|
||||
import SignaturePad from 'signature_pad';
|
||||
|
||||
interface DrawingCanvasProps {
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Stack, TextInput, Select, Combobox, useCombobox, Group, Box } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ColorPicker } from '@app/components/annotation/shared/ColorPicker';
|
||||
import { ColorPicker } from './ColorPicker';
|
||||
|
||||
interface TextInputWithFontProps {
|
||||
text: string;
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Stack } from '@mantine/core';
|
||||
import { BaseAnnotationTool } from '@app/components/annotation/shared/BaseAnnotationTool';
|
||||
import { DrawingCanvas } from '@app/components/annotation/shared/DrawingCanvas';
|
||||
import { BaseAnnotationTool } from '../shared/BaseAnnotationTool';
|
||||
import { DrawingCanvas } from '../shared/DrawingCanvas';
|
||||
|
||||
interface DrawingToolProps {
|
||||
onDrawingChange?: (data: string | null) => void;
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Stack } from '@mantine/core';
|
||||
import { BaseAnnotationTool } from '@app/components/annotation/shared/BaseAnnotationTool';
|
||||
import { ImageUploader } from '@app/components/annotation/shared/ImageUploader';
|
||||
import { BaseAnnotationTool } from '../shared/BaseAnnotationTool';
|
||||
import { ImageUploader } from '../shared/ImageUploader';
|
||||
|
||||
interface ImageToolProps {
|
||||
onImageChange?: (data: string | null) => void;
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Stack } from '@mantine/core';
|
||||
import { BaseAnnotationTool } from '@app/components/annotation/shared/BaseAnnotationTool';
|
||||
import { TextInputWithFont } from '@app/components/annotation/shared/TextInputWithFont';
|
||||
import { BaseAnnotationTool } from '../shared/BaseAnnotationTool';
|
||||
import { TextInputWithFont } from '../shared/TextInputWithFont';
|
||||
|
||||
interface TextToolProps {
|
||||
onTextChange?: (text: string) => void;
|
||||
+4
-4
@@ -2,10 +2,10 @@ import React, { useRef, useState } from 'react';
|
||||
import { Button, Group, useMantineColorScheme } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import AddIcon from '@mui/icons-material/Add';
|
||||
import { useFilesModalContext } from '@app/contexts/FilesModalContext';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
import { BASE_PATH } from '@app/constants/app';
|
||||
import styles from '@app/components/fileEditor/FileEditor.module.css';
|
||||
import { useFilesModalContext } from '../../contexts/FilesModalContext';
|
||||
import LocalIcon from '../shared/LocalIcon';
|
||||
import { BASE_PATH } from '../../constants/app';
|
||||
import styles from './FileEditor.module.css';
|
||||
|
||||
interface AddFileCardProps {
|
||||
onFileSelect: (files: File[]) => void;
|
||||
+12
-12
@@ -1,19 +1,19 @@
|
||||
import { useState, useCallback, useRef, useMemo, useEffect } from 'react';
|
||||
import React, { useState, useCallback, useRef, useMemo, useEffect } from 'react';
|
||||
import {
|
||||
Text, Center, Box, LoadingOverlay, Stack
|
||||
} from '@mantine/core';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { useFileSelection, useFileState, useFileManagement, useFileActions, useFileContext } from '@app/contexts/FileContext';
|
||||
import { useNavigationActions } from '@app/contexts/NavigationContext';
|
||||
import { zipFileService } from '@app/services/zipFileService';
|
||||
import { detectFileExtension } from '@app/utils/fileUtils';
|
||||
import FileEditorThumbnail from '@app/components/fileEditor/FileEditorThumbnail';
|
||||
import AddFileCard from '@app/components/fileEditor/AddFileCard';
|
||||
import FilePickerModal from '@app/components/shared/FilePickerModal';
|
||||
import { FileId, StirlingFile } from '@app/types/fileContext';
|
||||
import { alert } from '@app/components/toast';
|
||||
import { downloadBlob } from '@app/utils/downloadUtils';
|
||||
import { useFileEditorRightRailButtons } from '@app/components/fileEditor/fileEditorRightRailButtons';
|
||||
import { useFileSelection, useFileState, useFileManagement, useFileActions, useFileContext } from '../../contexts/FileContext';
|
||||
import { useNavigationActions } from '../../contexts/NavigationContext';
|
||||
import { zipFileService } from '../../services/zipFileService';
|
||||
import { detectFileExtension } from '../../utils/fileUtils';
|
||||
import FileEditorThumbnail from './FileEditorThumbnail';
|
||||
import AddFileCard from './AddFileCard';
|
||||
import FilePickerModal from '../shared/FilePickerModal';
|
||||
import { FileId, StirlingFile } from '../../types/fileContext';
|
||||
import { alert } from '../toast';
|
||||
import { downloadBlob } from '../../utils/downloadUtils';
|
||||
import { useFileEditorRightRailButtons } from './fileEditorRightRailButtons';
|
||||
|
||||
|
||||
interface FileEditorProps {
|
||||
+10
-10
@@ -1,7 +1,7 @@
|
||||
import React, { useState, useCallback, useRef, useMemo } from 'react';
|
||||
import { Text, ActionIcon, CheckboxIndicator, Tooltip, Modal, Button, Group, Stack } from '@mantine/core';
|
||||
import { useMediaQuery } from '@mantine/hooks';
|
||||
import { alert } from '@app/components/toast';
|
||||
import { alert } from '../toast';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import DownloadOutlinedIcon from '@mui/icons-material/DownloadOutlined';
|
||||
import CloseIcon from '@mui/icons-material/Close';
|
||||
@@ -11,16 +11,16 @@ import PushPinIcon from '@mui/icons-material/PushPin';
|
||||
import PushPinOutlinedIcon from '@mui/icons-material/PushPinOutlined';
|
||||
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
|
||||
import { draggable, dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter';
|
||||
import { StirlingFileStub } from '@app/types/fileContext';
|
||||
import { zipFileService } from '@app/services/zipFileService';
|
||||
import { StirlingFileStub } from '../../types/fileContext';
|
||||
import { zipFileService } from '../../services/zipFileService';
|
||||
|
||||
import styles from '@app/components/fileEditor/FileEditor.module.css';
|
||||
import { useFileContext } from '@app/contexts/FileContext';
|
||||
import { useFileState } from '@app/contexts/file/fileHooks';
|
||||
import { FileId } from '@app/types/file';
|
||||
import { formatFileSize } from '@app/utils/fileUtils';
|
||||
import ToolChain from '@app/components/shared/ToolChain';
|
||||
import HoverActionMenu, { HoverAction } from '@app/components/shared/HoverActionMenu';
|
||||
import styles from './FileEditor.module.css';
|
||||
import { useFileContext } from '../../contexts/FileContext';
|
||||
import { useFileState } from '../../contexts/file/fileHooks';
|
||||
import { FileId } from '../../types/file';
|
||||
import { formatFileSize } from '../../utils/fileUtils';
|
||||
import ToolChain from '../shared/ToolChain';
|
||||
import HoverActionMenu, { HoverAction } from '../shared/HoverActionMenu';
|
||||
|
||||
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useRightRailButtons, RightRailButtonWithAction } from '@app/hooks/useRightRailButtons';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
import { useRightRailButtons, RightRailButtonWithAction } from '../../hooks/useRightRailButtons';
|
||||
import LocalIcon from '../shared/LocalIcon';
|
||||
|
||||
interface FileEditorRightRailButtonsParams {
|
||||
totalItems: number;
|
||||
+2
-2
@@ -4,8 +4,8 @@ import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
|
||||
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
|
||||
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { getFileSize } from '@app/utils/fileUtils';
|
||||
import { StirlingFileStub } from '@app/types/fileContext';
|
||||
import { getFileSize } from '../../utils/fileUtils';
|
||||
import { StirlingFileStub } from '../../types/fileContext';
|
||||
|
||||
interface CompactFileDetailsProps {
|
||||
currentFile: StirlingFileStub | null;
|
||||
+7
-7
@@ -1,12 +1,12 @@
|
||||
import React from 'react';
|
||||
import { Grid } from '@mantine/core';
|
||||
import FileSourceButtons from '@app/components/fileManager/FileSourceButtons';
|
||||
import FileDetails from '@app/components/fileManager/FileDetails';
|
||||
import SearchInput from '@app/components/fileManager/SearchInput';
|
||||
import FileListArea from '@app/components/fileManager/FileListArea';
|
||||
import FileActions from '@app/components/fileManager/FileActions';
|
||||
import HiddenFileInput from '@app/components/fileManager/HiddenFileInput';
|
||||
import { useFileManagerContext } from '@app/contexts/FileManagerContext';
|
||||
import FileSourceButtons from './FileSourceButtons';
|
||||
import FileDetails from './FileDetails';
|
||||
import SearchInput from './SearchInput';
|
||||
import FileListArea from './FileListArea';
|
||||
import FileActions from './FileActions';
|
||||
import HiddenFileInput from './HiddenFileInput';
|
||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||
|
||||
const DesktopLayout: React.FC = () => {
|
||||
const {
|
||||
+3
-3
@@ -2,9 +2,9 @@ import React, { useState } from 'react';
|
||||
import { Button, Group, Text, Stack, useMantineColorScheme } from '@mantine/core';
|
||||
import HistoryIcon from '@mui/icons-material/History';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useFileManagerContext } from '@app/contexts/FileManagerContext';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
import { BASE_PATH } from '@app/constants/app';
|
||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||
import LocalIcon from '../shared/LocalIcon';
|
||||
import { BASE_PATH } from '../../constants/app';
|
||||
|
||||
const EmptyFilesState: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
+1
-1
@@ -4,7 +4,7 @@ import SelectAllIcon from "@mui/icons-material/SelectAll";
|
||||
import DeleteIcon from "@mui/icons-material/Delete";
|
||||
import DownloadIcon from "@mui/icons-material/Download";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useFileManagerContext } from "@app/contexts/FileManagerContext";
|
||||
import { useFileManagerContext } from "../../contexts/FileManagerContext";
|
||||
|
||||
const FileActions: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
+5
-5
@@ -1,11 +1,11 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Stack, Button, Box } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useIndexedDBThumbnail } from '@app/hooks/useIndexedDBThumbnail';
|
||||
import { useFileManagerContext } from '@app/contexts/FileManagerContext';
|
||||
import FilePreview from '@app/components/shared/FilePreview';
|
||||
import FileInfoCard from '@app/components/fileManager/FileInfoCard';
|
||||
import CompactFileDetails from '@app/components/fileManager/CompactFileDetails';
|
||||
import { useIndexedDBThumbnail } from '../../hooks/useIndexedDBThumbnail';
|
||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||
import FilePreview from '../shared/FilePreview';
|
||||
import FileInfoCard from './FileInfoCard';
|
||||
import CompactFileDetails from './CompactFileDetails';
|
||||
|
||||
interface FileDetailsProps {
|
||||
compact?: boolean;
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
import React from 'react';
|
||||
import { Box, Text, Collapse, Group } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { StirlingFileStub } from '@app/types/fileContext';
|
||||
import FileListItem from '@app/components/fileManager/FileListItem';
|
||||
import { StirlingFileStub } from '../../types/fileContext';
|
||||
import FileListItem from './FileListItem';
|
||||
|
||||
interface FileHistoryGroupProps {
|
||||
leafFile: StirlingFileStub;
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
import React from 'react';
|
||||
import { Stack, Card, Box, Text, Badge, Group, Divider, ScrollArea } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { detectFileExtension, getFileSize } from '@app/utils/fileUtils';
|
||||
import { StirlingFileStub } from '@app/types/fileContext';
|
||||
import ToolChain from '@app/components/shared/ToolChain';
|
||||
import { detectFileExtension, getFileSize } from '../../utils/fileUtils';
|
||||
import { StirlingFileStub } from '../../types/fileContext';
|
||||
import ToolChain from '../shared/ToolChain';
|
||||
|
||||
interface FileInfoCardProps {
|
||||
currentFile: StirlingFileStub | null;
|
||||
+4
-4
@@ -2,10 +2,10 @@ import React from 'react';
|
||||
import { Center, ScrollArea, Text, Stack } from '@mantine/core';
|
||||
import CloudIcon from '@mui/icons-material/Cloud';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import FileListItem from '@app/components/fileManager/FileListItem';
|
||||
import FileHistoryGroup from '@app/components/fileManager/FileHistoryGroup';
|
||||
import EmptyFilesState from '@app/components/fileManager/EmptyFilesState';
|
||||
import { useFileManagerContext } from '@app/contexts/FileManagerContext';
|
||||
import FileListItem from './FileListItem';
|
||||
import FileHistoryGroup from './FileHistoryGroup';
|
||||
import EmptyFilesState from './EmptyFilesState';
|
||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||
|
||||
interface FileListAreaProps {
|
||||
scrollAreaHeight: string;
|
||||
+6
-6
@@ -7,12 +7,12 @@ import HistoryIcon from '@mui/icons-material/History';
|
||||
import RestoreIcon from '@mui/icons-material/Restore';
|
||||
import UnarchiveIcon from '@mui/icons-material/Unarchive';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { getFileSize, getFileDate } from '@app/utils/fileUtils';
|
||||
import { FileId, StirlingFileStub } from '@app/types/fileContext';
|
||||
import { useFileManagerContext } from '@app/contexts/FileManagerContext';
|
||||
import { zipFileService } from '@app/services/zipFileService';
|
||||
import ToolChain from '@app/components/shared/ToolChain';
|
||||
import { Z_INDEX_OVER_FILE_MANAGER_MODAL } from '@app/styles/zIndex';
|
||||
import { getFileSize, getFileDate } from '../../utils/fileUtils';
|
||||
import { FileId, StirlingFileStub } from '../../types/fileContext';
|
||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||
import { zipFileService } from '../../services/zipFileService';
|
||||
import ToolChain from '../shared/ToolChain';
|
||||
import { Z_INDEX_OVER_FILE_MANAGER_MODAL } from '../../styles/zIndex';
|
||||
|
||||
interface FileListItemProps {
|
||||
file: StirlingFileStub;
|
||||
+2
-2
@@ -4,8 +4,8 @@ import HistoryIcon from '@mui/icons-material/History';
|
||||
import UploadIcon from '@mui/icons-material/Upload';
|
||||
import CloudIcon from '@mui/icons-material/Cloud';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useFileManagerContext } from '@app/contexts/FileManagerContext';
|
||||
import { useGoogleDrivePicker } from '@app/hooks/useGoogleDrivePicker';
|
||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||
import { useGoogleDrivePicker } from '../../hooks/useGoogleDrivePicker';
|
||||
|
||||
interface FileSourceButtonsProps {
|
||||
horizontal?: boolean;
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import { useFileManagerContext } from '@app/contexts/FileManagerContext';
|
||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||
|
||||
const HiddenFileInput: React.FC = () => {
|
||||
const { fileInputRef, onFileInputChange } = useFileManagerContext();
|
||||
+7
-7
@@ -1,12 +1,12 @@
|
||||
import React from 'react';
|
||||
import { Box } from '@mantine/core';
|
||||
import FileSourceButtons from '@app/components/fileManager/FileSourceButtons';
|
||||
import FileDetails from '@app/components/fileManager/FileDetails';
|
||||
import SearchInput from '@app/components/fileManager/SearchInput';
|
||||
import FileListArea from '@app/components/fileManager/FileListArea';
|
||||
import FileActions from '@app/components/fileManager/FileActions';
|
||||
import HiddenFileInput from '@app/components/fileManager/HiddenFileInput';
|
||||
import { useFileManagerContext } from '@app/contexts/FileManagerContext';
|
||||
import FileSourceButtons from './FileSourceButtons';
|
||||
import FileDetails from './FileDetails';
|
||||
import SearchInput from './SearchInput';
|
||||
import FileListArea from './FileListArea';
|
||||
import FileActions from './FileActions';
|
||||
import HiddenFileInput from './HiddenFileInput';
|
||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||
|
||||
const MobileLayout: React.FC = () => {
|
||||
const {
|
||||
+1
-1
@@ -2,7 +2,7 @@ import React from 'react';
|
||||
import { TextInput } from '@mantine/core';
|
||||
import SearchIcon from '@mui/icons-material/Search';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useFileManagerContext } from '@app/contexts/FileManagerContext';
|
||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||
|
||||
interface SearchInputProps {
|
||||
style?: React.CSSProperties;
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
import { HotkeyBinding } from '@app/utils/hotkeys';
|
||||
import { useHotkeys } from '@app/contexts/HotkeyContext';
|
||||
import { HotkeyBinding } from '../../utils/hotkeys';
|
||||
import { useHotkeys } from '../../contexts/HotkeyContext';
|
||||
|
||||
interface HotkeyDisplayProps {
|
||||
binding: HotkeyBinding | null | undefined;
|
||||
+46
-52
@@ -1,13 +1,13 @@
|
||||
import React from 'react';
|
||||
import React, { useMemo } from 'react';
|
||||
import { Box } from '@mantine/core';
|
||||
import { useRainbowThemeContext } from '../shared/RainbowThemeProvider';
|
||||
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
|
||||
import { useFileHandler } from '@app/hooks/useFileHandler';
|
||||
import { useFileState } from '@app/contexts/FileContext';
|
||||
import { useNavigationState, useNavigationActions } from '@app/contexts/NavigationContext';
|
||||
import { isBaseWorkbench } from '@app/types/workbench';
|
||||
import { useViewer } from '@app/contexts/ViewerContext';
|
||||
import { useAppConfig } from '@app/contexts/AppConfigContext';
|
||||
import { useToolWorkflow } from '../../contexts/ToolWorkflowContext';
|
||||
import { useFileHandler } from '../../hooks/useFileHandler';
|
||||
import { useFileState } from '../../contexts/FileContext';
|
||||
import { useNavigationState, useNavigationActions } from '../../contexts/NavigationContext';
|
||||
import { useViewer } from '../../contexts/ViewerContext';
|
||||
import { PageEditorProvider } from '../../contexts/PageEditorContext';
|
||||
import { isBaseWorkbench } from '../../types/workbench';
|
||||
import './Workbench.css';
|
||||
|
||||
import TopControls from '../shared/TopControls';
|
||||
@@ -22,14 +22,15 @@ import DismissAllErrorsButton from '../shared/DismissAllErrorsButton';
|
||||
// No props needed - component uses contexts directly
|
||||
export default function Workbench() {
|
||||
const { isRainbowMode } = useRainbowThemeContext();
|
||||
const { config } = useAppConfig();
|
||||
|
||||
// Use context-based hooks to eliminate all prop drilling
|
||||
const { selectors } = useFileState();
|
||||
const { state, selectors } = useFileState();
|
||||
const { workbench: currentView } = useNavigationState();
|
||||
const { actions: navActions } = useNavigationActions();
|
||||
const setCurrentView = navActions.setWorkbench;
|
||||
const activeFiles = selectors.getFiles();
|
||||
|
||||
// Create stable reference for activeFiles based on file IDs
|
||||
const activeFiles = useMemo(() => selectors.getFiles(), [state.files.ids]);
|
||||
const {
|
||||
previewFile,
|
||||
pageEditorFunctions,
|
||||
@@ -153,52 +154,45 @@ export default function Workbench() {
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
className="flex-1 h-full min-w-80 relative flex flex-col"
|
||||
data-tour="workbench"
|
||||
style={
|
||||
isRainbowMode
|
||||
? {} // No background color in rainbow mode
|
||||
: { backgroundColor: 'var(--bg-background)' }
|
||||
}
|
||||
>
|
||||
{/* Top Controls */}
|
||||
{activeFiles.length > 0 && (
|
||||
<TopControls
|
||||
currentView={currentView}
|
||||
setCurrentView={setCurrentView}
|
||||
customViews={customWorkbenchViews}
|
||||
activeFiles={activeFiles.map(f => {
|
||||
<PageEditorProvider>
|
||||
<Box
|
||||
className="flex-1 h-full min-w-80 relative flex flex-col"
|
||||
style={
|
||||
isRainbowMode
|
||||
? {} // No background color in rainbow mode
|
||||
: { backgroundColor: 'var(--bg-background)' }
|
||||
}
|
||||
>
|
||||
{/* Top Controls */}
|
||||
{activeFiles.length > 0 && (
|
||||
<TopControls
|
||||
currentView={currentView}
|
||||
setCurrentView={setCurrentView}
|
||||
customViews={customWorkbenchViews}
|
||||
activeFiles={activeFiles.map(f => {
|
||||
const stub = selectors.getStirlingFileStub(f.fileId);
|
||||
return { fileId: f.fileId, name: f.name, versionNumber: stub?.versionNumber };
|
||||
})}
|
||||
currentFileIndex={activeFileIndex}
|
||||
onFileSelect={setActiveFileIndex}
|
||||
})}
|
||||
currentFileIndex={activeFileIndex}
|
||||
onFileSelect={setActiveFileIndex}
|
||||
/>
|
||||
)}
|
||||
)}
|
||||
|
||||
{/* Dismiss All Errors Button */}
|
||||
<DismissAllErrorsButton />
|
||||
{/* Dismiss All Errors Button */}
|
||||
<DismissAllErrorsButton />
|
||||
|
||||
{/* Main content area */}
|
||||
<Box
|
||||
className="flex-1 min-h-0 relative z-10 workbench-scrollable "
|
||||
style={{
|
||||
transition: 'opacity 0.15s ease-in-out',
|
||||
paddingTop: currentView === 'viewer' ? '0' : (activeFiles.length > 0 ? '3.5rem' : '0'),
|
||||
}}
|
||||
>
|
||||
{renderMainContent()}
|
||||
{/* Main content area */}
|
||||
<Box
|
||||
className="flex-1 min-h-0 relative z-10 workbench-scrollable "
|
||||
style={{
|
||||
transition: 'opacity 0.15s ease-in-out',
|
||||
}}
|
||||
>
|
||||
{renderMainContent()}
|
||||
</Box>
|
||||
|
||||
<Footer analyticsEnabled />
|
||||
</Box>
|
||||
|
||||
<Footer
|
||||
analyticsEnabled={config?.enableAnalytics}
|
||||
termsAndConditions={config?.termsAndConditions}
|
||||
privacyPolicy={config?.privacyPolicy}
|
||||
cookiePolicy={config?.cookiePolicy}
|
||||
impressum={config?.impressum}
|
||||
accessibilityStatement={config?.accessibilityStatement}
|
||||
/>
|
||||
</Box>
|
||||
</PageEditorProvider>
|
||||
);
|
||||
}
|
||||
+13
-9
@@ -1,14 +1,18 @@
|
||||
import React from "react";
|
||||
import { TourProvider, useTour, type StepType } from '@reactour/tour';
|
||||
import { useOnboarding } from '@app/contexts/OnboardingContext';
|
||||
import {
|
||||
TourProvider,
|
||||
useTour,
|
||||
type StepType
|
||||
} from '@reactour/tour';
|
||||
import { useOnboarding } from '../../contexts/OnboardingContext';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { CloseButton, ActionIcon } from '@mantine/core';
|
||||
import { useFilesModalContext } from '@app/contexts/FilesModalContext';
|
||||
import { useTourOrchestration } from '@app/contexts/TourOrchestrationContext';
|
||||
import { useFilesModalContext } from '../../contexts/FilesModalContext';
|
||||
import { useTourOrchestration } from '../../contexts/TourOrchestrationContext';
|
||||
import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
|
||||
import CheckIcon from '@mui/icons-material/Check';
|
||||
import TourWelcomeModal from '@app/components/onboarding/TourWelcomeModal';
|
||||
import '@app/components/onboarding/OnboardingTour.css';
|
||||
import TourWelcomeModal from './TourWelcomeModal';
|
||||
import './OnboardingTour.css';
|
||||
|
||||
// Enum case order defines order steps will appear
|
||||
enum TourStep {
|
||||
@@ -250,14 +254,14 @@ export default function OnboardingTour() {
|
||||
e.stopPropagation();
|
||||
advanceTour(clickProps);
|
||||
}}
|
||||
keyboardHandler={(e, clickProps, status) => {
|
||||
keyboardHandler={(e, clickProps) => {
|
||||
// Handle right arrow key to advance tour
|
||||
if (e.key === 'ArrowRight' && !status?.isRightDisabled && clickProps) {
|
||||
if (e.key === 'ArrowRight' && clickProps) {
|
||||
e.preventDefault();
|
||||
advanceTour(clickProps);
|
||||
}
|
||||
// Handle escape key to close tour
|
||||
else if (e.key === 'Escape' && !status?.isEscDisabled && clickProps) {
|
||||
else if (e.key === 'Escape' && clickProps) {
|
||||
e.preventDefault();
|
||||
handleCloseTour(clickProps);
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { Modal, Title, Text, Button, Stack, Group } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from '@app/styles/zIndex';
|
||||
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from '../../styles/zIndex';
|
||||
|
||||
interface TourWelcomeModalProps {
|
||||
opened: boolean;
|
||||
+5
-5
@@ -1,9 +1,9 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import classes from '@app/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css';
|
||||
import { parseSelectionWithDiagnostics } from '@app/utils/bulkselection/parseSelection';
|
||||
import PageSelectionInput from '@app/components/pageEditor/bulkSelectionPanel/PageSelectionInput';
|
||||
import SelectedPagesDisplay from '@app/components/pageEditor/bulkSelectionPanel/SelectedPagesDisplay';
|
||||
import AdvancedSelectionPanel from '@app/components/pageEditor/bulkSelectionPanel/AdvancedSelectionPanel';
|
||||
import classes from './bulkSelectionPanel/BulkSelectionPanel.module.css';
|
||||
import { parseSelectionWithDiagnostics } from '../../utils/bulkselection/parseSelection';
|
||||
import PageSelectionInput from './bulkSelectionPanel/PageSelectionInput';
|
||||
import SelectedPagesDisplay from './bulkSelectionPanel/SelectedPagesDisplay';
|
||||
import AdvancedSelectionPanel from './bulkSelectionPanel/AdvancedSelectionPanel';
|
||||
|
||||
interface BulkSelectionPanelProps {
|
||||
csvInput: string;
|
||||
@@ -0,0 +1,781 @@
|
||||
import React, { useRef, useEffect, useState, useCallback, useMemo } from 'react';
|
||||
import { Box } from '@mantine/core';
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { GRID_CONSTANTS } from './constants';
|
||||
import {
|
||||
DndContext,
|
||||
DragEndEvent,
|
||||
DragStartEvent,
|
||||
DragOverlay,
|
||||
useSensor,
|
||||
useSensors,
|
||||
PointerSensor,
|
||||
closestCenter,
|
||||
useDraggable,
|
||||
useDroppable,
|
||||
} from '@dnd-kit/core';
|
||||
|
||||
interface DragDropItem {
|
||||
id: string;
|
||||
splitAfter?: boolean;
|
||||
isPlaceholder?: boolean;
|
||||
}
|
||||
|
||||
interface DragDropGridProps<T extends DragDropItem> {
|
||||
items: T[];
|
||||
onReorderPages: (sourcePageNumber: number, targetIndex: number, selectedPageIds?: string[]) => void;
|
||||
renderItem: (item: T, index: number, refs: React.MutableRefObject<Map<string, HTMLDivElement>>, boxSelectedIds: string[], clearBoxSelection: () => void, getBoxSelection: () => string[], activeId: string | null, activeDragIds: string[], justMoved: boolean, isOver: boolean, dragHandleProps?: any, zoomLevel?: number) => React.ReactNode;
|
||||
getThumbnailData?: (itemId: string) => { src: string; rotation: number } | null;
|
||||
zoomLevel?: number;
|
||||
}
|
||||
|
||||
type DropSide = 'left' | 'right' | null;
|
||||
|
||||
interface DropHint {
|
||||
hoveredId: string | null;
|
||||
dropSide: DropSide;
|
||||
}
|
||||
|
||||
function resolveDropHint(
|
||||
activeId: string | null,
|
||||
itemRefs: React.MutableRefObject<Map<string, HTMLDivElement>>,
|
||||
cursorX: number,
|
||||
cursorY: number,
|
||||
): DropHint {
|
||||
if (!activeId) {
|
||||
return { hoveredId: null, dropSide: null };
|
||||
}
|
||||
|
||||
const rows = new Map<number, Array<{ id: string; rect: DOMRect }>>();
|
||||
|
||||
itemRefs.current.forEach((element, itemId) => {
|
||||
if (!element || itemId === activeId) return;
|
||||
|
||||
const rect = element.getBoundingClientRect();
|
||||
const rowCenter = rect.top + rect.height / 2;
|
||||
|
||||
let row = rows.get(rowCenter);
|
||||
if (!row) {
|
||||
row = [];
|
||||
rows.set(rowCenter, row);
|
||||
}
|
||||
row.push({ id: itemId, rect });
|
||||
});
|
||||
|
||||
let hoveredId: string | null = null;
|
||||
let dropSide: DropSide = null;
|
||||
|
||||
let closestRowY = 0;
|
||||
let closestRowDistance = Infinity;
|
||||
|
||||
rows.forEach((_items, rowY) => {
|
||||
const distance = Math.abs(cursorY - rowY);
|
||||
if (distance < closestRowDistance) {
|
||||
closestRowDistance = distance;
|
||||
closestRowY = rowY;
|
||||
}
|
||||
});
|
||||
|
||||
const closestRow = rows.get(closestRowY);
|
||||
if (!closestRow || closestRow.length === 0) {
|
||||
return { hoveredId: null, dropSide: null };
|
||||
}
|
||||
|
||||
let closestDistance = Infinity;
|
||||
closestRow.forEach(({ id, rect }) => {
|
||||
const distanceToLeft = Math.abs(cursorX - rect.left);
|
||||
const distanceToRight = Math.abs(cursorX - rect.right);
|
||||
|
||||
if (distanceToLeft < closestDistance) {
|
||||
closestDistance = distanceToLeft;
|
||||
hoveredId = id;
|
||||
dropSide = 'left';
|
||||
}
|
||||
if (distanceToRight < closestDistance) {
|
||||
closestDistance = distanceToRight;
|
||||
hoveredId = id;
|
||||
dropSide = 'right';
|
||||
}
|
||||
});
|
||||
|
||||
return { hoveredId, dropSide };
|
||||
}
|
||||
|
||||
function resolveTargetIndex<T extends DragDropItem>(
|
||||
hoveredId: string | null,
|
||||
dropSide: DropSide,
|
||||
filteredItems: T[],
|
||||
filteredToOriginalIndex: number[],
|
||||
originalItemsLength: number,
|
||||
fallbackIndex: number | null,
|
||||
): number | null {
|
||||
const convertFilteredIndexToOriginal = (filteredIndex: number): number => {
|
||||
if (filteredToOriginalIndex.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (filteredIndex <= 0) {
|
||||
return filteredToOriginalIndex[0];
|
||||
}
|
||||
|
||||
if (filteredIndex >= filteredToOriginalIndex.length) {
|
||||
return originalItemsLength;
|
||||
}
|
||||
|
||||
return filteredToOriginalIndex[filteredIndex];
|
||||
};
|
||||
|
||||
if (hoveredId) {
|
||||
const filteredIndex = filteredItems.findIndex(item => item.id === hoveredId);
|
||||
if (filteredIndex !== -1) {
|
||||
const adjustedIndex = filteredIndex + (dropSide === 'right' ? 1 : 0);
|
||||
return convertFilteredIndexToOriginal(adjustedIndex);
|
||||
}
|
||||
}
|
||||
|
||||
if (fallbackIndex !== null && fallbackIndex !== undefined) {
|
||||
const adjustedIndex = fallbackIndex + (dropSide === 'right' ? 1 : 0);
|
||||
return convertFilteredIndexToOriginal(adjustedIndex);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Lightweight wrapper that handles dnd-kit hooks for each visible item
|
||||
interface DraggableItemProps<T extends DragDropItem> {
|
||||
item: T;
|
||||
index: number;
|
||||
itemRefs: React.MutableRefObject<Map<string, HTMLDivElement>>;
|
||||
boxSelectedPageIds: string[];
|
||||
clearBoxSelection: () => void;
|
||||
getBoxSelection: () => string[];
|
||||
activeId: string | null;
|
||||
activeDragIds: string[];
|
||||
justMoved: boolean;
|
||||
getThumbnailData?: (itemId: string) => { src: string; rotation: number } | null;
|
||||
onUpdateDropTarget: (itemId: string | null) => void;
|
||||
renderItem: (item: T, index: number, refs: React.MutableRefObject<Map<string, HTMLDivElement>>, boxSelectedIds: string[], clearBoxSelection: () => void, getBoxSelection: () => string[], activeId: string | null, activeDragIds: string[], justMoved: boolean, isOver: boolean, dragHandleProps?: any, zoomLevel?: number) => React.ReactNode;
|
||||
zoomLevel: number;
|
||||
}
|
||||
|
||||
const DraggableItem = <T extends DragDropItem>({ item, index, itemRefs, boxSelectedPageIds, clearBoxSelection, getBoxSelection, activeId, activeDragIds, justMoved, getThumbnailData, renderItem, onUpdateDropTarget, zoomLevel }: DraggableItemProps<T>) => {
|
||||
const { attributes, listeners, setNodeRef: setDraggableRef } = useDraggable({
|
||||
id: item.id,
|
||||
data: {
|
||||
index,
|
||||
pageNumber: index + 1,
|
||||
getThumbnail: () => {
|
||||
if (getThumbnailData) {
|
||||
const data = getThumbnailData(item.id);
|
||||
if (data?.src) return data;
|
||||
}
|
||||
|
||||
const element = itemRefs.current.get(item.id);
|
||||
const imgElement = element?.querySelector('img.ph-no-capture') as HTMLImageElement;
|
||||
if (imgElement?.src) {
|
||||
return {
|
||||
src: imgElement.src,
|
||||
rotation: imgElement.dataset.originalRotation ? parseInt(imgElement.dataset.originalRotation) : 0
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const { setNodeRef: setDroppableRef, isOver } = useDroppable({
|
||||
id: item.id,
|
||||
data: { index, pageNumber: index + 1 }
|
||||
});
|
||||
|
||||
// Notify parent when hover state changes
|
||||
React.useEffect(() => {
|
||||
if (isOver) {
|
||||
onUpdateDropTarget(item.id);
|
||||
} else {
|
||||
onUpdateDropTarget(null);
|
||||
}
|
||||
}, [isOver, item.id, onUpdateDropTarget]);
|
||||
|
||||
const setNodeRef = useCallback((element: HTMLDivElement | null) => {
|
||||
setDraggableRef(element);
|
||||
setDroppableRef(element);
|
||||
}, [setDraggableRef, setDroppableRef]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{renderItem(item, index, itemRefs, boxSelectedPageIds, clearBoxSelection, getBoxSelection, activeId, activeDragIds, justMoved, isOver, { ref: setNodeRef, ...attributes, ...listeners }, zoomLevel)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const DragDropGrid = <T extends DragDropItem>({
|
||||
items,
|
||||
renderItem,
|
||||
onReorderPages,
|
||||
getThumbnailData,
|
||||
zoomLevel = 1.0,
|
||||
}: DragDropGridProps<T>) => {
|
||||
const itemRefs = useRef<Map<string, HTMLDivElement>>(new Map());
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const getScrollElement = useCallback(() => {
|
||||
return containerRef.current?.closest('[data-scrolling-container]') as HTMLElement | null;
|
||||
}, []);
|
||||
|
||||
const { filteredItems: visibleItems, filteredToOriginalIndex } = useMemo(() => {
|
||||
const filtered: T[] = [];
|
||||
const indexMap: number[] = [];
|
||||
|
||||
items.forEach((item, index) => {
|
||||
if (!item.isPlaceholder) {
|
||||
filtered.push(item);
|
||||
indexMap.push(index);
|
||||
}
|
||||
});
|
||||
|
||||
return { filteredItems: filtered, filteredToOriginalIndex: indexMap };
|
||||
}, [items]);
|
||||
|
||||
// Box selection state
|
||||
const [boxSelectStart, setBoxSelectStart] = useState<{ x: number; y: number } | null>(null);
|
||||
const [boxSelectEnd, setBoxSelectEnd] = useState<{ x: number; y: number } | null>(null);
|
||||
const [isBoxSelecting, setIsBoxSelecting] = useState(false);
|
||||
const [boxSelectedPageIds, setBoxSelectedPageIds] = useState<string[]>([]);
|
||||
const [justMovedIds, setJustMovedIds] = useState<string[]>([]);
|
||||
const highlightTimeoutRef = useRef<number | null>(null);
|
||||
|
||||
// Drag state
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
const [dragPreview, setDragPreview] = useState<{ src: string; rotation: number } | null>(null);
|
||||
const [hoveredItemId, setHoveredItemId] = useState<string | null>(null);
|
||||
const [dropSide, setDropSide] = useState<DropSide>(null);
|
||||
|
||||
// Configure sensors for dnd-kit with activation constraint
|
||||
// Require 10px movement before drag starts to allow clicks for selection
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
activationConstraint: {
|
||||
distance: 10,
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
// Throttled pointer move handler for drop indicator
|
||||
// Calculate drop position based on cursor location relative to ALL items, not just hovered item
|
||||
useEffect(() => {
|
||||
if (!activeId) {
|
||||
setDropSide(null);
|
||||
setHoveredItemId(null);
|
||||
return;
|
||||
}
|
||||
|
||||
let rafId: number | null = null;
|
||||
|
||||
const handlePointerMove = (e: PointerEvent) => {
|
||||
// Use the actual cursor position (pointer coordinates)
|
||||
const cursorX = e.clientX;
|
||||
const cursorY = e.clientY;
|
||||
|
||||
if (rafId === null) {
|
||||
rafId = requestAnimationFrame(() => {
|
||||
const hint = resolveDropHint(activeId, itemRefs, cursorX, cursorY);
|
||||
setHoveredItemId(hint.hoveredId);
|
||||
setDropSide(hint.dropSide);
|
||||
rafId = null;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('pointermove', handlePointerMove, { passive: true });
|
||||
return () => {
|
||||
window.removeEventListener('pointermove', handlePointerMove);
|
||||
if (rafId !== null) {
|
||||
cancelAnimationFrame(rafId);
|
||||
}
|
||||
};
|
||||
}, [activeId]);
|
||||
|
||||
// Responsive grid configuration
|
||||
const [itemsPerRow, setItemsPerRow] = useState(4);
|
||||
const OVERSCAN = visibleItems.length > 1000 ? GRID_CONSTANTS.OVERSCAN_LARGE : GRID_CONSTANTS.OVERSCAN_SMALL;
|
||||
|
||||
// Calculate items per row based on container width
|
||||
const calculateItemsPerRow = useCallback(() => {
|
||||
if (!containerRef.current) return 4; // Default fallback
|
||||
|
||||
const containerWidth = containerRef.current.offsetWidth;
|
||||
if (containerWidth === 0) return 4; // Container not measured yet
|
||||
|
||||
// Convert rem to pixels for calculation
|
||||
const remToPx = parseFloat(getComputedStyle(document.documentElement).fontSize);
|
||||
const ITEM_WIDTH = parseFloat(GRID_CONSTANTS.ITEM_WIDTH) * remToPx * zoomLevel;
|
||||
const ITEM_GAP = parseFloat(GRID_CONSTANTS.ITEM_GAP) * remToPx * zoomLevel;
|
||||
|
||||
// Calculate how many items fit: (width - gap) / (itemWidth + gap)
|
||||
const availableWidth = containerWidth - ITEM_GAP; // Account for first gap
|
||||
const itemWithGap = ITEM_WIDTH + ITEM_GAP;
|
||||
const calculated = Math.floor(availableWidth / itemWithGap);
|
||||
|
||||
return Math.max(1, calculated); // At least 1 item per row
|
||||
}, [zoomLevel]);
|
||||
|
||||
// Update items per row when container resizes or zoom changes
|
||||
useEffect(() => {
|
||||
const updateLayout = () => {
|
||||
const newItemsPerRow = calculateItemsPerRow();
|
||||
setItemsPerRow(newItemsPerRow);
|
||||
};
|
||||
|
||||
// Initial calculation
|
||||
updateLayout();
|
||||
|
||||
// Listen for window resize
|
||||
window.addEventListener('resize', updateLayout);
|
||||
|
||||
// Use ResizeObserver for container size changes
|
||||
const resizeObserver = new ResizeObserver(updateLayout);
|
||||
if (containerRef.current) {
|
||||
resizeObserver.observe(containerRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('resize', updateLayout);
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [calculateItemsPerRow, zoomLevel]);
|
||||
|
||||
// Virtualization with react-virtual library
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
count: Math.ceil(visibleItems.length / itemsPerRow),
|
||||
getScrollElement,
|
||||
estimateSize: () => {
|
||||
const remToPx = parseFloat(getComputedStyle(document.documentElement).fontSize);
|
||||
return parseFloat(GRID_CONSTANTS.ITEM_HEIGHT) * remToPx * zoomLevel;
|
||||
},
|
||||
overscan: OVERSCAN,
|
||||
});
|
||||
|
||||
// Re-measure virtualizer when zoom or items per row changes
|
||||
useEffect(() => {
|
||||
rowVirtualizer.measure();
|
||||
}, [zoomLevel, itemsPerRow]);
|
||||
|
||||
// Cleanup highlight timeout on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (highlightTimeoutRef.current) {
|
||||
window.clearTimeout(highlightTimeoutRef.current);
|
||||
highlightTimeoutRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Box selection handlers
|
||||
const handleMouseDown = useCallback((e: React.MouseEvent) => {
|
||||
if (e.button !== 0) return; // Only respond to primary button
|
||||
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
|
||||
const clickTarget = e.target as Node;
|
||||
let clickedPageId: string | null = null;
|
||||
|
||||
itemRefs.current.forEach((element, pageId) => {
|
||||
if (element.contains(clickTarget)) {
|
||||
clickedPageId = pageId;
|
||||
}
|
||||
});
|
||||
|
||||
if (clickedPageId) {
|
||||
// Clicking directly on a page shouldn't initiate box selection
|
||||
// but clear previous box selection if clicking outside current group
|
||||
if (boxSelectedPageIds.length > 0 && !boxSelectedPageIds.includes(clickedPageId)) {
|
||||
setBoxSelectedPageIds([]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
const rect = container.getBoundingClientRect();
|
||||
setIsBoxSelecting(true);
|
||||
setBoxSelectStart({ x: e.clientX - rect.left, y: e.clientY - rect.top });
|
||||
setBoxSelectEnd({ x: e.clientX - rect.left, y: e.clientY - rect.top });
|
||||
setBoxSelectedPageIds([]);
|
||||
}, [boxSelectedPageIds]);
|
||||
|
||||
const handleMouseMove = useCallback((e: React.MouseEvent) => {
|
||||
if (!isBoxSelecting || !boxSelectStart) return;
|
||||
|
||||
const rect = containerRef.current?.getBoundingClientRect();
|
||||
if (!rect) return;
|
||||
|
||||
setBoxSelectEnd({ x: e.clientX - rect.left, y: e.clientY - rect.top });
|
||||
|
||||
// Calculate which pages intersect with selection box
|
||||
const boxLeft = Math.min(boxSelectStart.x, e.clientX - rect.left);
|
||||
const boxRight = Math.max(boxSelectStart.x, e.clientX - rect.left);
|
||||
const boxTop = Math.min(boxSelectStart.y, e.clientY - rect.top);
|
||||
const boxBottom = Math.max(boxSelectStart.y, e.clientY - rect.top);
|
||||
|
||||
const selectedIds: string[] = [];
|
||||
itemRefs.current.forEach((pageEl, pageId) => {
|
||||
const pageRect = pageEl.getBoundingClientRect();
|
||||
const pageLeft = pageRect.left - rect.left;
|
||||
const pageRight = pageRect.right - rect.left;
|
||||
const pageTop = pageRect.top - rect.top;
|
||||
const pageBottom = pageRect.bottom - rect.top;
|
||||
|
||||
// Check if page intersects with selection box
|
||||
const intersects = !(
|
||||
pageRight < boxLeft ||
|
||||
pageLeft > boxRight ||
|
||||
pageBottom < boxTop ||
|
||||
pageTop > boxBottom
|
||||
);
|
||||
|
||||
if (intersects) {
|
||||
selectedIds.push(pageId);
|
||||
}
|
||||
});
|
||||
|
||||
setBoxSelectedPageIds(selectedIds);
|
||||
}, [isBoxSelecting, boxSelectStart]);
|
||||
|
||||
const handleMouseUp = useCallback(() => {
|
||||
if (isBoxSelecting) {
|
||||
// Keep box-selected pages highlighted (don't clear boxSelectedPageIds yet)
|
||||
// They will remain highlighted until next interaction
|
||||
setIsBoxSelecting(false);
|
||||
setBoxSelectStart(null);
|
||||
setBoxSelectEnd(null);
|
||||
}
|
||||
}, [isBoxSelecting]);
|
||||
|
||||
// Function to clear box selection (exposed to child components)
|
||||
const clearBoxSelection = useCallback(() => {
|
||||
setBoxSelectedPageIds([]);
|
||||
}, []);
|
||||
|
||||
// Function to get current box selection (exposed to child components)
|
||||
const getBoxSelection = useCallback(() => {
|
||||
return boxSelectedPageIds;
|
||||
}, [boxSelectedPageIds]);
|
||||
|
||||
// Handle drag start
|
||||
const handleDragStart = useCallback((event: DragStartEvent) => {
|
||||
const activeId = event.active.id as string;
|
||||
setActiveId(activeId);
|
||||
|
||||
// Call the getter function to get fresh thumbnail data
|
||||
const getThumbnail = event.active.data.current?.getThumbnail;
|
||||
if (getThumbnail) {
|
||||
const thumbnailData = getThumbnail();
|
||||
if (thumbnailData?.src) {
|
||||
setDragPreview({ src: thumbnailData.src, rotation: thumbnailData.rotation });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setDragPreview(null);
|
||||
}, []);
|
||||
|
||||
|
||||
// Handle drag cancel
|
||||
const handleDragCancel = useCallback(() => {
|
||||
setActiveId(null);
|
||||
setDragPreview(null);
|
||||
setHoveredItemId(null);
|
||||
setDropSide(null);
|
||||
}, []);
|
||||
|
||||
// Handle drag end
|
||||
const handleDragEnd = useCallback((event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
|
||||
const finalDropSide = dropSide;
|
||||
setActiveId(null);
|
||||
setDragPreview(null);
|
||||
setHoveredItemId(null);
|
||||
setDropSide(null);
|
||||
|
||||
if (!over || active.id === over.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get data from hooks
|
||||
const activeData = active.data.current;
|
||||
if (!activeData) return;
|
||||
|
||||
const sourcePageNumber = activeData.pageNumber;
|
||||
|
||||
const overData = over?.data.current;
|
||||
let targetIndex = resolveTargetIndex(
|
||||
hoveredItemId,
|
||||
finalDropSide,
|
||||
visibleItems,
|
||||
filteredToOriginalIndex,
|
||||
items.length,
|
||||
overData ? overData.index : null
|
||||
);
|
||||
|
||||
if (targetIndex === null) return;
|
||||
if (targetIndex < 0) targetIndex = 0;
|
||||
if (targetIndex > items.length) targetIndex = items.length;
|
||||
|
||||
// Check if this page is box-selected
|
||||
const isBoxSelected = boxSelectedPageIds.includes(active.id as string);
|
||||
const pagesToDrag = isBoxSelected && boxSelectedPageIds.length > 0 ? boxSelectedPageIds : undefined;
|
||||
|
||||
// Call reorder with page number and target index
|
||||
onReorderPages(sourcePageNumber, targetIndex, pagesToDrag);
|
||||
|
||||
// Highlight moved pages briefly
|
||||
const movedIds = pagesToDrag ?? [active.id as string];
|
||||
setJustMovedIds(movedIds);
|
||||
if (highlightTimeoutRef.current) {
|
||||
window.clearTimeout(highlightTimeoutRef.current);
|
||||
}
|
||||
highlightTimeoutRef.current = window.setTimeout(() => {
|
||||
setJustMovedIds([]);
|
||||
highlightTimeoutRef.current = null;
|
||||
}, 1200);
|
||||
|
||||
// Clear box selection after drag
|
||||
if (pagesToDrag) {
|
||||
clearBoxSelection();
|
||||
}
|
||||
}, [boxSelectedPageIds, dropSide, hoveredItemId, visibleItems, filteredToOriginalIndex, items, onReorderPages, clearBoxSelection]);
|
||||
|
||||
// Calculate optimal width for centering
|
||||
const remToPx = parseFloat(getComputedStyle(document.documentElement).fontSize);
|
||||
const itemWidth = parseFloat(GRID_CONSTANTS.ITEM_WIDTH) * remToPx * zoomLevel;
|
||||
const itemGap = parseFloat(GRID_CONSTANTS.ITEM_GAP) * remToPx * zoomLevel;
|
||||
const gridWidth = itemsPerRow * itemWidth + (itemsPerRow - 1) * itemGap;
|
||||
|
||||
// Calculate selection box dimensions
|
||||
const selectionBoxStyle = isBoxSelecting && boxSelectStart && boxSelectEnd ? {
|
||||
position: 'absolute' as const,
|
||||
left: Math.min(boxSelectStart.x, boxSelectEnd.x),
|
||||
top: Math.min(boxSelectStart.y, boxSelectEnd.y),
|
||||
width: Math.abs(boxSelectEnd.x - boxSelectStart.x),
|
||||
height: Math.abs(boxSelectEnd.y - boxSelectStart.y),
|
||||
border: '2px dashed #3b82f6',
|
||||
backgroundColor: 'rgba(59, 130, 246, 0.1)',
|
||||
pointerEvents: 'none' as const,
|
||||
zIndex: 1000,
|
||||
} : null;
|
||||
|
||||
// Calculate drop indicator position
|
||||
const dropIndicatorStyle = useMemo(() => {
|
||||
if (!hoveredItemId || !dropSide || !activeId) return null;
|
||||
|
||||
const element = itemRefs.current.get(hoveredItemId);
|
||||
const container = containerRef.current;
|
||||
if (!element || !container) return null;
|
||||
|
||||
const itemRect = element.getBoundingClientRect();
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
|
||||
const top = itemRect.top - containerRect.top;
|
||||
const height = itemRect.height;
|
||||
const left = dropSide === 'left'
|
||||
? itemRect.left - containerRect.left - itemGap / 2
|
||||
: itemRect.right - containerRect.left + itemGap / 2;
|
||||
|
||||
return {
|
||||
position: 'absolute' as const,
|
||||
left: `${left}px`,
|
||||
top: `${top}px`,
|
||||
width: '4px',
|
||||
height: `${height}px`,
|
||||
backgroundColor: 'rgba(96, 165, 250, 0.8)',
|
||||
borderRadius: '2px',
|
||||
zIndex: 1001,
|
||||
pointerEvents: 'none' as const,
|
||||
};
|
||||
}, [hoveredItemId, dropSide, activeId, itemGap, zoomLevel]);
|
||||
|
||||
const activeDragIds = useMemo(() => {
|
||||
if (!activeId) return [];
|
||||
if (boxSelectedPageIds.includes(activeId)) {
|
||||
return boxSelectedPageIds;
|
||||
}
|
||||
return [activeId];
|
||||
}, [activeId, boxSelectedPageIds]);
|
||||
|
||||
const handleWheelWhileDragging = useCallback((event: React.WheelEvent<HTMLDivElement>) => {
|
||||
if (!activeId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scrollElement = getScrollElement();
|
||||
if (!scrollElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
scrollElement.scrollBy({
|
||||
top: event.deltaY,
|
||||
left: event.deltaX,
|
||||
});
|
||||
|
||||
event.preventDefault();
|
||||
}, [activeId, getScrollElement]);
|
||||
|
||||
return (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragStart={handleDragStart}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragCancel={handleDragCancel}
|
||||
>
|
||||
<Box
|
||||
ref={containerRef}
|
||||
onMouseDown={handleMouseDown}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseUp={handleMouseUp}
|
||||
onWheel={handleWheelWhileDragging}
|
||||
style={{
|
||||
// Basic container styles
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
position: 'relative',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{/* Selection box overlay */}
|
||||
{selectionBoxStyle && <div style={selectionBoxStyle} />}
|
||||
|
||||
{/* Global drop indicator */}
|
||||
{dropIndicatorStyle && <div style={dropIndicatorStyle} />}
|
||||
|
||||
<div
|
||||
style={{
|
||||
height: `${rowVirtualizer.getTotalSize()}px`,
|
||||
width: '100%',
|
||||
maxWidth: `${gridWidth}px`,
|
||||
position: 'relative',
|
||||
margin: '0 auto',
|
||||
}}
|
||||
>
|
||||
{rowVirtualizer.getVirtualItems().map((virtualRow) => {
|
||||
const startIndex = virtualRow.index * itemsPerRow;
|
||||
const endIndex = Math.min(startIndex + itemsPerRow, visibleItems.length);
|
||||
const rowItems = visibleItems.slice(startIndex, endIndex);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={virtualRow.index}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: `${virtualRow.size}px`,
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: `calc(${GRID_CONSTANTS.ITEM_GAP} * ${zoomLevel})`,
|
||||
justifyContent: 'flex-start',
|
||||
height: '100%',
|
||||
alignItems: 'center',
|
||||
position: 'relative'
|
||||
}}
|
||||
>
|
||||
{rowItems.map((item, itemIndex) => {
|
||||
const actualIndex = startIndex + itemIndex;
|
||||
return (
|
||||
<DraggableItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
index={actualIndex}
|
||||
itemRefs={itemRefs}
|
||||
boxSelectedPageIds={boxSelectedPageIds}
|
||||
clearBoxSelection={clearBoxSelection}
|
||||
getBoxSelection={getBoxSelection}
|
||||
activeId={activeId}
|
||||
activeDragIds={activeDragIds}
|
||||
justMoved={justMovedIds.includes(item.id)}
|
||||
getThumbnailData={getThumbnailData}
|
||||
onUpdateDropTarget={setHoveredItemId}
|
||||
renderItem={renderItem}
|
||||
zoomLevel={zoomLevel}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Drag Overlay */}
|
||||
<DragOverlay>
|
||||
{activeId && (
|
||||
<div style={{ position: 'relative', cursor: 'grabbing' }}>
|
||||
{/* Multi-page badge */}
|
||||
{boxSelectedPageIds.includes(activeId) && boxSelectedPageIds.length > 1 && (
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '-8px',
|
||||
right: '-8px',
|
||||
backgroundColor: '#3b82f6',
|
||||
color: 'white',
|
||||
borderRadius: '50%',
|
||||
width: '32px',
|
||||
height: '32px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontSize: '14px',
|
||||
fontWeight: 'bold',
|
||||
boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
|
||||
zIndex: 1001
|
||||
}}
|
||||
>
|
||||
{boxSelectedPageIds.length}
|
||||
</div>
|
||||
)}
|
||||
{/* Just the thumbnail image */}
|
||||
{dragPreview ? (
|
||||
<img
|
||||
src={dragPreview.src}
|
||||
alt="Dragging"
|
||||
style={{
|
||||
width: `calc(20rem * ${zoomLevel})`,
|
||||
height: `calc(20rem * ${zoomLevel})`,
|
||||
objectFit: 'contain',
|
||||
transform: `rotate(${dragPreview.rotation}deg)`,
|
||||
pointerEvents: 'none',
|
||||
opacity: 0.5,
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div style={{
|
||||
width: `calc(20rem * ${zoomLevel})`,
|
||||
height: `calc(20rem * ${zoomLevel})`,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontSize: '48px',
|
||||
opacity: 0.5,
|
||||
}}>
|
||||
📄
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DragOverlay>
|
||||
</DndContext>
|
||||
);
|
||||
};
|
||||
|
||||
export default DragDropGrid;
|
||||
+3
-3
@@ -9,9 +9,9 @@ import PushPinOutlinedIcon from '@mui/icons-material/PushPinOutlined';
|
||||
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
|
||||
import { draggable, dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter';
|
||||
|
||||
import styles from '@app/components/pageEditor/PageEditor.module.css';
|
||||
import { useFileContext } from '@app/contexts/FileContext';
|
||||
import { FileId } from '@app/types/file';
|
||||
import styles from './PageEditor.module.css';
|
||||
import { useFileContext } from '../../contexts/FileContext';
|
||||
import { FileId } from '../../types/file';
|
||||
|
||||
interface FileItem {
|
||||
id: FileId;
|
||||
+20
@@ -11,6 +11,26 @@
|
||||
transform: scale(1.02) translateZ(0);
|
||||
}
|
||||
|
||||
.pageSurface {
|
||||
transition: background-color 0.4s ease;
|
||||
}
|
||||
|
||||
.pageJustMoved {
|
||||
animation: pageMovedHighlight 1.2s ease-out;
|
||||
}
|
||||
|
||||
@keyframes pageMovedHighlight {
|
||||
0% {
|
||||
background-color: rgba(59, 130, 246, 0.32);
|
||||
}
|
||||
60% {
|
||||
background-color: rgba(59, 130, 246, 0.12);
|
||||
}
|
||||
100% {
|
||||
background-color: rgba(59, 130, 246, 0);
|
||||
}
|
||||
}
|
||||
|
||||
.pageContainer:hover .pageNumber {
|
||||
opacity: 1 !important;
|
||||
}
|
||||
+546
-165
@@ -1,19 +1,20 @@
|
||||
import { useState, useCallback, useRef, useEffect } from "react";
|
||||
import { useState, useCallback, useRef, useEffect, useMemo } from "react";
|
||||
import { Text, Center, Box, LoadingOverlay, Stack } from "@mantine/core";
|
||||
import { useFileState, useFileActions } from "@app/contexts/FileContext";
|
||||
import { useNavigationGuard } from "@app/contexts/NavigationContext";
|
||||
import { PDFDocument, PageEditorFunctions } from "@app/types/pageEditor";
|
||||
import { pdfExportService } from "@app/services/pdfExportService";
|
||||
import { documentManipulationService } from "@app/services/documentManipulationService";
|
||||
import { exportProcessedDocumentsToFiles } from "@app/services/pdfExportHelpers";
|
||||
import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";
|
||||
import { useFileState, useFileActions } from "../../contexts/FileContext";
|
||||
import { useNavigationGuard } from "../../contexts/NavigationContext";
|
||||
import { usePageEditor } from "../../contexts/PageEditorContext";
|
||||
import { PDFDocument, PDFPage, PageEditorFunctions } from "../../types/pageEditor";
|
||||
import { StirlingFileStub } from "../../types/fileContext";
|
||||
import { pdfExportService } from "../../services/pdfExportService";
|
||||
import { documentManipulationService } from "../../services/documentManipulationService";
|
||||
import { exportProcessedDocumentsToFiles } from "../../services/pdfExportHelpers";
|
||||
// Thumbnail generation is now handled by individual PageThumbnail components
|
||||
import '@app/components/pageEditor/PageEditor.module.css';
|
||||
import PageThumbnail from '@app/components/pageEditor/PageThumbnail';
|
||||
import DragDropGrid from '@app/components/pageEditor/DragDropGrid';
|
||||
import SkeletonLoader from '@app/components/shared/SkeletonLoader';
|
||||
import NavigationWarningModal from '@app/components/shared/NavigationWarningModal';
|
||||
import { FileId } from "@app/types/file";
|
||||
import './PageEditor.module.css';
|
||||
import PageThumbnail from './PageThumbnail';
|
||||
import DragDropGrid from './DragDropGrid';
|
||||
import SkeletonLoader from '../shared/SkeletonLoader';
|
||||
import NavigationWarningModal from '../shared/NavigationWarningModal';
|
||||
import { FileId } from "../../types/file";
|
||||
|
||||
import {
|
||||
DeletePagesCommand,
|
||||
@@ -22,12 +23,14 @@ import {
|
||||
BulkRotateCommand,
|
||||
PageBreakCommand,
|
||||
UndoManager
|
||||
} from '@app/components/pageEditor/commands/pageCommands';
|
||||
import { GRID_CONSTANTS } from '@app/components/pageEditor/constants';
|
||||
import { usePageDocument } from '@app/components/pageEditor/hooks/usePageDocument';
|
||||
import { usePageEditorState } from '@app/components/pageEditor/hooks/usePageEditorState';
|
||||
import { parseSelection } from "@app/utils/bulkselection/parseSelection";
|
||||
import { usePageEditorRightRailButtons } from "@app/components/pageEditor/pageEditorRightRailButtons";
|
||||
} from './commands/pageCommands';
|
||||
import { GRID_CONSTANTS } from './constants';
|
||||
import { useInitialPageDocument } from './hooks/useInitialPageDocument';
|
||||
import { usePageDocument } from './hooks/usePageDocument';
|
||||
import { usePageEditorState } from './hooks/usePageEditorState';
|
||||
import { parseSelection } from "../../utils/bulkselection/parseSelection";
|
||||
import { usePageEditorRightRailButtons } from "./pageEditorRightRailButtons";
|
||||
import { useFileColorMap } from "./hooks/useFileColorMap";
|
||||
|
||||
export interface PageEditorProps {
|
||||
onFunctionsReady?: (functions: PageEditorFunctions) => void;
|
||||
@@ -44,8 +47,90 @@ const PageEditor = ({
|
||||
// Navigation guard for unsaved changes
|
||||
const { setHasUnsavedChanges } = useNavigationGuard();
|
||||
|
||||
// Prefer IDs + selectors to avoid array identity churn
|
||||
const activeFileIds = state.files.ids;
|
||||
// Get PageEditor coordination functions
|
||||
const { updateFileOrderFromPages, fileOrder, reorderedPages, clearReorderedPages, updateCurrentPages } = usePageEditor();
|
||||
|
||||
// Zoom state management
|
||||
const [zoomLevel, setZoomLevel] = useState(1.0);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [isContainerHovered, setIsContainerHovered] = useState(false);
|
||||
|
||||
// Zoom actions
|
||||
const zoomIn = useCallback(() => {
|
||||
setZoomLevel(prev => Math.min(prev + 0.1, 3.0));
|
||||
}, []);
|
||||
|
||||
const zoomOut = useCallback(() => {
|
||||
setZoomLevel(prev => Math.max(prev - 0.1, 0.5));
|
||||
}, []);
|
||||
|
||||
// Derive page editor files from PageEditorContext's fileOrder (page editor workspace order)
|
||||
// Filter to only show PDF files (PageEditor only supports PDFs)
|
||||
// Use stable string keys to prevent infinite loops
|
||||
// Cache file objects to prevent infinite re-renders from new object references
|
||||
const fileOrderKey = fileOrder.join(',');
|
||||
const selectedIdsKey = [...state.ui.selectedFileIds].sort().join(',');
|
||||
const filesSignature = selectors.getFilesSignature();
|
||||
|
||||
const fileObjectsRef = useRef(new Map<FileId, any>());
|
||||
const pagePositionCacheRef = useRef<Map<string, number>>(new Map());
|
||||
const pageNeighborCacheRef = useRef<Map<string, string | null>>(new Map());
|
||||
|
||||
const pageEditorFiles = useMemo(() => {
|
||||
const cache = fileObjectsRef.current;
|
||||
const newFiles: any[] = [];
|
||||
|
||||
fileOrder.forEach(fileId => {
|
||||
const stub = selectors.getStirlingFileStub(fileId);
|
||||
const isSelected = state.ui.selectedFileIds.includes(fileId);
|
||||
const isPdf = stub?.name?.toLowerCase().endsWith('.pdf') ?? false;
|
||||
|
||||
if (!isPdf) return; // Skip non-PDFs
|
||||
|
||||
const cached = cache.get(fileId);
|
||||
|
||||
// Check if data actually changed (compare by fileId, not position)
|
||||
if (cached &&
|
||||
cached.fileId === fileId &&
|
||||
cached.name === (stub?.name || '') &&
|
||||
cached.versionNumber === stub?.versionNumber &&
|
||||
cached.isSelected === isSelected) {
|
||||
// Reuse existing object reference
|
||||
newFiles.push(cached);
|
||||
} else {
|
||||
// Create new object only if data changed
|
||||
const newFile = {
|
||||
fileId,
|
||||
name: stub?.name || '',
|
||||
versionNumber: stub?.versionNumber,
|
||||
isSelected,
|
||||
};
|
||||
cache.set(fileId, newFile);
|
||||
newFiles.push(newFile);
|
||||
}
|
||||
});
|
||||
|
||||
// Clean up removed files from cache
|
||||
const activeIds = new Set(newFiles.map(f => f.fileId));
|
||||
for (const cachedId of cache.keys()) {
|
||||
if (!activeIds.has(cachedId)) {
|
||||
cache.delete(cachedId);
|
||||
}
|
||||
}
|
||||
|
||||
return newFiles;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [fileOrderKey, selectedIdsKey, filesSignature]);
|
||||
|
||||
// Get ALL file IDs in order (not filtered by selection)
|
||||
const orderedFileIds = useMemo(() => {
|
||||
return pageEditorFiles.map(f => f.fileId);
|
||||
}, [pageEditorFiles]);
|
||||
|
||||
// Get selected file IDs for filtering
|
||||
const selectedFileIds = useMemo(() => {
|
||||
return pageEditorFiles.filter(f => f.isSelected).map(f => f.fileId);
|
||||
}, [pageEditorFiles]);
|
||||
const activeFilesSignature = selectors.getFilesSignature();
|
||||
|
||||
// UI state
|
||||
@@ -58,8 +143,153 @@ const PageEditor = ({
|
||||
const undoManagerRef = useRef(new UndoManager());
|
||||
|
||||
// Document state management
|
||||
// Get initial document ONCE - useInitialPageDocument captures first value only
|
||||
const initialDocument = useInitialPageDocument();
|
||||
|
||||
// Also get live mergedPdfDocument for delta sync (source of truth for page existence)
|
||||
const { document: mergedPdfDocument } = usePageDocument();
|
||||
|
||||
// Initialize editedDocument from initial document
|
||||
useEffect(() => {
|
||||
if (!initialDocument || editedDocument) return;
|
||||
|
||||
console.log('📄 Initializing editedDocument from initial document:', initialDocument.pages.length, 'pages');
|
||||
|
||||
// Clone to avoid mutation
|
||||
setEditedDocument({
|
||||
...initialDocument,
|
||||
pages: initialDocument.pages.map(p => ({ ...p }))
|
||||
});
|
||||
}, [initialDocument, editedDocument]);
|
||||
|
||||
// Apply file reordering from PageEditorContext
|
||||
useEffect(() => {
|
||||
if (reorderedPages && editedDocument) {
|
||||
setEditedDocument({
|
||||
...editedDocument,
|
||||
pages: reorderedPages
|
||||
});
|
||||
clearReorderedPages();
|
||||
}
|
||||
}, [reorderedPages, editedDocument, clearReorderedPages]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editedDocument) return;
|
||||
const positionCache = pagePositionCacheRef.current;
|
||||
const neighborCache = pageNeighborCacheRef.current;
|
||||
const pages = editedDocument.pages;
|
||||
pages.forEach((page, index) => {
|
||||
positionCache.set(page.id, index);
|
||||
neighborCache.set(page.id, index > 0 ? pages[index - 1].id : null);
|
||||
});
|
||||
}, [editedDocument]);
|
||||
|
||||
// Live delta sync: reflect external add/remove without touching existing order
|
||||
useEffect(() => {
|
||||
if (!mergedPdfDocument || !editedDocument) return;
|
||||
|
||||
const sourcePages = mergedPdfDocument.pages;
|
||||
const sourceIds = new Set(sourcePages.map(p => p.id));
|
||||
|
||||
// Group new pages by file (preserve within-file order from source)
|
||||
const prevIds = new Set(editedDocument.pages.map(p => p.id));
|
||||
const newPages: PDFPage[] = [];
|
||||
for (const p of sourcePages) {
|
||||
if (!prevIds.has(p.id)) {
|
||||
newPages.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
// Fast check: changes exist?
|
||||
const hasAdditions = newPages.length > 0;
|
||||
let hasRemovals = false;
|
||||
for (const p of editedDocument.pages) {
|
||||
if (!sourceIds.has(p.id)) {
|
||||
hasRemovals = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasAdditions && !hasRemovals) return;
|
||||
|
||||
setEditedDocument(prev => {
|
||||
if (!prev) return prev;
|
||||
let pages = [...prev.pages];
|
||||
|
||||
// Capture placeholder positions before they are removed so we can restore files without disrupting current order
|
||||
const placeholderPositions = new Map<FileId, number>();
|
||||
pages.forEach((page, index) => {
|
||||
if (page.isPlaceholder && page.originalFileId) {
|
||||
placeholderPositions.set(page.originalFileId, index);
|
||||
}
|
||||
});
|
||||
|
||||
// Track next insertion index per file when replacing placeholders
|
||||
const nextInsertIndexByFile = new Map(placeholderPositions);
|
||||
|
||||
// Remove pages that no longer exist in source
|
||||
if (hasRemovals) {
|
||||
pages = pages.filter(p => sourceIds.has(p.id));
|
||||
}
|
||||
|
||||
// Insert new pages while preserving current interleaving
|
||||
if (hasAdditions) {
|
||||
const mergedIndexMap = new Map<string, number>();
|
||||
sourcePages.forEach((page, index) => mergedIndexMap.set(page.id, index));
|
||||
|
||||
const additions = newPages
|
||||
.map(page => ({
|
||||
page,
|
||||
cachedIndex: pagePositionCacheRef.current.get(page.id),
|
||||
mergedIndex: mergedIndexMap.get(page.id) ?? sourcePages.length,
|
||||
neighborId: pageNeighborCacheRef.current.get(page.id)
|
||||
}))
|
||||
.sort((a, b) => {
|
||||
const aIndex = a.cachedIndex ?? a.mergedIndex;
|
||||
const bIndex = b.cachedIndex ?? b.mergedIndex;
|
||||
if (aIndex !== bIndex) return aIndex - bIndex;
|
||||
return a.mergedIndex - b.mergedIndex;
|
||||
});
|
||||
|
||||
additions.forEach(({ page, neighborId, cachedIndex, mergedIndex }) => {
|
||||
if (pages.some(existing => existing.id === page.id)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let insertIndex: number;
|
||||
const originalFileId = page.originalFileId;
|
||||
const placeholderIndex = originalFileId ? nextInsertIndexByFile.get(originalFileId) : undefined;
|
||||
|
||||
if (originalFileId && placeholderIndex !== undefined) {
|
||||
insertIndex = Math.min(placeholderIndex, pages.length);
|
||||
nextInsertIndexByFile.set(originalFileId, insertIndex + 1);
|
||||
} else if (neighborId === null) {
|
||||
insertIndex = 0;
|
||||
} else if (neighborId) {
|
||||
const neighborIndex = pages.findIndex(p => p.id === neighborId);
|
||||
if (neighborIndex !== -1) {
|
||||
insertIndex = neighborIndex + 1;
|
||||
} else {
|
||||
const fallbackIndex = cachedIndex ?? mergedIndex ?? pages.length;
|
||||
insertIndex = Math.min(fallbackIndex, pages.length);
|
||||
}
|
||||
} else {
|
||||
const fallbackIndex = cachedIndex ?? mergedIndex ?? pages.length;
|
||||
insertIndex = Math.min(fallbackIndex, pages.length);
|
||||
}
|
||||
|
||||
const clonedPage = { ...page };
|
||||
pages.splice(insertIndex, 0, clonedPage);
|
||||
});
|
||||
}
|
||||
|
||||
// Renumber without reordering
|
||||
pages = pages.map((p, i) => ({ ...p, pageNumber: i + 1 }));
|
||||
return { ...prev, pages };
|
||||
});
|
||||
// Only depend on identifiers to avoid loops; do not depend on editedDocument itself
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [mergedPdfDocument && mergedPdfDocument.pages.map(p => p.id).join(','), fileOrder.join(',')]);
|
||||
|
||||
// UI state management
|
||||
const {
|
||||
@@ -86,9 +316,14 @@ const PageEditor = ({
|
||||
|
||||
// Update undo/redo state
|
||||
const updateUndoRedoState = useCallback(() => {
|
||||
setCanUndo(undoManagerRef.current.canUndo());
|
||||
setCanRedo(undoManagerRef.current.canRedo());
|
||||
}, []);
|
||||
const undoManager = undoManagerRef.current;
|
||||
setCanUndo(undoManager.canUndo());
|
||||
setCanRedo(undoManager.canRedo());
|
||||
|
||||
if (!undoManager.hasHistory()) {
|
||||
setHasUnsavedChanges(false);
|
||||
}
|
||||
}, [setHasUnsavedChanges]);
|
||||
|
||||
// Set up undo manager callback
|
||||
useEffect(() => {
|
||||
@@ -126,9 +361,17 @@ const PageEditor = ({
|
||||
}, []);
|
||||
|
||||
// Interface functions for parent component
|
||||
const displayDocument = editedDocument || mergedPdfDocument;
|
||||
const totalPages = displayDocument?.pages.length ?? 0;
|
||||
const displayDocument = editedDocument || initialDocument;
|
||||
|
||||
// Feed current pages to PageEditorContext so file reordering can compute page-level changes
|
||||
useEffect(() => {
|
||||
updateCurrentPages(displayDocument?.pages ?? null);
|
||||
}, [displayDocument, updateCurrentPages]);
|
||||
|
||||
// Derived values for right rail and usePageEditorRightRailButtons (must be after displayDocument)
|
||||
const totalPages = displayDocument?.pages.length || 0;
|
||||
const selectedPageCount = selectedPageIds.length;
|
||||
const activeFileIds = selectedFileIds;
|
||||
|
||||
// Utility functions to convert between page IDs and page numbers
|
||||
const getPageNumbersFromIds = useCallback((pageIds: string[]): number[] => {
|
||||
@@ -158,6 +401,31 @@ const PageEditor = ({
|
||||
}
|
||||
}, [displayDocument, setSelectedPageIds, setSelectionMode]);
|
||||
|
||||
// Automatically include newly added pages in the current selection
|
||||
const previousPageIdsRef = useRef<Set<string>>(new Set());
|
||||
useEffect(() => {
|
||||
if (!displayDocument || displayDocument.pages.length === 0) {
|
||||
previousPageIdsRef.current = new Set();
|
||||
return;
|
||||
}
|
||||
|
||||
const currentIds = new Set(displayDocument.pages.map(page => page.id));
|
||||
const newlyAddedPageIds: string[] = [];
|
||||
currentIds.forEach(id => {
|
||||
if (!previousPageIdsRef.current.has(id)) {
|
||||
newlyAddedPageIds.push(id);
|
||||
}
|
||||
});
|
||||
|
||||
if (newlyAddedPageIds.length > 0) {
|
||||
const next = new Set(selectedPageIds);
|
||||
newlyAddedPageIds.forEach(id => next.add(id));
|
||||
setSelectedPageIds(Array.from(next));
|
||||
}
|
||||
|
||||
previousPageIdsRef.current = currentIds;
|
||||
}, [displayDocument, selectedPageIds, setSelectedPageIds]);
|
||||
|
||||
// DOM-first command handlers
|
||||
const handleRotatePages = useCallback((pageIds: string[], rotation: number) => {
|
||||
const bulkRotateCommand = new BulkRotateCommand(pageIds, rotation);
|
||||
@@ -323,51 +591,8 @@ const PageEditor = ({
|
||||
executeCommandWithTracking(smartSplitCommand);
|
||||
}, [selectedPageIds, displayDocument, splitPositions, setSplitPositions, getPageNumbersFromIds, executeCommandWithTracking]);
|
||||
|
||||
const handleSplitAll = useCallback(() => {
|
||||
if (!displayDocument || selectedPageIds.length === 0) return;
|
||||
|
||||
// Convert selected page IDs to page numbers, then to split positions (0-based indices)
|
||||
const selectedPageNumbers = getPageNumbersFromIds(selectedPageIds);
|
||||
const selectedPositions: number[] = [];
|
||||
selectedPageNumbers.forEach(pageNum => {
|
||||
const pageIndex = displayDocument.pages.findIndex(p => p.pageNumber === pageNum);
|
||||
if (pageIndex !== -1 && pageIndex < displayDocument.pages.length - 1) {
|
||||
// Only allow splits before the last page
|
||||
selectedPositions.push(pageIndex);
|
||||
}
|
||||
});
|
||||
|
||||
if (selectedPositions.length === 0) return;
|
||||
|
||||
// Smart toggle logic: follow the majority, default to adding splits if equal
|
||||
const existingSplitsCount = selectedPositions.filter(pos => splitPositions.has(pos)).length;
|
||||
const noSplitsCount = selectedPositions.length - existingSplitsCount;
|
||||
|
||||
// Remove splits only if majority already have splits
|
||||
// If equal (50/50), default to adding splits
|
||||
const shouldRemoveSplits = existingSplitsCount > noSplitsCount;
|
||||
|
||||
const newSplitPositions = new Set(splitPositions);
|
||||
|
||||
if (shouldRemoveSplits) {
|
||||
// Remove splits from all selected positions
|
||||
selectedPositions.forEach(pos => newSplitPositions.delete(pos));
|
||||
} else {
|
||||
// Add splits to all selected positions
|
||||
selectedPositions.forEach(pos => newSplitPositions.add(pos));
|
||||
}
|
||||
|
||||
// Create a custom command that sets the final state directly
|
||||
const smartSplitCommand = {
|
||||
execute: () => setSplitPositions(newSplitPositions),
|
||||
undo: () => setSplitPositions(splitPositions),
|
||||
description: shouldRemoveSplits
|
||||
? `Remove ${selectedPositions.length} split(s)`
|
||||
: `Add ${selectedPositions.length - existingSplitsCount} split(s)`
|
||||
};
|
||||
|
||||
executeCommandWithTracking(smartSplitCommand);
|
||||
}, [selectedPageIds, displayDocument, splitPositions, setSplitPositions, getPageNumbersFromIds, executeCommandWithTracking]);
|
||||
// Alias for consistency - handleSplitAll is the same as handleSplit (both have smart toggle logic)
|
||||
const handleSplitAll = handleSplit;
|
||||
|
||||
const handlePageBreak = useCallback(() => {
|
||||
if (!displayDocument || selectedPageIds.length === 0) return;
|
||||
@@ -383,32 +608,99 @@ const PageEditor = ({
|
||||
executeCommandWithTracking(pageBreakCommand);
|
||||
}, [selectedPageIds, displayDocument, getPageNumbersFromIds, executeCommandWithTracking]);
|
||||
|
||||
const handlePageBreakAll = useCallback(() => {
|
||||
if (!displayDocument || selectedPageIds.length === 0) return;
|
||||
// Alias for consistency - handlePageBreakAll is the same as handlePageBreak
|
||||
const handlePageBreakAll = handlePageBreak;
|
||||
|
||||
// Convert selected page IDs to page numbers for the command
|
||||
const selectedPageNumbers = getPageNumbersFromIds(selectedPageIds);
|
||||
|
||||
const pageBreakCommand = new PageBreakCommand(
|
||||
selectedPageNumbers,
|
||||
() => displayDocument,
|
||||
setEditedDocument
|
||||
);
|
||||
executeCommandWithTracking(pageBreakCommand);
|
||||
}, [selectedPageIds, displayDocument, getPageNumbersFromIds, executeCommandWithTracking]);
|
||||
|
||||
const handleInsertFiles = useCallback(async (files: File[], insertAfterPage: number) => {
|
||||
if (!displayDocument || files.length === 0) return;
|
||||
const handleInsertFiles = useCallback(async (
|
||||
files: File[] | StirlingFileStub[],
|
||||
insertAfterPage: number,
|
||||
isFromStorage?: boolean
|
||||
) => {
|
||||
if (!editedDocument || files.length === 0) return;
|
||||
|
||||
try {
|
||||
const targetPage = displayDocument.pages.find(p => p.pageNumber === insertAfterPage);
|
||||
const targetPage = editedDocument.pages.find(p => p.pageNumber === insertAfterPage);
|
||||
if (!targetPage) return;
|
||||
|
||||
await actions.addFiles(files, { insertAfterPageId: targetPage.id });
|
||||
console.log('📄 handleInsertFiles: Inserting files after page', insertAfterPage, 'targetPage:', targetPage.id);
|
||||
|
||||
// Add files to FileContext for metadata tracking and preserve insertion point
|
||||
const insertAfterPageId = targetPage.id;
|
||||
let addedFileIds: FileId[] = [];
|
||||
if (isFromStorage) {
|
||||
const stubs = files as StirlingFileStub[];
|
||||
const result = await actions.addStirlingFileStubs(stubs, {
|
||||
selectFiles: true,
|
||||
insertAfterPageId
|
||||
});
|
||||
addedFileIds = result.map(f => f.fileId);
|
||||
console.log('📄 handleInsertFiles: Added stubs, IDs:', addedFileIds);
|
||||
} else {
|
||||
const result = await actions.addFiles(files as File[], {
|
||||
selectFiles: true,
|
||||
insertAfterPageId
|
||||
});
|
||||
addedFileIds = result.map(f => f.fileId);
|
||||
console.log('📄 handleInsertFiles: Added files, IDs:', addedFileIds);
|
||||
}
|
||||
|
||||
// Wait a moment for files to be processed
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Extract pages from newly added files and insert them into editedDocument
|
||||
const newPages: PDFPage[] = [];
|
||||
for (const fileId of addedFileIds) {
|
||||
const stub = selectors.getStirlingFileStub(fileId);
|
||||
console.log('📄 handleInsertFiles: File', fileId, 'stub:', stub?.name, 'processedFile:', stub?.processedFile?.totalPages, 'pages:', stub?.processedFile?.pages?.length);
|
||||
if (stub?.processedFile?.pages) {
|
||||
// Clone pages and ensure proper PDFPage structure
|
||||
const clonedPages = stub.processedFile.pages.map((page, idx) => ({
|
||||
...page,
|
||||
id: `${fileId}-${page.pageNumber ?? idx + 1}`,
|
||||
pageNumber: page.pageNumber ?? idx + 1,
|
||||
originalFileId: fileId,
|
||||
originalPageNumber: page.originalPageNumber ?? page.pageNumber ?? idx + 1,
|
||||
rotation: page.rotation ?? 0,
|
||||
thumbnail: page.thumbnail ?? null,
|
||||
selected: false,
|
||||
splitAfter: page.splitAfter ?? false,
|
||||
}));
|
||||
newPages.push(...clonedPages);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('📄 handleInsertFiles: Collected', newPages.length, 'new pages');
|
||||
|
||||
if (newPages.length > 0) {
|
||||
// Find insertion index in editedDocument
|
||||
const targetIndex = editedDocument.pages.findIndex(p => p.id === targetPage.id);
|
||||
console.log('📄 handleInsertFiles: Target index in editedDocument:', targetIndex);
|
||||
|
||||
if (targetIndex >= 0) {
|
||||
// Clone pages and insert
|
||||
const updatedPages = [...editedDocument.pages];
|
||||
updatedPages.splice(targetIndex + 1, 0, ...newPages);
|
||||
|
||||
// Renumber all pages
|
||||
updatedPages.forEach((page, index) => {
|
||||
page.pageNumber = index + 1;
|
||||
});
|
||||
|
||||
console.log('📄 handleInsertFiles: Updated pages:', updatedPages.map(p => `${p.id}(${p.pageNumber})`));
|
||||
|
||||
setEditedDocument({
|
||||
...editedDocument,
|
||||
pages: updatedPages
|
||||
});
|
||||
|
||||
// Keep PageEditor file order in sync with newly inserted pages
|
||||
updateFileOrderFromPages(updatedPages);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to insert files:', error);
|
||||
}
|
||||
}, [displayDocument, actions]);
|
||||
}, [editedDocument, actions, selectors, updateFileOrderFromPages]);
|
||||
|
||||
const handleSelectAll = useCallback(() => {
|
||||
if (!displayDocument) return;
|
||||
@@ -442,17 +734,18 @@ const PageEditor = ({
|
||||
targetIndex,
|
||||
selectedPages,
|
||||
() => displayDocument,
|
||||
setEditedDocument
|
||||
setEditedDocument,
|
||||
(newPages) => updateFileOrderFromPages(newPages) // Sync file order when pages are reordered
|
||||
);
|
||||
executeCommandWithTracking(reorderCommand);
|
||||
}, [displayDocument, getPageNumbersFromIds, executeCommandWithTracking]);
|
||||
}, [displayDocument, getPageNumbersFromIds, executeCommandWithTracking, updateFileOrderFromPages]);
|
||||
|
||||
// Helper function to collect source files for multi-file export
|
||||
const getSourceFiles = useCallback((): Map<FileId, File> | null => {
|
||||
const sourceFiles = new Map<FileId, File>();
|
||||
|
||||
// Always include original files
|
||||
activeFileIds.forEach(fileId => {
|
||||
// Always include selected files
|
||||
selectedFileIds.forEach(fileId => {
|
||||
const file = selectors.getFile(fileId);
|
||||
if (file) {
|
||||
sourceFiles.set(fileId, file);
|
||||
@@ -461,31 +754,31 @@ const PageEditor = ({
|
||||
|
||||
// Use multi-file export if we have multiple original files
|
||||
const hasInsertedFiles = false;
|
||||
const hasMultipleOriginalFiles = activeFileIds.length > 1;
|
||||
const hasMultipleOriginalFiles = selectedFileIds.length > 1;
|
||||
|
||||
if (!hasInsertedFiles && !hasMultipleOriginalFiles) {
|
||||
return null; // Use single-file export method
|
||||
}
|
||||
|
||||
return sourceFiles.size > 0 ? sourceFiles : null;
|
||||
}, [activeFileIds, selectors]);
|
||||
}, [selectedFileIds, selectors]);
|
||||
|
||||
// Helper function to generate proper filename for exports
|
||||
const getExportFilename = useCallback((): string => {
|
||||
if (activeFileIds.length <= 1) {
|
||||
if (selectedFileIds.length <= 1) {
|
||||
// Single file - use original name
|
||||
return displayDocument?.name || 'document.pdf';
|
||||
}
|
||||
|
||||
// Multiple files - use first file name with " (merged)" suffix
|
||||
const firstFile = selectors.getFile(activeFileIds[0]);
|
||||
const firstFile = selectors.getFile(selectedFileIds[0]);
|
||||
if (firstFile) {
|
||||
const baseName = firstFile.name.replace(/\.pdf$/i, '');
|
||||
return `${baseName} (merged).pdf`;
|
||||
}
|
||||
|
||||
return 'merged-document.pdf';
|
||||
}, [activeFileIds, selectors, displayDocument]);
|
||||
}, [selectedFileIds, selectors, displayDocument]);
|
||||
|
||||
const onExportSelected = useCallback(async () => {
|
||||
if (!displayDocument || selectedPageIds.length === 0) return;
|
||||
@@ -494,7 +787,7 @@ const PageEditor = ({
|
||||
try {
|
||||
// Step 1: Apply DOM changes to document state first
|
||||
const processedDocuments = documentManipulationService.applyDOMChangesToDocument(
|
||||
mergedPdfDocument || displayDocument, // Original order
|
||||
displayDocument, // Original order (editedDocument is our working doc now)
|
||||
displayDocument, // Current display order (includes reordering)
|
||||
splitPositions // Position-based splits
|
||||
);
|
||||
@@ -534,7 +827,7 @@ const PageEditor = ({
|
||||
console.error('Export failed:', error);
|
||||
setExportLoading(false);
|
||||
}
|
||||
}, [displayDocument, selectedPageIds, mergedPdfDocument, splitPositions, getSourceFiles, getExportFilename, setHasUnsavedChanges]);
|
||||
}, [displayDocument, selectedPageIds, initialDocument, splitPositions, getSourceFiles, getExportFilename, setHasUnsavedChanges]);
|
||||
|
||||
const onExportAll = useCallback(async () => {
|
||||
if (!displayDocument) return;
|
||||
@@ -543,7 +836,7 @@ const PageEditor = ({
|
||||
try {
|
||||
// Step 1: Apply DOM changes to document state first
|
||||
const processedDocuments = documentManipulationService.applyDOMChangesToDocument(
|
||||
mergedPdfDocument || displayDocument,
|
||||
displayDocument,
|
||||
displayDocument,
|
||||
splitPositions
|
||||
);
|
||||
@@ -580,7 +873,7 @@ const PageEditor = ({
|
||||
console.error('Export failed:', error);
|
||||
setExportLoading(false);
|
||||
}
|
||||
}, [displayDocument, mergedPdfDocument, splitPositions, getSourceFiles, getExportFilename, setHasUnsavedChanges]);
|
||||
}, [displayDocument, initialDocument, splitPositions, getSourceFiles, getExportFilename, setHasUnsavedChanges]);
|
||||
|
||||
// Apply DOM changes to document state using dedicated service
|
||||
const applyChanges = useCallback(async () => {
|
||||
@@ -590,7 +883,7 @@ const PageEditor = ({
|
||||
try {
|
||||
// Step 1: Apply DOM changes to document state first
|
||||
const processedDocuments = documentManipulationService.applyDOMChangesToDocument(
|
||||
mergedPdfDocument || displayDocument,
|
||||
displayDocument,
|
||||
displayDocument,
|
||||
splitPositions
|
||||
);
|
||||
@@ -600,14 +893,11 @@ const PageEditor = ({
|
||||
const exportFilename = getExportFilename();
|
||||
const files = await exportProcessedDocumentsToFiles(processedDocuments, sourceFiles, exportFilename);
|
||||
|
||||
// Step 3: Create StirlingFiles and stubs for version history
|
||||
const parentStub = selectors.getStirlingFileStub(activeFileIds[0]);
|
||||
if (!parentStub) throw new Error('Parent stub not found');
|
||||
|
||||
const { stirlingFiles, stubs } = await createStirlingFilesAndStubs(files, parentStub, 'multiTool');
|
||||
|
||||
// Step 4: Consume files (replace in context)
|
||||
await actions.consumeFiles(activeFileIds, stirlingFiles, stubs);
|
||||
// Step 3: Add merged output as new files while keeping originals
|
||||
const newStirlingFiles = await actions.addFiles(files, { selectFiles: true });
|
||||
if (newStirlingFiles.length > 0) {
|
||||
actions.setSelectedFiles(newStirlingFiles.map(file => file.fileId));
|
||||
}
|
||||
|
||||
setHasUnsavedChanges(false);
|
||||
setExportLoading(false);
|
||||
@@ -615,7 +905,7 @@ const PageEditor = ({
|
||||
console.error('Apply changes failed:', error);
|
||||
setExportLoading(false);
|
||||
}
|
||||
}, [displayDocument, mergedPdfDocument, splitPositions, activeFileIds, getSourceFiles, getExportFilename, actions, selectors, setHasUnsavedChanges]);
|
||||
}, [displayDocument, initialDocument, splitPositions, getSourceFiles, getExportFilename, actions, setHasUnsavedChanges]);
|
||||
|
||||
|
||||
const closePdf = useCallback(() => {
|
||||
@@ -638,6 +928,7 @@ const PageEditor = ({
|
||||
handleDeselectAll,
|
||||
handleDelete,
|
||||
onExportSelected,
|
||||
onSaveChanges: applyChanges,
|
||||
exportLoading,
|
||||
activeFileCount: activeFileIds.length,
|
||||
closePdf,
|
||||
@@ -692,14 +983,88 @@ const PageEditor = ({
|
||||
selectionMode, selectedPageIds, splitPositions, displayDocument?.pages.length, closePdf
|
||||
]);
|
||||
|
||||
// Handle scroll wheel zoom with accumulator for smooth trackpad pinch
|
||||
useEffect(() => {
|
||||
let accumulator = 0;
|
||||
|
||||
const handleWheel = (event: WheelEvent) => {
|
||||
// Check if Ctrl (Windows/Linux) or Cmd (Mac) is pressed
|
||||
if (event.ctrlKey || event.metaKey) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
accumulator += event.deltaY;
|
||||
const threshold = 10;
|
||||
|
||||
if (accumulator <= -threshold) {
|
||||
// Accumulated scroll up - zoom in
|
||||
zoomIn();
|
||||
accumulator = 0;
|
||||
} else if (accumulator >= threshold) {
|
||||
// Accumulated scroll down - zoom out
|
||||
zoomOut();
|
||||
accumulator = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const container = containerRef.current;
|
||||
if (container) {
|
||||
container.addEventListener('wheel', handleWheel, { passive: false });
|
||||
return () => {
|
||||
container.removeEventListener('wheel', handleWheel);
|
||||
};
|
||||
}
|
||||
}, [zoomIn, zoomOut]);
|
||||
|
||||
// Handle keyboard zoom shortcuts
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (!isContainerHovered) return;
|
||||
|
||||
// Check if Ctrl (Windows/Linux) or Cmd (Mac) is pressed
|
||||
if (event.ctrlKey || event.metaKey) {
|
||||
if (event.key === '=' || event.key === '+') {
|
||||
// Ctrl+= or Ctrl++ for zoom in
|
||||
event.preventDefault();
|
||||
zoomIn();
|
||||
} else if (event.key === '-' || event.key === '_') {
|
||||
// Ctrl+- for zoom out
|
||||
event.preventDefault();
|
||||
zoomOut();
|
||||
} else if (event.key === '0') {
|
||||
// Ctrl+0 for reset zoom
|
||||
event.preventDefault();
|
||||
setZoomLevel(1.0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [isContainerHovered, zoomIn, zoomOut]);
|
||||
|
||||
// Display all pages - use edited or original document
|
||||
const displayedPages = displayDocument?.pages || [];
|
||||
|
||||
return (
|
||||
<Box pos="relative" h='100%' style={{ overflow: 'auto' }} data-scrolling-container="true">
|
||||
<LoadingOverlay visible={globalProcessing && !mergedPdfDocument} />
|
||||
// Track color assignments by insertion order (files keep their color)
|
||||
const fileColorIndexMap = useFileColorMap(orderedFileIds);
|
||||
|
||||
{!mergedPdfDocument && !globalProcessing && activeFileIds.length === 0 && (
|
||||
return (
|
||||
<Box
|
||||
ref={containerRef}
|
||||
pos="relative"
|
||||
h='100%'
|
||||
style={{ overflow: 'auto' }}
|
||||
data-scrolling-container="true"
|
||||
onMouseEnter={() => setIsContainerHovered(true)}
|
||||
onMouseLeave={() => setIsContainerHovered(false)}
|
||||
>
|
||||
<LoadingOverlay visible={globalProcessing && !initialDocument} />
|
||||
|
||||
{!initialDocument && !globalProcessing && selectedFileIds.length === 0 && (
|
||||
<Center h='100%'>
|
||||
<Stack align="center" gap="md">
|
||||
<Text size="lg" c="dimmed">📄</Text>
|
||||
@@ -709,7 +1074,7 @@ const PageEditor = ({
|
||||
</Center>
|
||||
)}
|
||||
|
||||
{!mergedPdfDocument && globalProcessing && (
|
||||
{!initialDocument && globalProcessing && (
|
||||
<Box p={0}>
|
||||
<SkeletonLoader type="controls" />
|
||||
<SkeletonLoader type="pageGrid" count={8} />
|
||||
@@ -717,21 +1082,20 @@ const PageEditor = ({
|
||||
)}
|
||||
|
||||
{displayDocument && (
|
||||
<Box ref={gridContainerRef} p={0} pb="15rem" style={{ position: 'relative' }}>
|
||||
<Box ref={gridContainerRef} p={0} pt="2rem" pb="15rem" style={{ position: 'relative' }}>
|
||||
|
||||
|
||||
{/* Split Lines Overlay */}
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
pointerEvents: 'none',
|
||||
zIndex: 10
|
||||
}}
|
||||
>
|
||||
{/* Split Lines Overlay */}
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
pointerEvents: 'none',
|
||||
zIndex: 10
|
||||
}}
|
||||
>
|
||||
{(() => {
|
||||
// Calculate remToPx once outside the map to avoid layout thrashing
|
||||
const containerWidth = containerDimensions.width;
|
||||
@@ -757,7 +1121,7 @@ const PageEditor = ({
|
||||
const gridOffset = Math.max(0, (containerWidth - gridWidth) / 2);
|
||||
|
||||
const leftPosition = gridOffset + col * itemWithGap + ITEM_WIDTH + (ITEM_GAP / 2);
|
||||
const topPosition = row * ITEM_HEIGHT + (ITEM_HEIGHT * 0.05); // Center vertically (5% offset since page is 90% height)
|
||||
const topPosition = row * ITEM_HEIGHT + (ITEM_HEIGHT * 0.05) + ITEM_GAP; // Center vertically (5% offset since page is 90% height) + gap offset
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -779,40 +1143,56 @@ const PageEditor = ({
|
||||
{/* Pages Grid */}
|
||||
<DragDropGrid
|
||||
items={displayedPages}
|
||||
selectedItems={selectedPageIds}
|
||||
selectionMode={selectionMode}
|
||||
isAnimating={isAnimating}
|
||||
onReorderPages={handleReorderPages}
|
||||
renderItem={(page, index, refs) => (
|
||||
<PageThumbnail
|
||||
key={page.id}
|
||||
page={page}
|
||||
index={index}
|
||||
totalPages={displayDocument.pages.length}
|
||||
originalFile={(page as any).originalFileId ? selectors.getFile((page as any).originalFileId) : undefined}
|
||||
selectedPageIds={selectedPageIds}
|
||||
selectionMode={selectionMode}
|
||||
movingPage={movingPage}
|
||||
isAnimating={isAnimating}
|
||||
pageRefs={refs}
|
||||
onReorderPages={handleReorderPages}
|
||||
onTogglePage={togglePage}
|
||||
onAnimateReorder={animateReorder}
|
||||
onExecuteCommand={executeCommand}
|
||||
onSetStatus={() => {}}
|
||||
onSetMovingPage={setMovingPage}
|
||||
onDeletePage={handleDeletePage}
|
||||
createRotateCommand={createRotateCommand}
|
||||
createDeleteCommand={createDeleteCommand}
|
||||
createSplitCommand={createSplitCommand}
|
||||
pdfDocument={displayDocument}
|
||||
setPdfDocument={setEditedDocument}
|
||||
splitPositions={splitPositions}
|
||||
onInsertFiles={handleInsertFiles}
|
||||
/>
|
||||
)}
|
||||
zoomLevel={zoomLevel}
|
||||
getThumbnailData={(pageId) => {
|
||||
const page = displayDocument.pages.find(p => p.id === pageId);
|
||||
if (!page?.thumbnail) return null;
|
||||
return {
|
||||
src: page.thumbnail,
|
||||
rotation: page.rotation || 0
|
||||
};
|
||||
}}
|
||||
renderItem={(page, index, refs, boxSelectedIds, clearBoxSelection, _getBoxSelection, _activeId, activeDragIds, justMoved, _isOver, dragHandleProps, zoomLevel) => {
|
||||
const fileColorIndex = page.originalFileId ? fileColorIndexMap.get(page.originalFileId) ?? 0 : 0;
|
||||
const isBoxSelected = boxSelectedIds.includes(page.id);
|
||||
return (
|
||||
<PageThumbnail
|
||||
key={page.id}
|
||||
page={page}
|
||||
index={index}
|
||||
totalPages={displayDocument.pages.length}
|
||||
originalFile={(page as any).originalFileId ? selectors.getFile((page as any).originalFileId) : undefined}
|
||||
fileColorIndex={fileColorIndex}
|
||||
selectedPageIds={selectedPageIds}
|
||||
selectionMode={selectionMode}
|
||||
movingPage={movingPage}
|
||||
isAnimating={isAnimating}
|
||||
isBoxSelected={isBoxSelected}
|
||||
clearBoxSelection={clearBoxSelection}
|
||||
activeDragIds={activeDragIds}
|
||||
justMoved={justMoved}
|
||||
pageRefs={refs}
|
||||
dragHandleProps={dragHandleProps}
|
||||
onReorderPages={handleReorderPages}
|
||||
onTogglePage={togglePage}
|
||||
onAnimateReorder={animateReorder}
|
||||
onExecuteCommand={executeCommand}
|
||||
onSetStatus={() => {}}
|
||||
onSetMovingPage={setMovingPage}
|
||||
onDeletePage={handleDeletePage}
|
||||
createRotateCommand={createRotateCommand}
|
||||
createDeleteCommand={createDeleteCommand}
|
||||
createSplitCommand={createSplitCommand}
|
||||
pdfDocument={displayDocument}
|
||||
setPdfDocument={setEditedDocument}
|
||||
splitPositions={splitPositions}
|
||||
onInsertFiles={handleInsertFiles}
|
||||
zoomLevel={zoomLevel}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
</Box>
|
||||
)}
|
||||
|
||||
@@ -825,6 +1205,7 @@ const PageEditor = ({
|
||||
await onExportAll();
|
||||
}}
|
||||
/>
|
||||
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user