126 Commits

Author SHA1 Message Date
Sebastian 2e9a6a5857 chore(deps): update dependency phpunit/phpunit to v12.5.33
JS Unit Tests / test (pull_request) Successful in 1m1s
Build Test / test (pull_request) Successful in 1m10s
PHP Integration Tests / Integration Tests (pull_request) Failing after 1m27s
PHP Unit Tests / test (pull_request) Successful in 1m10s
2026-07-30 03:02:59 +00:00
Sebastian 4cd249d019 fix: attachment upload on send
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-29 21:24:05 -04:00
Sebastian 152a8141d0 fix: logging
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-29 21:20:05 -04:00
Sebastian 5aa95fa329 feat: sync sending identities
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-28 21:50:37 -04:00
Sebastian f0b0f87ce2 fix: primary address saving
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-28 21:02:51 -04:00
Sebastian 75a462ad18 fix: disable auto complete
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-28 20:52:53 -04:00
Sebastian 8af08d8936 refactor: migrate to scoped execution contexts
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-27 00:52:29 -04:00
Sebastian edc1aece13 Merge pull request 'fix(deps): update dependency pinia to v4' (#57) from renovate/pinia-4.x into main
Reviewed-on: #57
2026-07-24 14:02:16 +00:00
Sebastian b81070338d fix(deps): update dependency pinia to v4
Build Test / test (pull_request) Successful in 35s
JS Unit Tests / test (pull_request) Successful in 37s
PHP Integration Tests / Integration Tests (pull_request) Successful in 56s
PHP Unit Tests / test (pull_request) Successful in 1m9s
2026-07-24 13:58:43 +00:00
Sebastian ab24fe2b54 Merge pull request 'chore(deps): update dependency vue-router to v5.2.0' (#63) from renovate/vue-router-5.x-lockfile into main
Reviewed-on: #63
2026-07-24 13:56:34 +00:00
Sebastian 3073cf9f75 Merge pull request 'chore(deps): update dependency @vitejs/plugin-vue to v6.0.8' (#60) from renovate/vitejs-plugin-vue-6.x-lockfile into main
Reviewed-on: #60
2026-07-24 13:55:54 +00:00
Sebastian 8cf4993107 Merge pull request 'chore(deps): update dependency vue-tsc to v3.3.8' (#61) from renovate/vue-language-tools-monorepo into main
Reviewed-on: #61
2026-07-24 13:55:47 +00:00
Sebastian 5bda58fbb9 Merge pull request 'chore(deps): update dependency vuetify to v4.1.6' (#62) from renovate/vuetify-4.x-lockfile into main
Reviewed-on: #62
2026-07-24 13:55:32 +00:00
Sebastian b6bc83e432 chore(deps): update dependency vue-router to v5.2.0
Build Test / test (pull_request) Successful in 36s
JS Unit Tests / test (pull_request) Successful in 34s
PHP Integration Tests / Integration Tests (pull_request) Successful in 2m33s
PHP Unit Tests / test (pull_request) Successful in 2m18s
2026-07-24 13:51:41 +00:00
Sebastian 02f3662f40 chore(deps): update dependency vuetify to v4.1.6
Build Test / test (pull_request) Successful in 40s
JS Unit Tests / test (pull_request) Successful in 36s
PHP Unit Tests / test (pull_request) Successful in 1m40s
PHP Integration Tests / Integration Tests (pull_request) Successful in 1m50s
2026-07-24 13:51:36 +00:00
Sebastian 2dd56e0662 chore(deps): update dependency vue-tsc to v3.3.8
JS Unit Tests / test (pull_request) Successful in 1m17s
Build Test / test (pull_request) Successful in 1m20s
PHP Unit Tests / test (pull_request) Successful in 1m47s
PHP Integration Tests / Integration Tests (pull_request) Successful in 3m10s
2026-07-24 13:51:34 +00:00
Sebastian d449a71e80 chore(deps): update dependency @vitejs/plugin-vue to v6.0.8
JS Unit Tests / test (pull_request) Successful in 1m7s
Build Test / test (pull_request) Successful in 1m23s
PHP Unit Tests / test (pull_request) Successful in 2m23s
PHP Integration Tests / Integration Tests (pull_request) Successful in 4m5s
2026-07-24 13:51:31 +00:00
Sebastian 1310de8a15 Merge pull request 'chore(deps): update mongo docker tag to v8' (#59) from renovate/mongo-8.x into main
Reviewed-on: #59
2026-07-24 04:49:46 +00:00
Sebastian c7eb46c7ac chore(deps): update mongo docker tag to v8
Build Test / test (pull_request) Successful in 1m26s
JS Unit Tests / test (pull_request) Successful in 1m29s
PHP Unit Tests / test (pull_request) Successful in 2m13s
PHP Integration Tests / Integration Tests (pull_request) Successful in 2m22s
2026-07-24 04:38:37 +00:00
Sebastian c58d99988c Merge pull request 'chore: implement js test suites' (#58) from chore/js-test-suites into main
Reviewed-on: #58
2026-07-24 04:37:07 +00:00
Sebastian f5e7fa5f81 chore: implement js test suites
JS Unit Tests / test (pull_request) Successful in 40s
Build Test / test (pull_request) Successful in 42s
PHP Integration Tests / Integration Tests (pull_request) Successful in 1m20s
PHP Unit Tests / test (pull_request) Successful in 1m54s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-24 00:34:39 -04:00
Sebastian 9a243e2c61 Merge pull request 'chore(deps): update dependency vue-router to v5.2.0' (#54) from renovate/vue-router-5.x-lockfile into main
Reviewed-on: #54
2026-07-24 03:58:09 +00:00
Sebastian 4a8cea943b Merge pull request 'chore(deps): update dependency vue-tsc to v3.3.8' (#53) from renovate/vue-language-tools-monorepo into main
Reviewed-on: #53
2026-07-24 03:22:10 +00:00
Sebastian 8965c047d1 Merge pull request 'chore(deps): update dependency @vitejs/plugin-vue to v6.0.8' (#49) from renovate/vitejs-plugin-vue-6.x-lockfile into main
Reviewed-on: #49
2026-07-24 03:22:00 +00:00
Sebastian 7fa75dafc9 Merge pull request 'chore(deps): update dependency vuetify to v4.1.6' (#46) from renovate/vuetify-4.x-lockfile into main
Reviewed-on: #46
2026-07-24 03:21:51 +00:00
Sebastian 8eb245f52f Merge pull request 'chore(deps): update dependency vue to v3.5.40' (#50) from renovate/vue-monorepo into main
Reviewed-on: #50
2026-07-24 03:21:20 +00:00
Sebastian 3c4b864339 chore(deps): update dependency vue-router to v5.2.0
JS Unit Tests / test (pull_request) Successful in 45s
Build Test / test (pull_request) Failing after 50s
PHP Integration Tests / Integration Tests (pull_request) Successful in 1m37s
PHP Unit Tests / test (pull_request) Successful in 2m46s
2026-07-24 02:56:25 +00:00
Sebastian 64b933534b chore(deps): update dependency vuetify to v4.1.6
Build Test / test (pull_request) Failing after 31s
JS Unit Tests / test (pull_request) Successful in 34s
PHP Unit Tests / test (pull_request) Successful in 1m57s
PHP Integration Tests / Integration Tests (pull_request) Successful in 2m40s
2026-07-24 02:56:16 +00:00
Sebastian d3f383e937 chore(deps): update dependency vue-tsc to v3.3.8
Build Test / test (pull_request) Failing after 36s
JS Unit Tests / test (pull_request) Successful in 29s
PHP Integration Tests / Integration Tests (pull_request) Successful in 1m33s
PHP Unit Tests / test (pull_request) Successful in 2m52s
2026-07-24 02:56:11 +00:00
Sebastian 816c1cf931 chore(deps): update dependency vue to v3.5.40
Build Test / test (pull_request) Failing after 41s
JS Unit Tests / test (pull_request) Failing after 31s
PHP Integration Tests / Integration Tests (pull_request) Successful in 1m41s
PHP Unit Tests / test (pull_request) Successful in 1m36s
2026-07-24 02:56:08 +00:00
Sebastian 072ea8c450 chore(deps): update dependency @vitejs/plugin-vue to v6.0.8
Build Test / test (pull_request) Failing after 57s
JS Unit Tests / test (pull_request) Successful in 50s
PHP Unit Tests / test (pull_request) Successful in 2m25s
PHP Integration Tests / Integration Tests (pull_request) Successful in 2m53s
2026-07-24 02:56:01 +00:00
Sebastian 44c3b629a2 Merge pull request 'Chore/php83 test suites' (#52) from chore/php83-test-suites into main
Reviewed-on: #52
2026-07-24 02:43:18 +00:00
Sebastian aa0ac2da51 fix: install module dependencies before running integration tests
JS Unit Tests / test (pull_request) Successful in 40s
PHP Unit Tests / test (pull_request) Successful in 1m16s
PHP Integration Tests / Integration Tests (pull_request) Successful in 1m27s
Build Test / test (pull_request) Failing after 25s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-23 22:32:09 -04:00
Sebastian 4ef881e5c1 chore: implement php test suites
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-23 22:20:36 -04:00
Sebastian dc6d6081ee fix: returned identifier on create and modify
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-19 06:45:48 -04:00
Sebastian 1a5339f069 Merge pull request 'chore(deps): update dependency vue-tsc to v3.3.7' (#45) from renovate/vue-language-tools-monorepo into main
Reviewed-on: #45
2026-07-17 23:18:12 +00:00
Sebastian 9d95521247 Merge pull request 'chore(deps): update vitest monorepo to v4.1.10' (#47) from renovate/vitest-monorepo into main
Reviewed-on: #47
2026-07-17 23:17:58 +00:00
Sebastian cfb99dfc01 Merge pull request 'chore(deps): update dependency typescript to v7' (#48) from renovate/typescript-7.x into main
Reviewed-on: #48
2026-07-17 23:17:50 +00:00
Sebastian 609e7e577c Merge pull request 'chore(deps): update dependency vite to v8.1.5' (#44) from renovate/vite-8.x-lockfile into main
Reviewed-on: #44
2026-07-17 23:17:41 +00:00
Sebastian fa5e91f0a9 chore(deps): update dependency vite to v8.1.5
JS Unit Tests / test (pull_request) Failing after 13m2s
Build Test / test (pull_request) Failing after 13m4s
PHP Unit Tests / test (pull_request) Failing after 18m0s
2026-07-17 03:08:36 +00:00
Sebastian 024c9656d4 chore(deps): update dependency typescript to v7
PHP Unit Tests / test (pull_request) Failing after 14m47s
JS Unit Tests / test (pull_request) Failing after 15m6s
Build Test / test (pull_request) Failing after 15m8s
2026-07-10 03:08:12 +00:00
Sebastian b950022081 chore(deps): update vitest monorepo to v4.1.10
JS Unit Tests / test (pull_request) Failing after 11m9s
Build Test / test (pull_request) Failing after 11m33s
PHP Unit Tests / test (pull_request) Failing after 16m6s
2026-07-10 03:08:04 +00:00
Sebastian 2da8bebe61 chore(deps): update dependency vue-tsc to v3.3.7
PHP Unit Tests / test (pull_request) Failing after 12m26s
JS Unit Tests / test (pull_request) Failing after 12m36s
Build Test / test (pull_request) Failing after 12m38s
2026-07-10 03:07:55 +00:00
Sebastian 439eaabce3 fix(renovate): install renovate in runner temp
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-09 20:12:07 -04:00
Sebastian 16df84cb28 Merge pull request 'chore(deps): update dependency vite to v8.1.3' (#41) from renovate/vite-8.x-lockfile into main
Reviewed-on: #41
2026-07-09 23:46:45 +00:00
Sebastian e7ba07bf03 Merge pull request 'chore(deps): update dependency guzzlehttp/psr7 to v2.12.4' (#42) from renovate/guzzlehttp-psr7-2.x-lockfile into main
Reviewed-on: #42
2026-07-09 23:46:37 +00:00
Sebastian 69bbbb6c86 Merge pull request 'chore(deps): update dependency phpunit/phpunit to v11.5.56' (#43) from renovate/phpunit-phpunit-11.x-lockfile into main
Reviewed-on: #43
2026-07-09 23:46:29 +00:00
Sebastian fdfaf562a0 Merge pull request 'chore(deps): update dependency guzzlehttp/guzzle to v7.14.0' (#40) from renovate/guzzlehttp-guzzle-7.x-lockfile into main
Reviewed-on: #40
2026-07-09 23:46:21 +00:00
Sebastian 4cbde63865 refactor: use new documents interfaces
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-09 19:39:15 -04:00
Sebastian 808ed192af chore(deps): update dependency phpunit/phpunit to v11.5.56
PHP Unit Tests / test (pull_request) Failing after 14m5s
JS Unit Tests / test (pull_request) Failing after 14m7s
Build Test / test (pull_request) Failing after 14m23s
2026-07-09 03:05:09 +00:00
Sebastian 511a94a0fa chore(deps): update dependency guzzlehttp/psr7 to v2.12.4
PHP Unit Tests / test (pull_request) Failing after 14m30s
JS Unit Tests / test (pull_request) Failing after 14m34s
Build Test / test (pull_request) Failing after 14m47s
2026-07-09 03:05:05 +00:00
Sebastian 52fdb17b09 chore(deps): update dependency vite to v8.1.3
PHP Unit Tests / test (pull_request) Failing after 13m50s
JS Unit Tests / test (pull_request) Failing after 14m0s
Build Test / test (pull_request) Failing after 14m2s
2026-07-05 03:03:14 +00:00
Sebastian 9dc7a90f42 chore(deps): update dependency guzzlehttp/guzzle to v7.13.1
PHP Unit Tests / test (pull_request) Failing after 14m4s
JS Unit Tests / test (pull_request) Failing after 14m10s
Build Test / test (pull_request) Failing after 14m25s
renovate/artifacts Artifact file update failure
2026-07-05 03:03:08 +00:00
Sebastian 88fae64c86 fix: add guzzel dependency
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-06-29 15:35:19 -04:00
Sebastian 0d6bf36441 Merge pull request 'chore(deps): update dependency vue to v3.5.39' (#38) from renovate/vue-monorepo into main
Reviewed-on: #38
2026-06-28 14:40:42 +00:00
Sebastian 09622e08c3 Merge pull request 'chore(deps): update dependency vite to v8.1.0' (#39) from renovate/vite-8.x-lockfile into main
Reviewed-on: #39
2026-06-28 14:40:34 +00:00
Sebastian 8d2129f00c chore(deps): update dependency vite to v8.1.0
PHP Unit Tests / test (pull_request) Failing after 14m26s
JS Unit Tests / test (pull_request) Failing after 14m28s
Build Test / test (pull_request) Failing after 14m46s
2026-06-27 03:02:59 +00:00
Sebastian 7f5a0a3792 chore(deps): update dependency vue to v3.5.39
PHP Unit Tests / test (pull_request) Failing after 14m48s
JS Unit Tests / test (pull_request) Failing after 15m17s
Build Test / test (pull_request) Failing after 15m19s
2026-06-27 03:02:53 +00:00
Sebastian f904b36a53 fix: use seen insstead of read flag
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-06-25 23:40:26 -04:00
Sebastian 190f118589 Merge pull request 'chore(deps): update vitest monorepo to v4.1.9' (#37) from renovate/vitest-monorepo into main
Reviewed-on: #37
2026-06-24 15:23:27 +00:00
Sebastian b5e15bdefe chore(deps): update vitest monorepo to v4.1.9
PHP Unit Tests / test (pull_request) Failing after 11m45s
JS Unit Tests / test (pull_request) Failing after 11m53s
Build Test / test (pull_request) Failing after 11m55s
2026-06-22 03:05:08 +00:00
Sebastian 1896214026 Merge pull request 'chore(deps): update dependency vite to v8.0.16' (#35) from renovate/vite-8.x-lockfile into main
Reviewed-on: #35
2026-06-20 22:59:30 +00:00
Sebastian 77d145eede refactor: cosmetic
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-06-20 18:59:20 -04:00
Sebastian 17cc703c68 Merge pull request 'chore(deps): update dependency vuetify to v4.1.2' (#36) from renovate/vuetify-4.x-lockfile into main
Reviewed-on: #36
2026-06-20 22:58:37 +00:00
Sebastian 30782ba07f chore(deps): update dependency vuetify to v4.1.2
PHP Unit Tests / test (pull_request) Failing after 13m54s
JS Unit Tests / test (pull_request) Failing after 13m56s
Build Test / test (pull_request) Failing after 14m10s
2026-06-20 03:07:16 +00:00
Sebastian c92950dcc1 chore(deps): update dependency vite to v8.0.16
PHP Unit Tests / test (pull_request) Successful in 1m3s
JS Unit Tests / test (pull_request) Failing after 14m28s
Build Test / test (pull_request) Failing after 14m30s
2026-06-20 03:07:13 +00:00
Sebastian 089c5db4e2 Merge pull request 'chore(deps): update dependency vuetify to v4.1.1' (#32) from renovate/vuetify-4.x-lockfile into main
Reviewed-on: #32
2026-06-16 17:40:36 +00:00
Sebastian 8c767b3481 Merge pull request 'chore(deps): update dependency vue-router to v5.1.0' (#33) from renovate/vue-router-5.x-lockfile into main
Reviewed-on: #33
2026-06-16 17:40:26 +00:00
Sebastian 947a1ec246 Merge pull request 'chore(deps): update vue monorepo to v3.5.38' (#30) from renovate/vue-monorepo into main
Reviewed-on: #30
2026-06-16 17:40:15 +00:00
Sebastian 5c52ba177e Merge pull request 'chore(deps): update vue-language-tools monorepo to v3.3.5' (#31) from renovate/vue-language-tools-monorepo into main
Reviewed-on: #31
2026-06-16 17:38:17 +00:00
Sebastian 2f0e5d83b7 Merge pull request 'feat: message send' (#34) from feat/message-send into main
Reviewed-on: #34
2026-06-16 17:34:38 +00:00
Sebastian a6d1ba5f10 feat: message send
Build Test / test (pull_request) Successful in 37s
JS Unit Tests / test (pull_request) Successful in 36s
PHP Unit Tests / test (pull_request) Successful in 59s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-06-16 13:34:11 -04:00
Sebastian 17d3115374 chore(deps): update vue-language-tools monorepo to v3.3.5
Build Test / test (pull_request) Successful in 33s
JS Unit Tests / test (pull_request) Successful in 32s
PHP Unit Tests / test (pull_request) Successful in 1m7s
2026-06-14 03:03:36 +00:00
Sebastian 4a4406c1ed chore(deps): update vue monorepo to v3.5.38
Build Test / test (pull_request) Successful in 36s
JS Unit Tests / test (pull_request) Successful in 36s
PHP Unit Tests / test (pull_request) Successful in 1m6s
2026-06-13 03:03:35 +00:00
Sebastian 46b2e97d4b chore(deps): update dependency vuetify to v4.1.1
JS Unit Tests / test (pull_request) Successful in 39s
Build Test / test (pull_request) Successful in 43s
PHP Unit Tests / test (pull_request) Successful in 1m7s
2026-06-09 03:04:59 +00:00
Sebastian bcc277eec8 chore(deps): update dependency vue-router to v5.1.0
Build Test / test (pull_request) Successful in 45s
JS Unit Tests / test (pull_request) Successful in 44s
PHP Unit Tests / test (pull_request) Successful in 46s
2026-06-01 03:05:37 +00:00
Sebastian 55b9369710 Merge pull request 'chore: implement serice interface changes' (#29) from chore/implement-service-interface-changes into main
Renovate / renovate (push) Failing after 1m31s
Reviewed-on: #29
2026-05-29 03:27:35 +00:00
Sebastian aecbd1dc3c chore: implement serice interface changes
Build Test / test (pull_request) Successful in 41s
JS Unit Tests / test (pull_request) Successful in 39s
PHP Unit Tests / test (pull_request) Successful in 55s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-05-28 23:27:01 -04:00
Sebastian 284d7fee0e Merge pull request 'chore(deps): update dependency vite to v8.0.14' (#25) from renovate/vite-8.x-lockfile into main
Reviewed-on: #25
2026-05-29 03:13:22 +00:00
Sebastian 7b79535fd3 Merge pull request 'chore(deps): update dependency vue-tsc to v3.3.1' (#26) from renovate/vue-tsc-3.x-lockfile into main
Reviewed-on: #26
2026-05-29 03:13:12 +00:00
Sebastian 9ee1169d82 Merge pull request 'chore(deps): update vitest monorepo to v4.1.7' (#27) from renovate/vitest-monorepo into main
Reviewed-on: #27
2026-05-29 03:12:58 +00:00
Sebastian 28e8b886c8 chore(deps): update vitest monorepo to v4.1.7
Build Test / test (pull_request) Successful in 36s
JS Unit Tests / test (pull_request) Successful in 34s
PHP Unit Tests / test (pull_request) Successful in 1m10s
2026-05-23 03:01:57 +00:00
Sebastian 933d40e9dc chore(deps): update dependency vue-tsc to v3.3.1
Build Test / test (pull_request) Successful in 39s
JS Unit Tests / test (pull_request) Successful in 33s
PHP Unit Tests / test (pull_request) Successful in 57s
2026-05-22 03:03:42 +00:00
Sebastian 3309ca594b chore(deps): update dependency vite to v8.0.14
Build Test / test (pull_request) Successful in 42s
JS Unit Tests / test (pull_request) Successful in 42s
PHP Unit Tests / test (pull_request) Successful in 1m21s
2026-05-22 03:03:38 +00:00
Sebastian 5c1c7906a3 Merge pull request 'chore(deps): update vitest monorepo to v4.1.6' (#24) from renovate/vitest-monorepo into main
Renovate / renovate (push) Failing after 1h12m54s
Reviewed-on: #24
2026-05-21 03:42:19 +00:00
Sebastian 6df768c15f Merge pull request 'chore(deps): update dependency vue-tsc to v3.3.0' (#23) from renovate/vue-tsc-3.x-lockfile into main
Reviewed-on: #23
2026-05-21 03:40:40 +00:00
Sebastian 175672385e chore(deps): update vitest monorepo to v4.1.6
Build Test / test (pull_request) Successful in 32s
JS Unit Tests / test (pull_request) Successful in 32s
PHP Unit Tests / test (pull_request) Successful in 57s
2026-05-19 03:02:53 +00:00
Sebastian 06466ce8b8 chore(deps): update dependency vue-tsc to v3.3.0
Build Test / test (pull_request) Successful in 33s
JS Unit Tests / test (pull_request) Successful in 36s
PHP Unit Tests / test (pull_request) Successful in 1m9s
2026-05-19 03:02:43 +00:00
Sebastian d1d102e46b Merge pull request 'chore(deps): update dependency vue-tsc to v3.2.9' (#22) from renovate/vue-tsc-3.x-lockfile into main
Renovate / renovate (push) Failing after 1m43s
Reviewed-on: #22
2026-05-15 13:38:59 +00:00
Sebastian 25691f12aa chore(deps): update dependency vue-tsc to v3.2.9
Build Test / test (pull_request) Successful in 34s
JS Unit Tests / test (pull_request) Successful in 33s
PHP Unit Tests / test (pull_request) Successful in 1m5s
2026-05-15 13:38:39 +00:00
Sebastian 61c2cba9cc Merge pull request 'fix(deps): update dependency vue-router to v5' (#19) from renovate/vue-router-5.x into main
Reviewed-on: #19
2026-05-15 12:29:54 +00:00
Sebastian 5d9bdfac72 Merge pull request 'chore(deps): update dependency typescript to v6' (#16) from renovate/typescript-6.x into main
Reviewed-on: #16
2026-05-15 12:29:44 +00:00
Sebastian d5aeb05398 Merge pull request 'chore(deps): update dependency @vitejs/plugin-vue to v6.0.7' (#21) from renovate/vitejs-plugin-vue-6.x-lockfile into main
Reviewed-on: #21
2026-05-15 12:29:33 +00:00
Sebastian 216f0b5a2f fix(deps): update dependency vue-router to v5
Build Test / test (pull_request) Successful in 53s
JS Unit Tests / test (pull_request) Successful in 40s
PHP Unit Tests / test (pull_request) Successful in 1m17s
2026-05-15 12:29:17 +00:00
Sebastian 53a940b2e4 chore(deps): update dependency typescript to v6
JS Unit Tests / test (pull_request) Successful in 54s
Build Test / test (pull_request) Successful in 59s
PHP Unit Tests / test (pull_request) Successful in 1m29s
2026-05-15 12:29:13 +00:00
Sebastian 07799ff30f chore(deps): update dependency @vitejs/plugin-vue to v6.0.7
Build Test / test (pull_request) Successful in 35s
JS Unit Tests / test (pull_request) Successful in 43s
PHP Unit Tests / test (pull_request) Successful in 1m56s
2026-05-15 12:29:11 +00:00
Sebastian 7f097e14e2 Merge pull request 'chore(deps): update dependency phpunit/phpunit to v11.5.55' (#13) from renovate/phpunit-phpunit-11.x-lockfile into main
Reviewed-on: #13
2026-05-15 12:24:17 +00:00
Sebastian e1933b5a76 Merge pull request 'chore(deps): update dependency vite to v8' (#17) from renovate/vite-8.x into main
Reviewed-on: #17
2026-05-15 12:23:52 +00:00
Sebastian 2a780b5b30 chore(deps): update dependency vite to v8
Build Test / test (pull_request) Successful in 37s
JS Unit Tests / test (pull_request) Successful in 34s
PHP Unit Tests / test (pull_request) Successful in 1m14s
2026-05-15 12:23:38 +00:00
Sebastian 0d6cd59ad5 chore(deps): update dependency phpunit/phpunit to v11.5.55
Build Test / test (pull_request) Successful in 36s
JS Unit Tests / test (pull_request) Successful in 43s
PHP Unit Tests / test (pull_request) Successful in 2m7s
2026-05-15 12:23:31 +00:00
Sebastian b1f6dcc226 Merge pull request 'chore(deps): update dependency @vue/tsconfig to ^0.9.0' (#15) from renovate/vue-tsconfig-0.x into main
Reviewed-on: #15
2026-05-15 04:18:56 +00:00
Sebastian 4d6f57cc99 Merge pull request 'fix(deps): update dependency pinia to v3' (#18) from renovate/pinia-3.x into main
Reviewed-on: #18
2026-05-15 04:18:41 +00:00
Sebastian d097732646 Merge pull request 'fix(deps): update dependency vuetify to v4' (#20) from renovate/vuetify-4.x into main
Reviewed-on: #20
2026-05-15 04:18:28 +00:00
Sebastian 0f329e62ad fix(deps): update dependency vuetify to v4
Build Test / test (pull_request) Successful in 46s
JS Unit Tests / test (pull_request) Successful in 46s
PHP Unit Tests / test (pull_request) Successful in 1m53s
2026-05-15 04:01:29 +00:00
Sebastian c8852127c5 fix(deps): update dependency pinia to v3
JS Unit Tests / test (pull_request) Successful in 44s
Build Test / test (pull_request) Successful in 49s
PHP Unit Tests / test (pull_request) Successful in 1m56s
2026-05-15 04:01:20 +00:00
Sebastian 6cc73b477a chore(deps): update dependency @vue/tsconfig to ^0.9.0
Build Test / test (pull_request) Successful in 31s
JS Unit Tests / test (pull_request) Successful in 36s
PHP Unit Tests / test (pull_request) Successful in 1m13s
2026-05-15 04:01:06 +00:00
Sebastian 0c2cfe2f8b Merge pull request 'chore(deps): update dependency @vitejs/plugin-vue to v6.0.6' (#12) from renovate/vitejs-plugin-vue-6.x-lockfile into main
Reviewed-on: #12
2026-05-15 03:28:06 +00:00
Sebastian 8595d8bedd chore(deps): update dependency @vitejs/plugin-vue to v6.0.6
Build Test / test (pull_request) Successful in 38s
JS Unit Tests / test (pull_request) Successful in 38s
PHP Unit Tests / test (pull_request) Successful in 1m23s
2026-05-09 03:03:09 +00:00
Sebastian 591917778f Merge pull request 'chore: renovate' (#11) from chore/renovate into main
Renovate / renovate (push) Failing after 2m17s
Reviewed-on: #11
2026-05-07 02:20:21 +00:00
Sebastian 4eec1175a6 chore: renovate
Build Test / test (pull_request) Successful in 34s
JS Unit Tests / test (pull_request) Successful in 35s
PHP Unit Tests / test (pull_request) Successful in 1m17s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-05-06 22:09:25 -04:00
Sebastian d68015561f Merge pull request 'chore: improve delete' (#10) from chore/improve-delete into main
Renovate / renovate (push) Failing after 1m19s
Reviewed-on: #10
2026-04-26 01:53:46 +00:00
Sebastian 1220e9e8ab chore: improve delete
Build Test / test (pull_request) Successful in 27s
JS Unit Tests / test (pull_request) Successful in 26s
PHP Unit Tests / test (pull_request) Successful in 1m19s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-04-25 21:52:48 -04:00
Sebastian b1b3ee33cd Merge pull request 'feat: lots more improvements' (#9) from feat/lots-more-improvements into main
Reviewed-on: #9
2026-04-25 19:44:39 +00:00
Sebastian bc59fc5984 feat: lots more improvements
Build Test / test (pull_request) Successful in 33s
JS Unit Tests / test (pull_request) Successful in 31s
PHP Unit Tests / test (pull_request) Successful in 1m5s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-04-25 15:43:44 -04:00
Sebastian 1158426981 Merge pull request 'refactor: bunch of improvements' (#8) from refactor/bunch-of-improvements into main
Renovate / renovate (push) Failing after 1m17s
Reviewed-on: #8
2026-04-24 02:04:54 +00:00
Sebastian acc42d09ee refactor: bunch of improvements
Build Test / test (pull_request) Successful in 35s
JS Unit Tests / test (pull_request) Successful in 33s
PHP Unit Tests / test (pull_request) Successful in 1m5s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-04-23 22:04:36 -04:00
Sebastian d0e8406830 Merge pull request 'feat: entity move' (#7) from feat/entity-move into main
Renovate / renovate (push) Failing after 1m18s
Reviewed-on: #7
2026-03-28 16:37:34 +00:00
Sebastian 6486799e2c feat: entity move
Build Test / test (pull_request) Successful in 24s
JS Unit Tests / test (pull_request) Successful in 27s
PHP Unit Tests / test (pull_request) Successful in 52s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-03-28 12:37:01 -04:00
Sebastian afa6325e05 Merge pull request 'refactor: improvemets' (#6) from refactor/improvements into main
Renovate / renovate (push) Failing after 1m19s
Reviewed-on: #6
2026-03-24 23:14:37 +00:00
Sebastian 4730b75a05 refactor: improvemets
Build Test / test (pull_request) Successful in 1m44s
JS Unit Tests / test (pull_request) Successful in 1m45s
PHP Unit Tests / test (pull_request) Successful in 2m24s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-03-24 19:12:26 -04:00
Sebastian 3e899a50bd Merge pull request 'refactor: code cleanup' (#5) from refactor/code-cleanup into main
Renovate / renovate (push) Failing after 1m39s
Reviewed-on: #5
2026-03-07 03:57:30 +00:00
Sebastian 006c303917 refactor: code cleanup
JS Unit Tests / test (pull_request) Successful in 29s
Build Test / test (pull_request) Successful in 33s
PHP Unit Tests / test (pull_request) Successful in 54s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-03-06 22:51:32 -05:00
Sebastian 07fab0873d Merge pull request 'feat: entity streaming' (#4) from feat/entity-streaming into main
Renovate / renovate (push) Failing after 1m30s
Reviewed-on: #4
2026-03-03 01:42:45 +00:00
Sebastian 6bf3cb11e1 feat: entity streaming
Build Test / test (pull_request) Successful in 30s
JS Unit Tests / test (pull_request) Successful in 28s
PHP Unit Tests / test (pull_request) Successful in 1m8s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-02-20 16:27:31 -05:00
Sebastian faab22af67 Merge pull request 'chore: implement basic tests' (#3) from chore/implement-basic-tests into main
Renovate / renovate (push) Failing after 1m22s
Reviewed-on: #3
2026-02-16 03:08:28 +00:00
Sebastian 3374d3a287 chore: implement basic tests
Build Test / test (pull_request) Successful in 24s
JS Unit Tests / test (pull_request) Successful in 22s
PHP Unit Tests / test (pull_request) Successful in 1m2s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-02-15 22:06:37 -05:00
41 changed files with 6490 additions and 3360 deletions
+4 -5
View File
@@ -4,8 +4,7 @@ on:
pull_request: pull_request:
jobs: jobs:
test-single-module: test:
name: Single Module (No Dependencies)
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -17,7 +16,7 @@ jobs:
path: action-server-install path: action-server-install
github-server-url: https://git.ktrix.dev github-server-url: https://git.ktrix.dev
- name: Install Server Environment - name: Install Server
uses: ./action-server-install uses: ./action-server-install
with: with:
install-php: 'false' install-php: 'false'
@@ -26,7 +25,7 @@ jobs:
node-version: '24' node-version: '24'
server-path: './server' server-path: './server'
- name: Install Mail Manager Module - name: Install Mail Manager
uses: actions/checkout@v6.0.2 uses: actions/checkout@v6.0.2
with: with:
repository: Nodarx/mail_manager repository: Nodarx/mail_manager
@@ -34,7 +33,7 @@ jobs:
path: server/modules/mail_manager path: server/modules/mail_manager
github-server-url: https://git.ktrix.dev github-server-url: https://git.ktrix.dev
- name: Checkout PR Module - name: Checkout Pull Request
uses: actions/checkout@v6.0.2 uses: actions/checkout@v6.0.2
with: with:
repository: ${{ github.repository }} repository: ${{ github.repository }}
+4 -3
View File
@@ -6,6 +6,7 @@ on:
jobs: jobs:
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Retrieve Server Install Action - name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2 uses: actions/checkout@v6.0.2
@@ -15,7 +16,7 @@ jobs:
path: action-server-install path: action-server-install
github-server-url: https://git.ktrix.dev github-server-url: https://git.ktrix.dev
- name: Install Server Environment - name: Install Server
uses: ./action-server-install uses: ./action-server-install
with: with:
install-php: 'false' install-php: 'false'
@@ -24,7 +25,7 @@ jobs:
node-version: '24' node-version: '24'
server-path: './server' server-path: './server'
- name: Install Mail Manager Module - name: Install Mail Manager
uses: actions/checkout@v6.0.2 uses: actions/checkout@v6.0.2
with: with:
repository: Nodarx/mail_manager repository: Nodarx/mail_manager
@@ -32,7 +33,7 @@ jobs:
path: server/modules/mail_manager path: server/modules/mail_manager
github-server-url: https://git.ktrix.dev github-server-url: https://git.ktrix.dev
- name: Checkout PR Module - name: Checkout Pull Request
uses: actions/checkout@v6.0.2 uses: actions/checkout@v6.0.2
with: with:
repository: ${{ github.repository }} repository: ${{ github.repository }}
@@ -0,0 +1,59 @@
name: PHP Integration Tests
on:
pull_request:
workflow_dispatch:
jobs:
test:
name: Integration Tests
runs-on: ubuntu-latest
services:
mongo:
image: mongo:8
options: >-
--health-cmd "mongosh --quiet --eval \"db.adminCommand('ping')\""
--health-interval 5s
--health-timeout 5s
--health-retries 12
steps:
- name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2
with:
repository: Nodarx/action-server-install
ref: main
path: action-server-install
github-server-url: https://git.ktrix.dev
- name: Install server
uses: ./action-server-install
with:
install-php: 'true'
php-version: '8.5'
server-path: './server'
database-uri: 'mongodb://mongo:27017/?tls=false'
database-name: 'ktrix_ci'
app-environment: 'test'
- name: Checkout module under test
uses: actions/checkout@v6.0.2
with:
repository: ${{ github.repository }}
ref: ${{ github.event.pull_request.head.sha || github.sha }}
path: server/modules/provider_jmapc
github-server-url: https://git.ktrix.dev
- name: Install module dependencies
run: composer install --prefer-dist --no-progress
working-directory: server/modules/provider_jmapc
- name: Install and enable module
working-directory: server
run: |
php bin/console module:install provider_jmapc
php bin/console module:enable provider_jmapc
- name: Run integration tests
working-directory: server/modules/provider_jmapc
run: composer test:integration
+4 -3
View File
@@ -6,6 +6,7 @@ on:
jobs: jobs:
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Retrieve Server Install Action - name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2 uses: actions/checkout@v6.0.2
@@ -15,7 +16,7 @@ jobs:
path: action-server-install path: action-server-install
github-server-url: https://git.ktrix.dev github-server-url: https://git.ktrix.dev
- name: Install Server Environment - name: Install Server
uses: ./action-server-install uses: ./action-server-install
with: with:
install-php: 'true' install-php: 'true'
@@ -24,7 +25,7 @@ jobs:
node-version: '24' node-version: '24'
server-path: './server' server-path: './server'
- name: Install Mail Manager Module - name: Install Mail Manager
uses: actions/checkout@v6.0.2 uses: actions/checkout@v6.0.2
with: with:
repository: Nodarx/mail_manager repository: Nodarx/mail_manager
@@ -32,7 +33,7 @@ jobs:
path: server/modules/mail_manager path: server/modules/mail_manager
github-server-url: https://git.ktrix.dev github-server-url: https://git.ktrix.dev
- name: Checkout PR Module - name: Checkout Pull Request
uses: actions/checkout@v6.0.2 uses: actions/checkout@v6.0.2
with: with:
repository: ${{ github.repository }} repository: ${{ github.repository }}
+8 -2
View File
@@ -25,11 +25,17 @@ jobs:
tools: composer:v2 tools: composer:v2
- name: Install Renovate - name: Install Renovate
run: npm install -g renovate run: |
npm install --global --no-audit --fund=false \
--prefix "${{ runner.temp }}/renovate-npm" \
--cache "${{ runner.temp }}/renovate-npm-cache" \
renovate
"${{ runner.temp }}/renovate-npm/bin/renovate" --version
- name: Run Renovate - name: Run Renovate
env: env:
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }} RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
RENOVATE_PLATFORM: gitea RENOVATE_PLATFORM: gitea
RENOVATE_ENDPOINT: https://git.ktrix.dev/api/v1 RENOVATE_ENDPOINT: https://git.ktrix.dev/api/v1
run: renovate ${{ gitea.repository }} run: |
"${{ runner.temp }}/renovate-npm/bin/renovate" ${{ gitea.repository }}
+1 -5
View File
@@ -14,11 +14,7 @@ node_modules/
# Backend development # Backend development
/lib/vendor/ /lib/vendor/
coverage/ coverage/
phpunit.xml.cache *.cache
.phpunit.cache
.phpunit.result.cache
.php-cs-fixer.cache
.phpstan.cache
.phpactor/ .phpactor/
# Editors # Editors
+18 -15
View File
@@ -10,7 +10,7 @@
"config": { "config": {
"optimize-autoloader": true, "optimize-autoloader": true,
"platform": { "platform": {
"php": "8.2" "php": "8.3"
}, },
"autoloader-suffix": "ProviderJmapc", "autoloader-suffix": "ProviderJmapc",
"vendor-dir": "lib/vendor", "vendor-dir": "lib/vendor",
@@ -25,11 +25,13 @@
} }
], ],
"require": { "require": {
"php": ">=8.2 <=8.5", "guzzlehttp/guzzle": "^7.0",
"guzzlehttp/psr7": "^2.0",
"php": ">=8.3 <=8.5",
"sebastiankrupinski/jmap-client-php": "dev-main" "sebastiankrupinski/jmap-client-php": "dev-main"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^11.0" "phpunit/phpunit": "^12.0"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
@@ -37,16 +39,17 @@
} }
}, },
"autoload-dev": { "autoload-dev": {
"psr-4": { "psr-4": {
"KTXT\\ProviderJmapc\\": "tests/php/" "KTXT\\ProviderJmapc\\": "tests/php/"
} }
}, },
"scripts": { "scripts": {
"post-install-cmd": [ "post-install-cmd": [
], ],
"post-update-cmd": [ "post-update-cmd": [
], ],
"test:unit": "phpunit --configuration tests/php/phpunit.unit.xml --colors=always --testdox", "test:unit": "phpunit --configuration tests/php/phpunit.xml --testsuite \"Unit Tests\" --colors=always --testdox",
"test:coverage": "XDEBUG_MODE=coverage phpunit --configuration tests/php/phpunit.unit.xml --coverage-html .phpunit.coverage --coverage-text" "test:integration": "phpunit --configuration tests/php/phpunit.xml --testsuite \"Integration Tests\" --colors=always --testdox",
} "test:coverage": "XDEBUG_MODE=coverage phpunit --configuration tests/php/phpunit.xml --testsuite \"Unit Tests\" --coverage-html .phpunit.coverage --coverage-text"
}
} }
Generated
+487 -402
View File
File diff suppressed because it is too large Load Diff
+4 -2
View File
@@ -16,6 +16,7 @@ use KTXF\Resource\Provider\ProviderInterface;
use KTXM\ProviderJmapc\Providers\Mail\Provider as MailProvider; use KTXM\ProviderJmapc\Providers\Mail\Provider as MailProvider;
use KTXM\ProviderJmapc\Providers\Chrono\Provider as ChronoProvider; use KTXM\ProviderJmapc\Providers\Chrono\Provider as ChronoProvider;
use KTXM\ProviderJmapc\Providers\People\Provider as PeopleProvider; use KTXM\ProviderJmapc\Providers\People\Provider as PeopleProvider;
use KTXM\ProviderJmapc\Providers\Document\Provider as DocumentProvider;
/** /**
* JMAP Client Provider Module * JMAP Client Provider Module
@@ -68,8 +69,9 @@ class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
{ {
// Register JMAP providers - all three share the same service store // Register JMAP providers - all three share the same service store
$this->providerManager->register(ProviderInterface::TYPE_MAIL, 'jmap', MailProvider::class); $this->providerManager->register(ProviderInterface::TYPE_MAIL, 'jmap', MailProvider::class);
$this->providerManager->register(ProviderInterface::TYPE_CHRONO, 'jmap', ChronoProvider::class); //$this->providerManager->register(ProviderInterface::TYPE_CHRONO, 'jmap', ChronoProvider::class);
$this->providerManager->register(ProviderInterface::TYPE_PEOPLE, 'jmap', PeopleProvider::class); //$this->providerManager->register(ProviderInterface::TYPE_PEOPLE, 'jmap', PeopleProvider::class);
$this->providerManager->register(ProviderInterface::TYPE_DOCUMENT, 'jmap', DocumentProvider::class);
} }
public function registerBI(): array { public function registerBI(): array {
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderJmapc\Providers\Document;
use KTXF\Documents\Collection\CollectionPropertiesMutableAbstract;
/**
* Document Collection Properties Implementation
*/
class CollectionProperties extends CollectionPropertiesMutableAbstract {
/**
* Convert JMAP parameters array to document collection properties object
*
* @param array $parameters JMAP parameters array
*/
public function fromJmap(array $parameters): static {
if (isset($parameters['name'])) {
$this->data['label'] = $parameters['name'];
}
return $this;
}
/**
* Convert mail collection properties object to JMAP parameters array
*/
public function toJmap(): array {
$parameters = [];
if (isset($this->data['label'])) {
$parameters['name'] = $this->data['label'];
}
return $parameters;
}
}
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderJmapc\Providers\Document;
use KTXF\Documents\Collection\CollectionMutableAbstract;
/**
* Document Collection Resource Implementation
*/
class CollectionResource extends CollectionMutableAbstract {
public function __construct(
string $provider = 'jmapc',
string|int|null $service = null,
) {
parent::__construct($provider, $service);
}
/**
* Converts JMAP parameters array to document collection object
*
* @param array $parameters JMAP parameters array
*/
public function fromJmap(array $parameters): static {
if (isset($parameters['parentId'])) {
$this->data['collection'] = $parameters['parentId'];
}
if (isset($parameters['id'])) {
$this->data['identifier'] = $parameters['id'];
}
if (isset($parameters['created'])) {
$this->data['created'] = $parameters['created'];
}
if (isset($parameters['modified'])) {
$this->data['modified'] = $parameters['modified'];
}
if (isset($parameters['signature'])) {
$this->data['signature'] = $parameters['signature'];
}
$this->getProperties()->fromJmap($parameters);
return $this;
}
/**
* Convert document collection object to JMAP parameters array
*/
public function toJmap(): array {
$parameters = [];
if (isset($this->data['collection'])) {
$parameters['parentId'] = $this->data['collection'];
}
if (isset($this->data['identifier'])) {
$parameters['id'] = $this->data['identifier'];
}
$parameters = array_merge($parameters, $this->getProperties()->toJmap());
return $parameters;
}
/**
* @inheritDoc
*/
public function getProperties(): CollectionProperties {
if (!isset($this->properties)) {
$this->properties = new CollectionProperties([]);
}
return $this->properties;
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderJmapc\Providers\Document;
use KTXF\Documents\Entity\EntityPropertiesMutableAbstract;
/**
* Document Collection Properties Implementation
*/
class EntityProperties extends EntityPropertiesMutableAbstract {
/**
* Convert JMAP parameters array to document entity properties object
*
* @param array $parameters JMAP parameters array
*/
public function fromJmap(array $parameters): static {
if (isset($data['size'])) {
$this->data[self::PROPERTY_SIZE] = (int) $data['size'];
}
if (isset($data['label'])) {
$this->data[self::PROPERTY_LABEL] = (string) $data['name'];
}
if (isset($data['mime'])) {
$this->data[self::PROPERTY_MIME] = (string) $data['type'];
}
if (isset($data['format'])) {
$this->data[self::PROPERTY_FORMAT] = null;
}
if (isset($data['encoding'])) {
$this->data[self::PROPERTY_ENCODING] = null;
}
return $this;
}
/**
* Convert document entity properties object to JMAP parameters array
*/
public function toJmap(): array {
$parameters = array_filter([
'name' => $this->data[self::PROPERTY_LABEL],
'type' => $this->data[self::PROPERTY_MIME] ?? 'application/octet-stream'
], static fn($value) => $value !== null);
return $parameters;
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderJmapc\Providers\Document;
use KTXF\Documents\Entity\EntityMutableAbstract;
/**
* Mail Entity Resource Implementation
*/
class EntityResource extends EntityMutableAbstract {
public function __construct(
string $provider = 'jmapc',
string|int|null $service = null,
) {
parent::__construct($provider, $service);
}
/**
* Convert JMAP parameters array to mail entity object
*
* @param array $parameters JMAP parameters array
*/
public function fromJmap(array $parameters): static {
if (isset($parameters['parentId'])) {
$this->data['collection'] = $parameters['parentId'];
}
if (isset($parameters['id'])) {
$this->data['identifier'] = $parameters['id'];
}
if (isset($parameters['signature'])) {
$this->data['signature'] = $parameters['signature'];
}
if (isset($parameters['created'])) {
$this->data['created'] = $parameters['created'] ?? $parameters['created'];
}
if (isset($parameters['modified'])) {
$this->data['modified'] = $parameters['modified'];
}
if (isset($parameters['accessed']))
$this->getProperties()->fromJmap($parameters);
return $this;
}
/**
* Convert mail entity object to JMAP parameters array
*/
public function toJmap(): array {
$parameters = [];
if (isset($this->data['collection'])) {
$parameters['parentId'] = $this->data['collection'];
}
if (isset($this->data['identifier'])) {
$parameters['id'] = $this->data['identifier'];
}
$parameters = array_merge($parameters, $this->getProperties()->toJmap());
return $parameters;
}
/**
* @inheritDoc
*/
public function getProperties(): EntityProperties {
if (!isset($this->properties)) {
$this->properties = new EntityProperties([]);
}
return $this->properties;
}
}
+201
View File
@@ -0,0 +1,201 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderJmapc\Providers\Document;
use KTXF\Documents\Provider\ProviderBaseInterface;
use KTXF\Documents\Provider\ProviderServiceMutateInterface;
use KTXF\Documents\Provider\ProviderServiceTestInterface;
use KTXF\Documents\Service\ServiceBaseInterface;
use KTXF\Documents\Service\ServiceMutableInterface;
use KTXF\Resource\Provider\ResourceServiceLocationInterface;
use KTXF\Resource\Provider\ResourceServiceMutateInterface;
use KTXM\ProviderJmapc\Service\Discovery;
use KTXM\ProviderJmapc\Service\Remote\RemoteService;
use KTXM\ProviderJmapc\Stores\ServiceStore;
/**
* JMAP Documents Provider
*/
class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface, ProviderServiceTestInterface
{
public const JSON_TYPE = ProviderBaseInterface::JSON_TYPE;
protected const PROVIDER_IDENTIFIER = 'jmap';
protected const PROVIDER_LABEL = 'JMAP Documents Provider';
protected const PROVIDER_DESCRIPTION = 'Provides documents services via JMAP protocol (RFC 8620)';
protected const PROVIDER_ICON = 'mdi-file-sync';
protected array $providerAbilities = [
self::CAPABILITY_SERVICE_LIST => true,
self::CAPABILITY_SERVICE_FETCH => true,
self::CAPABILITY_SERVICE_EXTANT => true,
self::CAPABILITY_SERVICE_CREATE => true,
self::CAPABILITY_SERVICE_MODIFY => true,
self::CAPABILITY_SERVICE_DESTROY => true,
self::CAPABILITY_SERVICE_TEST => true,
];
public function __construct(
private readonly ServiceStore $serviceStore,
) {}
public function jsonSerialize(): array
{
return [
self::PROPERTY_TYPE => self::JSON_TYPE,
self::PROPERTY_IDENTIFIER => self::PROVIDER_IDENTIFIER,
self::PROPERTY_LABEL => self::PROVIDER_LABEL,
self::PROPERTY_CAPABILITIES => $this->providerAbilities,
];
}
public function jsonDeserialize(array|string $data): static
{
return $this;
}
public function type(): string
{
return self::TYPE_DOCUMENT;
}
public function identifier(): string
{
return self::PROVIDER_IDENTIFIER;
}
public function label(): string
{
return self::PROVIDER_LABEL;
}
public function description(): string
{
return self::PROVIDER_DESCRIPTION;
}
public function icon(): string
{
return self::PROVIDER_ICON;
}
public function capable(string $value): bool
{
return !empty($this->providerAbilities[$value]);
}
public function capabilities(): array
{
return $this->providerAbilities;
}
public function serviceList(string $tenantId, string $userId, array $filter = []): array
{
$list = $this->serviceStore->list($tenantId, $userId, $filter);
foreach ($list as $serviceData) {
$serviceInstance = $this->serviceFresh()->fromStore($serviceData);
$list[$serviceInstance->identifier()] = $serviceInstance;
}
return $list;
}
public function serviceFetch(string $tenantId, string $userId, string|int $identifier): ?Service
{
$serviceData = $this->serviceStore->fetch($tenantId, $userId, $identifier);
if ($serviceData === null) {
return null;
}
$serviceInstance = $this->serviceFresh()->fromStore($serviceData);
return $serviceInstance;
}
public function serviceExtant(string $tenantId, string $userId, string|int ...$identifiers): array
{
return $this->serviceStore->extant($tenantId, $userId, $identifiers);
}
public function serviceFresh(): ServiceMutableInterface
{
return new Service();
}
public function serviceCreate(string $tenantId, string $userId, ResourceServiceMutateInterface $service): string
{
if (!($service instanceof Service)) {
throw new \InvalidArgumentException('Service must be instance of JMAP Service');
}
$created = $this->serviceStore->create($tenantId, $userId, $service);
return (string) $created['id'];
}
public function serviceModify(string $tenantId, string $userId, ResourceServiceMutateInterface $service): string
{
if (!($service instanceof Service)) {
throw new \InvalidArgumentException('Service must be instance of JMAP Service');
}
$updated = $this->serviceStore->modify($tenantId, $userId, $service);
return (string) $updated['id'];
}
public function serviceDestroy(string $tenantId, string $userId, ResourceServiceMutateInterface $service): bool
{
if (!($service instanceof Service)) {
return false;
}
return $this->serviceStore->delete($tenantId, $userId, $service->identifier());
}
public function serviceDiscover(
string $tenantId,
string $userId,
string $identity,
?string $location = null,
?string $secret = null
): ResourceServiceLocationInterface|null {
$discovery = new Discovery();
// TODO: Make SSL verification configurable based on tenant/user settings
$verifySSL = true;
return $discovery->discover($identity, $location, $secret, $verifySSL);
}
public function serviceTest(ServiceBaseInterface|ServiceMutableInterface $service, array $options = []): array {
$startTime = microtime(true);
try {
if (!($service instanceof Service)) {
throw new \InvalidArgumentException('Service must be instance of JMAP Service');
}
$client = RemoteService::freshClient($service);
$session = $client->connect();
$latency = round((microtime(true) - $startTime) * 1000); // ms4
return [
'success' => true,
'message' => 'JMAP connection successful'
. ' (Account ID: ' . ($session->username() ?? 'N/A') . ')'
. ' (Latency: ' . $latency . ' ms)',
];
} catch (\Exception $e) {
$latency = round((microtime(true) - $startTime) * 1000);
return [
'success' => false,
'message' => 'Test failed: ' . $e->getMessage(),
];
}
}
}
+502
View File
@@ -0,0 +1,502 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderJmapc\Providers\Document;
use Generator;
use KTXF\Documents\Collection\CollectionBaseInterface;
use KTXF\Documents\Collection\CollectionMutableInterface;
use KTXF\Documents\Collection\CollectionPropertiesBaseInterface;
use KTXF\Documents\Service\ServiceBaseInterface;
use KTXF\Documents\Service\ServiceCollectionMutableInterface;
use KTXF\Documents\Service\ServiceConfigurableInterface;
use KTXF\Documents\Service\ServiceMutableInterface;
use KTXF\Resource\Delta\Delta;
use KTXF\Resource\Filter\Filter;
use KTXF\Resource\Filter\IFilter;
use KTXF\Resource\Identifier\CollectionIdentifierInterface;
use KTXF\Resource\Identifier\EntityIdentifierInterface;
use KTXF\Resource\Provider\ResourceServiceIdentityInterface;
use KTXF\Resource\Provider\ResourceServiceLocationInterface;
use KTXF\Resource\Range\IRange;
use KTXF\Resource\Range\Range;
use KTXF\Resource\Range\RangeType;
use KTXF\Resource\Sort\ISort;
use KTXF\Resource\Sort\Sort;
use KTXM\ProviderJmapc\Providers\ServiceIdentityBasic;
use KTXM\ProviderJmapc\Providers\ServiceLocation;
use KTXM\ProviderJmapc\Service\Remote\RemoteFilesService;
use KTXM\ProviderJmapc\Service\Remote\RemoteService;
class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceConfigurableInterface, ServiceCollectionMutableInterface
{
public const JSON_TYPE = ServiceBaseInterface::JSON_TYPE;
private const PROVIDER_IDENTIFIER = 'jmap';
private ?string $serviceTenantId = null;
private ?string $serviceUserId = null;
private ?string $serviceIdentifier = null;
private ?string $serviceLabel = null;
private bool $serviceEnabled = false;
private bool $serviceDebug = false;
private ?ServiceLocation $location = null;
private ?ServiceIdentityBasic $identity = null;
private array $auxiliary = [];
private array $serviceAbilities = [
self::CAPABILITY_COLLECTION_LIST => true,
self::CAPABILITY_COLLECTION_LIST_FILTER => [
self::CAPABILITY_COLLECTION_FILTER_LABEL => 's:100:256:256',
],
self::CAPABILITY_COLLECTION_LIST_SORT => [
self::CAPABILITY_COLLECTION_SORT_LABEL,
],
self::CAPABILITY_COLLECTION_EXTANT => true,
self::CAPABILITY_COLLECTION_FETCH => true,
self::CAPABILITY_COLLECTION_CREATE => true,
self::CAPABILITY_COLLECTION_UPDATE => true,
self::CAPABILITY_COLLECTION_DELETE => true,
self::CAPABILITY_ENTITY_LIST => true,
self::CAPABILITY_ENTITY_LIST_FILTER => [
self::CAPABILITY_ENTITY_FILTER_ALL => 's:200:256:256',
],
self::CAPABILITY_ENTITY_LIST_SORT => [
self::CAPABILITY_ENTITY_SORT_LABEL
],
self::CAPABILITY_ENTITY_LIST_RANGE => [
'tally' => ['absolute', 'relative']
],
self::CAPABILITY_ENTITY_DELTA => true,
self::CAPABILITY_ENTITY_EXTANT => true,
self::CAPABILITY_ENTITY_FETCH => true,
];
private readonly RemoteFilesService $remoteService;
public function __construct(
) {}
private function initialize(): void {
if (!isset($this->remoteService)) {
$client = RemoteService::freshClient($this);
$this->remoteService = RemoteService::documentsService($client);
}
}
public function toStore(): array {
return array_filter([
'tid' => $this->serviceTenantId,
'uid' => $this->serviceUserId,
'sid' => $this->serviceIdentifier,
'label' => $this->serviceLabel,
'enabled' => $this->serviceEnabled,
'debug' => $this->serviceDebug,
'location' => $this->location?->toStore(),
'identity' => $this->identity?->toStore(),
'auxiliary' => $this->auxiliary,
], fn($v) => $v !== null);
}
public function fromStore(array $data): static {
$this->serviceTenantId = $data['tid'] ?? null;
$this->serviceUserId = $data['uid'] ?? null;
$this->serviceIdentifier = $data['sid'];
$this->serviceLabel = $data['label'] ?? '';
$this->serviceEnabled = $data['enabled'] ?? false;
$this->serviceDebug = $data['debug'] ?? false;
if (isset($data['location'])) {
$this->location = (new ServiceLocation())->fromStore($data['location']);
}
if (isset($data['identity'])) {
$this->identity = (new ServiceIdentityBasic())->fromStore($data['identity']);
}
if (isset($data['auxiliary']) && is_array($data['auxiliary'])) {
$this->auxiliary = $data['auxiliary'];
}
return $this;
}
public function jsonSerialize(): array {
return array_filter([
self::PROPERTY_TYPE => self::JSON_TYPE,
self::PROPERTY_PROVIDER => self::PROVIDER_IDENTIFIER,
self::PROPERTY_IDENTIFIER => $this->serviceIdentifier,
self::PROPERTY_LABEL => $this->serviceLabel,
self::PROPERTY_ENABLED => $this->serviceEnabled,
self::PROPERTY_CAPABILITIES => $this->serviceAbilities,
self::PROPERTY_LOCATION => $this->location?->jsonSerialize(),
self::PROPERTY_IDENTITY => $this->identity?->jsonSerialize(),
self::PROPERTY_AUXILIARY => $this->auxiliary,
], fn($v) => $v !== null);
}
public function jsonDeserialize(array|string $data): static {
if (is_string($data)) {
$data = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
}
if (isset($data[self::PROPERTY_LABEL])) {
$this->setLabel($data[self::PROPERTY_LABEL]);
}
if (isset($data[self::PROPERTY_ENABLED])) {
$this->setEnabled($data[self::PROPERTY_ENABLED]);
}
if (isset($data[self::PROPERTY_LOCATION])) {
$this->setLocation($this->freshLocation(null, $data[self::PROPERTY_LOCATION]));
}
if (isset($data[self::PROPERTY_IDENTITY])) {
$this->setIdentity($this->freshIdentity(null, $data[self::PROPERTY_IDENTITY]));
}
if (isset($data[self::PROPERTY_AUXILIARY]) && is_array($data[self::PROPERTY_AUXILIARY])) {
$this->setAuxiliary($data[self::PROPERTY_AUXILIARY]);
}
return $this;
}
public function capable(string $value): bool
{
return isset($this->serviceAbilities[$value]);
}
public function capabilities(): array {
return $this->serviceAbilities;
}
public function provider(): string
{
return self::PROVIDER_IDENTIFIER;
}
public function identifier(): string|int
{
return $this->serviceIdentifier;
}
public function getLabel(): string|null
{
return $this->serviceLabel;
}
public function setLabel(string $label): static
{
$this->serviceLabel = $label;
return $this;
}
public function getEnabled(): bool
{
return $this->serviceEnabled;
}
public function setEnabled(bool $enabled): static
{
$this->serviceEnabled = $enabled;
return $this;
}
public function getLocation(): ServiceLocation
{
return $this->location;
}
public function setLocation(ResourceServiceLocationInterface $location): static
{
$this->location = $location;
return $this;
}
public function freshLocation(string|null $type = null, array $data = []): ServiceLocation
{
$location = new ServiceLocation();
$location->jsonDeserialize($data);
return $location;
}
public function getIdentity(): ServiceIdentityBasic
{
return $this->identity;
}
public function setIdentity(ResourceServiceIdentityInterface $identity): static
{
$this->identity = $identity;
return $this;
}
public function freshIdentity(string|null $type, array $data = []): ServiceIdentityBasic
{
$identity = new ServiceIdentityBasic();
$identity->jsonDeserialize($data);
return $identity;
}
public function getDebug(): bool
{
return $this->serviceDebug;
}
public function setDebug(bool $debug): static
{
$this->serviceDebug = $debug;
return $this;
}
public function getAuxiliary(): array
{
return $this->auxiliary;
}
public function setAuxiliary(array $auxiliary): static
{
$this->auxiliary = $auxiliary;
return $this;
}
// Collection operations
public function collectionList(string|int|null $location, ?IFilter $filter = null, ?ISort $sort = null): array
{
$this->initialize();
$collections = $this->remoteService->collectionList($location, $filter, $sort);
foreach ($collections as &$collection) {
if (is_array($collection) && isset($collection['id'])) {
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($collection);
$collection = $object;
}
}
return $collections;
}
public function collectionListFilter(): Filter
{
return new Filter($this->serviceAbilities[self::CAPABILITY_COLLECTION_LIST_FILTER] ?? []);
}
public function collectionListSort(): Sort
{
return new Sort($this->serviceAbilities[self::CAPABILITY_COLLECTION_LIST_SORT] ?? []);
}
public function collectionExtant(string|int|null $location, string|int ...$identifiers): array
{
$this->initialize();
return $this->remoteService->collectionExtant($location, ...$identifiers);
}
public function collectionFetch(string|int|null $identifier): ?CollectionBaseInterface
{
$this->initialize();
$collection = $this->remoteService->collectionFetch($identifier);
if (is_array($collection) && isset($collection['id'])) {
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($collection);
$collection = $object;
}
return $collection;
}
public function collectionFresh(): CollectionMutableInterface
{
return new CollectionResource(provider: $this->provider(), service: $this->identifier());
}
/**
* Convert incoming collection properties into a native CollectionResource
*/
private function collectionNative(CollectionPropertiesBaseInterface $properties, string|int|null $identifier = null): CollectionResource
{
if ($properties instanceof CollectionResource) {
return clone $properties;
}
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$object->jsonDeserialize(array_filter([
CollectionResource::PROPERTY_IDENTIFIER => $identifier,
CollectionResource::PROPERTY_PROPERTIES => $properties->jsonSerialize(),
], fn($v) => $v !== null));
return $object;
}
public function collectionCreate(CollectionIdentifierInterface|null $target, CollectionPropertiesBaseInterface $properties, array $options = []): CollectionBaseInterface
{
$this->initialize();
$collection = $this->collectionNative($properties);
$collection = $collection->toJmap();
$collection = $this->remoteService->collectionCreate($target?->collection(), $collection, $options);
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($collection);
return $object;
}
public function collectionUpdate(CollectionIdentifierInterface $target, CollectionPropertiesBaseInterface $properties): CollectionBaseInterface
{
$this->initialize();
$identifier = $target->collection();
$collection = $this->collectionNative($properties, $identifier);
$collection = $collection->toJmap();
$collection = $this->remoteService->collectionModify($identifier, $collection);
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($collection);
return $object;
}
public function collectionDelete(CollectionIdentifierInterface $target, bool $force = false): CollectionBaseInterface | true
{
$this->initialize();
if ($this->remoteService->collectionDestroy($target->collection(), $force, $force) === null) {
throw new \RuntimeException("Failed to delete collection: {$target->collection()}");
}
return true;
}
public function collectionMove(CollectionIdentifierInterface|null $target, CollectionIdentifierInterface $source): CollectionBaseInterface
{
// TODO: Implement collection move
$this->initialize();
$collection = new CollectionResource(provider: $this->provider(), service: $this->identifier());
return $collection;
}
public function collectionCopy(CollectionIdentifierInterface|null $target, CollectionIdentifierInterface $source): CollectionBaseInterface
{
// TODO: Implement collection copy
$this->initialize();
$collection = new CollectionResource(provider: $this->provider(), service: $this->identifier());
return $collection;
}
// Entity operations
public function entityListBulk(string|int|null $collection, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null, ?array $properties = null): array
{
$this->initialize();
$result = $this->remoteService->entityList($collection, $filter, $sort, $range, $properties);
$list = [];
foreach ($result['list'] as $index => $entry) {
if (is_array($entry) && isset($entry['id'])) {
$object = new EntityResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($entry);
$list[$object->identifier()] = $object;
}
unset($result['list'][$index]);
}
return $list;
}
public function entityListStream(string|int|null $collection, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null, ?array $properties = null): Generator
{
$this->initialize();
$result = $this->remoteService->entityList($collection, $filter, $sort, $range, $properties);
foreach ($result['list'] as $index => $entry) {
if (is_array($entry) && isset($entry['id'])) {
$object = new EntityResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($entry);
yield $object;
}
unset($result['list'][$index]);
}
}
public function entityListFilter(): Filter
{
return new Filter($this->serviceAbilities[self::CAPABILITY_ENTITY_LIST_FILTER] ?? []);
}
public function entityListSort(): Sort
{
return new Sort($this->serviceAbilities[self::CAPABILITY_ENTITY_LIST_SORT] ?? []);
}
public function entityListRange(RangeType $type): IRange
{
return new Range();
}
public function entityDelta(string|int|null $collection, string $signature): Delta
{
$this->initialize();
return $this->remoteService->entityDelta($collection, $signature, 'ids');
}
public function entityExtant(string|int|null $collection, string|int ...$identifiers): array
{
$this->initialize();
return $this->remoteService->entityExtant(...$identifiers);
}
public function entityFetchBulk(EntityIdentifierInterface ...$identifiers): array
{
$this->initialize();
$entityIds = array_map(fn($identifier) => $identifier->entity(), $identifiers);
$entities = $this->remoteService->entityFetch(...$entityIds);
$list = [];
foreach ($entities as $key => $entity) {
if (is_array($entity) && isset($entity['id'])) {
$object = new EntityResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($entity);
$list[$object->identifier()] = $object;
} else {
$list[$key] = $entity;
}
}
return $list;
}
public function entityFetchStream(EntityIdentifierInterface ...$identifiers): Generator
{
yield from $this->entityFetchBulk(...$identifiers);
}
public function entityRead(EntityIdentifierInterface $target): ?string
{
return null;
}
public function entityReadStream(EntityIdentifierInterface $target)
{
return null;
}
public function entityReadChunk(EntityIdentifierInterface $target, int $offset, int $length): ?string
{
return null;
}
}
-186
View File
@@ -1,186 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderJmapc\Providers\Mail;
/**
* Mail Attachment Object
*
* @since 30.0.0
*/
class MessageAttachment implements MessagePart {
protected MessagePart $_meta;
protected ?string $_contents = null;
public function __construct(?MessagePart $meta = null, ?string $contents = null) {
// determine if meta data exists
// if meta data is missing create new
if ($meta === null) {
$meta = new MessagePart();
$meta->setDisposition('attachment');
$meta->setType('application/octet-stream');
}
$this->setParameters($meta);
// determine if attachment contents exists
// if contents exists set the contents
if ($contents !== null) {
$this->setContents($contents);
}
}
/**
* sets the attachments parameters
*
* @since 1.0.0
*
* @param MessagePart|null $meta collection of all message parameters
*
* @return self return this object for command chaining
*/
public function setParameters(?MessagePart $meta): self {
// replace meta data store
$this->_meta = $meta;
// return this object for command chaining
return $this;
}
/**
* gets the attachments of this message
*
* @since 1.0.0
*
* @return array collection of all message parameters
*/
public function getParameters(): MessagePart {
// evaluate if data store field exists and return value(s) or null otherwise
return $this->_meta;
}
/**
* arbitrary unique text string identifying this message
*
* @since 1.0.0
*
* @return string id of this message
*/
public function id(): string {
// return id of message
return $this->_meta->getBlobId();
}
/**
* sets the attachment file name
*
* @since 30.0.0
*
* @param string $value file name (e.g example.txt)
*
* @return self return this object for command chaining
*/
public function setName(string $value): self {
$this->_meta->setName($value);
return $this;
}
/**
* gets the attachment file name
*
* @since 30.0.0
*
* @return string | null returns the attachment file name or null if not set
*/
public function getName(): ?string {
return $this->_meta->getName();
}
/**
* sets the attachment mime type
*
* @since 30.0.0
*
* @param string $value mime type (e.g. text/plain)
*
* @return self return this object for command chaining
*/
public function setType(string $value): self {
$this->_meta->setType($value);
return $this;
}
/**
* gets the attachment mime type
*
* @since 30.0.0
*
* @return string | null returns the attachment mime type or null if not set
*/
public function getType(): ?string {
return $this->_meta->getType();
}
/**
* sets the attachment contents (actual data)
*
* @since 30.0.0
*
* @param string $value binary contents of file
*
* @return self return this object for command chaining
*/
public function setContents(string $value): self {
$this->_contents = $value;
return $this;
}
/**
* gets the attachment contents (actual data)
*
* @since 30.0.0
*
* @return string | null returns the attachment contents or null if not set
*/
public function getContents(): ?string {
return $this->_contents;
}
/**
* sets the embedded status of the attachment
*
* @since 30.0.0
*
* @param bool $value true - embedded / false - not embedded
*
* @return self return this object for command chaining
*/
public function setEmbedded(bool $value): self {
if ($value) {
$this->_meta->setDisposition('inline');
} else {
$this->_meta->setDisposition('attachment');
}
return $this;
}
/**
* gets the embedded status of the attachment
*
* @since 30.0.0
*
* @return bool embedded status of the attachment
*/
public function getEmbedded(): bool {
if ($this->_meta->getDisposition() === 'inline') {
return true;
} else {
return false;
}
}
}
+224 -95
View File
@@ -16,6 +16,142 @@ use KTXF\Mail\Object\MessagePropertiesMutableAbstract;
*/ */
class MessageProperties extends MessagePropertiesMutableAbstract { class MessageProperties extends MessagePropertiesMutableAbstract {
private function buildJmapBodyStructure(array &$bodyValues): ?array {
$counter = 0;
$body = isset($this->data[static::PROPERTY_BODY]) && is_array($this->data[static::PROPERTY_BODY])
? $this->serializeBodyPartForJmap($this->data[static::PROPERTY_BODY], $bodyValues, $counter)
: null;
$attachments = [];
if (isset($this->data[static::PROPERTY_ATTACHMENTS]) && is_array($this->data[static::PROPERTY_ATTACHMENTS])) {
foreach ($this->data[static::PROPERTY_ATTACHMENTS] as $attachment) {
if (!is_array($attachment)) {
continue;
}
$serialized = $this->serializeBodyPartForJmap($attachment, $bodyValues, $counter);
if ($serialized !== null) {
$attachments[] = $serialized;
}
}
}
if ($body === null) {
if ($attachments === []) {
return null;
}
if (count($attachments) === 1) {
return $attachments[0];
}
return [
'type' => 'multipart/mixed',
'subParts' => $attachments,
];
}
if ($attachments === []) {
return $body;
}
return [
'type' => 'multipart/mixed',
'subParts' => array_merge([$body], $attachments),
];
}
private function serializeBodyPartForJmap(array $part, array &$bodyValues, int &$counter): ?array {
$type = isset($part['type']) && is_string($part['type']) && $part['type'] !== ''
? strtolower($part['type'])
: null;
if ($type === null) {
return null;
}
$isMultipart = str_starts_with($type, 'multipart/');
$serialized = [
'type' => $type,
];
if (isset($part['name']) && is_string($part['name']) && $part['name'] !== '') {
$serialized['name'] = $part['name'];
}
if (isset($part['disposition']) && is_string($part['disposition']) && $part['disposition'] !== '') {
$serialized['disposition'] = $part['disposition'];
}
if (isset($part['cid']) && is_string($part['cid']) && $part['cid'] !== '') {
$serialized['cid'] = $part['cid'];
}
if (isset($part['language']) && is_array($part['language']) && $part['language'] !== []) {
$serialized['language'] = $part['language'];
}
if (isset($part['location']) && is_string($part['location']) && $part['location'] !== '') {
$serialized['location'] = $part['location'];
}
if ($isMultipart) {
$subParts = [];
foreach ($part['subParts'] ?? [] as $subPart) {
if (!is_array($subPart)) {
continue;
}
$serializedSubPart = $this->serializeBodyPartForJmap($subPart, $bodyValues, $counter);
if ($serializedSubPart !== null) {
$subParts[] = $serializedSubPart;
}
}
if ($subParts !== []) {
$serialized['subParts'] = $subParts;
}
return $serialized;
}
$blobId = isset($part['blobId']) && is_string($part['blobId']) && $part['blobId'] !== ''
? $part['blobId']
: null;
$content = isset($part['content']) && is_string($part['content']) ? $part['content'] : null;
if ($blobId !== null) {
$serialized['blobId'] = $blobId;
if (isset($part['charset']) && is_string($part['charset']) && $part['charset'] !== '' && str_starts_with($type, 'text/')) {
$serialized['charset'] = $part['charset'];
}
if (isset($part['size']) && is_int($part['size'])) {
$serialized['size'] = $part['size'];
}
return $serialized;
}
if ($content !== null && str_starts_with($type, 'text/')) {
$partId = isset($part['partId']) && is_string($part['partId']) && $part['partId'] !== ''
? $part['partId']
: 'part-' . (++$counter);
$serialized['partId'] = $partId;
$bodyValues[$partId] = [
'value' => $content,
'isEncodingProblem' => false,
'isTruncated' => false,
];
return $serialized;
}
return $serialized;
}
/** /**
* Convert JMAP parameters array to mail message properties object * Convert JMAP parameters array to mail message properties object
* *
@@ -23,91 +159,91 @@ class MessageProperties extends MessagePropertiesMutableAbstract {
*/ */
public function fromJmap(array $parameters): static { public function fromJmap(array $parameters): static {
if (isset($parameters['messageId'])) {
$this->data['urid'] = $parameters['messageId'][0];
}
if (isset($parameters['size'])) { if (isset($parameters['size'])) {
$this->data['size'] = $parameters['size']; $this->data[static::PROPERTY_SIZE] = $parameters['size'];
} }
if (isset($parameters['headers']) && is_array($parameters['headers'])) {
$this->data[static::PROPERTY_HEADERS] = $parameters['headers'];
}
if (isset($parameters['messageId'])) {
$this->data[static::PROPERTY_URID] = $parameters['messageId'][0];
}
if (isset($parameters['receivedAt'])) { if (isset($parameters['receivedAt'])) {
$this->data['receivedDate'] = $parameters['receivedAt']; $this->data[static::PROPERTY_RECEIVED] = $parameters['receivedAt'];
} }
if (isset($parameters['sentAt'])) { if (isset($parameters['sentAt'])) {
$this->data['date'] = $parameters['sentAt']; $this->data[static::PROPERTY_SENT] = $parameters['sentAt'];
} }
if (isset($parameters['inReplyTo'])) { if (isset($parameters['inReplyTo'])) {
$this->data['inReplyTo'] = $parameters['inReplyTo']; $this->data[static::PROPERTY_IN_REPLY_TO] = $parameters['inReplyTo'];
} }
if (isset($parameters['references'])) { if (isset($parameters['references'])) {
$this->data['references'] = is_array($parameters['references']) ? $parameters['references'] : []; $this->data[static::PROPERTY_REFERENCES] = is_array($parameters['references']) ? $parameters['references'] : [];
}
if (isset($parameters['subject'])) {
$this->data['subject'] = $parameters['subject'];
}
if (isset($parameters['preview'])) {
$this->data['snippet'] = $parameters['preview'];
} }
if (isset($parameters['sender'])) { if (isset($parameters['sender'])) {
$this->data['sender'] = $parameters['sender']; $this->data[static::PROPERTY_SENDER] = $parameters['sender'];
} }
if (isset($parameters['from']) && is_array($parameters['from']) && !empty($parameters['from'])) { if (isset($parameters['from']) && is_array($parameters['from']) && !empty($parameters['from'])) {
$this->data['from'] = [ $this->data[static::PROPERTY_FROM] = [
'address' => $parameters['from'][0]['email'] ?? '', 'address' => $parameters['from'][0]['email'] ?? '',
'label' => $parameters['from'][0]['name'] ?? null 'label' => $parameters['from'][0]['name'] ?? null
]; ];
} }
if (isset($parameters['to']) && is_array($parameters['to'])) {
$this->data['to'] = [];
foreach ($parameters['to'] as $addr) {
$this->data['to'][] = [
'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null
];
}
}
if (isset($parameters['cc']) && is_array($parameters['cc'])) {
$this->data['cc'] = [];
foreach ($parameters['cc'] as $addr) {
$this->data['cc'][] = [
'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null
];
}
}
if (isset($parameters['bcc']) && is_array($parameters['bcc'])) {
$this->data['bcc'] = [];
foreach ($parameters['bcc'] as $addr) {
$this->data['bcc'][] = [
'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null
];
}
}
if (isset($parameters['replyTo']) && is_array($parameters['replyTo'])) { if (isset($parameters['replyTo']) && is_array($parameters['replyTo'])) {
$this->data['replyTo'] = []; $this->data[static::PROPERTY_REPLY_TO] = [];
foreach ($parameters['replyTo'] as $addr) { foreach ($parameters['replyTo'] as $addr) {
$this->data['replyTo'][] = [ $this->data[static::PROPERTY_REPLY_TO][] = [
'address' => $addr['email'] ?? '', 'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null 'label' => $addr['name'] ?? null
]; ];
} }
} }
if (isset($parameters['keywords']) && is_array($parameters['keywords'])) {
$this->data['flags'] = []; if (isset($parameters['to']) && is_array($parameters['to'])) {
foreach ($parameters['keywords'] as $keyword => $value) { $this->data[static::PROPERTY_TO] = [];
$flag = match($keyword) { foreach ($parameters['to'] as $addr) {
'$seen' => 'read', $this->data[static::PROPERTY_TO][] = [
'$flagged' => 'flagged', 'address' => $addr['email'] ?? '',
'$answered' => 'answered', 'label' => $addr['name'] ?? null
'$draft' => 'draft', ];
'$deleted' => 'deleted',
default => $keyword
};
$this->data['flags'][$flag] = $value;
} }
} }
if (isset($parameters['cc']) && is_array($parameters['cc'])) {
$this->data[static::PROPERTY_CC] = [];
foreach ($parameters['cc'] as $addr) {
$this->data[static::PROPERTY_CC][] = [
'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null
];
}
}
if (isset($parameters['bcc']) && is_array($parameters['bcc'])) {
$this->data[static::PROPERTY_BCC] = [];
foreach ($parameters['bcc'] as $addr) {
$this->data[static::PROPERTY_BCC][] = [
'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null
];
}
}
if (isset($parameters['subject'])) {
$this->data[static::PROPERTY_SUBJECT] = $parameters['subject'];
}
if (isset($parameters['bodyStructure'])) { if (isset($parameters['bodyStructure'])) {
$this->data['body'] = $parameters['bodyStructure']; $this->data[static::PROPERTY_BODY] = $parameters['bodyStructure'];
// Recursively add content from bodyValues to matching parts // Recursively add content from bodyValues to matching parts
if (isset($parameters['bodyValues']) && is_array($parameters['bodyValues'])) { if (isset($parameters['bodyValues']) && is_array($parameters['bodyValues'])) {
$addContentToParts = function(&$structure, $bodyValues) use (&$addContentToParts) { $addContentToParts = function(&$structure, $bodyValues) use (&$addContentToParts) {
@@ -123,14 +259,27 @@ class MessageProperties extends MessagePropertiesMutableAbstract {
} }
}; };
$addContentToParts($this->data['body'], $parameters['bodyValues']); $addContentToParts($this->data[static::PROPERTY_BODY], $parameters['bodyValues']);
} }
} }
if (isset($parameters['headers']) && is_array($parameters['headers'])) {
$this->data['headers'] = $parameters['headers'];
}
if (isset($parameters['attachments'])) { if (isset($parameters['attachments'])) {
$this->data['attachments'] = $parameters['attachments']; $this->data[static::PROPERTY_ATTACHMENTS] = $parameters['attachments'];
}
if (isset($parameters['keywords']) && is_array($parameters['keywords'])) {
$this->data[static::PROPERTY_FLAGS] = [];
foreach ($parameters['keywords'] as $keyword => $value) {
$flag = match($keyword) {
'$seen' => 'seen',
'$flagged' => 'flagged',
'$answered' => 'answered',
'$draft' => 'draft',
'$deleted' => 'deleted',
default => $keyword
};
$this->data[static::PROPERTY_FLAGS][$flag] = $value;
}
} }
return $this; return $this;
@@ -149,11 +298,11 @@ class MessageProperties extends MessagePropertiesMutableAbstract {
if (isset($this->data['size'])) { if (isset($this->data['size'])) {
$parameters['size'] = $this->data['size']; $parameters['size'] = $this->data['size'];
} }
if (isset($this->data['receivedDate'])) { if (isset($this->data['received'])) {
$parameters['receivedAt'] = $this->data['receivedDate']; $parameters['receivedAt'] = $this->data['received'];
} }
if (isset($this->data['date'])) { if (isset($this->data['sent'])) {
$parameters['sentAt'] = $this->data['date']; $parameters['sentAt'] = $this->data['sent'];
} }
if (isset($this->data['inReplyTo'])) { if (isset($this->data['inReplyTo'])) {
$parameters['inReplyTo'] = $this->data['inReplyTo']; $parameters['inReplyTo'] = $this->data['inReplyTo'];
@@ -216,7 +365,7 @@ class MessageProperties extends MessagePropertiesMutableAbstract {
$parameters['keywords'] = []; $parameters['keywords'] = [];
foreach ($this->data['flags'] as $flag => $value) { foreach ($this->data['flags'] as $flag => $value) {
$keyword = match($flag) { $keyword = match($flag) {
'read' => '$seen', 'seen' => '$seen',
'flagged' => '$flagged', 'flagged' => '$flagged',
'answered' => '$answered', 'answered' => '$answered',
'draft' => '$draft', 'draft' => '$draft',
@@ -226,37 +375,17 @@ class MessageProperties extends MessagePropertiesMutableAbstract {
$parameters['keywords'][$keyword] = $value; $parameters['keywords'][$keyword] = $value;
} }
} }
if (isset($this->data['bodyStructure'])) {
$parameters['bodyStructure'] = $this->data['bodyStructure']; $bodyValues = [];
} $bodyStructure = $this->buildJmapBodyStructure($bodyValues);
if (isset($this->data['body'])) { if ($bodyStructure !== null) {
$parameters['bodyValues'] = []; $parameters['bodyStructure'] = $bodyStructure;
$parameters['bodyValues'] = $bodyValues;
if (isset($this->data['body']['text']['content'])) {
$parameters['bodyValues']['0'] = [
'value' => $this->data['body']['text']['content'],
'isEncodingProblem' => false,
'isTruncated' => false
];
}
if (isset($this->data['body']['html']['content'])) {
$parameters['bodyValues']['1'] = [
'value' => $this->data['body']['html']['content'],
'isEncodingProblem' => false,
'isTruncated' => false
];
}
} }
if (isset($this->data['headers'])) { if (isset($this->data['headers'])) {
$parameters['headers'] = $this->data['headers']; $parameters['headers'] = $this->data['headers'];
} }
if (isset($this->data['attachments'])) {
$parameters['attachments'] = $this->data['attachments'];
$parameters['hasAttachment'] = !empty($this->data['attachments']);
} else {
$parameters['hasAttachment'] = false;
}
return $parameters; return $parameters;
} }
+86 -31
View File
@@ -9,27 +9,22 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Providers\Mail; namespace KTXM\ProviderJmapc\Providers\Mail;
use KTXF\Mail\Object\Address;
use KTXF\Mail\Provider\ProviderBaseInterface; use KTXF\Mail\Provider\ProviderBaseInterface;
use KTXF\Mail\Provider\ProviderServiceDiscoverInterface; use KTXF\Mail\Provider\ProviderServiceDiscoverInterface;
use KTXF\Mail\Provider\ProviderServiceMutateInterface; use KTXF\Mail\Provider\ProviderServiceMutateInterface;
use KTXF\Mail\Provider\ProviderServiceTestInterface; use KTXF\Mail\Provider\ProviderServiceTestInterface;
use KTXF\Mail\Service\ServiceBaseInterface; use KTXF\Mail\Service\ServiceBaseInterface;
use KTXF\Mail\Service\ServiceMutableInterface;
use KTXF\Resource\Provider\ResourceServiceLocationInterface; use KTXF\Resource\Provider\ResourceServiceLocationInterface;
use KTXF\Resource\Provider\ResourceServiceMutateInterface; use KTXF\Resource\Provider\ResourceServiceMutateInterface;
use KTXM\ProviderJmapc\Service\Discovery; use KTXM\ProviderJmapc\Service\Discovery;
use KTXM\ProviderJmapc\Service\Remote\RemoteService; use KTXM\ProviderJmapc\Service\Remote\RemoteService;
use KTXM\ProviderJmapc\Stores\ServiceStore; use KTXM\ProviderJmapc\Stores\ServiceStore;
/** class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface, ProviderServiceDiscoverInterface, ProviderServiceTestInterface
* JMAP Mail Provider
*
* Provides Mail services via JMAP protocol.
* Filters services by urn:ietf:params:jmap:mail capability.
*/
class Provider implements ProviderServiceMutateInterface, ProviderServiceDiscoverInterface, ProviderServiceTestInterface
{ {
public const JSON_TYPE = ProviderBaseInterface::JSON_TYPE;
protected const PROVIDER_IDENTIFIER = 'jmap'; protected const PROVIDER_IDENTIFIER = 'jmap';
protected const PROVIDER_LABEL = 'JMAP Mail Provider'; protected const PROVIDER_LABEL = 'JMAP Mail Provider';
protected const PROVIDER_DESCRIPTION = 'Provides mail services via JMAP protocol (RFC 8620)'; protected const PROVIDER_DESCRIPTION = 'Provides mail services via JMAP protocol (RFC 8620)';
@@ -52,10 +47,10 @@ class Provider implements ProviderServiceMutateInterface, ProviderServiceDiscove
public function jsonSerialize(): array public function jsonSerialize(): array
{ {
return [ return [
self::JSON_PROPERTY_TYPE => self::JSON_TYPE, self::PROPERTY_TYPE => self::JSON_TYPE,
self::JSON_PROPERTY_IDENTIFIER => self::PROVIDER_IDENTIFIER, self::PROPERTY_IDENTIFIER => self::PROVIDER_IDENTIFIER,
self::JSON_PROPERTY_LABEL => self::PROVIDER_LABEL, self::PROPERTY_LABEL => self::PROVIDER_LABEL,
self::JSON_PROPERTY_CAPABILITIES => $this->providerAbilities, self::PROPERTY_CAPABILITIES => $this->providerAbilities,
]; ];
} }
@@ -102,22 +97,21 @@ class Provider implements ProviderServiceMutateInterface, ProviderServiceDiscove
public function serviceList(string $tenantId, string $userId, array $filter = []): array public function serviceList(string $tenantId, string $userId, array $filter = []): array
{ {
$list = $this->serviceStore->list($tenantId, $userId, $filter); $list = $this->serviceStore->list($tenantId, $userId, $filter);
foreach ($list as $entry) { foreach ($list as $serviceData) {
$service = new Service(); $serviceInstance = $this->serviceFresh()->fromStore($serviceData);
$service->fromStore($entry); $list[$serviceInstance->identifier()] = $serviceInstance;
$list[$service->identifier()] = $service;
} }
return $list; return $list;
} }
public function serviceExtant(string $tenantId, string $userId, string|int ...$identifiers): array
{
return $this->serviceStore->extant($tenantId, $userId, $identifiers);
}
public function serviceFetch(string $tenantId, string $userId, string|int $identifier): ?Service public function serviceFetch(string $tenantId, string $userId, string|int $identifier): ?Service
{ {
return $this->serviceStore->fetch($tenantId, $userId, $identifier); $serviceData = $this->serviceStore->fetch($tenantId, $userId, $identifier);
if ($serviceData === null) {
return null;
}
$serviceInstance = $this->serviceFresh()->fromStore($serviceData);
return $serviceInstance;
} }
public function serviceFindByAddress(string $tenantId, string $userId, string $address): ?Service public function serviceFindByAddress(string $tenantId, string $userId, string $address): ?Service
@@ -132,7 +126,12 @@ class Provider implements ProviderServiceMutateInterface, ProviderServiceDiscove
return null; return null;
} }
public function serviceFresh(): ResourceServiceMutateInterface public function serviceExtant(string $tenantId, string $userId, string|int ...$identifiers): array
{
return $this->serviceStore->extant($tenantId, $userId, $identifiers);
}
public function serviceFresh(): Service
{ {
return new Service(); return new Service();
} }
@@ -144,7 +143,64 @@ class Provider implements ProviderServiceMutateInterface, ProviderServiceDiscove
} }
$created = $this->serviceStore->create($tenantId, $userId, $service); $created = $this->serviceStore->create($tenantId, $userId, $service);
return (string) $created->identifier(); $this->serviceIdentitiesSync($tenantId, $userId, (new Service())->fromStore($created));
return (string) $created['sid'];
}
/**
* Fetches sending identities from the JMAP server and overwrites
* primaryAddress/secondaryAddresses on the service with them.
*/
private function serviceIdentitiesSync(string $tenantId, string $userId, Service $service): void
{
try {
$client = RemoteService::freshClient($service);
$identities = RemoteService::mailService($client)->identityFetch();
// A JMAP server may expose multiple identities sharing the same
// address (e.g. distinct signatures/display names for one
// mailbox) — collapse those down to one entry per address,
// keeping the first label seen.
$addresses = [];
foreach ($identities as $identity) {
if ($identity->address() === null) {
continue;
}
$key = strtolower($identity->address());
if (!isset($addresses[$key])) {
$addresses[$key] = Address::fromArray(['address' => $identity->address(), 'label' => $identity->name()]);
}
}
$addresses = array_values($addresses);
if (empty($addresses)) {
return;
}
$currentAddress = strtolower($service->getPrimaryAddress()->getAddress());
$primaryIndex = 0;
foreach ($addresses as $index => $address) {
if (strtolower($address->getAddress()) === $currentAddress) {
$primaryIndex = $index;
break;
}
}
$secondary = [];
foreach ($addresses as $index => $address) {
if ($index !== $primaryIndex) {
$secondary[] = $address;
}
}
$service->setPrimaryAddress($addresses[$primaryIndex]);
$service->setSecondaryAddresses($secondary);
$this->serviceStore->modify($tenantId, $userId, $service);
} catch (\Throwable) {
// Server may not support urn:ietf:params:jmap:submission, or have
// no identities configured — fall back to what the user entered.
}
} }
public function serviceModify(string $tenantId, string $userId, ResourceServiceMutateInterface $service): string public function serviceModify(string $tenantId, string $userId, ResourceServiceMutateInterface $service): string
@@ -153,8 +209,9 @@ class Provider implements ProviderServiceMutateInterface, ProviderServiceDiscove
throw new \InvalidArgumentException('Service must be instance of JMAP Service'); throw new \InvalidArgumentException('Service must be instance of JMAP Service');
} }
$updated = $this->serviceStore->modify($tenantId, $userId, $service); $this->serviceStore->modify($tenantId, $userId, $service);
return (string) $updated->identifier(); $this->serviceIdentitiesSync($tenantId, $userId, $service);
return (string) $service->identifier();
} }
public function serviceDestroy(string $tenantId, string $userId, ResourceServiceMutateInterface $service): bool public function serviceDestroy(string $tenantId, string $userId, ResourceServiceMutateInterface $service): bool
@@ -174,14 +231,13 @@ class Provider implements ProviderServiceMutateInterface, ProviderServiceDiscove
?string $secret = null ?string $secret = null
): ResourceServiceLocationInterface|null { ): ResourceServiceLocationInterface|null {
$discovery = new Discovery(); $discovery = new Discovery();
// TODO: Make SSL verification configurable based on tenant/user settings
$verifySSL = true; $verifySSL = true;
return $discovery->discover($identity, $location, $secret, $verifySSL); return $discovery->discover($identity, $location, $secret, $verifySSL);
} }
public function serviceTest(ServiceBaseInterface $service, array $options = []): array { public function serviceTest(ServiceBaseInterface|ServiceMutableInterface $service, array $options = []): array
{
$startTime = microtime(true); $startTime = microtime(true);
try { try {
@@ -200,8 +256,7 @@ class Provider implements ProviderServiceMutateInterface, ProviderServiceDiscove
. ' (Account ID: ' . ($session->username() ?? 'N/A') . ')' . ' (Account ID: ' . ($session->username() ?? 'N/A') . ')'
. ' (Latency: ' . $latency . ' ms)', . ' (Latency: ' . $latency . ' ms)',
]; ];
} catch (\Exception $e) { } catch (\Throwable $e) {
$latency = round((microtime(true) - $startTime) * 1000);
return [ return [
'success' => false, 'success' => false,
'message' => 'Test failed: ' . $e->getMessage(), 'message' => 'Test failed: ' . $e->getMessage(),
+629 -119
View File
@@ -9,19 +9,29 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Providers\Mail; namespace KTXM\ProviderJmapc\Providers\Mail;
use Generator;
use KTXF\Mail\Collection\CollectionBaseInterface; use KTXF\Mail\Collection\CollectionBaseInterface;
use KTXF\Mail\Collection\CollectionMutableInterface; use KTXF\Mail\Collection\CollectionRoles;
use KTXF\Mail\Collection\CollectionPropertiesBaseInterface;
use KTXF\Mail\Object\Address; use KTXF\Mail\Object\Address;
use KTXF\Mail\Object\AddressInterface; use KTXF\Mail\Object\AddressInterface;
use KTXF\Mail\Object\MessagePropertiesMutableInterface;
use KTXF\Mail\Service\ServiceBaseInterface; use KTXF\Mail\Service\ServiceBaseInterface;
use KTXF\Mail\Service\ServiceCollectionMutableInterface; use KTXF\Mail\Service\ServiceCollectionMutableInterface;
use KTXF\Mail\Service\ServiceConfigurableInterface; use KTXF\Mail\Service\ServiceConfigurableInterface;
use KTXF\Mail\Service\ServiceEntityMutableInterface;
use KTXF\Mail\Service\ServiceEntitySubmitInterface;
use KTXF\Mail\Service\ServiceMutableInterface; use KTXF\Mail\Service\ServiceMutableInterface;
use KTXF\Mail\Submission\EntitySubmitResult;
use KTXF\Resource\BinaryResource;
use KTXF\Resource\Provider\ResourceServiceIdentityInterface; use KTXF\Resource\Provider\ResourceServiceIdentityInterface;
use KTXF\Resource\Provider\ResourceServiceLocationInterface; use KTXF\Resource\Provider\ResourceServiceLocationInterface;
use KTXF\Resource\Delta\Delta; use KTXF\Resource\Delta\Delta;
use KTXF\Resource\Filter\Filter; use KTXF\Resource\Filter\Filter;
use KTXF\Resource\Filter\IFilter; use KTXF\Resource\Filter\IFilter;
use KTXF\Resource\Identifier\CollectionIdentifier;
use KTXF\Resource\Identifier\EntityIdentifier;
use KTXF\Resource\Identifier\EntityIdentifierInterface;
use KTXF\Resource\Range\IRange; use KTXF\Resource\Range\IRange;
use KTXF\Resource\Range\Range; use KTXF\Resource\Range\Range;
use KTXF\Resource\Range\RangeType; use KTXF\Resource\Range\RangeType;
@@ -32,14 +42,8 @@ use KTXM\ProviderJmapc\Providers\ServiceLocation;
use KTXM\ProviderJmapc\Service\Remote\RemoteMailService; use KTXM\ProviderJmapc\Service\Remote\RemoteMailService;
use KTXM\ProviderJmapc\Service\Remote\RemoteService; use KTXM\ProviderJmapc\Service\Remote\RemoteService;
/** class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceConfigurableInterface, ServiceCollectionMutableInterface, ServiceEntityMutableInterface, ServiceEntitySubmitInterface
* JMAP Service
*
* Represents a configured JMAP account
*/
class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceConfigurableInterface, ServiceCollectionMutableInterface
{ {
public const JSON_TYPE = ServiceBaseInterface::JSON_TYPE;
private const PROVIDER_IDENTIFIER = 'jmap'; private const PROVIDER_IDENTIFIER = 'jmap';
@@ -48,8 +52,7 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
private ?string $serviceIdentifier = null; private ?string $serviceIdentifier = null;
private ?string $serviceLabel = null; private ?string $serviceLabel = null;
private bool $serviceEnabled = false; private bool $serviceEnabled = false;
private bool $serviceDebug = false; private array $primaryAddress = [];
private string $primaryAddress = '';
private array $secondaryAddresses = []; private array $secondaryAddresses = [];
private ?ServiceLocation $location = null; private ?ServiceLocation $location = null;
private ?ServiceIdentityBasic $identity = null; private ?ServiceIdentityBasic $identity = null;
@@ -58,18 +61,20 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
private array $serviceAbilities = [ private array $serviceAbilities = [
self::CAPABILITY_COLLECTION_LIST => true, self::CAPABILITY_COLLECTION_LIST => true,
self::CAPABILITY_COLLECTION_LIST_FILTER => [ self::CAPABILITY_COLLECTION_LIST_FILTER => [
self::CAPABILITY_COLLECTION_FILTER_LABEL => 's:100:256:256', self::CAPABILITY_COLLECTION_FILTER_LABEL => 's:128:256:256',
self::CAPABILITY_COLLECTION_FILTER_ROLE => 's:100:256:256', self::CAPABILITY_COLLECTION_FILTER_ROLE => 's:32:1:1',
self::CAPABILITY_COLLECTION_FILTER_SUBSCRIBED => 'b:0:1:1',
], ],
self::CAPABILITY_COLLECTION_LIST_SORT => [ self::CAPABILITY_COLLECTION_LIST_SORT => [
self::CAPABILITY_COLLECTION_SORT_LABEL, self::CAPABILITY_COLLECTION_SORT_LABEL,
self::CAPABILITY_COLLECTION_SORT_RANK, self::CAPABILITY_COLLECTION_SORT_RANK,
], ],
self::CAPABILITY_COLLECTION_EXTANT => true,
self::CAPABILITY_COLLECTION_FETCH => true, self::CAPABILITY_COLLECTION_FETCH => true,
self::CAPABILITY_COLLECTION_EXTANT => true,
self::CAPABILITY_COLLECTION_CREATE => true, self::CAPABILITY_COLLECTION_CREATE => true,
self::CAPABILITY_COLLECTION_UPDATE => true, self::CAPABILITY_COLLECTION_UPDATE => true,
self::CAPABILITY_COLLECTION_DELETE => true, self::CAPABILITY_COLLECTION_DELETE => true,
self::CAPABILITY_COLLECTION_MOVE => true,
self::CAPABILITY_ENTITY_LIST => true, self::CAPABILITY_ENTITY_LIST => true,
self::CAPABILITY_ENTITY_LIST_FILTER => [ self::CAPABILITY_ENTITY_LIST_FILTER => [
self::CAPABILITY_ENTITY_FILTER_ALL => 's:200:256:256', self::CAPABILITY_ENTITY_FILTER_ALL => 's:200:256:256',
@@ -95,9 +100,17 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
self::CAPABILITY_ENTITY_LIST_RANGE => [ self::CAPABILITY_ENTITY_LIST_RANGE => [
'tally' => ['absolute', 'relative'] 'tally' => ['absolute', 'relative']
], ],
self::CAPABILITY_ENTITY_DELTA => true,
self::CAPABILITY_ENTITY_EXTANT => true,
self::CAPABILITY_ENTITY_FETCH => true, self::CAPABILITY_ENTITY_FETCH => true,
self::CAPABILITY_ENTITY_EXTANT => true,
self::CAPABILITY_ENTITY_CREATE => false,
self::CAPABILITY_ENTITY_MODIFY => false,
self::CAPABILITY_ENTITY_PATCH => true,
self::CAPABILITY_ENTITY_DELETE => true,
self::CAPABILITY_ENTITY_MOVE => true,
self::CAPABILITY_ENTITY_COPY => false,
self::CAPABILITY_ENTITY_SUBMIT_FRESH => true,
self::CAPABILITY_ENTITY_SUBMIT_DRAFT => true,
'EntityTransmit' => true,
]; ];
private readonly RemoteMailService $mailService; private readonly RemoteMailService $mailService;
@@ -119,9 +132,8 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
'tid' => $this->serviceTenantId, 'tid' => $this->serviceTenantId,
'uid' => $this->serviceUserId, 'uid' => $this->serviceUserId,
'sid' => $this->serviceIdentifier, 'sid' => $this->serviceIdentifier,
'label' => $this->serviceLabel,
'enabled' => $this->serviceEnabled, 'enabled' => $this->serviceEnabled,
'debug' => $this->serviceDebug, 'label' => $this->serviceLabel,
'primaryAddress' => $this->primaryAddress, 'primaryAddress' => $this->primaryAddress,
'secondaryAddresses' => $this->secondaryAddresses, 'secondaryAddresses' => $this->secondaryAddresses,
'location' => $this->location?->toStore(), 'location' => $this->location?->toStore(),
@@ -137,7 +149,6 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
$this->serviceIdentifier = $data['sid']; $this->serviceIdentifier = $data['sid'];
$this->serviceLabel = $data['label'] ?? ''; $this->serviceLabel = $data['label'] ?? '';
$this->serviceEnabled = $data['enabled'] ?? false; $this->serviceEnabled = $data['enabled'] ?? false;
$this->serviceDebug = $data['debug'] ?? false;
if (isset($data['primaryAddress'])) { if (isset($data['primaryAddress'])) {
$this->primaryAddress = $data['primaryAddress']; $this->primaryAddress = $data['primaryAddress'];
@@ -163,51 +174,50 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
public function jsonSerialize(): array public function jsonSerialize(): array
{ {
return array_filter([ return array_filter([
self::JSON_PROPERTY_TYPE => self::JSON_TYPE, self::PROPERTY_TYPE => self::JSON_TYPE,
self::JSON_PROPERTY_PROVIDER => self::PROVIDER_IDENTIFIER, self::PROPERTY_PROVIDER => self::PROVIDER_IDENTIFIER,
self::JSON_PROPERTY_IDENTIFIER => $this->serviceIdentifier, self::PROPERTY_IDENTIFIER => $this->serviceIdentifier,
self::JSON_PROPERTY_LABEL => $this->serviceLabel, self::PROPERTY_LABEL => $this->serviceLabel,
self::JSON_PROPERTY_ENABLED => $this->serviceEnabled, self::PROPERTY_ENABLED => $this->serviceEnabled,
self::JSON_PROPERTY_CAPABILITIES => $this->serviceAbilities, self::PROPERTY_CAPABILITIES => $this->serviceAbilities,
self::JSON_PROPERTY_PRIMARY_ADDRESS => $this->primaryAddress, self::PROPERTY_PRIMARY_ADDRESS => $this->primaryAddress,
self::JSON_PROPERTY_SECONDARY_ADDRESSES => $this->secondaryAddresses, self::PROPERTY_SECONDARY_ADDRESSES => $this->secondaryAddresses,
self::JSON_PROPERTY_LOCATION => $this->location?->jsonSerialize(), self::PROPERTY_LOCATION => $this->location?->jsonSerialize(),
self::JSON_PROPERTY_IDENTITY => $this->identity?->jsonSerialize(), self::PROPERTY_IDENTITY => $this->identity?->jsonSerialize(),
self::JSON_PROPERTY_AUXILIARY => $this->auxiliary, self::PROPERTY_AUXILIARY => $this->auxiliary,
], fn($v) => $v !== null); ], fn($v) => $v !== null);
} }
public function jsonDeserialize(array|string $data): static public function jsonDeserialize(array|string $data, bool $delta = false): static
{ {
if (is_string($data)) { if (is_string($data)) {
$data = json_decode($data, true, 512, JSON_THROW_ON_ERROR); $data = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
} }
if (isset($data[self::JSON_PROPERTY_LABEL])) { if (isset($data[self::PROPERTY_ENABLED])) {
$this->setLabel($data[self::JSON_PROPERTY_LABEL]); $this->setEnabled($data[self::PROPERTY_ENABLED]);
} }
if (isset($data[self::JSON_PROPERTY_ENABLED])) { if (isset($data[self::PROPERTY_LABEL])) {
$this->setEnabled($data[self::JSON_PROPERTY_ENABLED]); $this->setLabel($data[self::PROPERTY_LABEL]);
} }
if (isset($data[self::JSON_PROPERTY_LOCATION])) { if (isset($data[self::PROPERTY_LOCATION])) {
$this->setLocation($this->freshLocation(null, $data[self::JSON_PROPERTY_LOCATION])); $this->setLocation($this->freshLocation(null, $data[self::PROPERTY_LOCATION]));
} }
if (isset($data[self::JSON_PROPERTY_IDENTITY])) { if (isset($data[self::PROPERTY_IDENTITY])) {
$this->setIdentity($this->freshIdentity(null, $data[self::JSON_PROPERTY_IDENTITY])); $this->setIdentity($this->freshIdentity(null, $data[self::PROPERTY_IDENTITY]));
} }
if (isset($data[self::JSON_PROPERTY_PRIMARY_ADDRESS]) && is_string($data[self::JSON_PROPERTY_PRIMARY_ADDRESS])) { if (isset($data[self::PROPERTY_PRIMARY_ADDRESS])) {
if (is_array($data[self::JSON_PROPERTY_PRIMARY_ADDRESS]) && isset($data[self::JSON_PROPERTY_PRIMARY_ADDRESS]['address'])) { $value = $data[self::PROPERTY_PRIMARY_ADDRESS];
$this->setPrimaryAddress(new Address($data[self::JSON_PROPERTY_PRIMARY_ADDRESS])); $this->setPrimaryAddress(is_array($value) ? Address::fromArray($value) : new Address((string)$value));
}
} }
if (isset($data[self::JSON_PROPERTY_SECONDARY_ADDRESSES]) && is_array($data[self::JSON_PROPERTY_SECONDARY_ADDRESSES])) { if (isset($data[self::PROPERTY_SECONDARY_ADDRESSES]) && is_array($data[self::PROPERTY_SECONDARY_ADDRESSES])) {
$this->setSecondaryAddresses(array_map( $this->setSecondaryAddresses(array_map(
fn($addr) => new Address($addr['address']), fn($addr) => new Address(is_array($addr) ? ($addr['address'] ?? $addr) : $addr),
$data[self::JSON_PROPERTY_SECONDARY_ADDRESSES] $data[self::PROPERTY_SECONDARY_ADDRESSES]
)); ));
} }
if (isset($data[self::JSON_PROPERTY_AUXILIARY]) && is_array($data[self::JSON_PROPERTY_AUXILIARY])) { if (isset($data[self::PROPERTY_AUXILIARY]) && is_array($data[self::PROPERTY_AUXILIARY])) {
$this->setAuxiliary($data[self::JSON_PROPERTY_AUXILIARY]); $this->setAuxiliary($data[self::PROPERTY_AUXILIARY]);
} }
return $this; return $this;
@@ -218,14 +228,10 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return isset($this->serviceAbilities[$value]); return isset($this->serviceAbilities[$value]);
} }
public function capabilities(): array public function capabilities(): array
{ {
$caps = []; return $this->serviceAbilities;
foreach (array_keys($this->serviceAbilities) as $cap) { }
$caps[$cap] = true;
}
return $caps;
}
public function provider(): string public function provider(): string
{ {
@@ -261,41 +267,47 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
public function getPrimaryAddress(): AddressInterface public function getPrimaryAddress(): AddressInterface
{ {
return new Address($this->primaryAddress); return Address::fromArray($this->primaryAddress);
} }
public function setPrimaryAddress(AddressInterface $value): static public function setPrimaryAddress(AddressInterface $value): static
{ {
$this->primaryAddress = $value->getAddress(); $this->primaryAddress = $value->toArray();
return $this; return $this;
} }
public function getSecondaryAddresses(): array public function getSecondaryAddresses(): array
{ {
return $this->secondaryAddresses; return array_map(
fn($addr) => $addr instanceof AddressInterface ? $addr : Address::fromArray(is_array($addr) ? $addr : ['address' => (string) $addr])
, $this->secondaryAddresses);
} }
public function setSecondaryAddresses(array $addresses): static public function setSecondaryAddresses(array $addresses): static
{ {
$this->secondaryAddresses = $addresses; $this->secondaryAddresses = array_map(
fn($addr) => $addr instanceof AddressInterface ? $addr : Address::fromArray(is_array($addr) ? $addr : ['address' => (string) $addr]),
$addresses
);
return $this; return $this;
} }
public function hasAddress(string $address): bool public function hasAddress(string $address): bool
{ {
$address = strtolower(trim($address)); $address = strtolower(trim($address));
if ($this->primaryAddress && strtolower($this->primaryAddress) === $address) { if ($this->primaryAddress && strtolower($this->primaryAddress['address'] ?? '') === $address) {
return true; return true;
} }
foreach ($this->secondaryAddresses as $secondary) {
foreach ($this->secondaryAddresses as $secondaryAddress) { $secondaryAddr = $secondary instanceof AddressInterface ? $secondary->getAddress() : (string) $secondary;
if (strtolower($secondaryAddress->getAddress()) === $address) { if (strtolower($secondaryAddr) === $address) {
return true; return true;
} }
} }
return false; return false;
} }
public function getLocation(): ServiceLocation public function getLocation(): ServiceLocation
@@ -336,12 +348,12 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
public function getDebug(): bool public function getDebug(): bool
{ {
return $this->serviceDebug; return ($this->auxiliary['debug'] ?? false) === true;
} }
public function setDebug(bool $debug): static public function setDebug(bool $debug): static
{ {
$this->serviceDebug = $debug; $this->auxiliary['debug'] = $debug;
return $this; return $this;
} }
@@ -356,8 +368,6 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return $this; return $this;
} }
// Collection operations
public function collectionList(string|int|null $location, ?IFilter $filter = null, ?ISort $sort = null): array public function collectionList(string|int|null $location, ?IFilter $filter = null, ?ISort $sort = null): array
{ {
$this->initialize(); $this->initialize();
@@ -385,6 +395,22 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return new Sort($this->serviceAbilities[self::CAPABILITY_COLLECTION_LIST_SORT] ?? []); return new Sort($this->serviceAbilities[self::CAPABILITY_COLLECTION_LIST_SORT] ?? []);
} }
public function collectionFetch(string|int $identifier): ?CollectionResource
{
$this->initialize();
$mailbox = $this->mailService->collectionFetch($identifier);
if (!is_array($mailbox) || !isset($mailbox['id'])) {
return null;
}
$collection = $this->collectionFresh();
$collection->fromJmap($mailbox);
return $collection;
}
public function collectionExtant(string|int ...$identifiers): array public function collectionExtant(string|int ...$identifiers): array
{ {
$this->initialize(); $this->initialize();
@@ -392,82 +418,109 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return $this->mailService->collectionExtant(...$identifiers); return $this->mailService->collectionExtant(...$identifiers);
} }
public function collectionFetch(string|int $identifier): ?CollectionBaseInterface public function collectionFresh(): CollectionResource
{ {
$this->initialize(); return new CollectionResource($this->provider(), $this->identifier());
$collection = $this->mailService->collectionFetch($identifier);
if (is_array($collection) && isset($collection['id'])) {
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($collection);
$collection = $object;
}
return $collection;
} }
public function collectionFresh(): CollectionMutableInterface public function collectionCreate(CollectionIdentifier|null $target, CollectionPropertiesBaseInterface $properties, array $options = []): CollectionBaseInterface
{
return new CollectionResource(provider: $this->provider(), service: $this->identifier());
}
public function collectionCreate(string|int|null $location, CollectionMutableInterface $collection, array $options = []): CollectionBaseInterface
{ {
$this->initialize(); $this->initialize();
if ($collection instanceof CollectionResource === false) { if ($properties instanceof CollectionProperties === false) {
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier()); $native = new CollectionProperties([]);
$object->jsonDeserialize($collection->jsonSerialize()); $native->jsonDeserialize($properties->jsonSerialize());
$collection = $object; } else {
$native = $properties;
} }
$collection = $collection->toJmap(); $collection = $native->toJmap();
$collection = $this->mailService->collectionCreate($location, $collection, $options); $collection = $this->mailService->collectionCreate($target?->collection(), $collection, $options);
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier()); $object = $this->collectionFresh();
$object->fromJmap($collection); $object->fromJmap($collection);
return $object; return $object;
} }
public function collectionUpdate(string|int $identifier, CollectionMutableInterface $collection): CollectionBaseInterface public function collectionUpdate(CollectionIdentifier $target, CollectionPropertiesBaseInterface $properties): CollectionBaseInterface
{ {
$this->initialize(); $this->initialize();
if ($collection instanceof CollectionResource === false) { if ($properties instanceof CollectionProperties === false) {
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier()); $native = new CollectionProperties([]);
$object->jsonDeserialize($collection->jsonSerialize()); $native->jsonDeserialize($properties->jsonSerialize());
$collection = $object; } else {
$native = $properties;
} }
$collection = $collection->toJmap(); $collection = $native->toJmap();
$collection = $this->mailService->collectionModify($identifier, $collection); $collection = $this->mailService->collectionModify($target->collection(), $collection);
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier()); $object = $this->collectionFresh();
$object->fromJmap($collection); $object->fromJmap($collection);
return $object; return $object;
} }
public function collectionDelete(string|int $identifier, bool $force = false, bool $recursive = false): bool public function collectionDelete(CollectionIdentifier $target, bool $force = false): CollectionBaseInterface | true
{ {
$this->initialize(); $this->initialize();
return $this->mailService->collectionDestroy($identifier, $force, $recursive) !== null; $deleteMode = $this->auxiliary['deleteMode'] ?? 'soft';
$deleteTarget = $this->auxiliary['deleteTarget'] ?? null;
if ($deleteMode !== 'soft' && $deleteMode !== 'hard') {
throw new \InvalidArgumentException("Invalid delete mode: $deleteMode");
}
$deleteTargetIdentifier = null;
if ($deleteMode === 'soft') {
$deleteTargetIdentifier = $deleteTarget !== null && (string) $deleteTarget !== ''
? new CollectionIdentifier($this->provider(), (string) $this->identifier(), (string) $deleteTarget)
: $this->resolveCollectionByRole(CollectionRoles::Trash->value);
if ($deleteTargetIdentifier === null) {
throw new \RuntimeException('No Trash collection configured or found for deletion');
}
}
// we need to determine if the folder being deleted is already in the trash
if (str_starts_with((string) $target->collection(), (string) $deleteTargetIdentifier?->collection())) {
// if so, we should hard delete instead of moving to avoid duplicates in the trash
$deleteMode = 'hard';
}
$result = match ($deleteMode) {
'soft' => $this->collectionMove($deleteTargetIdentifier, $target),
'hard' => $this->mailService->collectionDestroy($target->collection(), $force),
};
return $result;
} }
public function collectionMove(string|int $identifier, string|int|null $targetLocation): CollectionBaseInterface public function collectionMove(CollectionIdentifier $target, CollectionIdentifier $source): CollectionBaseInterface
{ {
// TODO: Implement collection move
$this->initialize(); $this->initialize();
$collection = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$sourceMailbox = $this->mailService->collectionFetch((string) $source->collection());
$targetMailbox = $this->mailService->collectionFetch((string) $target->collection());
if ($sourceMailbox === null) {
throw new \RuntimeException('Source collection not found for move operation');
}
if ($targetMailbox === null) {
throw new \RuntimeException('Target collection not found for move operation');
}
$mutation['parentId'] = $targetMailbox['id'];
$mutation = $this->mailService->collectionModify($sourceMailbox['id'], $mutation);
$mutation = array_merge($sourceMailbox, $mutation);
$collection = $this->collectionFresh();
$collection->fromJmap($mutation);
return $collection; return $collection;
} }
// Entity operations public function entityListBulk(string|int $collection, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null, ?array $properties = null): array
public function entityList(string|int $collection, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null, ?array $properties = null): array
{ {
$this->initialize(); $this->initialize();
@@ -476,9 +529,9 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
$list = []; $list = [];
foreach ($result['list'] as $index => $entry) { foreach ($result['list'] as $index => $entry) {
if (is_array($entry) && isset($entry['id'])) { if (is_array($entry) && isset($entry['id'])) {
$object = new EntityResource(provider: $this->provider(), service: $this->identifier()); $object = $this->entityFresh();
$object->fromJmap($entry); $object->fromJmap($entry);
$list[$object->identifier()] = $object; $list[$object->urn()] = $object;
} }
unset($result['list'][$index]); unset($result['list'][$index]);
} }
@@ -486,6 +539,13 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return $list; return $list;
} }
public function entityListStream(string|int $collection, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null, ?array $properties = null): Generator
{
foreach ($this->entityListBulk($collection, $filter, $sort, $range, $properties) as $urn => $entity) {
yield $urn => $entity;
}
}
public function entityListFilter(): Filter public function entityListFilter(): Filter
{ {
return new Filter($this->serviceAbilities[self::CAPABILITY_ENTITY_LIST_FILTER] ?? []); return new Filter($this->serviceAbilities[self::CAPABILITY_ENTITY_LIST_FILTER] ?? []);
@@ -501,6 +561,45 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return new Range(); return new Range();
} }
public function entityFetchBulk(EntityIdentifierInterface ...$identifiers): array
{
$this->initialize();
$ids = [];
foreach ($identifiers as $identifier) {
$ids[] = $identifier->entity();
}
$entities = $this->mailService->entityFetch(...$ids);
$list = [];
foreach ($entities as $entity) {
if (is_array($entity) && isset($entity['id'])) {
$object = $this->entityFresh();
$object->fromJmap($entity);
$list[$object->urn()] = $object;
}
}
return $list;
}
public function entityFetchStream(EntityIdentifierInterface ...$identifiers): Generator
{
foreach ($this->entityFetchBulk(...$identifiers) as $urn => $entity) {
yield $urn => $entity;
}
}
public function entityDownload(EntityIdentifierInterface $target, array|null $part): BinaryResource
{
$this->initialize();
$blobId = isset($part['blobId']) ? (string) $part['blobId'] : null;
return $this->mailService->entityDownload($target->entity(), $blobId);
}
public function entityDelta(string|int $collection, string $signature, string $detail = 'ids'): Delta public function entityDelta(string|int $collection, string $signature, string $detail = 'ids'): Delta
{ {
$this->initialize(); $this->initialize();
@@ -515,21 +614,432 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return $this->mailService->entityExtant(...$identifiers); return $this->mailService->entityExtant(...$identifiers);
} }
public function entityFetch(string|int $collection, string|int ...$identifiers): array public function entityFresh(): EntityResource
{ {
return new EntityResource($this->provider(), $this->identifier());
}
public function entityCreate(CollectionIdentifier $target, MessagePropertiesMutableInterface $properties, array $options = []): EntityResource
{
// TODO: Implement entity create
return $this->entityFresh();
}
public function entityModify(EntityIdentifier $identifier, MessagePropertiesMutableInterface $properties): EntityResource
{
// TODO: Implement entity modify
return $this->entityFresh();
}
public function entityPatch(MessagePropertiesMutableInterface $properties, EntityIdentifier ...$targets): array
{
// validate identifiers and construct ID list
$targets = $this->mapEntities(...$targets);
// move entities on remote store and construct result map
$this->initialize(); $this->initialize();
$entities = $this->mailService->entityFetch(...$identifiers); $patch = $this->mailService->entityFresh();
$flags = $properties->getFlags();
foreach ($flags as $flag => $value) {
// translate canonical flag names to JMAP keywords
$keyword = match($flag) {
'seen' => '$seen',
'flagged' => '$flagged',
'answered' => '$answered',
'draft' => '$draft',
'deleted' => '$deleted',
default => $flag
};
$patch->keyword($keyword, $value);
}
$dispositions = $this->mailService->entityPatch($patch, ...array_keys($targets));
$list = [];
foreach ($targets as $target) {
$entityId = $target->entity();
// if the source entity ID is not in the dispositions, it means an unknown error occurred during the move operation for that entity
if (!isset($dispositions[$entityId])) {
$list[(string)$target] = [
'disposition' => 'error',
'error' => 'Unknown error occurred during move operation',
];
continue;
}
// if the disposition for the entity ID is not true, it means the move operation failed for that entity with a known error
if ($dispositions[$entityId] !== true) {
$list[(string)$target] = [
'disposition' => 'error',
'error' => $dispositions[$entityId] ?? 'Unknown error occurred during move operation',
];
continue;
}
$list[(string)$target] = [
'disposition' => 'patched'
];
unset($targets[$entityId]);
}
return $list;
}
public function entityDelete(EntityIdentifier ...$targets): array
{
// validate identifiers and construct ID list
$targets = $this->mapEntities(...$targets);
// determine delete mode and target collection (e.g. Trash) if applicable
$deleteMode = $this->auxiliary['deleteMode'] ?? 'soft';
$deleteTarget = $this->auxiliary['deleteTarget'] ?? null;
foreach ($entities as &$entity) { if ($deleteMode !== 'soft' && $deleteMode !== 'hard') {
if (is_array($entity) && isset($entity['id'])) { throw new \InvalidArgumentException("Invalid delete mode: $deleteMode");
$object = new EntityResource(provider: $this->provider(), service: $this->identifier()); }
$object->fromJmap($entity);
$entity = $object; // connect to remote store
$this->initialize();
$deleteTargetIdentifier = null;
if ($deleteMode === 'soft') {
$deleteTargetIdentifier = $deleteTarget !== null && (string) $deleteTarget !== ''
? new CollectionIdentifier($this->provider(), (string) $this->identifier(), (string) $deleteTarget)
: $this->resolveCollectionByRole(CollectionRoles::Trash->value);
if ($deleteTargetIdentifier === null) {
throw new \RuntimeException('No Trash collection configured or found for deletion');
} }
} }
return $entities; $deleteTargetNative = $deleteTargetIdentifier?->collection();
// if all targets are already in the delete target collection, we should hard delete instead of moving to avoid duplicates in the trash
$targetCollections = [];
foreach ($targets as $target) {
$targetCollections[$target->collection()] = true;
}
if (array_keys($targetCollections) === [$deleteTargetNative]) {
$deleteMode = 'hard';
}
// move or delete target entities on remote store and construct result map
$dispositions = match ($deleteMode) {
'soft' => $this->mailService->entityMove($deleteTargetNative, ...array_keys($targets)),
'hard' => $this->mailService->entityDelete(...array_keys($targets)),
};
$list = [];
foreach ($targets as $target) {
$entityId = $target->entity();
// if the source entity ID is not in the dispositions, it means an unknown error occurred during the move operation for that entity
if (!isset($dispositions[$entityId])) {
$list[(string)$target] = [
'disposition' => 'error',
'error' => 'Unknown error occurred during move operation',
];
continue;
}
// if the disposition for the entity ID is not true, it means the move operation failed for that entity with a known error
if ($dispositions[$entityId] !== true) {
$list[(string)$target] = [
'disposition' => 'error',
'error' => $dispositions[$entityId] ?? 'Unknown error occurred during move operation',
];
continue;
}
if ($deleteMode === 'soft') {
$list[(string)$target] = [
'disposition' => 'moved',
'destination' => $deleteTargetIdentifier,
'mutation' => new EntityIdentifier($this->provider(), $this->identifier(), $target->collection(), $entityId),
];
} else {
$list[(string)$target] = [
'disposition' => 'deleted',
];
}
unset($targets[$entityId]);
}
return $list;
}
public function entityMove(CollectionIdentifier $target, EntityIdentifier ...$sources): array
{
// validate target belongs to this service
if ($target->provider() !== $this->provider() || $target->service() !== (string)$this->identifier()) {
throw new \InvalidArgumentException('Target collection does not belong to this service');
}
// validate identifiers and construct ID list
$sources = $this->mapEntities(...$sources);
// move entities on remote store and construct result map
$this->initialize();
$dispositions = $this->mailService->entityMove($target->collection(), ...array_keys($sources));
$list = [];
foreach ($sources as $source) {
$entityId = $source->entity();
// if the source entity ID is not in the dispositions, it means an unknown error occurred during the move operation for that entity
if (!isset($dispositions[$entityId])) {
$list[(string)$source] = [
'disposition' => 'error',
'error' => 'Unknown error occurred during move operation',
];
continue;
}
// if the disposition for the entity ID is not true, it means the move operation failed for that entity with a known error
if ($dispositions[$entityId] !== true) {
$list[(string)$source] = [
'disposition' => 'error',
'error' => $dispositions[$entityId] ?? 'Unknown error occurred during move operation',
];
continue;
}
$list[(string)$source] = [
'disposition' => 'moved',
'destination' => $target,
'mutation' => new EntityIdentifier($this->provider(), $this->identifier(), $target->collection(), $entityId),
];
unset($sources[$entityId]);
}
return $list;
}
public function entityCopy(CollectionIdentifier $target, EntityIdentifier ...$sources): array
{
// TODO: Implement entity copy
return [];
}
public function entitySubmit(AddressInterface $sender, EntityIdentifierInterface|null $source = null, MessagePropertiesMutableInterface|null $message = null): EntitySubmitResult
{
try {
$this->initialize();
if ($source === null && $message === null) {
throw new \InvalidArgumentException('At least one of source or message must be provided for submission');
}
if ($source !== null) {
if ($source->provider() !== $this->provider() || (string)$source->service() !== (string)$this->identifier()) {
throw new \InvalidArgumentException('Source entity does not belong to this service');
}
return $this->entityTransmitDraft($sender, $source, $message);
}
if ($message === null) {
throw new \InvalidArgumentException('Message properties are required for fresh submission');
}
return $this->entityTransmitFresh($sender, $message);
} catch (\Throwable $e) {
return new EntitySubmitResult(
EntitySubmitResult::DISPOSITION_ERROR,
errorCode: 'submit_failed',
errorMessage: $e->getMessage(),
);
}
}
public function entityTransmitFresh(AddressInterface $sender, MessagePropertiesMutableInterface $message): EntitySubmitResult
{
// determine the drafts folder
// if no explicit drafts folder is configured, we will attempt to find a folder with the "drafts" role.
$preSendTarget = $this->auxiliary['draftTarget'] ?? null;
$preSendTarget = $preSendTarget !== null && (string) $preSendTarget !== ''
? new CollectionIdentifier($this->provider(), (string) $this->identifier(), (string) $preSendTarget)
: $this->resolveCollectionByRole(CollectionRoles::Drafts->value);
if ($preSendTarget->provider() !== $this->provider() || $preSendTarget->service() !== (string)$this->identifier()) {
throw new \InvalidArgumentException('Drafts target collection does not belong to this service');
}
// determine the sent folder
// if no explicit sent folder is configured, we will attempt to find a folder with the "sent" role.
$postSentTarget = $this->auxiliary['sentTarget'] ?? null;
$postSentTarget = $postSentTarget !== null && (string) $postSentTarget !== ''
? new CollectionIdentifier($this->provider(), (string) $this->identifier(), (string) $postSentTarget)
: $this->resolveCollectionByRole(CollectionRoles::Sent->value);
if ($postSentTarget->provider() !== $this->provider() || $postSentTarget->service() !== (string)$this->identifier()) {
throw new \InvalidArgumentException('Sent target collection does not belong to this service');
}
// determine the identity to submit with based on the sender address
$identityId = $this->resolveIdentityId($sender);
if ($identityId === null) {
return new EntitySubmitResult(
EntitySubmitResult::DISPOSITION_ERROR,
errorCode: 'identity_not_found',
errorMessage: sprintf('No matching JMAP identity found for sender %s', $sender->getAddress()),
);
}
$nativeProperties = $this->normalizeMessageProperties($message);
$attachments = $nativeProperties->getAttachments();
foreach ($attachments as $attachment) {
if ($attachment->getBlobId() !== null) {
continue;
}
$content = $attachment->getContent();
if ($content === null) {
throw new \InvalidArgumentException(sprintf(
'Attachment "%s" has neither content nor a JMAP blob identifier',
$attachment->getName() ?? 'unnamed',
));
}
$attachment->setBlobId($this->mailService->blobDeposit(
$attachment->getType() ?? 'application/octet-stream',
$content,
));
}
if ($attachments !== []) {
$nativeProperties->setAttachments(...$attachments);
}
$nativeMessage = $nativeProperties->toJmap();
$transportId = $this->mailService->entitySubmitFresh($identityId, $nativeMessage, $preSendTarget->collection(), $postSentTarget->collection());
return new EntitySubmitResult(
EntitySubmitResult::DISPOSITION_SENT,
transportId: $transportId,
);
}
public function entityTransmitDraft(AddressInterface $sender, EntityIdentifierInterface $source, MessagePropertiesMutableInterface|null $message = null): EntitySubmitResult {
$identityId = $this->resolveIdentityId($sender);
if ($identityId === null) {
return new EntitySubmitResult(
EntitySubmitResult::DISPOSITION_ERROR,
errorCode: 'identity_not_found',
errorMessage: sprintf('No matching JMAP identity found for sender %s', $sender->getAddress()),
);
}
$patch = null;
if ($message !== null) {
$patch = $this->normalizeMessageProperties($message)->toJmap();
}
$transportId = $this->mailService->entitySubmitDraft($identityId, (string)$source->entity(), $patch);
return new EntitySubmitResult(
EntitySubmitResult::DISPOSITION_SENT,
transportId: $transportId,
sourceDraft: new EntityIdentifier($this->provider(), $this->identifier(), $source->collection(), $source->entity()),
);
}
private function normalizeMessageProperties(MessagePropertiesMutableInterface $message): MessageProperties
{
if ($message instanceof MessageProperties) {
return $message;
}
$native = new MessageProperties([]);
$native->jsonDeserialize($message->jsonSerialize());
return $native;
}
private function resolveCollectionByRole(string $role): ?CollectionIdentifier
{
$filter = $this->collectionListFilter();
$filter->condition('role', $role);
$collections = iterator_to_array($this->mailService->collectionList(null, $filter, null));
if (empty($collections)) {
return null;
}
foreach ($collections as $key => $collection) {
$collectionId = $this->extractCollectionId($collection, $key);
if ($collectionId !== null) {
return new CollectionIdentifier($this->provider(), (string) $this->identifier(), $collectionId);
}
}
return null;
}
private function extractCollectionId(mixed $collection, string|int|null $fallback = null): ?string
{
if (is_object($collection) && method_exists($collection, 'id')) {
$collectionId = $collection->id();
if (is_string($collectionId) || is_int($collectionId)) {
return (string) $collectionId;
}
}
if (is_array($collection) && isset($collection['id']) && (is_string($collection['id']) || is_int($collection['id']))) {
return (string) $collection['id'];
}
if (is_string($fallback) || is_int($fallback)) {
$fallback = (string) $fallback;
return $fallback !== '' ? $fallback : null;
}
return null;
}
private function resolveIdentityId(AddressInterface $sender): ?string
{
$identities = $this->mailService->identityFetch();
$senderAddress = strtolower(trim($sender->getAddress()));
$fallbackIdentity = null;
foreach ($identities as $identity) {
$identityId = null;
$identityAddress = null;
if (is_object($identity)) {
if (method_exists($identity, 'id')) {
$identityId = (string)$identity->id();
}
if (method_exists($identity, 'email')) {
$email = $identity->email();
$identityAddress = is_string($email) ? $email : null;
}
}
if (is_array($identity)) {
$identityId = isset($identity['id']) ? (string)$identity['id'] : $identityId;
$identityAddress = isset($identity['email']) && is_string($identity['email']) ? $identity['email'] : $identityAddress;
}
if ($identityId === null || $identityId === '') {
continue;
}
$fallbackIdentity ??= $identityId;
if ($identityAddress !== null && strtolower(trim($identityAddress)) === $senderAddress) {
return $identityId;
}
}
return $fallbackIdentity;
}
private function mapEntities(EntityIdentifier ...$identifiers): array
{
$list = [];
foreach ($identifiers as $identifier) {
if ($identifier->provider() !== $this->provider() || $identifier->service() !== (string)$this->identifier()) {
throw new \InvalidArgumentException('Entity identifier does not belong to this service: ' . (string)$identifier);
}
$list[$identifier->entity()] = $identifier;
}
return $list;
} }
} }
+1 -1
View File
@@ -97,7 +97,7 @@ class Provider implements IProviderBase, IProviderServiceMutate
} }
// Note: This simplified interface doesn't pass tenantId // Note: This simplified interface doesn't pass tenantId
// Will need to get it from SessionTenant in actual implementation // Will need to get it from TenantContextInterface in actual implementation
throw new \RuntimeException('Use Mail Provider interface for service creation'); throw new \RuntimeException('Use Mail Provider interface for service creation');
} }
+726
View File
@@ -0,0 +1,726 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderJmapc\Service\Remote;
use Exception;
use JmapClient\Client;
use JmapClient\Requests\Files\NodeGet;
use JmapClient\Requests\Files\NodeQuery;
use JmapClient\Requests\Files\NodeParameters as NodeParametersRequest;
use JmapClient\Requests\Files\NodeQueryChanges;
use JmapClient\Requests\Files\NodeSet;
use JmapClient\Responses\Files\NodeParameters as NodeParametersResponse;
use JmapClient\Responses\ResponseException;
use KTXF\Resource\Delta\Delta;
use KTXF\Resource\Delta\DeltaCollection;
use KTXF\Resource\Filter\Filter;
use KTXF\Resource\Filter\IFilter;
use KTXF\Resource\Range\IRange;
use KTXF\Resource\Range\RangeAnchorType;
use KTXF\Resource\Range\RangeTally;
use KTXF\Resource\Sort\ISort;
use KTXF\Resource\Sort\Sort;
use KTXM\ProviderJmapc\Exception\JmapUnknownMethod;
class RemoteFilesService {
private const ROOT_ID = '00000000-0000-0000-0000-000000000000';
private const COLLECTION_FILTER_ATTRIBUTES = ['any', 'label', 'role', 'roles', 'createdBefore', 'createdAfter', 'modifiedBefore', 'modifiedAfter'];
private const COLLECTION_SORT_ATTRIBUTES = ['tree'];
private const ENTITY_FILTER_ATTRIBUTES = ['any', 'label', 'createdBefore', 'createdAfter', 'modifiedBefore', 'modifiedAfter'];
private const ENTITY_SORT_ATTRIBUTES = ['tree'];
protected Client $dataStore;
protected string $dataAccount;
protected ?string $resourceNamespace = null;
protected ?string $resourceCollectionLabel = null;
protected ?string $resourceEntityLabel = null;
public function __construct() {
}
public function initialize(Client $dataStore, ?string $dataAccount = null) {
$this->dataStore = $dataStore;
// evaluate if client is connected
if (!$this->dataStore->sessionStatus()) {
$this->dataStore->connect();
}
// determine account
if ($dataAccount === null) {
if ($this->resourceNamespace !== null) {
$account = $dataStore->sessionAccountDefault($this->resourceNamespace, false);
} else {
$account = $dataStore->sessionAccountDefault('filenode');
}
$this->dataAccount = $account !== null ? $account->id() : '';
} else {
$this->dataAccount = $dataAccount;
}
}
/**
* list of collections in remote storage
*
* @since Release 1.0.0
*/
public function collectionList(?string $location = null, IFilter|null $filter = null, ISort|null $sort = null, IRange|null $range = null): array {
// construct request
$r0 = new NodeQuery($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->filter()->is(false);
$r0->depth(1);
// define location
if (!empty($location) && $location !== self::ROOT_ID) {
$r0->filter()->in($location);
}
// define filter
if ($filter !== null) {
foreach ($filter->conditions() as $condition) {
$value = $condition['value'];
match($condition['attribute']) {
'label' => $r0->filter()->labelMatches($value),
default => null
};
}
}
// define order
if ($sort !== null) {
foreach ($sort->conditions() as $condition) {
$direction = $condition['direction'];
match($condition['attribute']) {
'tree' => $r0->sort()->tree($direction),
default => null
};
}
}
// construct request
$r1 = new NodeGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
// define target
//$r1->targetFromRequest($r0, '/ids');
if (!empty($location) && $location !== self::ROOT_ID) {
$r1->target($location);
}
// transceive
//$bundle = $this->dataStore->perform([$r1]);
$bundle = $this->dataStore->perform([$r0, $r1]);
// extract response
//$response = $bundle->response(0);
$response = $bundle->response(1);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// convert jmap objects to collection objects
$list = [];
foreach ($response->objects() as $so) {
if (!$so instanceof NodeParametersResponse) {
continue;
}
$id = $so->id();
$list[$id] = $so->parametersRaw();
$list[$id]['signature'] = $response->state();
}
// return collection of collections
return $list;
}
/**
* fresh instance of collection filter object
*
* @since Release 1.0.0
*/
public function collectionListFilter(): Filter {
return new Filter(self::COLLECTION_FILTER_ATTRIBUTES);
}
/**
* fresh instance of collection sort object
*
* @since Release 1.0.0
*/
public function collectionListSort(): Sort {
return new Sort([self::COLLECTION_SORT_ATTRIBUTES]);
}
/**
* check existence of collections in remote storage
*
* @since Release 1.0.0
*/
public function collectionExtant(string ...$identifiers): array {
$extant = [];
// construct request
$r0 = new NodeGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->target(...$identifiers);
$r0->property('id');
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// convert jmap objects to collection objects
foreach ($response->objects() as $so) {
if (!$so instanceof NodeParametersResponse) {
continue;
}
$extant[$so->id()] = true;
}
return $extant;
}
/**
* retrieve properties for specific collection
*
* @since Release 1.0.0
*/
public function collectionFetch(string $identifier): ?array {
// construct request
$r0 = new NodeGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->target($identifier);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// convert jmap object to collection object
$so = $response->object(0);
$to = null;
if ($so instanceof NodeParametersResponse) {
$to = $so->parametersRaw();
$to['signature'] = $response->state();
}
return $to;
}
/**
* create collection in remote storage
*
* @since Release 1.0.0
*/
public function collectionCreate(string|null $location, array $so): ?array {
// convert entity
$to = new NodeParametersRequest();
$to->parametersRaw($so);
// define location
if (!empty($location) && $location !== self::ROOT_ID) {
$to->in($location);
}
$id = uniqid();
// construct request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->create($id, $to);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// check for success
$result = $response->createSuccess($id);
if ($result !== null) {
return array_merge($so, $result);
}
// check for failure
$result = $response->createFailure($id);
if ($result !== null) {
$type = $result['type'] ?? 'unknownError';
$description = $result['description'] ?? 'An unknown error occurred during collection creation.';
throw new Exception("$type: $description", 1);
}
// return null if creation failed without failure reason
return null;
}
/**
* modify collection in remote storage
*
* @since Release 1.0.0
*
*/
public function collectionModify(string $identifier, array $so): ?array {
// convert entity
$to = new NodeParametersRequest();
$to->parametersRaw($so);
// construct request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($identifier, $to);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// check for success
$result = $response->updateSuccess($identifier);
if ($result !== null) {
return array_merge($so, $result);
}
// check for failure
$result = $response->updateFailure($identifier);
if ($result !== null) {
$type = $result['type'] ?? 'unknownError';
$description = $result['description'] ?? 'An unknown error occurred during collection modification.';
throw new Exception("$type: $description", 1);
}
// return null if modification failed without failure reason
return null;
}
/**
* delete collection in remote storage
*
* @since Release 1.0.0
*
*/
public function collectionDestroy(string $identifier, bool $force = false, bool $recursive = false): ?string {
// construct request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->delete($identifier);
if ($force) {
$r0->destroyContents(true);
}
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// check for success
$result = $response->deleteSuccess($identifier);
if ($result !== null) {
return (string)$result['id'];
}
// check for failure
$result = $response->deleteFailure($identifier);
if ($result !== null) {
$type = $result['type'] ?? 'unknownError';
$description = $result['description'] ?? 'An unknown error occurred during collection deletion.';
throw new Exception("$type: $description", 1);
}
// return null if deletion failed without failure reason
return null;
}
/**
* retrieve entities from remote storage
*
* @since Release 1.0.0
*/
public function entityList(?string $location = null, IFilter|null $filter = null, ISort|null $sort = null, IRange|null $range = null, string|null $granularity = null): array {
// construct request
$r0 = new NodeQuery($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
// define location
if (!empty($location)) {
$r0->filter()->in($location);
}
// define filter
if ($filter !== null) {
foreach ($filter->conditions() as $condition) {
$value = $condition['value'];
match($condition['attribute']) {
'any' => $r0->filter()->text($value),
'in' => $r0->filter()->in($value),
'label' => $r0->filter()->labelMatches($value),
'format' => $r0->filter()->formatIs($value),
default => null
};
}
}
// define order
if ($sort !== null) {
foreach ($sort->conditions() as $condition) {
$direction = $condition['direction'];
match($condition['attribute']) {
'type' => $r0->sort()->type($direction),
default => null
};
}
}
// define range
if ($range !== null) {
if ($range instanceof RangeTally && $range->getAnchor() === RangeAnchorType::ABSOLUTE) {
$r0->limitAbsolute($range->getPosition(), $range->getTally());
}
if ($range instanceof RangeTally && $range->getAnchor() === RangeAnchorType::RELATIVE) {
$r0->limitRelative($range->getPosition(), $range->getTally());
}
}
// construct get request
$r1 = new NodeGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
// set target to query request
//$r1->targetFromRequest($r0, '/ids');
if (!empty($location)) {
$r1->target($location);
}
// transmit request and receive response
$bundle = $this->dataStore->perform([$r1]);
//$bundle = $this->dataStore->perform([$r0, $r1]);
// extract response
$response = $bundle->response(0);
//$response = $bundle->response(1);
// convert json objects to message objects
$state = $response->state();
$list = $response->objects();
foreach ($list as $id => $entry) {
if (!$entry instanceof NodeParametersResponse) {
continue;
}
$list[$id] = $entry->parametersRaw();
}
// return message collection
return ['list' => $list, 'state' => $state];
}
/**
* fresh instance of object filter
*
* @since Release 1.0.0
*/
public function entityListFilter(): Filter {
return new Filter(self::ENTITY_FILTER_ATTRIBUTES);
}
/**
* fresh instance of object sort
*
* @since Release 1.0.0
*/
public function entityListSort(): Sort {
return new Sort(self::ENTITY_SORT_ATTRIBUTES);
}
/**
* fresh instance of object range
*
* @since Release 1.0.0
*/
public function entityListRange(): RangeTally {
return new RangeTally();
}
/**
* check existence of entities in remote storage
*
* @since Release 1.0.0
*/
public function entityExtant(string ...$identifiers): array {
$extant = [];
// construct request
$r0 = new NodeGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->target(...$identifiers);
$r0->property('id');
// transmit request and receive response
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// convert json objects to message objects
foreach ($response->objects() as $so) {
if (!$so instanceof NodeParametersResponse) {
continue;
}
$extant[$so->id()] = true;
}
return $extant;
}
/**
* delta for entities in remote storage
*
* @since Release 1.0.0
*
* @return Delta
*/
public function entityDelta(?string $location, string $state, string $granularity = 'D'): Delta {
if (empty($state)) {
$results = $this->entityList($location, null, null, null, 'B');
$delta = new Delta();
$delta->signature = $results['state'];
foreach ($results['list'] as $entry) {
$delta->additions[] = $entry['id'];
}
return $delta;
}
if (empty($location)) {
return $this->entityDeltaDefault($state, $granularity);
} else {
return $this->entityDeltaSpecific($location, $state, $granularity);
}
}
/**
* delta of changes for specific collection in remote storage
*
* @since Release 1.0.0
*
*/
public function entityDeltaSpecific(?string $location, string $state, string $granularity = 'D'): Delta {
// construct set request
$r0 = new NodeQueryChanges($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
// set location constraint
if (!empty($location)) {
$r0->filter()->in($location);
}
// set state constraint
if (!empty($state)) {
$r0->state($state);
} else {
$r0->state('0');
}
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// convert jmap object to delta object
$delta = new Delta();
$delta->signature = $response->stateNew();
$delta->additions = new DeltaCollection(array_column($response->added(), 'id'));
$delta->modifications = new DeltaCollection([]);
$delta->deletions = new DeltaCollection(array_column($response->removed(), 'id'));
return $delta;
}
/**
* delta of changes in remote storage
*
* @since Release 1.0.0
*
*/
public function entityDeltaDefault(string $state, string $granularity = 'D'): Delta {
// construct set request
$r0 = new NodeQueryChanges($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
// set state constraint
if (!empty($state)) {
$r0->state($state);
} else {
$r0->state('');
}
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// convert jmap object to delta object
$delta = new Delta();
$delta->signature = $response->stateNew();
$delta->additions = new DeltaCollection(array_column($response->added(), 'id'));
$delta->modifications = new DeltaCollection([]);
$delta->deletions = new DeltaCollection(array_column($response->removed(), 'id'));
return $delta;
}
/**
* retrieve entity from remote storage
*
* @since Release 1.0.0
*/
public function entityFetch(string ...$identifiers): ?array {
// construct request
$r0 = new NodeGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->target(...$identifiers);
// transmit request and receive response
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// convert json objects to message objects
$list = [];
foreach ($response->objects() as $so) {
if (!$so instanceof NodeParametersResponse) {
continue;
}
$id = $so->id();
$list[$id] = $so->parametersRaw();
$list[$id]['signature'] = $response->state();
}
// return message collection
return $list;
}
/**
* create entity in remote storage
*
* @since Release 1.0.0
*/
public function entityCreate(string $location, array $so): ?array {
// convert entity
$to = new NodeParametersRequest();
$to->parametersRaw($so);
$to->in($location);
$id = uniqid();
// construct request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->create($id, $to);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// check for success
$result = $response->createSuccess($id);
if ($result !== null) {
return array_merge($so, $result);
}
// check for failure
$result = $response->createFailure($id);
if ($result !== null) {
$type = $result['type'] ?? 'unknownError';
$description = $result['description'] ?? 'An unknown error occurred during collection creation.';
throw new Exception("$type: $description", 1);
}
// return null if creation failed without failure reason
return null;
}
/**
* update entity in remote storage
*
* @since Release 1.0.0
*/
public function entityModify(array $so): ?array {
// extract entity id
$id = $so['id'];
// convert entity
$to = new NodeParametersRequest();
$to->parametersRaw($so);
// construct request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($id, $to);
// transmit request and receive response
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// determine if command succeeded
if (array_key_exists($id, $response->updated())) {
// update entity
$ro = $response->updated()[$id];
$so = array_merge($so, $ro);
return $so;
}
return null;
}
/**
* delete entity from remote storage
*
* @since Release 1.0.0
*/
public function entityDelete(string $id): ?string {
// construct set request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
// construct object
$r0->delete($id);
// transmit request and receive response
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// determine if command succeeded
if (array_search($id, $response->deleted()) !== false) {
return $response->stateNew();
}
return null;
}
/**
* copy entity in remote storage
*
* @since Release 1.0.0
*
*/
public function entityCopy(string $location, MailMessageObject $so): ?MailMessageObject {
return null;
}
/**
* move entity in remote storage
*
* @since Release 1.0.0
*
*/
public function entityMove(string $location, array $so): ?array {
// extract entity id
$id = $so['id'];
// construct request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($id)->in($location);
// transmit request and receive response
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// determine if command succeeded
if (array_key_exists($id, $response->updated())) {
$so = array_merge($so, ['mailboxIds' => [$location => true]]);
return $so;
}
return null;
}
}
+306 -145
View File
@@ -11,8 +11,6 @@ namespace KTXM\ProviderJmapc\Service\Remote;
use Exception; use Exception;
use JmapClient\Client; use JmapClient\Client;
use JmapClient\Requests\Blob\BlobGet;
use JmapClient\Requests\Blob\BlobSet;
use JmapClient\Requests\Mail\MailboxGet; use JmapClient\Requests\Mail\MailboxGet;
use JmapClient\Requests\Mail\MailboxParameters as MailboxParametersRequest; use JmapClient\Requests\Mail\MailboxParameters as MailboxParametersRequest;
use JmapClient\Requests\Mail\MailboxQuery; use JmapClient\Requests\Mail\MailboxQuery;
@@ -26,15 +24,15 @@ use JmapClient\Requests\Mail\MailQueryChanges;
use JmapClient\Requests\Mail\MailSet; use JmapClient\Requests\Mail\MailSet;
use JmapClient\Requests\Mail\MailSubmissionSet; use JmapClient\Requests\Mail\MailSubmissionSet;
use JmapClient\Responses\Mail\MailboxParameters as MailboxParametersResponse; use JmapClient\Responses\Mail\MailboxParameters as MailboxParametersResponse;
use JmapClient\Responses\Mail\MailPart;
use JmapClient\Responses\Mail\MailParameters as MailParametersResponse; use JmapClient\Responses\Mail\MailParameters as MailParametersResponse;
use JmapClient\Responses\ResponseException; use JmapClient\Responses\ResponseException;
use KTXF\Resource\BinaryResource;
use KTXF\Resource\Delta\Delta; use KTXF\Resource\Delta\Delta;
use KTXF\Resource\Delta\DeltaCollection; use KTXF\Resource\Delta\DeltaCollection;
use KTXF\Resource\Filter\Filter; use KTXF\Resource\Filter\Filter;
use KTXF\Resource\Filter\IFilter; use KTXF\Resource\Filter\IFilter;
use KTXF\Resource\Range\IRange; use KTXF\Resource\Range\IRange;
use KTXF\Resource\Range\IRangeTally;
use KTXF\Resource\Range\Range;
use KTXF\Resource\Range\RangeAnchorType; use KTXF\Resource\Range\RangeAnchorType;
use KTXF\Resource\Range\RangeTally; use KTXF\Resource\Range\RangeTally;
use KTXF\Resource\Sort\ISort; use KTXF\Resource\Sort\ISort;
@@ -495,6 +493,103 @@ class RemoteMailService {
return new RangeTally(); return new RangeTally();
} }
/**
* retrieve entity from remote storage
*
* @since Release 1.0.0
*/
public function entityFetch(string ...$identifiers): ?array {
// construct request
$r0 = new MailGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->target(...$identifiers);
// select properties to return
$r0->property(...$this->defaultMailProperties);
$r0->bodyAll(true);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// convert json objects to message objects
$list = [];
foreach ($response->objects() as $so) {
if (!$so instanceof MailParametersResponse) {
continue;
}
$id = $so->id();
$list[$id] = $so->parametersRaw();
$list[$id]['signature'] = $response->state();
}
// return message collection
return $list;
}
public function entityDownload(string $identifier, string|null $blobId = null): BinaryResource {
// construct request
$r0 = new MailGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->target($identifier);
// select properties to return
$r0->property(...['id', 'blobId', 'bodyStructure']);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
$parameters = $response->object(0);
if (!$parameters instanceof MailParametersResponse) {
throw new Exception('Unexpected response type received from server.', 1);
}
if ($blobId === null) {
$blobId = $parameters->blob();
$filename = 'message.eml';
$mimeType = 'text/plain';
} else {
$walk = function (?MailPart $part) use (&$walk, $blobId): ?MailPart {
if ($part === null) {
return null;
}
if ($part->blob() === $blobId) {
return $part;
}
foreach ($part->parts() ?? [] as $subPart) {
$subPartResult = $walk($subPart);
if ($subPartResult !== null) {
return $subPartResult;
}
}
return null;
};
$part = $walk($parameters->bodyPartStructure());
$filename = $part->name() ?? 'file.bin';
$mimeType = $part->type() ?? 'application/octet-stream';
}
$streamResource = $this->dataStore->downloadStream($this->dataAccount, $blobId, $mimeType, $filename);
$stream = (function () use ($streamResource): \Generator {
try {
while (!$streamResource->eof()) {
$chunk = $streamResource->read(8192);
if ($chunk === '' && !$streamResource->eof()) {
throw new Exception('Unable to read from download stream.', 1);
}
if ($chunk !== '') {
yield $chunk;
}
}
} finally {
$streamResource->close();
}
})();
return new BinaryResource($filename, $mimeType, $stream);
}
/** /**
* check existence of entities in remote storage * check existence of entities in remote storage
* *
@@ -623,34 +718,8 @@ class RemoteMailService {
return $delta; return $delta;
} }
/** public function entityFresh(): MailParametersRequest {
* retrieve entity from remote storage return new MailParametersRequest();
*
* @since Release 1.0.0
*/
public function entityFetch(string ...$identifiers): ?array {
// construct request
$r0 = new MailGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->target(...$identifiers);
// select properties to return
$r0->property(...$this->defaultMailProperties);
$r0->bodyAll(true);
// transmit request and receive response
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// convert json objects to message objects
$list = [];
foreach ($response->objects() as $so) {
if (!$so instanceof MailParametersResponse) {
continue;
}
$id = $so->id();
$list[$id] = $so->parametersRaw();
$list[$id]['signature'] = $response->state();
}
// return message collection
return $list;
} }
/** /**
@@ -709,7 +778,7 @@ class RemoteMailService {
// construct request // construct request
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel); $r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($id, $to); $r0->update($id, $to);
// transmit request and receive response // transceive
$bundle = $this->dataStore->perform([$r0]); $bundle = $this->dataStore->perform([$r0]);
// extract response // extract response
$response = $bundle->response(0); $response = $bundle->response(0);
@@ -723,25 +792,109 @@ class RemoteMailService {
return null; return null;
} }
public function entityPatch(MailParametersRequest $properties, string ...$identifiers): ?array {
// construct request
$r0 = new MailSet($this->dataAccount);
foreach ($identifiers as $id) {
$r0->patch($id, $properties);
}
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->first();
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
$results = [];
// check for success
foreach ($response->updateSuccesses() as $id => $data) {
$results[$id] = true;
}
// check for failure
foreach ($response->updateFailures() as $id => $data) {
$results[$id] = $data['type'] ?? 'unknownError';
}
return $results;
}
/** /**
* delete entity from remote storage * delete entities from remote storage
* *
* @since Release 1.0.0 * @since Release 1.0.0
*/ */
public function entityDelete(string $id): ?string { public function entityDelete(string ...$identifiers): array {
// construct set request // construct set request
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel); $r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
// construct object foreach ($identifiers as $id) {
$r0->delete($id); $r0->delete($id);
// transmit request and receive response }
// transceive
$bundle = $this->dataStore->perform([$r0]); $bundle = $this->dataStore->perform([$r0]);
// extract response // extract response
$response = $bundle->response(0); $response = $bundle->response(0);
// determine if command succeeded // check for command error
if (array_search($id, $response->deleted()) !== false) { if ($response instanceof ResponseException) {
return $response->stateNew(); if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
} }
return null;
$results = [];
// check for success
foreach ($response->deleteSuccesses() as $id) {
$results[$id] = true;
}
// check for failure
foreach ($response->deleteFailures() as $id => $data) {
$results[$id] = $data['type'] ?? 'unknownError';
}
return $results;
}
/**
* move entity in remote storage
*
* @since Release 1.0.0
*/
public function entityMove(string $target, string ...$identifiers): array {
// construct request
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
foreach ($identifiers as $id) {
$r0->update($id)->in($target);
}
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->first();
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
$results = [];
// check for success
foreach ($response->updateSuccesses() as $identifier => $data) {
$results[$identifier] = true;
}
// check for failure
foreach ($response->updateFailures() as $identifier => $data) {
$results[$identifier] = $data['type'] ?? 'unknownError';
}
return $results;
} }
/** /**
@@ -750,128 +903,136 @@ class RemoteMailService {
* @since Release 1.0.0 * @since Release 1.0.0
* *
*/ */
public function entityCopy(string $location, MailMessageObject $so): ?MailMessageObject { public function entityCopy(string $target, string ...$identifiers): array {
return null; return [];
} }
/** /**
* move entity in remote storage * Submit a fresh message by creating it as a draft and then creating a submission.
*
* @since Release 1.0.0
* *
* @since Release 2.0.0
*/ */
public function entityMove(string $location, array $so): ?array { public function entitySubmitFresh(string $identityId, array $message, string $preSendTarget, string $postSentTarget): string {
// extract entity id
$id = $so['id']; $mail = new MailParametersRequest();
// construct request $mail->parametersRaw($message);
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($id)->in($location); $messageCreateId = 'm_' . uniqid();
// transmit request and receive response $submissionCreateId = 's_' . uniqid();
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// determine if command succeeded
if (array_key_exists($id, $response->updated())) {
$so = array_merge($so, ['mailboxIds' => [$location => true]]);
return $so;
}
return null;
}
/**
* send entity
*
* @since Release 1.0.0
*
*/
public function entitySend(string $identity, MailMessageObject $message, ?string $presendLocation = null, ?string $postsendLocation = null): string {
// determine if pre-send location is present
if ($presendLocation === null || empty($presendLocation)) {
throw new Exception('Pre-Send Location is missing', 1);
}
// determine if post-send location is present
if ($postsendLocation === null || empty($postsendLocation)) {
throw new Exception('Post-Send Location is missing', 1);
}
// determine if we have the basic required data and fail otherwise
if (empty($message->getFrom())) {
throw new Exception('Missing Requirements: Message MUST have a From address', 1);
}
if (empty($message->getTo())) {
throw new Exception('Missing Requirements: Message MUST have a To address(es)', 1);
}
// determine if message has attachments
if (count($message->getAttachments()) > 0) {
// process attachments first
$message = $this->depositAttachmentsFromMessage($message);
}
// convert from address object to string
$from = $message->getFrom()->getAddress();
// convert to, cc and bcc address object arrays to single strings array
$to = array_map(
function ($entry) { return $entry->getAddress(); },
array_merge($message->getTo(), $message->getCc(), $message->getBcc())
);
unset($cc, $bcc);
// construct set request
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel); $r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->create('1', $message)->in($presendLocation); $createdMessage = $r0->create($messageCreateId, $mail);
// construct set request $createdMessage->in($preSendTarget);
$r1 = new MailSubmissionSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel); $r1 = new MailSubmissionSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
// construct envelope $submission = $r1->create($submissionCreateId);
$e1 = $r1->create('2'); $submission->identity($identityId);
$e1->identity($identity); $submission->message('#' . $messageCreateId);
$e1->message('#1');
$e1->from($from);
$e1->to($to);
// transmit request and receive response
$bundle = $this->dataStore->perform([$r0, $r1]); $bundle = $this->dataStore->perform([$r0, $r1]);
// extract response $messageResponse = $bundle->response(0);
$response = $bundle->response(1); if ($messageResponse instanceof ResponseException) {
// return collection information throw new Exception($messageResponse->type() . ': ' . $messageResponse->description(), 1);
return (string)$response->created()['2']['id']; }
} if (method_exists($messageResponse, 'createFailure')) {
$failure = $messageResponse->createFailure($messageCreateId);
/** if (is_array($failure)) {
* retrieve collection entity attachment from remote storage $type = $failure['type'] ?? 'unknownError';
* $description = $failure['description'] ?? 'Email creation failed';
* @since Release 1.0.0 throw new Exception($type . ': ' . $description, 1);
*
*/
public function depositAttachmentsFromMessage(MailMessageObject $message): MailMessageObject {
$parameters = $message->toJmap();
$attachments = $message->getAttachments();
$matches = [];
$this->findAttachmentParts($parameters['bodyStructure'], $matches);
foreach ($attachments as $attachment) {
$part = $attachment->toJmap();
if (isset($matches[$part->getId()])) {
// deposit attachment in data store
$response = $this->blobDeposit($account, $part->getType(), $attachment->getContents());
// transfer blobId and size to mail part
$matches[$part->getId()]->blobId = $response['blobId'];
$matches[$part->getId()]->size = $response['size'];
unset($matches[$part->getId()]->partId);
} }
} }
return (new MailMessageObject())->fromJmap($parameters); $response = $bundle->response(1);
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
}
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
return $this->extractSubmissionIdentifier($response, $submissionCreateId);
} }
protected function findAttachmentParts(object &$part, array &$matches) { /**
* Upload attachment content and return its JMAP blob identifier.
if ($part->disposition === 'attachment' || $part->disposition === 'inline') { */
$matches[$part->partId] = $part; public function blobDeposit(string $type, string $data): string {
$response = json_decode($this->dataStore->upload($this->dataAccount, $type, $data), true);
if (!is_array($response) || !isset($response['blobId']) || !is_string($response['blobId']) || $response['blobId'] === '') {
throw new Exception('JMAP attachment upload did not return a blob identifier', 1);
} }
foreach ($part->subParts as $entry) { return $response['blobId'];
$this->findAttachmentParts($entry, $matches); }
/**
* Submit an existing draft message.
*
* @since Release 2.0.0
*/
public function entitySubmitDraft(string $identityId, string $draftId, ?array $patch = null): string {
if ($draftId === '') {
throw new Exception('Draft identifier is required for draft submission', 1);
} }
$requests = [];
if ($patch !== null && $patch !== []) {
$draftMutation = new MailParametersRequest();
$draftMutation->parametersRaw($patch);
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($draftId, $draftMutation);
$requests[] = $r0;
}
$submissionCreateId = 's_' . uniqid();
$r1 = new MailSubmissionSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$submission = $r1->create($submissionCreateId);
$submission->identity($identityId);
$submission->message($draftId);
$requests[] = $r1;
$bundle = $this->dataStore->perform($requests);
$responseIndex = count($requests) - 1;
$response = $bundle->response($responseIndex);
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
}
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
return $this->extractSubmissionIdentifier($response, $submissionCreateId);
}
private function collectionByRole(string $role): ?string {
$filter = $this->collectionListFilter();
$filter->condition('role', $role);
$collections = $this->collectionList(null, $filter, null);
if ($collections === []) {
return null;
}
return (string)array_key_first($collections);
}
private function extractSubmissionIdentifier(object $response, string $createId): string {
if (method_exists($response, 'createSuccess')) {
$success = $response->createSuccess($createId);
if (is_array($success) && isset($success['id'])) {
return (string)$success['id'];
}
}
if (method_exists($response, 'created')) {
$created = $response->created();
if (is_array($created) && isset($created[$createId]['id'])) {
return (string)$created[$createId]['id'];
}
}
throw new Exception('Submission succeeded without a returned identifier', 1);
} }
/** /**
+45 -20
View File
@@ -9,17 +9,18 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Service\Remote; namespace KTXM\ProviderJmapc\Service\Remote;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Psr7\HttpFactory;
use JmapClient\Authentication\Basic; use JmapClient\Authentication\Basic;
use JmapClient\Authentication\Bearer;
use JmapClient\Authentication\JsonBasic;
use JmapClient\Authentication\JsonBasicCookie;
use JmapClient\Client as JmapClient; use JmapClient\Client as JmapClient;
use KTXF\Resource\Provider\ResourceServiceBaseInterface; use KTXF\Security\Crypto;
use KTXF\Resource\Provider\ResourceServiceIdentityBasic; use KTXF\Resource\Provider\ResourceServiceIdentityBasic;
use KTXF\Resource\Provider\ResourceServiceIdentityBearer;
use KTXF\Resource\Provider\ResourceServiceIdentityOAuth;
use KTXF\Resource\Provider\ResourceServiceLocationUri; use KTXF\Resource\Provider\ResourceServiceLocationUri;
use KTXM\ProviderJmapc\Providers\Mail\Service; use KTXM\ProviderJmapc\Providers\Mail\Service as MailService;
use KTXM\ProviderJmapc\Providers\Contacts\Service as ContactsService;
use KTXM\ProviderJmapc\Providers\Events\Service as EventsService;
use KTXM\ProviderJmapc\Providers\Tasks\Service as TasksService;
use KTXM\ProviderJmapc\Providers\Document\Service as FilesService;
use KTXM\ProviderJmapc\Service\Remote\FM\RemoteContactsServiceFM; use KTXM\ProviderJmapc\Service\Remote\FM\RemoteContactsServiceFM;
use KTXM\ProviderJmapc\Service\Remote\FM\RemoteCoreServiceFM; use KTXM\ProviderJmapc\Service\Remote\FM\RemoteCoreServiceFM;
use KTXM\ProviderJmapc\Service\Remote\FM\RemoteEventsServiceFM; use KTXM\ProviderJmapc\Service\Remote\FM\RemoteEventsServiceFM;
@@ -33,11 +34,8 @@ class RemoteService {
* *
* @since Release 1.0.0 * @since Release 1.0.0
*/ */
public static function freshClient(Service $service): JmapClient { public static function freshClient(MailService|FilesService $service): JmapClient {
// defaults
$client = new JmapClient();
$client->setTransportAgent(self::$clientTransportAgent);
$location = $service->getLocation(); $location = $service->getLocation();
$identity = $service->getIdentity(); $identity = $service->getIdentity();
@@ -45,12 +43,23 @@ class RemoteService {
if ($location instanceof ResourceServiceLocationUri === false) { if ($location instanceof ResourceServiceLocationUri === false) {
throw new \InvalidArgumentException('Service location is not a valid URI'); throw new \InvalidArgumentException('Service location is not a valid URI');
} }
// The JMAP client accepts transport abstractions only. Guzzle supplies the
// PSR-18 client, while HttpFactory supplies both required PSR-17 factories.
$httpFactory = new HttpFactory();
$client = new JmapClient(
transportClient: new HttpClient([
'verify' => $location->getVerifyPeer(),
]),
requestFactory: $httpFactory,
streamFactory: $httpFactory,
);
$client->setTransportAgent(self::$clientTransportAgent);
$client->configureTransportMode($location->getScheme()); $client->configureTransportMode($location->getScheme());
$client->setHost($location->getHost() . ':' . $location->getPort()); $client->setHost($location->getHost() . ':' . $location->getPort());
if (!empty($location->getPath())) { if (!empty($location->getPath())) {
$client->setDiscoveryPath($location->getPath()); $client->setDiscoveryPath($location->getPath());
} }
$client->configureTransportVerification((bool)$location->getVerifyPeer());
// authentication // authentication
if (($identity instanceof ResourceServiceIdentityBasic) === false) { if (($identity instanceof ResourceServiceIdentityBasic) === false) {
throw new \InvalidArgumentException('Service identity is not a valid Basic or Bearer authentication'); throw new \InvalidArgumentException('Service identity is not a valid Basic or Bearer authentication');
@@ -64,10 +73,13 @@ class RemoteService {
} }
// debugging // debugging
if ($service->getDebug()) { if ($service->getDebug()) {
$logDirectory = dirname(__DIR__, 5) . '/var/logs/jmap';
if (!is_dir($logDirectory) && !mkdir($logDirectory, 0775, true) && !is_dir($logDirectory)) {
throw new \RuntimeException(sprintf('Unable to create JMAP log directory: %s', $logDirectory));
}
$logFile = $logDirectory . '/' . $service->identifier() . '.json';
$client->configureTransportLogState(true); $client->configureTransportLogState(true);
$client->configureTransportLogLocation( $client->configureTransportLogLocation($logFile);
sys_get_temp_dir() . '/' . $location->getHost() . '-' . $identity->getIdentity() . '.log'
);
} }
// return // return
return $client; return $client;
@@ -98,7 +110,7 @@ class RemoteService {
} }
// construct service based on capabilities // construct service based on capabilities
if ($Client->sessionCapable('https://www.fastmail.com/dev/user', false)) { if ($Client->sessionCapable('https://www.fastmail.com/dev/user', false)) {
$service = new RemoteCoreServiceFM(); //$service = new RemoteCoreServiceFM();
} else { } else {
$service = new RemoteCoreService(); $service = new RemoteCoreService();
} }
@@ -176,7 +188,22 @@ class RemoteService {
return $service; return $service;
} }
public static function cookieStoreRetrieve(mixed $id): ?array { /**
* Appropriate Documents Service for Connection
*
* @since Release 1.0.0
*/
public static function documentsService(JmapClient $Client, ?string $dataAccount = null): RemoteFilesService {
// determine if client is connected
if (!$Client->sessionStatus()) {
$Client->connect();
}
$service = new RemoteFilesService();
$service->initialize($Client, $dataAccount);
return $service;
}
public static function cookieStoreRetrieve(mixed $id, Crypto $crypto): ?array {
$file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . (string)$id . '.jmapc'; $file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . (string)$id . '.jmapc';
@@ -185,7 +212,6 @@ class RemoteService {
} }
$data = file_get_contents($file); $data = file_get_contents($file);
$crypto = \OC::$server->get(\OCP\Security\ICrypto::class);
$data = $crypto->decrypt($data); $data = $crypto->decrypt($data);
if (!empty($data)) { if (!empty($data)) {
@@ -196,13 +222,12 @@ class RemoteService {
} }
public static function cookieStoreDeposit(mixed $id, array $value): void { public static function cookieStoreDeposit(mixed $id, array $value, Crypto $crypto): void {
if (empty($value)) { if (empty($value)) {
return; return;
} }
$crypto = \OC::$server->get(\OCP\Security\ICrypto::class);
$data = $crypto->encrypt(json_encode($value)); $data = $crypto->encrypt(json_encode($value));
$file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . (string)$id . '.jmapc'; $file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . (string)$id . '.jmapc';
+7 -7
View File
@@ -91,7 +91,7 @@ class ServiceStore
/** /**
* Retrieve a single service by ID * Retrieve a single service by ID
*/ */
public function fetch(string $tenantId, string $userId, string|int $serviceId): ?Service public function fetch(string $tenantId, string $userId, string|int $serviceId): ?array
{ {
$document = $this->dataStore->selectCollection(self::COLLECTION_NAME)->findOne([ $document = $this->dataStore->selectCollection(self::COLLECTION_NAME)->findOne([
'tid' => $tenantId, 'tid' => $tenantId,
@@ -107,13 +107,13 @@ class ServiceStore
$document['identity']['secret'] = $this->crypto->decrypt($document['identity']['secret']); $document['identity']['secret'] = $this->crypto->decrypt($document['identity']['secret']);
} }
return (new Service())->fromStore($document); return $document;
} }
/** /**
* Create a new service * Create a new service
*/ */
public function create(string $tenantId, string $userId, Service $service): Service public function create(string $tenantId, string $userId, Service $service): array
{ {
$document = $service->toStore(); $document = $service->toStore();
@@ -129,15 +129,15 @@ class ServiceStore
$result = $this->dataStore->selectCollection(self::COLLECTION_NAME)->insertOne($document); $result = $this->dataStore->selectCollection(self::COLLECTION_NAME)->insertOne($document);
return (new Service())->fromStore($document); return $document;
} }
/** /**
* Modify an existing service * Modify an existing service
*/ */
public function modify(string $tenantId, string $userId, Service $service): Service public function modify(string $tenantId, string $userId, Service $service): array
{ {
$serviceId = $service->id(); $serviceId = $service->identifier();
if (empty($serviceId)) { if (empty($serviceId)) {
throw new \InvalidArgumentException('Service ID is required for update'); throw new \InvalidArgumentException('Service ID is required for update');
} }
@@ -159,7 +159,7 @@ class ServiceStore
['$set' => $document] ['$set' => $document]
); );
return (new Service())->fromStore($document); return $document;
} }
/** /**
+2082 -1104
View File
File diff suppressed because it is too large Load Diff
+9 -6
View File
@@ -18,18 +18,21 @@
"test:coverage": "vitest run --coverage --config tests/js/vitest.config.ts" "test:coverage": "vitest run --coverage --config tests/js/vitest.config.ts"
}, },
"dependencies": { "dependencies": {
"pinia": "^2.3.1", "pinia": "^4.0.0",
"vue": "^3.5.18", "vue": "^3.5.18",
"vue-router": "^4.5.1", "vue-router": "^5.0.0",
"vuetify": "^3.10.2" "vuetify": "^4.0.0"
}, },
"devDependencies": { "devDependencies": {
"@vitejs/plugin-vue": "^6.0.1", "@vitejs/plugin-vue": "^6.0.1",
"@vitest/coverage-v8": "^4.0.18", "@vitest/coverage-v8": "^4.0.18",
"@vitest/ui": "^4.0.18", "@vitest/ui": "^4.0.18",
"@vue/tsconfig": "^0.7.0", "@vue/test-utils": "^2.4.10",
"typescript": "~5.8.3", "@vue/tsconfig": "^0.9.0",
"vite": "^7.1.2", "jsdom": "^29.1.1",
"typescript": "~6.0.0",
"vite": "^8.0.0",
"vitest": "^4.0.18",
"vue-tsc": "^3.0.5" "vue-tsc": "^3.0.5"
} }
} }
+8 -1
View File
@@ -1,3 +1,10 @@
{ {
"$schema": "https://docs.renovatebot.com/renovate-schema.json" "$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": ["config:recommended"],
"enabledManagers": ["npm", "composer", "github-actions"],
"timezone": "UTC",
"schedule": ["* 0-3 * * *"],
"dependencyDashboard": true,
"prConcurrentLimit": 5,
"prHourlyLimit": 2
} }
@@ -1,506 +0,0 @@
<template>
<div class="jmap-config-panel">
<h3 class="text-h6 mb-4">Connection</h3>
<p class="text-body-2 mb-6">Enter your server and account information then press connect.</p>
<!-- Account Description -->
<v-text-field
v-model="accountLabel"
label="Account Description"
hint="Description for this Account"
persistent-hint
variant="outlined"
prepend-inner-icon="mdi-card-account-details"
class="mb-4"
:rules="[rules.required]"
/>
<!-- Authentication Type Selection -->
<div class="mb-4">
<label class="text-subtitle-2 mb-2 d-block">Authentication Type</label>
<v-btn-toggle
v-model="authType"
color="primary"
variant="outlined"
mandatory
divided
class="mb-4"
>
<v-btn value="BA">Basic</v-btn>
<v-btn value="OA">OAuth</v-btn>
<v-btn value="JB">Json Basic</v-btn>
</v-btn-toggle>
</div>
<!-- Basic Auth / Json Basic Auth Fields -->
<template v-if="authType === 'BA' || authType === 'JB'">
<v-text-field
v-model="bauthId"
label="Account ID"
hint="Authentication ID for your Account"
persistent-hint
variant="outlined"
prepend-inner-icon="mdi-account"
class="mb-4"
autocomplete="off"
autocorrect="off"
autocapitalize="none"
:rules="[rules.required]"
/>
<v-text-field
v-model="bauthSecret"
type="password"
label="Account Secret"
hint="Authentication secret for your Account"
persistent-hint
variant="outlined"
prepend-inner-icon="mdi-lock"
class="mb-4"
autocomplete="off"
autocorrect="off"
autocapitalize="none"
:rules="[rules.required]"
/>
</template>
<!-- OAuth Fields -->
<template v-if="authType === 'OA'">
<v-text-field
v-model="oauthId"
label="Account ID"
hint="Authentication ID for your Account"
persistent-hint
variant="outlined"
prepend-inner-icon="mdi-account"
class="mb-4"
autocomplete="off"
autocorrect="off"
autocapitalize="none"
:rules="[rules.required]"
/>
<v-text-field
v-model="oauthToken"
type="password"
label="Account Token"
hint="OAuth access token for your Account"
persistent-hint
variant="outlined"
prepend-inner-icon="mdi-key"
class="mb-4"
autocomplete="off"
autocorrect="off"
autocapitalize="none"
:rules="[rules.required]"
/>
</template>
<!-- Manual Configuration Toggle -->
<v-switch
v-model="configureManually"
label="Configure server manually"
color="primary"
class="mb-4"
/>
<!-- Manual Configuration Fields -->
<template v-if="!configureManually">
<v-text-field
v-model="sessionUrl"
label="JMAP Session URL"
hint="e.g., https://jmap.example.com/.well-known/jmap"
persistent-hint
variant="outlined"
prepend-inner-icon="mdi-link"
class="mb-4"
:rules="[rules.required, rules.url]"
/>
</template>
<template v-if="configureManually">
<v-text-field
v-model="serviceHost"
label="Service Address"
hint="Domain or IP Address"
persistent-hint
variant="outlined"
prepend-inner-icon="mdi-server"
class="mb-4"
autocomplete="off"
autocorrect="off"
autocapitalize="none"
:rules="[rules.required]"
/>
<div class="mb-4">
<label class="text-subtitle-2 mb-2 d-block">Service Protocol</label>
<v-btn-toggle
v-model="serviceProtocol"
color="primary"
variant="outlined"
mandatory
divided
>
<v-btn value="http">http</v-btn>
<v-btn value="https">https</v-btn>
</v-btn-toggle>
</div>
<v-switch
v-model="verifyPeer"
label="Secure Transport Verification (SSL Certificate Verification)"
color="primary"
class="mb-4"
hint="Should always be ON, unless connecting to a service over a secure internal network"
persistent-hint
/>
<v-text-field
v-model="servicePort"
label="Service Port"
hint="Leave empty for default. http (80) https (443)"
persistent-hint
variant="outlined"
prepend-inner-icon="mdi-numeric"
class="mb-4"
autocomplete="off"
autocorrect="off"
autocapitalize="none"
/>
<v-text-field
v-model="servicePath"
label="Service Path"
hint="Leave empty for default path (/.well-known/jmap)"
persistent-hint
variant="outlined"
prepend-inner-icon="mdi-folder"
class="mb-4"
autocomplete="off"
autocorrect="off"
autocapitalize="none"
/>
</template>
<!-- Advanced Settings -->
<v-expansion-panels class="mt-4">
<v-expansion-panel>
<v-expansion-panel-title>
<v-icon start>mdi-cog</v-icon>
Advanced Settings
</v-expansion-panel-title>
<v-expansion-panel-text>
<v-select
v-model="capabilities"
:items="jmapCapabilities"
label="Enabled Capabilities"
multiple
chips
variant="outlined"
hint="Select which JMAP capabilities to enable"
persistent-hint
/>
<v-text-field
v-model.number="timeout"
type="number"
label="Timeout (seconds)"
variant="outlined"
class="mt-4"
hint="Connection timeout in seconds"
persistent-hint
:min="5"
:max="300"
/>
<v-switch
v-model="verifyHost"
label="Verify SSL Hostname"
color="primary"
hint="Verify the certificate matches the hostname"
persistent-hint
/>
</v-expansion-panel-text>
</v-expansion-panel>
</v-expansion-panels>
<!-- Info Alert -->
<v-alert
type="info"
variant="tonal"
density="compact"
class="mt-4"
>
<template #prepend>
<v-icon>mdi-information</v-icon>
</template>
<div class="text-caption">
JMAP is a modern protocol for mail access. Most JMAP servers use
<code>/.well-known/jmap</code> for autodiscovery.
</div>
</v-alert>
</div>
</template>
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { ServiceLocationUri } from '@KTXM/MailManager/types/service'
// Types
interface ServiceConfiguration {
label?: string
auth?: 'BA' | 'OA' | 'JB'
bauth_id?: string
bauth_secret?: string
oauth_id?: string
oauth_access_token?: string
location_host?: string
location_protocol?: string
location_security?: boolean
location_port?: string
location_path?: string
}
const props = defineProps<{
modelValue?: ServiceLocationUri
discoveredLocation?: ServiceLocationUri
service?: ServiceConfiguration
}>()
const emit = defineEmits<{
'update:modelValue': [value: ServiceLocationUri]
'update:service': [value: ServiceConfiguration]
}>()
// Initialize from discovered location or create new
function buildSessionUrl(location?: ServiceLocationUri): string {
if (!location || location.type !== 'URI') return ''
const protocol = location.scheme || 'https'
const host = location.host || ''
const port = location.port || (protocol === 'https' ? 443 : 80)
const path = location.path || '/.well-known/jmap'
// Don't include port if it's the default for the protocol
const portStr = (protocol === 'https' && port === 443) || (protocol === 'http' && port === 80)
? ''
: `:${port}`
return `${protocol}://${host}${portStr}${path}`
}
function parseSessionUrl(url: string): ServiceLocationUri {
try {
const parsed = new URL(url)
return {
type: 'URI',
scheme: parsed.protocol.replace(':', '') as 'http' | 'https',
host: parsed.hostname,
port: parsed.port ? parseInt(parsed.port) : (parsed.protocol === 'https:' ? 443 : 80),
path: parsed.pathname || '/.well-known/jmap',
verifyPeer: verifyPeer.value,
verifyHost: verifyHost.value
}
} catch {
return {
type: 'URI',
scheme: 'https',
host: '',
port: 443,
path: '/.well-known/jmap',
verifyPeer: verifyPeer.value,
verifyHost: verifyHost.value
}
}
}
// Account configuration fields
const accountLabel = ref(props.service?.label || 'New Connection')
const authType = ref<'BA' | 'OA' | 'JB'>(props.service?.auth || 'BA')
const bauthId = ref(props.service?.bauth_id || '')
const bauthSecret = ref(props.service?.bauth_secret || '')
const oauthId = ref(props.service?.oauth_id || '')
const oauthToken = ref(props.service?.oauth_access_token || '')
// Manual configuration toggle and fields
const configureManually = ref(false)
const serviceHost = ref(props.service?.location_host || '')
const serviceProtocol = ref(props.service?.location_protocol || 'https')
const servicePort = ref(props.service?.location_port || '')
const servicePath = ref(props.service?.location_path || '')
// Local state - protocol settings only
const sessionUrl = ref(buildSessionUrl(props.modelValue || props.discoveredLocation))
const capabilities = ref<string[]>(['urn:ietf:params:jmap:mail'])
const timeout = ref(30)
const verifyPeer = ref(
props.service?.location_security ?? props.modelValue?.verifyPeer ?? props.discoveredLocation?.verifyPeer ?? true
)
const verifyHost = ref(
props.modelValue?.verifyHost ?? props.discoveredLocation?.verifyHost ?? true
)
// Validation rules
const rules = {
required: (value: any) => !!value || 'This field is required',
url: (value: string) => {
try {
new URL(value)
return true
} catch {
return 'Please enter a valid URL'
}
}
}
// Build location from current state
const currentLocation = computed((): ServiceLocationUri | null => {
if (configureManually.value) {
// Build from manual fields
if (!serviceHost.value) return null
const port = servicePort.value
? parseInt(servicePort.value)
: (serviceProtocol.value === 'https' ? 443 : 80)
return {
type: 'URI',
scheme: serviceProtocol.value as 'http' | 'https',
host: serviceHost.value,
port,
path: servicePath.value || '/.well-known/jmap',
verifyPeer: verifyPeer.value,
verifyHost: verifyHost.value
}
} else {
// Build from session URL
if (!sessionUrl.value) return null
return parseSessionUrl(sessionUrl.value)
}
})
// Build service configuration from current state
const currentService = computed((): ServiceConfiguration => {
return {
label: accountLabel.value,
auth: authType.value,
bauth_id: bauthId.value,
bauth_secret: bauthSecret.value,
oauth_id: oauthId.value,
oauth_access_token: oauthToken.value,
location_host: serviceHost.value,
location_protocol: serviceProtocol.value,
location_security: verifyPeer.value,
location_port: servicePort.value,
location_path: servicePath.value
}
})
// Emit location whenever it changes
watch(
[sessionUrl, serviceHost, serviceProtocol, servicePort, servicePath, verifyPeer, verifyHost, configureManually],
() => {
if (currentLocation.value) {
emit('update:modelValue', currentLocation.value)
}
},
{ immediate: true }
)
// Emit service configuration whenever it changes
watch(
[accountLabel, authType, bauthId, bauthSecret, oauthId, oauthToken, serviceHost, serviceProtocol, servicePort, servicePath, verifyPeer],
() => {
emit('update:service', currentService.value)
},
{ immediate: true }
)
// Update local state when props change
watch(
() => props.modelValue,
(newValue) => {
if (newValue) {
sessionUrl.value = buildSessionUrl(newValue)
verifyPeer.value = newValue.verifyPeer ?? true
verifyHost.value = newValue.verifyHost ?? true
}
}
)
watch(
() => props.discoveredLocation,
(newValue) => {
if (newValue && !props.modelValue) {
sessionUrl.value = buildSessionUrl(newValue)
verifyPeer.value = newValue.verifyPeer ?? true
verifyHost.value = newValue.verifyHost ?? true
}
},
{ immediate: true }
)
watch(
() => props.service,
(newValue) => {
if (newValue) {
accountLabel.value = newValue.label || 'New Connection'
authType.value = newValue.auth || 'BA'
bauthId.value = newValue.bauth_id || ''
bauthSecret.value = newValue.bauth_secret || ''
oauthId.value = newValue.oauth_id || ''
oauthToken.value = newValue.oauth_access_token || ''
serviceHost.value = newValue.location_host || ''
serviceProtocol.value = newValue.location_protocol || 'https'
servicePort.value = newValue.location_port || ''
servicePath.value = newValue.location_path || ''
verifyPeer.value = newValue.location_security ?? true
}
}
)
const jmapCapabilities = [
{ title: 'Mail', value: 'urn:ietf:params:jmap:mail' },
{ title: 'Contacts', value: 'urn:ietf:params:jmap:contacts' },
{ title: 'Calendars', value: 'urn:ietf:params:jmap:calendars' },
{ title: 'Tasks', value: 'urn:ietf:params:jmap:tasks' },
{ title: 'Notes', value: 'urn:ietf:params:jmap:notes' },
]
</script>
<style scoped>
.jmap-config-panel {
max-width: 800px;
}
code {
background-color: rgba(var(--v-theme-surface-variant), 0.3);
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
}
.text-h6 {
font-size: 1.25rem;
font-weight: 500;
line-height: 2rem;
letter-spacing: 0.0125em;
}
.text-subtitle-2 {
font-size: 0.875rem;
font-weight: 500;
line-height: 1.375rem;
letter-spacing: 0.00714em;
}
.text-body-2 {
font-size: 0.875rem;
font-weight: 400;
line-height: 1.25rem;
letter-spacing: 0.0178571429em;
color: rgba(var(--v-theme-on-surface), 0.7);
}
</style>
+235 -151
View File
@@ -1,15 +1,241 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import {
IdentityBasic,
IdentityOAuth,
IdentityToken,
} from '@KTXM/MailManager/models/identity'
import { ServiceObject } from '@KTXM/MailManager/models/service'
import type { ServiceIdentity } from '@KTXM/MailManager/types/service'
import type { ProviderAuthPanelProps, ProviderAuthPanelEmits } from '@KTXM/MailManager/types/integration'
const props = defineProps<ProviderAuthPanelProps>()
const emit = defineEmits<ProviderAuthPanelEmits>()
const authType = ref<'BA' | 'TA' | 'OA'>('BA')
const basicIdentity = ref('')
const basicSecret = ref('')
const bearerToken = ref('')
const oauthLoading = ref(false)
const oauthSuccess = ref(false)
const oauthAccessToken = ref('')
const oauthRefreshToken = ref('')
const rules = {
required: (value: unknown) => !!value || 'This field is required'
}
const isValid = computed(() => {
switch (authType.value) {
case 'BA':
return !!basicIdentity.value && !!basicSecret.value
case 'TA':
return !!bearerToken.value
case 'OA':
return oauthSuccess.value && !!oauthAccessToken.value
default:
return false
}
})
const currentIdentity = computed((): ServiceIdentity | null => {
if (!isValid.value) {
return null
}
switch (authType.value) {
case 'BA':
return {
type: 'BA',
identity: basicIdentity.value,
secret: basicSecret.value,
}
case 'TA':
return {
type: 'TA',
token: bearerToken.value,
}
case 'OA':
return {
type: 'OA',
accessToken: oauthAccessToken.value,
refreshToken: oauthRefreshToken.value || undefined,
accessScope: ['mail'],
accessExpiry: Math.floor(Date.now() / 1000) + 3600,
}
default:
return null
}
})
watch(
() => props.service,
service => {
syncFromService(service)
},
{ immediate: true }
)
watch(
() => props.emailAddress,
email => {
if (authType.value === 'BA' && email && !basicIdentity.value) {
basicIdentity.value = email
}
},
{ immediate: true }
)
watch(
currentIdentity,
identity => {
const existingIdentity = props.service?.identity?.toJson() ?? null
if (sameIdentity(existingIdentity, identity)) {
return
}
const nextService = props.service ?? new ServiceObject()
const nextIdentity = createIdentityModel(identity)
if (nextIdentity === null) {
nextService.identity = null
emit('update:service', nextService)
return
}
if (nextIdentity instanceof IdentityBasic && nextService.identity instanceof IdentityBasic) {
nextService.identity.identity = nextIdentity.identity
nextService.identity.secret = nextIdentity.secret
} else if (nextIdentity instanceof IdentityToken && nextService.identity instanceof IdentityToken) {
nextService.identity.token = nextIdentity.token
} else if (nextIdentity instanceof IdentityOAuth && nextService.identity instanceof IdentityOAuth) {
nextService.identity.accessToken = nextIdentity.accessToken
nextService.identity.accessScope = nextIdentity.accessScope
nextService.identity.accessExpiry = nextIdentity.accessExpiry
nextService.identity.refreshToken = nextIdentity.refreshToken
nextService.identity.refreshLocation = nextIdentity.refreshLocation
} else {
nextService.identity = nextIdentity
}
emit('update:service', nextService)
},
{ immediate: true, deep: true }
)
function syncFromService(service?: ServiceObject) {
const identity = service?.identity?.toJson() ?? null
if (!identity) {
authType.value = 'BA'
basicIdentity.value = props.prefilledIdentity || props.emailAddress || ''
basicSecret.value = props.prefilledSecret || ''
bearerToken.value = ''
oauthAccessToken.value = ''
oauthRefreshToken.value = ''
oauthSuccess.value = false
return
}
authType.value = identity.type as 'BA' | 'TA' | 'OA'
switch (identity.type) {
case 'BA':
basicIdentity.value = identity.identity || props.prefilledIdentity || props.emailAddress || ''
basicSecret.value = identity.secret || props.prefilledSecret || ''
bearerToken.value = ''
oauthAccessToken.value = ''
oauthRefreshToken.value = ''
oauthSuccess.value = false
break
case 'TA':
basicIdentity.value = props.prefilledIdentity || props.emailAddress || ''
basicSecret.value = props.prefilledSecret || ''
bearerToken.value = identity.token || ''
oauthAccessToken.value = ''
oauthRefreshToken.value = ''
oauthSuccess.value = false
break
case 'OA':
basicIdentity.value = props.prefilledIdentity || props.emailAddress || ''
basicSecret.value = props.prefilledSecret || ''
bearerToken.value = ''
oauthAccessToken.value = identity.accessToken || ''
oauthRefreshToken.value = identity.refreshToken || ''
oauthSuccess.value = !!identity.accessToken
break
}
}
function createIdentityModel(identity: ServiceIdentity | null) {
if (identity === null) {
return null
}
switch (identity.type) {
case 'BA':
return new IdentityBasic(identity.identity, identity.secret)
case 'TA':
return new IdentityToken(identity.token)
case 'OA':
return new IdentityOAuth(
identity.accessToken,
identity.accessScope,
identity.accessExpiry,
identity.refreshToken,
identity.refreshLocation
)
default:
return null
}
}
function sameIdentity(a: ServiceIdentity | null, b: ServiceIdentity | null): boolean {
if (a === null || b === null) {
return a === b
}
if (a.type !== b.type) {
return false
}
switch (a.type) {
case 'BA':
return b.type === 'BA'
&& a.identity === b.identity
&& a.secret === b.secret
case 'TA':
return b.type === 'TA'
&& a.token === b.token
case 'OA':
return b.type === 'OA'
&& a.accessToken === b.accessToken
&& a.refreshToken === b.refreshToken
default:
return false
}
}
async function initiateOAuth() {
oauthLoading.value = true
try {
throw new Error('OAuth implementation pending')
} catch (error) {
console.warn('[JMAP Auth Panel] OAuth implementation pending', error)
} finally {
oauthLoading.value = false
}
}
</script>
<template> <template>
<div class="jmap-auth-panel"> <div class="jmap-auth-panel">
<h3 class="text-h6 mb-4">Authentication</h3> <h3 class="text-h6 mb-4">Authentication</h3>
<p class="text-body-2 mb-6">Choose your authentication method and enter your credentials.</p> <p class="text-body-2 mb-6">Choose your authentication method and enter your credentials.</p>
<v-alert type="info" variant="tonal" class="mb-4"> <v-alert type="info" variant="tonal">
<template #prepend> JMAP supports multiple authentication methods. Choose the one your server uses.
<v-icon>mdi-information</v-icon>
</template>
<div class="text-caption">
JMAP supports multiple authentication methods. Choose the one your server uses.
</div>
</v-alert> </v-alert>
<!-- Authentication Type Selection --> <!-- Authentication Type Selection -->
@@ -48,7 +274,7 @@
variant="outlined" variant="outlined"
prepend-inner-icon="mdi-account" prepend-inner-icon="mdi-account"
class="mb-4" class="mb-4"
autocomplete="username" autocomplete="off"
autocorrect="off" autocorrect="off"
autocapitalize="none" autocapitalize="none"
:rules="[rules.required]" :rules="[rules.required]"
@@ -63,7 +289,7 @@
variant="outlined" variant="outlined"
prepend-inner-icon="mdi-lock" prepend-inner-icon="mdi-lock"
class="mb-4" class="mb-4"
autocomplete="current-password" autocomplete="new-password"
:rules="[rules.required]" :rules="[rules.required]"
/> />
</template> </template>
@@ -119,148 +345,6 @@
</div> </div>
</template> </template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { ServiceIdentity } from '@KTXM/MailManager/types/service'
import type { ProviderAuthPanelProps, ProviderAuthPanelEmits } from '@KTXM/MailManager/types/integration'
const props = defineProps<ProviderAuthPanelProps>()
const emit = defineEmits<ProviderAuthPanelEmits>()
// Auth method selection
const authType = ref<'BA' | 'TA' | 'OA'>('BA')
// Basic auth state
const basicIdentity = ref(props.prefilledIdentity || props.emailAddress || '')
const basicSecret = ref(props.prefilledSecret || '')
// Token auth state
const bearerToken = ref('')
// OAuth state
const oauthLoading = ref(false)
const oauthSuccess = ref(false)
const oauthAccessToken = ref('')
const oauthRefreshToken = ref('')
// Validation rules
const rules = {
required: (value: any) => !!value || 'This field is required'
}
// Validation
const isValid = computed(() => {
switch (authType.value) {
case 'BA':
return !!basicIdentity.value && !!basicSecret.value
case 'TA':
return !!bearerToken.value
case 'OA':
return oauthSuccess.value
default:
return false
}
})
// Build ServiceIdentity object
const currentIdentity = computed((): ServiceIdentity | null => {
if (!isValid.value) return null
switch (authType.value) {
case 'BA':
return {
type: 'BA',
identity: basicIdentity.value,
secret: basicSecret.value
}
case 'TA':
return {
type: 'TA',
token: bearerToken.value
}
case 'OA':
return {
type: 'OA',
accessToken: oauthAccessToken.value,
refreshToken: oauthRefreshToken.value,
accessScope: ['mail'],
accessExpiry: Date.now() + 3600000
}
default:
return null
}
})
// Watch and emit changes
watch(
currentIdentity,
(identity) => {
if (identity) {
emit('update:modelValue', identity)
}
},
{ immediate: true, deep: true }
)
watch(
isValid,
(valid) => {
emit('valid', valid)
},
{ immediate: true }
)
// Update local state if modelValue changes externally
watch(
() => props.modelValue,
(newValue) => {
if (newValue) {
authType.value = newValue.type as 'BA' | 'TA' | 'OA'
switch (newValue.type) {
case 'BA':
basicIdentity.value = newValue.identity || ''
basicSecret.value = newValue.secret || ''
break
case 'TA':
bearerToken.value = newValue.token || ''
break
case 'OA':
oauthAccessToken.value = newValue.accessToken || ''
oauthRefreshToken.value = newValue.refreshToken || ''
oauthSuccess.value = !!newValue.accessToken
break
}
}
}
)
// Prefill identity when email address is provided
watch(
() => props.emailAddress,
(email) => {
if (email && !basicIdentity.value) {
basicIdentity.value = email
}
},
{ immediate: true }
)
// OAuth flow (stub for now)
async function initiateOAuth() {
oauthLoading.value = true
try {
// TODO: Implement OAuth flow when backend is ready
emit('error', 'OAuth implementation pending')
throw new Error('OAuth implementation pending')
} catch (error: any) {
emit('error', error.message)
} finally {
oauthLoading.value = false
}
}
</script>
<style scoped> <style scoped>
.jmap-auth-panel { .jmap-auth-panel {
max-width: 800px; max-width: 800px;
+275
View File
@@ -0,0 +1,275 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ServiceObject } from '@KTXM/MailManager/models/service'
import { ServiceAddressObject } from '@KTXM/MailManager/models/address'
type AuxiliaryTab = 'addresses' | 'messages' | 'sync'
type DeleteMode = 'soft' | 'hard'
const props = defineProps<{
service?: ServiceObject
}>()
const emit = defineEmits<{
'update:service': [value: ServiceObject]
}>()
const activeTab = ref<AuxiliaryTab>('addresses')
const deleteMode = ref<DeleteMode>('soft')
const deleteDestination = ref('Trash')
const primaryAddress = ref<ServiceAddressObject>(new ServiceAddressObject())
const secondaryAddresses = ref<ServiceAddressObject[]>([])
const settingGroups = [
{
title: 'Addresses',
value: 'addresses' as const,
icon: 'mdi-at',
description: 'View the primary mailbox identity and sender aliases synced from the JMAP server.'
},
{
title: 'Messages',
value: 'messages' as const,
icon: 'mdi-email-outline',
description: 'Control how message actions should be translated to operations.'
},
{
title: 'Sync',
value: 'sync' as const,
icon: 'mdi-sync',
description: 'Reserved for future synchronization settings.'
},
]
const deleteModeOptions = [
{
title: 'Move to another mailbox',
value: 'soft' as const,
subtitle: 'Marks delete as a move operation and keeps the message in a destination mailbox.'
},
{
title: 'Permanently delete',
value: 'hard' as const,
subtitle: 'Removes the message immediately without moving it first.'
}
]
const destinationHint = computed(() => {
if (deleteMode.value === 'hard') {
return 'Not used when messages are deleted permanently.'
}
return 'Mailbox identifier or well-known role target, for example Trash.'
})
watch(
() => props.service,
service => {
syncFromService(service)
},
{ immediate: true }
)
watch(
[deleteMode, deleteDestination],
() => {
const nextService = props.service ?? new ServiceObject()
const nextAuxiliary = {
...(nextService.auxiliary ?? {}),
deleteMode: deleteMode.value,
deleteDestination: deleteMode.value === 'soft'
? normalizeDeleteDestination(deleteDestination.value)
: undefined,
}
if (sameAuxiliary(nextService.auxiliary ?? {}, nextAuxiliary)) {
return
}
nextService.auxiliary = nextAuxiliary
emit('update:service', nextService)
},
{ deep: true, immediate: true }
)
function syncFromService(service?: ServiceObject) {
const auxiliary = service?.auxiliary ?? {}
deleteMode.value = auxiliary.deleteMode === 'hard' ? 'hard' : 'soft'
deleteDestination.value = typeof auxiliary.deleteDestination === 'string' && auxiliary.deleteDestination.length > 0
? auxiliary.deleteDestination
: 'Trash'
primaryAddress.value = service?.primaryAddress ?? new ServiceAddressObject()
secondaryAddresses.value = service?.secondaryAddresses ?? []
}
function normalizeDeleteDestination(value: string): string {
const trimmedValue = value.trim()
return trimmedValue.length > 0 ? trimmedValue : 'Trash'
}
function sameAuxiliary(current: Record<string, any>, next: Record<string, any>): boolean {
return (current.deleteMode === 'hard' ? 'hard' : 'soft') === next.deleteMode
&& (current.deleteDestination ?? undefined) === (next.deleteDestination ?? undefined)
}
</script>
<template>
<div class="jmap-auxiliary-panel">
<div class="jmap-auxiliary-shell">
<v-tabs
v-model="activeTab"
direction="vertical"
color="primary"
class="jmap-auxiliary-tabs"
>
<v-tab
v-for="group in settingGroups"
:key="group.value"
:value="group.value"
class="justify-start"
>
<v-icon start>{{ group.icon }}</v-icon>
{{ group.title }}
</v-tab>
</v-tabs>
<v-window v-model="activeTab" class="flex-1-1">
<v-window-item value="addresses">
<div class="jmap-settings-card">
<h3 class="text-h6 mb-2">Addresses</h3>
<p class="text-body-2 text-medium-emphasis mb-6">
The primary mailbox identity and sender aliases are managed by the JMAP server and synced automatically.
</p>
<div class="text-subtitle-2 mb-2">Primary Address</div>
<div class="d-flex ga-2 mb-6">
<v-text-field
:model-value="primaryAddress.label"
label="Display Name"
variant="outlined"
density="compact"
hide-details="auto"
readonly
/>
<v-text-field
:model-value="primaryAddress.address"
label="Email Address"
variant="outlined"
density="compact"
prepend-inner-icon="mdi-email-outline"
hide-details="auto"
readonly
/>
</div>
<div class="text-subtitle-2 mb-2">Secondary Addresses</div>
<p v-if="secondaryAddresses.length === 0" class="text-body-2 text-medium-emphasis">
No aliases reported by the server.
</p>
<div
v-for="(entry, index) in secondaryAddresses"
:key="index"
class="d-flex ga-2 mb-2"
>
<v-text-field
:model-value="entry.label"
label="Display Name"
variant="outlined"
density="compact"
hide-details="auto"
readonly
/>
<v-text-field
:model-value="entry.address"
label="Email Address"
variant="outlined"
density="compact"
prepend-inner-icon="mdi-email-multiple-outline"
hide-details="auto"
readonly
/>
</div>
</div>
</v-window-item>
<v-window-item value="messages">
<div class="jmap-settings-card">
<h3 class="text-h6 mb-2">Message Deletion</h3>
<p class="text-body-2 text-medium-emphasis mb-6">
Choose how the mail system should react when a delete command is issued.
</p>
<v-radio-group
v-model="deleteMode"
color="primary"
class="mb-4"
>
<v-radio
v-for="option in deleteModeOptions"
:key="option.value"
:value="option.value"
>
<template #label>
<div>
<div class="text-body-1">{{ option.title }}</div>
<div class="text-caption text-medium-emphasis">{{ option.subtitle }}</div>
</div>
</template>
</v-radio>
</v-radio-group>
<v-text-field
v-model="deleteDestination"
label="Delete Destination"
variant="outlined"
prepend-inner-icon="mdi-folder-move-outline"
:disabled="deleteMode === 'hard'"
:hint="destinationHint"
persistent-hint
/>
</div>
</v-window-item>
<v-window-item value="sync">
<div class="jmap-settings-card">
<h3 class="text-h6 mb-2">Sync Settings</h3>
<p class="text-body-2 text-medium-emphasis mb-0">
Additional synchronization controls can be added here as the provider grows.
</p>
</div>
</v-window-item>
</v-window>
</div>
</div>
</template>
<style scoped>
.jmap-auxiliary-shell {
display: grid;
grid-template-columns: minmax(180px, 220px) minmax(0, 1fr);
gap: 24px;
align-items: start;
}
.jmap-auxiliary-tabs {
border-right: 1px solid rgba(var(--v-theme-outline), 0.16);
padding-right: 12px;
}
.jmap-settings-card {
padding: 4px 4px 4px 0;
}
@media (max-width: 768px) {
.jmap-auxiliary-shell {
grid-template-columns: 1fr;
}
.jmap-auxiliary-tabs {
border-right: 0;
border-bottom: 1px solid rgba(var(--v-theme-outline), 0.16);
padding-right: 0;
padding-bottom: 12px;
}
}
</style>
@@ -1,3 +1,198 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { LocationUri } from '@KTXM/MailManager/models/location'
import { ServiceObject } from '@KTXM/MailManager/models/service'
import type { ServiceLocationUri, ServiceLocation } from '@KTXM/MailManager/types/service'
import type { ProviderProtocolPanelProps, ProviderProtocolPanelEmits } from '@KTXM/MailManager/types/integration'
const props = defineProps<ProviderProtocolPanelProps>()
const emit = defineEmits<ProviderProtocolPanelEmits>()
const serviceLocationUrl = ref('')
const verifyPeer = ref(true)
const verifyHost = ref(true)
// Manual configuration toggle and fields
const configureManually = ref(false)
const serviceHost = ref('')
const serviceProtocol = ref<'http' | 'https'>('https')
const servicePort = ref('')
const servicePath = ref('')
// Validation rules
const rules = {
required: (value: any) => !!value || 'This field is required',
url: (value: string) => {
try {
new URL(value)
return true
} catch {
return 'Please enter a valid URL'
}
}
}
// Build location from current state
const currentLocation = computed((): ServiceLocationUri | null => {
if (configureManually.value) {
// Build from manual fields
if (!serviceHost.value) return null
const port = servicePort.value
? parseInt(servicePort.value)
: (serviceProtocol.value === 'https' ? 443 : 80)
return {
type: 'URI',
scheme: serviceProtocol.value,
host: serviceHost.value,
port,
path: servicePath.value || '/.well-known/jmap',
verifyPeer: verifyPeer.value,
verifyHost: verifyHost.value
}
} else {
// Build from session URL
if (!serviceLocationUrl.value) return null
return parseSessionUrl(serviceLocationUrl.value)
}
})
watch(
() => [props.service, props.discoveredLocation] as const,
([service, discoveredLocation]) => {
syncFromLocation(service?.location?.toJson() ?? discoveredLocation ?? null)
},
{ immediate: true }
)
watch(
currentLocation,
(location) => {
const existingLocation = props.service?.location?.toJson() ?? null
if (sameLocation(existingLocation, location)) {
return
}
const nextService = props.service ?? new ServiceObject()
if (location === null) {
nextService.location = null
emit('update:service', nextService)
return
}
if (nextService.location instanceof LocationUri) {
nextService.location.scheme = location.scheme
nextService.location.host = location.host
nextService.location.port = location.port
nextService.location.path = location.path
nextService.location.verifyPeer = location.verifyPeer ?? true
nextService.location.verifyHost = location.verifyHost ?? true
} else {
nextService.location = LocationUri.fromJson(location)
}
emit('update:service', nextService)
},
{ immediate: true }
)
function syncFromLocation(location: ServiceLocation | null) {
const uriLocation = getUriLocation(location)
serviceLocationUrl.value = buildSessionUrl(uriLocation)
verifyPeer.value = getUriVerifyPeer(uriLocation)
verifyHost.value = getUriVerifyHost(uriLocation)
serviceProtocol.value = uriLocation?.scheme === 'http' ? 'http' : 'https'
serviceHost.value = uriLocation?.host ?? ''
servicePort.value = normalizePort(uriLocation)
servicePath.value = uriLocation?.path ?? ''
}
function sameLocation(a: ServiceLocation | null, b: ServiceLocation | null): boolean {
if (a === null || b === null) {
return a === b
}
if (a.type !== 'URI' || b.type !== 'URI') {
return false
}
return a.scheme === b.scheme
&& a.host === b.host
&& a.port === b.port
&& (a.path ?? '') === (b.path ?? '')
&& getUriVerifyPeer(a) === getUriVerifyPeer(b)
&& getUriVerifyHost(a) === getUriVerifyHost(b)
}
function getUriLocation(location?: ServiceLocation | null): ServiceLocationUri | null {
return location?.type === 'URI' ? location : null
}
function normalizePort(location: ServiceLocationUri | null): string {
if (!location) {
return ''
}
const defaultPort = location.scheme === 'http' ? 80 : 443
return location.port === defaultPort ? '' : String(location.port)
}
// Helper to build session URL from location
function buildSessionUrl(location?: ServiceLocation | null): string {
if (!location || location.type !== 'URI') return ''
const protocol = location.scheme || 'https'
const host = location.host || ''
const port = location.port || (protocol === 'https' ? 443 : 80)
const path = location.path || '/.well-known/jmap'
// Don't include port if it's the default for the protocol
const portStr = (protocol === 'https' && port === 443) || (protocol === 'http' && port === 80)
? ''
: `:${port}`
return `${protocol}://${host}${portStr}${path}`
}
// Helper to parse session URL into location
function parseSessionUrl(url: string): ServiceLocationUri {
try {
const parsed = new URL(url)
return {
type: 'URI',
scheme: parsed.protocol.replace(':', '') as 'http' | 'https',
host: parsed.hostname,
port: parsed.port ? parseInt(parsed.port) : (parsed.protocol === 'https:' ? 443 : 80),
path: parsed.pathname || '/.well-known/jmap',
verifyPeer: verifyPeer.value,
verifyHost: verifyHost.value
}
} catch {
return {
type: 'URI',
scheme: 'https',
host: '',
port: 443,
path: '/.well-known/jmap',
verifyPeer: verifyPeer.value,
verifyHost: verifyHost.value
}
}
}
// Helper to extract URI properties safely
function getUriVerifyPeer(location?: ServiceLocation | null): boolean {
return (location?.type === 'URI' ? location.verifyPeer : undefined) ?? true
}
function getUriVerifyHost(location?: ServiceLocation | null): boolean {
return (location?.type === 'URI' ? location.verifyHost : undefined) ?? true
}
</script>
<template> <template>
<div class="jmap-config-panel"> <div class="jmap-config-panel">
<h3 class="text-h6 mb-4">JMAP Connection Settings</h3> <h3 class="text-h6 mb-4">JMAP Connection Settings</h3>
@@ -14,7 +209,7 @@
<!-- Session URL (Simple Mode) --> <!-- Session URL (Simple Mode) -->
<template v-if="!configureManually"> <template v-if="!configureManually">
<v-text-field <v-text-field
v-model="sessionUrl" v-model="serviceLocationUrl"
label="JMAP Session URL" label="JMAP Session URL"
hint="e.g., https://jmap.example.com/.well-known/jmap" hint="e.g., https://jmap.example.com/.well-known/jmap"
persistent-hint persistent-hint
@@ -91,241 +286,23 @@
/> />
</template> </template>
<!-- Advanced Settings --> <v-switch
<v-expansion-panels class="mt-4"> v-model="verifyHost"
<v-expansion-panel> label="Verify SSL Hostname"
<v-expansion-panel-title> color="primary"
<v-icon start>mdi-cog</v-icon> class="mt-4"
Advanced Settings hint="Verify the certificate matches the hostname"
</v-expansion-panel-title> persistent-hint
<v-expansion-panel-text> />
<v-select
v-model="capabilities"
:items="jmapCapabilities"
label="Enabled Capabilities"
multiple
chips
variant="outlined"
hint="Select which JMAP capabilities to enable"
persistent-hint
/>
<v-text-field
v-model.number="timeout"
type="number"
label="Timeout (seconds)"
variant="outlined"
class="mt-4"
hint="Connection timeout in seconds"
persistent-hint
:min="5"
:max="300"
/>
<v-switch
v-model="verifyHost"
label="Verify SSL Hostname"
color="primary"
hint="Verify the certificate matches the hostname"
persistent-hint
/>
</v-expansion-panel-text>
</v-expansion-panel>
</v-expansion-panels>
<!-- Info Alert --> <!-- Info Alert -->
<v-alert <v-alert type="info" variant="tonal">
type="info"
variant="tonal"
density="compact"
class="mt-4"
>
<template #prepend>
<v-icon>mdi-information</v-icon>
</template>
<div class="text-caption">
JMAP is a modern protocol for mail access. Most JMAP servers use JMAP is a modern protocol for mail access. Most JMAP servers use
<code>/.well-known/jmap</code> for autodiscovery. <code>/.well-known/jmap</code> for autodiscovery.
</div>
</v-alert> </v-alert>
</div> </div>
</template> </template>
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { ServiceLocationUri, ServiceLocation } from '@KTXM/MailManager/types/service'
import type { ProviderConfigPanelProps, ProviderConfigPanelEmits } from '@KTXM/MailManager/types/integration'
const props = defineProps<ProviderConfigPanelProps>()
const emit = defineEmits<ProviderConfigPanelEmits>()
// Helper to build session URL from location
function buildSessionUrl(location?: ServiceLocation): string {
if (!location || location.type !== 'URI') return ''
const protocol = location.scheme || 'https'
const host = location.host || ''
const port = location.port || (protocol === 'https' ? 443 : 80)
const path = location.path || '/.well-known/jmap'
// Don't include port if it's the default for the protocol
const portStr = (protocol === 'https' && port === 443) || (protocol === 'http' && port === 80)
? ''
: `:${port}`
return `${protocol}://${host}${portStr}${path}`
}
// Helper to parse session URL into location
function parseSessionUrl(url: string): ServiceLocationUri {
try {
const parsed = new URL(url)
return {
type: 'URI',
scheme: parsed.protocol.replace(':', '') as 'http' | 'https',
host: parsed.hostname,
port: parsed.port ? parseInt(parsed.port) : (parsed.protocol === 'https:' ? 443 : 80),
path: parsed.pathname || '/.well-known/jmap',
verifyPeer: verifyPeer.value,
verifyHost: verifyHost.value
}
} catch {
return {
type: 'URI',
scheme: 'https',
host: '',
port: 443,
path: '/.well-known/jmap',
verifyPeer: verifyPeer.value,
verifyHost: verifyHost.value
}
}
}
// Helper to extract URI properties safely
function getUriVerifyPeer(location?: ServiceLocation): boolean {
return (location?.type === 'URI' ? location.verifyPeer : undefined) ?? true
}
function getUriVerifyHost(location?: ServiceLocation): boolean {
return (location?.type === 'URI' ? location.verifyHost : undefined) ?? true
}
// Manual configuration toggle and fields
const configureManually = ref(false)
const serviceHost = ref('')
const serviceProtocol = ref<'http' | 'https'>('https')
const servicePort = ref('')
const servicePath = ref('')
// Local state - protocol settings only
const sessionUrl = ref(buildSessionUrl(props.modelValue || props.discoveredLocation))
const capabilities = ref<string[]>(['urn:ietf:params:jmap:mail'])
const timeout = ref(30)
const verifyPeer = ref(getUriVerifyPeer(props.modelValue || props.discoveredLocation))
const verifyHost = ref(getUriVerifyHost(props.modelValue || props.discoveredLocation))
// Validation rules
const rules = {
required: (value: any) => !!value || 'This field is required',
url: (value: string) => {
try {
new URL(value)
return true
} catch {
return 'Please enter a valid URL'
}
}
}
// Build location from current state
const currentLocation = computed((): ServiceLocationUri | null => {
if (configureManually.value) {
// Build from manual fields
if (!serviceHost.value) return null
const port = servicePort.value
? parseInt(servicePort.value)
: (serviceProtocol.value === 'https' ? 443 : 80)
return {
type: 'URI',
scheme: serviceProtocol.value,
host: serviceHost.value,
port,
path: servicePath.value || '/.well-known/jmap',
verifyPeer: verifyPeer.value,
verifyHost: verifyHost.value
}
} else {
// Build from session URL
if (!sessionUrl.value) return null
return parseSessionUrl(sessionUrl.value)
}
})
// Validation state
const isValid = computed(() => {
if (configureManually.value) {
return !!serviceHost.value
} else {
return !!sessionUrl.value && rules.url(sessionUrl.value) === true
}
})
// Emit location whenever it changes
watch(
currentLocation,
(newLocation) => {
if (newLocation) {
emit('update:modelValue', newLocation)
}
},
{ immediate: true, deep: true }
)
// Emit validation state
watch(
isValid,
(valid) => {
emit('valid', valid)
},
{ immediate: true }
)
// Update local state when props change
watch(
() => props.modelValue,
(newValue) => {
if (newValue && newValue.type === 'URI') {
sessionUrl.value = buildSessionUrl(newValue)
verifyPeer.value = newValue.verifyPeer ?? true
verifyHost.value = newValue.verifyHost ?? true
}
}
)
watch(
() => props.discoveredLocation,
(newValue) => {
if (newValue && newValue.type === 'URI' && !props.modelValue) {
sessionUrl.value = buildSessionUrl(newValue)
verifyPeer.value = newValue.verifyPeer ?? true
verifyHost.value = newValue.verifyHost ?? true
}
},
{ immediate: true }
)
const jmapCapabilities = [
{ title: 'Mail', value: 'urn:ietf:params:jmap:mail' },
{ title: 'Contacts', value: 'urn:ietf:params:jmap:contacts' },
{ title: 'Calendars', value: 'urn:ietf:params:jmap:calendars' },
{ title: 'Tasks', value: 'urn:ietf:params:jmap:tasks' },
{ title: 'Notes', value: 'urn:ietf:params:jmap:notes' },
]
</script>
<style scoped> <style scoped>
.jmap-config-panel { .jmap-config-panel {
max-width: 800px; max-width: 800px;
+17 -29
View File
@@ -1,56 +1,44 @@
import type { ModuleIntegrations } from "@KTXC/types/moduleTypes"; import type { ModuleIntegrations } from "@KTXC/types/moduleTypes";
import type { ProviderMetadata } from "@KTXM/MailManager/types/provider";
import type { ServiceInterface } from "@KTXM/MailManager/types/service"; import type { ServiceInterface } from "@KTXM/MailManager/types/service";
import { JmapServiceObject } from './models/JmapServiceObject' import { JmapServiceObject } from './models/JmapServiceObject'
const integrations: ModuleIntegrations = { const integrations: ModuleIntegrations = {
mail_account_config_panels: [ mail_provider_panels_auxiliary: [
{ {
id: 'jmap', id: 'jmap',
label: 'JMAP', label: 'JMAP Settings',
icon: 'mdi-api', component: () => import('@/components/JmapAuxiliaryPanel.vue'),
caption: 'Modern JSON-based mail protocol',
component: () => import('@/components/JmapConfigPanel.vue'),
priority: 10, priority: 10,
} }
], ],
mail_account_auth_panels: [ mail_provider_panels_protocol: [
{ {
id: 'jmap', id: 'jmap',
label: 'JMAP Protocol',
component: () => import('@/components/JmapProtocolPanel.vue'),
priority: 10,
}
],
mail_provider_panels_auth: [
{
id: 'jmap',
label: 'JMAP Authentication',
component: () => import('@/components/JmapAuthPanel.vue'), component: () => import('@/components/JmapAuthPanel.vue'),
} }
], ],
mail_service_factory: [ mail_provider_factory_service: [
{ {
id: 'jmap', id: 'jmap',
factory: (data: ServiceInterface) => new JmapServiceObject().fromJson(data) factory: (data: ServiceInterface) => new JmapServiceObject().fromJson(data)
} }
], ],
mail_provider_metadata: [ mail_provider_details: [
{ {
id: 'jmap', id: 'jmap',
label: 'JMAP', label: 'JMAP Protocol',
description: 'Modern JSON-based mail API protocol', description: 'Modern JSON-based mail API protocol',
icon: 'mdi-api', icon: 'mdi-api',
auth: { }
methods: ['BA', 'OA', 'TA'],
default: 'BA',
allowMethodSelection: true,
oauth: {
// OAuth config will be provider-specific
// Some JMAP providers use OAuth (e.g., Fastmail)
authorizeUrl: '', // Configured per-instance
tokenUrl: '',
scopes: ['mail'],
flowType: 'authorization_code'
}
},
supportsDiscovery: true,
meta: {
protocol: 'JMAP',
wellKnownPath: '/.well-known/jmap'
}
} as ProviderMetadata
] ]
}; };
+8
View File
@@ -51,5 +51,13 @@ export class JmapServiceObject extends ServiceObject {
get accountId(): string | undefined { get accountId(): string | undefined {
return this.jmapAuxiliary.accountId return this.jmapAuxiliary.accountId
} }
get deleteMode(): 'soft' | 'hard' {
return this.jmapAuxiliary.deleteMode === 'hard' ? 'hard' : 'soft'
}
get deleteDestination(): string | undefined {
return this.jmapAuxiliary.deleteDestination
}
} }
-81
View File
@@ -1,81 +0,0 @@
import { fetchWrapper } from '@KTXC/utils/helpers/fetch-wrapper';
import type {
Service,
ConnectionTestRequest,
ConnectionTestResponse,
CollectionsResponse,
DiscoverResponse
} from '@/models/service';
const BASE_PATH = '/m/provider_jmapc';
export const serviceService = {
/**
* List all JMAP services for current user
*/
async list(capability?: string): Promise<{ services: Service[] }> {
const params = capability ? `?capability=${encodeURIComponent(capability)}` : '';
return fetchWrapper.get(`${BASE_PATH}/services${params}`);
},
/**
* Get a single service by ID
*/
async fetch(id: string): Promise<Service> {
return fetchWrapper.get(`${BASE_PATH}/services/${id}`);
},
/**
* Create a new service
*/
async create(service: Partial<Service>): Promise<Service> {
return fetchWrapper.post(`${BASE_PATH}/services`, service);
},
/**
* Update an existing service
*/
async update(id: string, service: Partial<Service>): Promise<Service> {
return fetchWrapper.put(`${BASE_PATH}/services/${id}`, service);
},
/**
* Delete a service
*/
async destroy(id: string): Promise<{ success: boolean }> {
return fetchWrapper.delete(`${BASE_PATH}/services/${id}`);
},
/**
* Test JMAP connection
*/
async test(request: ConnectionTestRequest): Promise<ConnectionTestResponse> {
return fetchWrapper.post(`${BASE_PATH}/services/test`, request);
},
/**
* Auto-discover JMAP endpoint from hostname
*/
async discover(hostname: string, protocol?: string, port?: number, path?: string): Promise<DiscoverResponse> {
return fetchWrapper.post(`${BASE_PATH}/services/discover`, {
hostname,
protocol,
port,
path
});
},
/**
* Fetch collections for a service
*/
async fetchCollections(id: string): Promise<CollectionsResponse> {
return fetchWrapper.get(`${BASE_PATH}/services/${id}/collections`);
},
/**
* Refresh collections for a service (re-query remote server)
*/
async refreshCollections(id: string): Promise<CollectionsResponse> {
return fetchWrapper.post(`${BASE_PATH}/services/${id}/collections/refresh`, {});
},
};
-208
View File
@@ -1,208 +0,0 @@
import { defineStore } from 'pinia';
import { serviceService } from '@/services/serviceService';
import { ServiceModel } from '@/models/service';
import type { Service } from '@/models/service';
export const useServicesStore = defineStore('jmapc_services', {
state: () => ({
services: [] as ServiceModel[],
loading: false,
error: null as string | null,
}),
getters: {
/**
* Get services filtered by capability
*/
byCapability: (state) => (capability: string) => {
return state.services.filter(s => s.capabilities.includes(capability));
},
/**
* Get mail services
*/
mailServices: (state) => {
return state.services.filter(s => s.hasMail());
},
/**
* Get contact services
*/
contactServices: (state) => {
return state.services.filter(s => s.hasContacts());
},
/**
* Get calendar services
*/
calendarServices: (state) => {
return state.services.filter(s => s.hasCalendars());
},
/**
* Get service by ID
*/
getById: (state) => (id: string) => {
return state.services.find(s => s.id === id);
},
},
actions: {
/**
* Load all services from API
*/
async loadServices(capability?: string) {
this.loading = true;
this.error = null;
try {
const response = await serviceService.list(capability);
this.services = response.services.map(s => new ServiceModel(s));
} catch (error: any) {
this.error = error.message || 'Failed to load services';
throw error;
} finally {
this.loading = false;
}
},
/**
* Load a single service
*/
async loadService(id: string) {
this.loading = true;
this.error = null;
try {
const service = await serviceService.fetch(id);
const model = new ServiceModel(service);
// Update or add to store
const index = this.services.findIndex(s => s.id === id);
if (index >= 0) {
this.services[index] = model;
} else {
this.services.push(model);
}
return model;
} catch (error: any) {
this.error = error.message || 'Failed to load service';
throw error;
} finally {
this.loading = false;
}
},
/**
* Create a new service
*/
async createService(service: Partial<Service>) {
this.loading = true;
this.error = null;
try {
const created = await serviceService.create(service);
const model = new ServiceModel(created);
this.services.push(model);
return model;
} catch (error: any) {
this.error = error.message || 'Failed to create service';
throw error;
} finally {
this.loading = false;
}
},
/**
* Update an existing service
*/
async updateService(id: string, service: Partial<Service>) {
this.loading = true;
this.error = null;
try {
const updated = await serviceService.update(id, service);
const model = new ServiceModel(updated);
const index = this.services.findIndex(s => s.id === id);
if (index >= 0) {
this.services[index] = model;
}
return model;
} catch (error: any) {
this.error = error.message || 'Failed to update service';
throw error;
} finally {
this.loading = false;
}
},
/**
* Delete a service
*/
async deleteService(id: string) {
this.loading = true;
this.error = null;
try {
await serviceService.destroy(id);
this.services = this.services.filter(s => s.id !== id);
} catch (error: any) {
this.error = error.message || 'Failed to delete service';
throw error;
} finally {
this.loading = false;
}
},
/**
* Test connection with provided settings
*/
async testConnection(config: any) {
return serviceService.test(config);
},
/**
* Auto-discover JMAP endpoint
*/
async discover(hostname: string, protocol?: string, port?: number, path?: string) {
return serviceService.discover(hostname, protocol, port, path);
},
/**
* Fetch collections for a service
*/
async fetchCollections(id: string) {
return serviceService.fetchCollections(id);
},
/**
* Refresh collections for a service
*/
async refreshCollections(id: string) {
const result = await serviceService.refreshCollections(id);
// Update local service with fresh collection data
const service = this.getById(id);
if (service && result.success) {
service.collections = {
contacts: result.contacts || [],
calendars: result.calendars || []
};
}
return result;
},
/**
* Clear all services
*/
reset() {
this.services = [];
this.error = null;
this.loading = false;
},
},
});
+6
View File
@@ -22,6 +22,12 @@ export interface JmapAuxiliary {
/** JMAP account ID */ /** JMAP account ID */
accountId?: string; accountId?: string;
/** Message delete behavior */
deleteMode?: 'soft' | 'hard';
/** Optional destination mailbox identifier for soft delete */
deleteDestination?: string;
/** Allow additional custom fields */ /** Allow additional custom fields */
[key: string]: any; [key: string]: any;
+3 -3
View File
@@ -1,17 +1,17 @@
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
import { defineConfig, configDefaults } from 'vitest/config' import { defineConfig, configDefaults } from 'vitest/config'
import vue from '@vitejs/plugin-vue' import vue from '@vitejs/plugin-vue'
import vuetify from 'vite-plugin-vuetify'
import path from 'path' import path from 'path'
const __filename = fileURLToPath(import.meta.url) const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename) const __dirname = path.dirname(__filename)
export default defineConfig({ export default defineConfig({
plugins: [vue(), vuetify()], plugins: [vue()],
resolve: { resolve: {
alias: { alias: {
'@KTXC': path.resolve(__dirname, '../../../core/src'), '@': path.resolve(__dirname, '../../src'),
'@KTXC': path.resolve(__dirname, '../../../../core/src'),
}, },
}, },
test: { test: {
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace KTXT\ProviderJmapc\Integration;
use PHPUnit\Framework\TestCase;
class BaseTest extends TestCase
{
public function testBasicAssertion(): void
{
$this->assertTrue(true);
}
public function testArrayOperations(): void
{
$array = ['foo' => 'bar'];
$this->assertArrayHasKey('foo', $array);
$this->assertEquals('bar', $array['foo']);
}
public function testStringOperations(): void
{
$string = 'Hello, World!';
$this->assertStringContainsString('World', $string);
$this->assertEquals(13, strlen($string));
}
}
+10
View File
@@ -2,6 +2,16 @@
require dirname(__DIR__, 2).'/lib/vendor/autoload.php'; require dirname(__DIR__, 2).'/lib/vendor/autoload.php';
// When this module is checked out inside a full server (server/modules/<handle>,
// as it is in CI and in this monorepo checkout), also load the server's own
// core/shared autoloader so tests can reference framework (KTXC/KTXF) types.
// Standalone module checkouts without a server alongside them skip this.
define('SERVER_ROOT', dirname(__DIR__, 4));
$serverAutoload = SERVER_ROOT . '/vendor/autoload.php';
if (is_file($serverAutoload)) {
require $serverAutoload;
}
if (isset($_SERVER['APP_DEBUG']) && $_SERVER['APP_DEBUG']) { if (isset($_SERVER['APP_DEBUG']) && $_SERVER['APP_DEBUG']) {
umask(0000); umask(0000);
} }
@@ -21,6 +21,9 @@
<testsuite name="Unit Tests"> <testsuite name="Unit Tests">
<directory>unit</directory> <directory>unit</directory>
</testsuite> </testsuite>
<testsuite name="Integration Tests">
<directory>Integration</directory>
</testsuite>
</testsuites> </testsuites>
<source ignoreSuppressionOfDeprecations="true" <source ignoreSuppressionOfDeprecations="true"
@@ -29,8 +32,7 @@
restrictWarnings="true" restrictWarnings="true"
> >
<include> <include>
<directory>../../core/lib</directory> <directory>../../lib</directory>
<directory>../../shared/lib</directory>
</include> </include>
<deprecationTrigger> <deprecationTrigger>
+8
View File
@@ -44,8 +44,16 @@ export default defineConfig({
'vue', 'vue',
'vue-router', 'vue-router',
'pinia', 'pinia',
/^@KTXM\/MailManager\//,
], ],
output: { output: {
paths: (id) => {
if (id.startsWith('@KTXM/MailManager/')) {
return '/modules/mail_manager/static/module.mjs'
}
return id
},
assetFileNames: (assetInfo) => { assetFileNames: (assetInfo) => {
if (assetInfo.name?.endsWith('.css')) { if (assetInfo.name?.endsWith('.css')) {
return 'provider_jmapc-[hash].css' return 'provider_jmapc-[hash].css'