pigallery2-extension-kit 3.5.2 → 3.6.0-edge

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (420) hide show
  1. package/README.md +11 -5
  2. package/index.d.ts +1 -0
  3. package/index.js +2 -3
  4. package/lib/backend/Logger.d.ts +7 -7
  5. package/lib/backend/Logger.js +104 -0
  6. package/lib/backend/ProjectPath.d.ts +12 -0
  7. package/lib/backend/ProjectPath.js +28 -2
  8. package/lib/backend/exceptions/DirectoryNotFound.d.ts +2 -0
  9. package/lib/backend/exceptions/DirectoryNotFound.js +7 -0
  10. package/lib/backend/exceptions/FileAlreadyExists.js +10 -0
  11. package/lib/backend/exceptions/FolderNotWritable.d.ts +2 -0
  12. package/lib/backend/exceptions/FolderNotWritable.js +7 -0
  13. package/lib/backend/exceptions/LocationLookupException.js +10 -0
  14. package/lib/backend/index.d.ts +1 -1
  15. package/lib/backend/middlewares/AlbumMWs.js +61 -0
  16. package/lib/backend/middlewares/GalleryMWs.d.ts +4 -0
  17. package/lib/backend/middlewares/GalleryMWs.js +380 -0
  18. package/lib/backend/middlewares/MetaFileMWs.js +41 -0
  19. package/lib/backend/middlewares/NotificationMWs.js +21 -0
  20. package/lib/backend/middlewares/PersonMWs.d.ts +1 -1
  21. package/lib/backend/middlewares/PersonMWs.js +64 -0
  22. package/lib/backend/middlewares/RenderingMWs.d.ts +24 -0
  23. package/lib/backend/middlewares/RenderingMWs.js +182 -0
  24. package/lib/backend/middlewares/RequestParams.d.ts +13 -0
  25. package/lib/backend/middlewares/RequestParams.js +25 -0
  26. package/lib/backend/middlewares/RequestSession.d.ts +9 -0
  27. package/lib/backend/middlewares/RequestSession.js +16 -0
  28. package/lib/backend/middlewares/ServerTimingMWs.d.ts +6 -6
  29. package/lib/backend/middlewares/ServerTimingMWs.js +108 -0
  30. package/lib/backend/middlewares/SharingMWs.d.ts +2 -1
  31. package/lib/backend/middlewares/SharingMWs.js +240 -0
  32. package/lib/backend/middlewares/UploadMWs.js +95 -0
  33. package/lib/backend/middlewares/VersionMWs.d.ts +1 -1
  34. package/lib/backend/middlewares/VersionMWs.js +41 -0
  35. package/lib/backend/middlewares/admin/AdminMWs.js +115 -0
  36. package/lib/backend/middlewares/admin/ExtensionMWs.js +85 -0
  37. package/lib/backend/middlewares/admin/SettingsMWs.js +54 -0
  38. package/lib/backend/middlewares/thumbnail/ThumbnailGeneratorMWs.d.ts +1 -1
  39. package/lib/backend/middlewares/thumbnail/ThumbnailGeneratorMWs.js +153 -0
  40. package/lib/backend/middlewares/user/AuthenticationMWs.d.ts +37 -0
  41. package/lib/backend/middlewares/user/AuthenticationMWs.js +346 -0
  42. package/lib/backend/middlewares/user/OIDCAuthService.d.ts +36 -5
  43. package/lib/backend/middlewares/user/OIDCAuthService.js +216 -0
  44. package/lib/backend/middlewares/user/OIDCMWs.d.ts +10 -0
  45. package/lib/backend/middlewares/user/OIDCMWs.js +30 -0
  46. package/lib/backend/middlewares/user/UserMWs.d.ts +1 -0
  47. package/lib/backend/middlewares/user/UserMWs.js +120 -0
  48. package/lib/backend/middlewares/user/UserRequestConstrainsMWs.d.ts +0 -1
  49. package/lib/backend/middlewares/user/UserRequestConstrainsMWs.js +29 -0
  50. package/lib/backend/model/DirectoryAccess.d.ts +78 -0
  51. package/lib/backend/model/DirectoryAccess.js +222 -0
  52. package/lib/backend/model/EventLoopHandler.d.ts +1 -1
  53. package/lib/backend/model/EventLoopHandler.js +24 -0
  54. package/lib/backend/model/FFmpeg.d.ts +47 -0
  55. package/lib/backend/model/FFmpeg.js +75 -0
  56. package/lib/backend/model/FFmpegFactory.d.ts +11 -2
  57. package/lib/backend/model/FFmpegFactory.js +28 -0
  58. package/lib/backend/model/Localizations.js +19 -0
  59. package/lib/backend/model/ObjectManagers.d.ts +1 -1
  60. package/lib/backend/model/ObjectManagers.js +253 -0
  61. package/lib/backend/model/PasswordHelper.d.ts +1 -1
  62. package/lib/backend/model/PasswordHelper.js +6 -2
  63. package/lib/backend/model/SessionContext.d.ts +16 -6
  64. package/lib/backend/model/SessionContext.js +11 -0
  65. package/lib/backend/model/UploadManager.d.ts +6 -3
  66. package/lib/backend/model/UploadManager.js +101 -0
  67. package/lib/backend/model/database/AlbumManager.js +122 -0
  68. package/lib/backend/model/database/CoverManager.d.ts +8 -2
  69. package/lib/backend/model/database/CoverManager.js +169 -0
  70. package/lib/backend/model/database/GalleryManager.d.ts +15 -9
  71. package/lib/backend/model/database/GalleryManager.js +363 -0
  72. package/lib/backend/model/database/IObjectManager.js +2 -0
  73. package/lib/backend/model/database/IndexingManager.d.ts +7 -7
  74. package/lib/backend/model/database/IndexingManager.js +452 -0
  75. package/lib/backend/model/database/LocationManager.d.ts +2 -3
  76. package/lib/backend/model/database/LocationManager.js +39 -0
  77. package/lib/backend/model/database/PersonManager.d.ts +5 -3
  78. package/lib/backend/model/database/PersonManager.js +248 -0
  79. package/lib/backend/model/database/ProjectedCacheManager.d.ts +9 -8
  80. package/lib/backend/model/database/ProjectedCacheManager.js +297 -0
  81. package/lib/backend/model/database/ProjectionAwareManager.d.ts +4 -4
  82. package/lib/backend/model/database/ProjectionAwareManager.js +56 -0
  83. package/lib/backend/model/database/SQLConnection.d.ts +4 -2
  84. package/lib/backend/model/database/SQLConnection.js +295 -0
  85. package/lib/backend/model/database/SearchManager.d.ts +23 -8
  86. package/lib/backend/model/database/SearchManager.js +1032 -0
  87. package/lib/backend/model/database/SessionManager.d.ts +41 -4
  88. package/lib/backend/model/database/SessionManager.js +228 -0
  89. package/lib/backend/model/database/SharingManager.d.ts +11 -6
  90. package/lib/backend/model/database/SharingManager.js +160 -0
  91. package/lib/backend/model/database/UserManager.d.ts +8 -1
  92. package/lib/backend/model/database/UserManager.js +148 -0
  93. package/lib/backend/model/database/VersionManager.js +60 -0
  94. package/lib/backend/model/database/enitites/DirectoryEntity.d.ts +1 -1
  95. package/lib/backend/model/database/enitites/DirectoryEntity.js +76 -0
  96. package/lib/backend/model/database/enitites/EntityUtils.d.ts +22 -1
  97. package/lib/backend/model/database/enitites/EntityUtils.js +66 -0
  98. package/lib/backend/model/database/enitites/FileEntity.js +31 -0
  99. package/lib/backend/model/database/enitites/MDFileEntity.js +21 -0
  100. package/lib/backend/model/database/enitites/MediaEntity.d.ts +5 -2
  101. package/lib/backend/model/database/enitites/MediaEntity.js +223 -0
  102. package/lib/backend/model/database/enitites/PhotoEntity.js +19 -0
  103. package/lib/backend/model/database/enitites/ProjectedDirectoryCacheEntity.d.ts +2 -2
  104. package/lib/backend/model/database/enitites/ProjectedDirectoryCacheEntity.js +61 -0
  105. package/lib/backend/model/database/enitites/SharingEntity.d.ts +11 -5
  106. package/lib/backend/model/database/enitites/SharingEntity.js +100 -0
  107. package/lib/backend/model/database/enitites/UserEntity.d.ts +8 -5
  108. package/lib/backend/model/database/enitites/UserEntity.js +97 -0
  109. package/lib/backend/model/database/enitites/VersionEntity.js +19 -0
  110. package/lib/backend/model/database/enitites/VideoEntity.d.ts +2 -2
  111. package/lib/backend/model/database/enitites/VideoEntity.js +38 -0
  112. package/lib/backend/model/database/enitites/album/AlbumBaseEntity.js +32 -0
  113. package/lib/backend/model/database/enitites/album/ProjectedAlbumCacheEntity.d.ts +2 -2
  114. package/lib/backend/model/database/enitites/album/ProjectedAlbumCacheEntity.js +52 -0
  115. package/lib/backend/model/database/enitites/album/SavedSearchEntity.js +29 -0
  116. package/lib/backend/model/database/enitites/person/PersonEntry.js +36 -0
  117. package/lib/backend/model/database/enitites/person/PersonJunctionTable.js +37 -0
  118. package/lib/backend/model/database/enitites/person/ProjectedPersonCacheEntity.d.ts +1 -1
  119. package/lib/backend/model/database/enitites/person/ProjectedPersonCacheEntity.js +49 -0
  120. package/lib/backend/model/diagnostics/ConfigDiagnostics.d.ts +31 -12
  121. package/lib/backend/model/diagnostics/ConfigDiagnostics.js +537 -0
  122. package/lib/backend/model/extension/ExpressRouterWrapper.d.ts +10 -4
  123. package/lib/backend/model/extension/ExpressRouterWrapper.js +113 -0
  124. package/lib/backend/model/extension/ExtensionApp.d.ts +2 -3
  125. package/lib/backend/model/extension/ExtensionApp.js +18 -0
  126. package/lib/backend/model/extension/ExtensionConfig.js +17 -0
  127. package/lib/backend/model/extension/ExtensionConfigTemplateLoader.js +4 -3
  128. package/lib/backend/model/extension/ExtensionConfigWrapper.js +6 -5
  129. package/lib/backend/model/extension/ExtensionDB.d.ts +2 -2
  130. package/lib/backend/model/extension/ExtensionDB.js +22 -0
  131. package/lib/backend/model/extension/ExtensionDecorator.js +33 -0
  132. package/lib/backend/model/extension/ExtensionEvent.d.ts +12 -1
  133. package/lib/backend/model/extension/ExtensionEvent.js +81 -0
  134. package/lib/backend/model/extension/ExtensionManager.d.ts +22 -4
  135. package/lib/backend/model/extension/ExtensionManager.js +424 -0
  136. package/lib/backend/model/extension/ExtensionMessengerHandler.js +28 -0
  137. package/lib/backend/model/extension/ExtensionObject.d.ts +6 -3
  138. package/lib/backend/model/extension/ExtensionObject.js +45 -0
  139. package/lib/backend/model/extension/ExtensionRepository.js +69 -0
  140. package/lib/backend/model/extension/IExtension.d.ts +35 -18
  141. package/lib/backend/model/extension/IExtension.js +2 -0
  142. package/lib/backend/model/extension/UIExtension.js +23 -0
  143. package/lib/backend/model/fileaccess/DiskManager.d.ts +3 -1
  144. package/lib/backend/model/fileaccess/DiskManager.js +313 -0
  145. package/lib/backend/model/fileaccess/MetadataCreationDate.js +27 -0
  146. package/lib/backend/model/fileaccess/MetadataLoader.d.ts +17 -0
  147. package/lib/backend/model/fileaccess/MetadataLoader.js +765 -0
  148. package/lib/backend/model/fileaccess/PhotoWorker.js +159 -0
  149. package/lib/backend/model/fileaccess/TaskExecuter.js +41 -0
  150. package/lib/backend/model/fileaccess/TaskQue.d.ts +4 -4
  151. package/lib/backend/model/fileaccess/TaskQue.js +50 -0
  152. package/lib/backend/model/fileaccess/VideoConverterWorker.d.ts +4 -1
  153. package/lib/backend/model/fileaccess/VideoConverterWorker.js +59 -0
  154. package/lib/backend/model/fileaccess/fileprocessing/GPXProcessing.js +136 -0
  155. package/lib/backend/model/fileaccess/fileprocessing/PhotoProcessing.d.ts +3 -2
  156. package/lib/backend/model/fileaccess/fileprocessing/PhotoProcessing.js +251 -0
  157. package/lib/backend/model/fileaccess/fileprocessing/VideoProcessing.js +97 -0
  158. package/lib/backend/model/jobs/JobManager.d.ts +2 -4
  159. package/lib/backend/model/jobs/JobManager.js +129 -0
  160. package/lib/backend/model/jobs/JobProgressManager.d.ts +5 -3
  161. package/lib/backend/model/jobs/JobProgressManager.js +94 -0
  162. package/lib/backend/model/jobs/JobRepository.d.ts +1 -3
  163. package/lib/backend/model/jobs/JobRepository.js +50 -0
  164. package/lib/backend/model/jobs/jobs/AlbumCoverFillingJob.d.ts +1 -1
  165. package/lib/backend/model/jobs/jobs/AlbumCoverFillingJob.js +91 -0
  166. package/lib/backend/model/jobs/jobs/AlbumCoverResetJob.js +32 -0
  167. package/lib/backend/model/jobs/jobs/AlbumResetJob.js +30 -0
  168. package/lib/backend/model/jobs/jobs/FileJob.js +243 -0
  169. package/lib/backend/model/jobs/jobs/GPXCompressionJob.js +35 -0
  170. package/lib/backend/model/jobs/jobs/GPXCompressionResetJob.js +23 -0
  171. package/lib/backend/model/jobs/jobs/GalleryResetJob.js +30 -0
  172. package/lib/backend/model/jobs/jobs/IJob.js +2 -0
  173. package/lib/backend/model/jobs/jobs/IJobListener.d.ts +2 -2
  174. package/lib/backend/model/jobs/jobs/IJobListener.js +2 -0
  175. package/lib/backend/model/jobs/jobs/IndexingJob.js +99 -0
  176. package/lib/backend/model/jobs/jobs/Job.d.ts +4 -1
  177. package/lib/backend/model/jobs/jobs/Job.js +135 -0
  178. package/lib/backend/model/jobs/jobs/JobProgress.js +100 -0
  179. package/lib/backend/model/jobs/jobs/PhotoConvertingJob.js +78 -0
  180. package/lib/backend/model/jobs/jobs/TempFolderCleaningJob.js +122 -0
  181. package/lib/backend/model/jobs/jobs/TopPickSendJob.js +113 -0
  182. package/lib/backend/model/jobs/jobs/VideoConvertingJob.js +31 -0
  183. package/lib/backend/model/messenger/EmailMessenger.d.ts +1 -1
  184. package/lib/backend/model/messenger/EmailMessenger.js +87 -0
  185. package/lib/backend/model/messenger/ExtensionMessenger.js +16 -0
  186. package/lib/backend/model/messenger/Messenger.d.ts +1 -2
  187. package/lib/backend/model/messenger/Messenger.js +36 -0
  188. package/lib/backend/model/messenger/MessengerRepository.d.ts +1 -3
  189. package/lib/backend/model/messenger/MessengerRepository.js +38 -0
  190. package/lib/backend/model/messenger/StdoutMessenger.js +16 -0
  191. package/lib/backend/routes/AlbumRouter.js +39 -0
  192. package/lib/backend/routes/ErrorRouter.d.ts +1 -0
  193. package/lib/backend/routes/ErrorRouter.js +39 -0
  194. package/lib/backend/routes/GalleryRouter.d.ts +8 -0
  195. package/lib/backend/routes/GalleryRouter.js +165 -0
  196. package/lib/backend/routes/LoggerRouter.js +43 -0
  197. package/lib/backend/routes/NotificationRouter.js +19 -0
  198. package/lib/backend/routes/OIDCRouter.js +20 -0
  199. package/lib/backend/routes/PersonRouter.js +41 -0
  200. package/lib/backend/routes/PublicRouter.d.ts +3 -6
  201. package/lib/backend/routes/PublicRouter.js +301 -0
  202. package/lib/backend/routes/Router.js +36 -0
  203. package/lib/backend/routes/SharingRouter.d.ts +1 -1
  204. package/lib/backend/routes/SharingRouter.js +55 -0
  205. package/lib/backend/routes/UploadRouter.js +18 -0
  206. package/lib/backend/routes/UserRouter.d.ts +1 -0
  207. package/lib/backend/routes/UserRouter.js +53 -0
  208. package/lib/backend/routes/admin/AdminRouter.js +32 -0
  209. package/lib/backend/routes/admin/ExtensionRouter.js +30 -0
  210. package/lib/backend/routes/admin/SettingsRouter.js +18 -0
  211. package/lib/backend/server.d.ts +3 -3
  212. package/lib/backend/server.js +176 -0
  213. package/lib/common/CookieNames.js +10 -0
  214. package/lib/common/CustomHeaders.js +8 -0
  215. package/lib/common/DataStructureVersion.d.ts +1 -1
  216. package/lib/common/DataStructureVersion.js +7 -0
  217. package/lib/common/PG2ConfMap.js +36 -0
  218. package/lib/common/QueryParams.js +45 -0
  219. package/lib/common/SearchQueryParser.d.ts +2 -2
  220. package/lib/common/SearchQueryParser.js +611 -0
  221. package/lib/common/SearchQueryUtils.d.ts +71 -4
  222. package/lib/common/SearchQueryUtils.js +443 -0
  223. package/lib/common/SupportedFormats.d.ts +11 -1
  224. package/lib/common/SupportedFormats.js +13 -19
  225. package/lib/common/TextFold.d.ts +6 -0
  226. package/lib/common/TextFold.js +19 -0
  227. package/lib/common/UploadUtils.d.ts +4 -0
  228. package/lib/common/UploadUtils.js +20 -0
  229. package/lib/common/Utils.d.ts +23 -24
  230. package/lib/common/Utils.js +37 -97
  231. package/lib/common/config/private/Config.d.ts +1 -1
  232. package/lib/common/config/private/Config.js +2 -0
  233. package/lib/common/config/private/PrivateConfig.d.ts +17 -4
  234. package/lib/common/config/private/PrivateConfig.js +262 -33
  235. package/lib/common/config/private/PrivateConfigClass.js +10 -13
  236. package/lib/common/config/private/WebConfig.d.ts +1 -2
  237. package/lib/common/config/private/WebConfig.js +0 -2
  238. package/lib/common/config/private/subconfigs/MessagingConfig.js +8 -0
  239. package/lib/common/config/private/subconfigs/ServerExtensionsConfig.d.ts +2 -3
  240. package/lib/common/config/private/subconfigs/ServerExtensionsConfig.js +7 -3
  241. package/lib/common/config/public/ClientConfig.d.ts +55 -17
  242. package/lib/common/config/public/ClientConfig.js +291 -20
  243. package/lib/common/config/public/Config.js +5 -4
  244. package/lib/common/entities/AutoCompleteItem.d.ts +3 -3
  245. package/lib/common/entities/ContentWrapper.d.ts +21 -8
  246. package/lib/common/entities/ContentWrapper.js +286 -318
  247. package/lib/common/entities/DirectoryDTO.d.ts +7 -6
  248. package/lib/common/entities/DirectoryDTO.js +10 -5
  249. package/lib/common/entities/Error.d.ts +12 -7
  250. package/lib/common/entities/Error.js +15 -3
  251. package/lib/common/entities/MediaDTO.d.ts +13 -0
  252. package/lib/common/entities/MediaDTO.js +10 -7
  253. package/lib/common/entities/Message.d.ts +3 -3
  254. package/lib/common/entities/NotificationDTO.d.ts +2 -2
  255. package/lib/common/entities/SearchQueryDTO.d.ts +9 -1
  256. package/lib/common/entities/SearchQueryDTO.js +1 -0
  257. package/lib/common/entities/SharingDTO.d.ts +39 -5
  258. package/lib/common/entities/SortingMethods.d.ts +26 -2
  259. package/lib/common/entities/SortingMethods.js +14 -1
  260. package/lib/common/entities/UserDTO.d.ts +5 -2
  261. package/lib/common/entities/UserSettingsDTO.d.ts +3 -1
  262. package/lib/common/entities/VideoDTO.d.ts +2 -5
  263. package/lib/common/entities/album/AlbumBaseDTO.d.ts +2 -2
  264. package/lib/common/entities/extension/ExtensionListItem.d.ts +1 -1
  265. package/lib/common/entities/extension/IClientUIConfig.d.ts +19 -12
  266. package/lib/common/entities/job/JobDTO.d.ts +1 -1
  267. package/lib/common/entities/job/JobProgressDTO.d.ts +1 -1
  268. package/lib/common/entities/job/JobScheduleDTO.d.ts +5 -5
  269. package/lib/common/entities/job/JobScheduleDTO.js +9 -5
  270. package/lib/common/event/Event.js +49 -0
  271. package/lib/common/event/EventLimit.d.ts +1 -1
  272. package/package.json +21 -8
  273. package/REPOSITORY.md +0 -13
  274. package/events.drawio +0 -1
  275. package/events.png +0 -0
  276. package/index.js.map +0 -1
  277. package/index.ts +0 -2
  278. package/lib/backend/model/database/enitites/PersonEntry.d.ts +0 -11
  279. package/lib/backend/model/database/enitites/PersonJunctionTable.d.ts +0 -10
  280. package/lib/common/entities/ConentWrapper.d.ts +0 -18
  281. package/lib/common/entities/ConentWrapper.js +0 -490
  282. package/lib/frontend/app/app.component.d.ts +0 -18
  283. package/lib/frontend/app/app.module.d.ts +0 -23
  284. package/lib/frontend/app/app.routing.d.ts +0 -4
  285. package/lib/frontend/app/icon.component.d.ts +0 -7
  286. package/lib/frontend/app/model/IRenderable.d.ts +0 -17
  287. package/lib/frontend/app/model/backendtext.service.d.ts +0 -7
  288. package/lib/frontend/app/model/backendtext.service.spec.d.ts +0 -1
  289. package/lib/frontend/app/model/extension.service.d.ts +0 -5
  290. package/lib/frontend/app/model/navigation.service.d.ts +0 -12
  291. package/lib/frontend/app/model/network/autehentication.service.spec.d.ts +0 -1
  292. package/lib/frontend/app/model/network/authentication.service.d.ts +0 -22
  293. package/lib/frontend/app/model/network/helper/auth.guard.d.ts +0 -9
  294. package/lib/frontend/app/model/network/helper/csrf.interceptor.d.ts +0 -8
  295. package/lib/frontend/app/model/network/helper/error.interceptor.d.ts +0 -8
  296. package/lib/frontend/app/model/network/network.service.d.ts +0 -29
  297. package/lib/frontend/app/model/network/network.service.spec.d.ts +0 -1
  298. package/lib/frontend/app/model/network/user.service.d.ts +0 -13
  299. package/lib/frontend/app/model/network/user.service.spec.d.ts +0 -1
  300. package/lib/frontend/app/model/notification.service.d.ts +0 -28
  301. package/lib/frontend/app/model/page.helper.d.ts +0 -15
  302. package/lib/frontend/app/model/pi-title.service.d.ts +0 -15
  303. package/lib/frontend/app/model/query.service.d.ts +0 -19
  304. package/lib/frontend/app/model/seededRandom.service.d.ts +0 -7
  305. package/lib/frontend/app/model/theme.service.d.ts +0 -16
  306. package/lib/frontend/app/model/version.service.d.ts +0 -10
  307. package/lib/frontend/app/pipes/DurationPipe.d.ts +0 -4
  308. package/lib/frontend/app/pipes/FileDTOToPathPipe.d.ts +0 -5
  309. package/lib/frontend/app/pipes/FileDTOToRelativePathPipe.d.ts +0 -5
  310. package/lib/frontend/app/pipes/FileSizePipe.d.ts +0 -4
  311. package/lib/frontend/app/pipes/GPXFilesFilterPipe.d.ts +0 -5
  312. package/lib/frontend/app/pipes/MDFilesFilterPipe.d.ts +0 -6
  313. package/lib/frontend/app/pipes/ParseIntPipe.d.ts +0 -4
  314. package/lib/frontend/app/pipes/PhotoFilterPipe.d.ts +0 -6
  315. package/lib/frontend/app/pipes/SafeHTMLPipe.d.ts +0 -7
  316. package/lib/frontend/app/pipes/StringifyEnum.d.ts +0 -4
  317. package/lib/frontend/app/pipes/StringifyGridSize.d.ts +0 -5
  318. package/lib/frontend/app/pipes/StringifyRolePipe.d.ts +0 -4
  319. package/lib/frontend/app/pipes/StringifySearchQuery.d.ts +0 -8
  320. package/lib/frontend/app/pipes/StringifySearchType.d.ts +0 -5
  321. package/lib/frontend/app/pipes/StringifySortingMethod.d.ts +0 -4
  322. package/lib/frontend/app/ui/EnumTranslations.d.ts +0 -5
  323. package/lib/frontend/app/ui/admin/admin.component.d.ts +0 -36
  324. package/lib/frontend/app/ui/albums/album/album.component.d.ts +0 -26
  325. package/lib/frontend/app/ui/albums/albums.component.d.ts +0 -31
  326. package/lib/frontend/app/ui/albums/albums.service.d.ts +0 -12
  327. package/lib/frontend/app/ui/albums/saved-search-popup/saved-search-popup.component.d.ts +0 -15
  328. package/lib/frontend/app/ui/duplicates/duplicates.component.d.ts +0 -36
  329. package/lib/frontend/app/ui/duplicates/duplicates.service.d.ts +0 -9
  330. package/lib/frontend/app/ui/duplicates/photo/photo.duplicates.component.d.ts +0 -11
  331. package/lib/frontend/app/ui/faces/Person.d.ts +0 -9
  332. package/lib/frontend/app/ui/faces/face/face.component.d.ts +0 -22
  333. package/lib/frontend/app/ui/faces/faces.component.d.ts +0 -18
  334. package/lib/frontend/app/ui/faces/faces.service.d.ts +0 -14
  335. package/lib/frontend/app/ui/faces/navigator/navigator.faces.component.d.ts +0 -15
  336. package/lib/frontend/app/ui/frame/frame.component.d.ts +0 -60
  337. package/lib/frontend/app/ui/gallery/Media.d.ts +0 -15
  338. package/lib/frontend/app/ui/gallery/MediaIcon.d.ts +0 -29
  339. package/lib/frontend/app/ui/gallery/blog/blog.gallery.component.d.ts +0 -16
  340. package/lib/frontend/app/ui/gallery/blog/blog.service.d.ts +0 -85
  341. package/lib/frontend/app/ui/gallery/blog/blog.service.spec.d.ts +0 -1
  342. package/lib/frontend/app/ui/gallery/cache.gallery.service.d.ts +0 -51
  343. package/lib/frontend/app/ui/gallery/content.service.d.ts +0 -11
  344. package/lib/frontend/app/ui/gallery/contentLoader.service.d.ts +0 -37
  345. package/lib/frontend/app/ui/gallery/directories/directories.component.d.ts +0 -14
  346. package/lib/frontend/app/ui/gallery/directories/directory/directory.gallery.component.d.ts +0 -20
  347. package/lib/frontend/app/ui/gallery/filter/filter.gallery.component.d.ts +0 -32
  348. package/lib/frontend/app/ui/gallery/filter/filter.service.d.ts +0 -51
  349. package/lib/frontend/app/ui/gallery/filter/filter.service.spec.d.ts +0 -1
  350. package/lib/frontend/app/ui/gallery/fullscreen.service.d.ts +0 -7
  351. package/lib/frontend/app/ui/gallery/gallery.component.d.ts +0 -64
  352. package/lib/frontend/app/ui/gallery/gallery.component.spec.d.ts +0 -1
  353. package/lib/frontend/app/ui/gallery/gallery.service.d.ts +0 -13
  354. package/lib/frontend/app/ui/gallery/grid/GridMedia.d.ts +0 -13
  355. package/lib/frontend/app/ui/gallery/grid/GridRowBuilder.d.ts +0 -16
  356. package/lib/frontend/app/ui/gallery/grid/grid.gallery.component.d.ts +0 -88
  357. package/lib/frontend/app/ui/gallery/grid/grid.gallery.component.spec.d.ts +0 -1
  358. package/lib/frontend/app/ui/gallery/grid/photo/loading/loading.photo.grid.gallery.component.d.ts +0 -4
  359. package/lib/frontend/app/ui/gallery/grid/photo/media-button-modal/media-button-modal.component.d.ts +0 -20
  360. package/lib/frontend/app/ui/gallery/grid/photo/media-button-modal/media-button-modal.service.d.ts +0 -27
  361. package/lib/frontend/app/ui/gallery/grid/photo/photo.grid.gallery.component.d.ts +0 -53
  362. package/lib/frontend/app/ui/gallery/lightbox/controls/controls.lightbox.gallery.component.d.ts +0 -103
  363. package/lib/frontend/app/ui/gallery/lightbox/infopanel/info-panel.lightbox.gallery.component.d.ts +0 -51
  364. package/lib/frontend/app/ui/gallery/lightbox/lightbox.gallery.component.d.ts +0 -95
  365. package/lib/frontend/app/ui/gallery/lightbox/lightbox.gallery.component.spec.d.ts +0 -1
  366. package/lib/frontend/app/ui/gallery/lightbox/lightbox.service.d.ts +0 -45
  367. package/lib/frontend/app/ui/gallery/lightbox/media/media.lightbox.gallery.component.d.ts +0 -71
  368. package/lib/frontend/app/ui/gallery/map/MarkerFactory.d.ts +0 -12
  369. package/lib/frontend/app/ui/gallery/map/lightbox/lightbox.map.gallery.component.d.ts +0 -80
  370. package/lib/frontend/app/ui/gallery/map/map.gallery.component.d.ts +0 -36
  371. package/lib/frontend/app/ui/gallery/map/map.service.d.ts +0 -30
  372. package/lib/frontend/app/ui/gallery/navigator/navigator.gallery.component.d.ts +0 -81
  373. package/lib/frontend/app/ui/gallery/navigator/navigator.service.d.ts +0 -14
  374. package/lib/frontend/app/ui/gallery/navigator/sorting.service.d.ts +0 -38
  375. package/lib/frontend/app/ui/gallery/overlay.service.d.ts +0 -9
  376. package/lib/frontend/app/ui/gallery/photo-frame-builder/photo-frame-builder.gallery.component.d.ts +0 -40
  377. package/lib/frontend/app/ui/gallery/random-query-builder/random-query-builder.gallery.component.d.ts +0 -30
  378. package/lib/frontend/app/ui/gallery/search/AutoCompleteRenderItem.d.ts +0 -11
  379. package/lib/frontend/app/ui/gallery/search/autocomplete.service.d.ts +0 -33
  380. package/lib/frontend/app/ui/gallery/search/query-builder/query-bulder.gallery.component.d.ts +0 -22
  381. package/lib/frontend/app/ui/gallery/search/query-enrty/query-entry.search.gallery.component.d.ts +0 -43
  382. package/lib/frontend/app/ui/gallery/search/search-field/search-field.gallery.component.d.ts +0 -31
  383. package/lib/frontend/app/ui/gallery/search/search-field-base/search-field-base.gallery.component.d.ts +0 -57
  384. package/lib/frontend/app/ui/gallery/search/search-query-parser.service.d.ts +0 -7
  385. package/lib/frontend/app/ui/gallery/search/search.gallery.component.d.ts +0 -39
  386. package/lib/frontend/app/ui/gallery/share/share.gallery.component.d.ts +0 -67
  387. package/lib/frontend/app/ui/gallery/share.service.d.ts +0 -35
  388. package/lib/frontend/app/ui/gallery/thumbnailLoader.service.d.ts +0 -41
  389. package/lib/frontend/app/ui/gallery/thumbnailManager.service.d.ts +0 -46
  390. package/lib/frontend/app/ui/gallery/uploader/uploader.gallery.component.d.ts +0 -15
  391. package/lib/frontend/app/ui/gallery/uploader/uploader.service.d.ts +0 -36
  392. package/lib/frontend/app/ui/gallery/wakelock.service.d.ts +0 -19
  393. package/lib/frontend/app/ui/language/language.component.d.ts +0 -10
  394. package/lib/frontend/app/ui/login/login.component.d.ts +0 -18
  395. package/lib/frontend/app/ui/settings/extension-installer/extension-installer.component.d.ts +0 -18
  396. package/lib/frontend/app/ui/settings/extension-installer/extension-installer.service.d.ts +0 -10
  397. package/lib/frontend/app/ui/settings/gallery-statistic/gallery-statistic.component.d.ts +0 -5
  398. package/lib/frontend/app/ui/settings/scheduled-jobs.service.d.ts +0 -41
  399. package/lib/frontend/app/ui/settings/settings.service.d.ts +0 -27
  400. package/lib/frontend/app/ui/settings/sharings-list/sharings-list.component.d.ts +0 -14
  401. package/lib/frontend/app/ui/settings/template/CustomSettingsEntries.d.ts +0 -57
  402. package/lib/frontend/app/ui/settings/template/ISettingsComponent.d.ts +0 -13
  403. package/lib/frontend/app/ui/settings/template/settings-entry/settings-entry.component.d.ts +0 -118
  404. package/lib/frontend/app/ui/settings/template/settings-entry/sorting-method/sorting-method.settings-entry.component.d.ts +0 -28
  405. package/lib/frontend/app/ui/settings/template/template.component.d.ts +0 -97
  406. package/lib/frontend/app/ui/settings/users/users.component.d.ts +0 -47
  407. package/lib/frontend/app/ui/settings/users/users.service.d.ts +0 -12
  408. package/lib/frontend/app/ui/settings/workflow/button/job-button.settings.component.d.ts +0 -32
  409. package/lib/frontend/app/ui/settings/workflow/progress/job-progress.settings.component.d.ts +0 -25
  410. package/lib/frontend/app/ui/settings/workflow/workflow.component.d.ts +0 -68
  411. package/lib/frontend/app/ui/sharelogin/share-login.component.d.ts +0 -16
  412. package/lib/frontend/app/ui/utils/grid-size-icon/grid-size-icon.component.d.ts +0 -5
  413. package/lib/frontend/app/ui/utils/sorting-method-icon/sorting-method-icon.component.d.ts +0 -13
  414. package/lib/frontend/app/ui/utils/timestamp-datepicker/datepicker.component.d.ts +0 -10
  415. package/lib/frontend/app/ui/utils/timestamp-timepicker/timepicker.component.d.ts +0 -11
  416. package/lib/frontend/environments/environment.d.ts +0 -3
  417. package/lib/frontend/environments/environment.prod.d.ts +0 -3
  418. package/lib/frontend/main.d.ts +0 -21
  419. package/lib/frontend/polyfills.d.ts +0 -60
  420. package/lib/frontend/test.d.ts +0 -1
@@ -0,0 +1,1032 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SearchManager = void 0;
4
+ const tslib_1 = require("tslib");
5
+ /* eslint-disable no-case-declarations */
6
+ const AutoCompleteItem_1 = require("../../../common/entities/AutoCompleteItem");
7
+ const SQLConnection_1 = require("./SQLConnection");
8
+ const PhotoEntity_1 = require("./enitites/PhotoEntity");
9
+ const DirectoryEntity_1 = require("./enitites/DirectoryEntity");
10
+ const MediaEntity_1 = require("./enitites/MediaEntity");
11
+ const PersonEntry_1 = require("./enitites/person/PersonEntry");
12
+ const typeorm_1 = require("typeorm");
13
+ const Config_1 = require("../../../common/config/private/Config");
14
+ const SearchQueryDTO_1 = require("../../../common/entities/SearchQueryDTO");
15
+ const ObjectManagers_1 = require("../ObjectManagers");
16
+ const PrivateConfig_1 = require("../../../common/config/private/PrivateConfig");
17
+ const Utils_1 = require("../../../common/Utils");
18
+ const FileEntity_1 = require("./enitites/FileEntity");
19
+ const EntityUtils_1 = require("./enitites/EntityUtils");
20
+ const SortingMethods_1 = require("../../../common/entities/SortingMethods");
21
+ const path = tslib_1.__importStar(require("node:path"));
22
+ class SearchManager {
23
+ constructor() {
24
+ this.DIRECTORY_SELECT = [
25
+ 'directory.id',
26
+ 'directory.name',
27
+ 'directory.path',
28
+ ];
29
+ // makes all search query params unique, so typeorm won't mix them
30
+ this.queryIdBase = 0;
31
+ }
32
+ // The value of a param of like()
33
+ static likeValue(value) {
34
+ return (0, EntityUtils_1.sqlFoldsText)() ? (0, EntityUtils_1.foldText)(value) : value;
35
+ }
36
+ /**
37
+ * A text condition that ignores the accents and the case as far as the DB can, see sqlFoldsText().
38
+ * @param escape '\' escapes the wildcards of the value (MySQL does it by default, SQLite only with ESCAPE)
39
+ * @param wrap an SQL expression around the compared text (not around the IS NOT NULL check)
40
+ */
41
+ static like(field, param, options = {}) {
42
+ const op = options.negate ? 'NOT LIKE' : 'LIKE';
43
+ const wrap = options.wrap ?? ((expr) => expr);
44
+ if (Config_1.Config.Database.type === PrivateConfig_1.DatabaseType.sqlite) {
45
+ const esc = options.escape ? ' ESCAPE \'\\\'' : '';
46
+ if (!(0, EntityUtils_1.sqlFoldsText)()) {
47
+ return `${wrap(field)} ${op} :${param}${esc}`;
48
+ }
49
+ // most captions, keywords and persons are empty: those rows need no call of the JS function (idea from #1218).
50
+ // FALSE instead of NULL makes no difference, as the conditions are never negated with NOT (...)
51
+ // The raw column is checked and folded, so the wrap runs once and only for rows that have a text.
52
+ return `(${field} IS NOT NULL AND ${wrap(`fold(${field})`)} ${op} :${param}${esc})`;
53
+ }
54
+ return `${wrap(field)} ${op} :${param} COLLATE ${EntityUtils_1.SQL_COLLATE}`;
55
+ }
56
+ // Whether an autocomplete text contains what was typed, ignoring the accents and the case (like MySQL's SQL_COLLATE)
57
+ static containsText(text, value) {
58
+ return (0, EntityUtils_1.foldText)(text).toLowerCase().includes((0, EntityUtils_1.foldText)(value).toLowerCase());
59
+ }
60
+ static setSorting(query, sortings) {
61
+ if (!sortings || !Array.isArray(sortings)) {
62
+ return query;
63
+ }
64
+ if (sortings.findIndex(s => s.method == SortingMethods_1.SortByTypes.Random) !== -1 && sortings.length > 1) {
65
+ throw new Error('Error during applying sorting: Can\' randomize and also sort the result. Bad input:' + sortings.map(s => SortingMethods_1.GroupSortByTypes[s.method]).join(', '));
66
+ }
67
+ for (const sort of sortings) {
68
+ switch (sort.method) {
69
+ case SortingMethods_1.SortByTypes.Date:
70
+ if (Config_1.Config.Gallery.ignoreTimestampOffset === true) {
71
+ query.addOrderBy('media.metadata.creationDate + (coalesce(media.metadata.creationDateOffset,0) * 60000)', sort.ascending ? 'ASC' : 'DESC');
72
+ }
73
+ else {
74
+ query.addOrderBy('media.metadata.creationDate', sort.ascending ? 'ASC' : 'DESC');
75
+ }
76
+ break;
77
+ case SortingMethods_1.SortByTypes.Rating:
78
+ query.addOrderBy('media.metadata.rating', sort.ascending ? 'ASC' : 'DESC');
79
+ break;
80
+ case SortingMethods_1.SortByTypes.Name:
81
+ query.addOrderBy('media.name', sort.ascending ? 'ASC' : 'DESC');
82
+ break;
83
+ case SortingMethods_1.SortByTypes.Directory:
84
+ // Not the same order as the frontend's (GallerySortingService): that compares the paths segment by segment
85
+ // (tree order: 2020, 2020/Summer, 2021) with a numeric collator. Here it is the parent path first
86
+ // (2020, 2021, 2020/Summer) in the DB's collation, as the tree order needs a string concat that
87
+ // differs between SQLite and MySQL. The frontend re-sorts the results anyway; this order only decides
88
+ // which media survive the maxMediaResult limit and which one is the cover with AlbumCover.Sorting.
89
+ query.addOrderBy('directory.path', sort.ascending ? 'ASC' : 'DESC');
90
+ query.addOrderBy('directory.name', sort.ascending ? 'ASC' : 'DESC');
91
+ query.addOrderBy('media.name', sort.ascending ? 'ASC' : 'DESC');
92
+ break;
93
+ case SortingMethods_1.SortByTypes.PersonCount:
94
+ query.addOrderBy('media.metadata.personsLength', sort.ascending ? 'ASC' : 'DESC');
95
+ break;
96
+ case SortingMethods_1.SortByTypes.FileSize:
97
+ query.addOrderBy('media.metadata.fileSize', sort.ascending ? 'ASC' : 'DESC');
98
+ break;
99
+ case SortingMethods_1.SortByTypes.Random:
100
+ if (Config_1.Config.Database.type === PrivateConfig_1.DatabaseType.mysql) {
101
+ query.groupBy('RAND(), media.id');
102
+ }
103
+ else {
104
+ query.groupBy('RANDOM()');
105
+ }
106
+ break;
107
+ }
108
+ }
109
+ return query;
110
+ }
111
+ static autoCompleteItemsUnique(array) {
112
+ const a = array.concat();
113
+ for (let i = 0; i < a.length; ++i) {
114
+ for (let j = i + 1; j < a.length; ++j) {
115
+ if (a[i].equals(a[j])) {
116
+ a.splice(j--, 1);
117
+ }
118
+ }
119
+ }
120
+ return a;
121
+ }
122
+ async autocomplete(session, value, type) {
123
+ const connection = await SQLConnection_1.SQLConnection.getConnection();
124
+ const photoRepository = connection.getRepository(PhotoEntity_1.PhotoEntity);
125
+ const mediaRepository = connection.getRepository(MediaEntity_1.MediaEntity);
126
+ const personRepository = connection.getRepository(PersonEntry_1.PersonEntry);
127
+ const directoryRepository = connection.getRepository(DirectoryEntity_1.DirectoryEntity);
128
+ const partialResult = [];
129
+ if (type === SearchQueryDTO_1.SearchQueryTypes.any_text ||
130
+ type === SearchQueryDTO_1.SearchQueryTypes.keyword) {
131
+ const acList = [];
132
+ const q = photoRepository
133
+ .createQueryBuilder('media')
134
+ .select('DISTINCT(media.metadata.keywords)')
135
+ .where(SearchManager.like('media.metadata.keywords', 'valueKW'), {
136
+ valueKW: SearchManager.likeValue('%' + value + '%'),
137
+ });
138
+ if (session.projectionQuery) {
139
+ if (session.hasDirectoryProjection) {
140
+ q.leftJoin('media.directory', 'directory');
141
+ }
142
+ q.andWhere(session.projectionQuery);
143
+ }
144
+ q.limit(Config_1.Config.Search.AutoComplete.ItemsPerCategory.keyword);
145
+ (await q.getRawMany())
146
+ .map((r) => r.metadataKeywords.split(','))
147
+ .forEach((keywords) => {
148
+ acList.push(...this.encapsulateAutoComplete(keywords.filter((k) => SearchManager.containsText(k, value)), SearchQueryDTO_1.SearchQueryTypes.keyword));
149
+ });
150
+ partialResult.push(acList);
151
+ }
152
+ if (type === SearchQueryDTO_1.SearchQueryTypes.any_text ||
153
+ type === SearchQueryDTO_1.SearchQueryTypes.person) {
154
+ // make sure all persons have up-to-date cache
155
+ await ObjectManagers_1.ObjectManagers.getInstance().PersonManager.getAll(session);
156
+ partialResult.push(this.encapsulateAutoComplete((await personRepository
157
+ .createQueryBuilder('person')
158
+ .select('DISTINCT(person.name), cache.count')
159
+ .leftJoin('person.cache', 'cache', 'cache.projectionKey = :pk', { pk: session.user.projectionKey })
160
+ .where(SearchManager.like('person.name', 'value'), {
161
+ value: SearchManager.likeValue('%' + value + '%'),
162
+ })
163
+ .andWhere('cache.count > 0 AND cache.valid = 1')
164
+ .limit(Config_1.Config.Search.AutoComplete.ItemsPerCategory.person)
165
+ .orderBy('cache.count', 'DESC')
166
+ .getRawMany()).map((r) => r.name), SearchQueryDTO_1.SearchQueryTypes.person));
167
+ }
168
+ if (type === SearchQueryDTO_1.SearchQueryTypes.any_text ||
169
+ type === SearchQueryDTO_1.SearchQueryTypes.position ||
170
+ type === SearchQueryDTO_1.SearchQueryTypes.distance) {
171
+ const acList = [];
172
+ const q = photoRepository
173
+ .createQueryBuilder('media')
174
+ .select('media.metadata.positionData.country as country, ' +
175
+ 'media.metadata.positionData.state as state, media.metadata.positionData.city as city');
176
+ const b = new typeorm_1.Brackets((q) => {
177
+ q.where(SearchManager.like('media.metadata.positionData.country', 'value'), { value: SearchManager.likeValue('%' + value + '%') }).orWhere(SearchManager.like('media.metadata.positionData.state', 'value'), { value: SearchManager.likeValue('%' + value + '%') }).orWhere(SearchManager.like('media.metadata.positionData.city', 'value'), { value: SearchManager.likeValue('%' + value + '%') });
178
+ });
179
+ q.where(b);
180
+ if (session.projectionQuery) {
181
+ if (session.hasDirectoryProjection) {
182
+ q.leftJoin('media.directory', 'directory');
183
+ }
184
+ q.andWhere(session.projectionQuery);
185
+ }
186
+ q.groupBy('media.metadata.positionData.country, media.metadata.positionData.state, media.metadata.positionData.city')
187
+ .limit(Config_1.Config.Search.AutoComplete.ItemsPerCategory.position);
188
+ (await q.getRawMany())
189
+ .filter((pm) => !!pm)
190
+ .map((pm) => [pm.city || '', pm.country || '', pm.state || ''])
191
+ .forEach((positions) => {
192
+ acList.push(...this.encapsulateAutoComplete(positions.filter((p) => SearchManager.containsText(p, value)), type === SearchQueryDTO_1.SearchQueryTypes.distance
193
+ ? type
194
+ : SearchQueryDTO_1.SearchQueryTypes.position));
195
+ });
196
+ partialResult.push(acList);
197
+ }
198
+ if (type === SearchQueryDTO_1.SearchQueryTypes.any_text ||
199
+ type === SearchQueryDTO_1.SearchQueryTypes.file_name) {
200
+ const q = mediaRepository
201
+ .createQueryBuilder('media')
202
+ .select('DISTINCT(media.name)')
203
+ .where(SearchManager.like('media.name', 'value'), {
204
+ value: SearchManager.likeValue('%' + value + '%'),
205
+ });
206
+ if (session.projectionQuery) {
207
+ if (session.hasDirectoryProjection) {
208
+ q.leftJoin('media.directory', 'directory');
209
+ }
210
+ q.andWhere(session.projectionQuery);
211
+ }
212
+ q.limit(Config_1.Config.Search.AutoComplete.ItemsPerCategory.fileName);
213
+ partialResult.push(this.encapsulateAutoComplete((await q.getRawMany()).map((r) => r.name), SearchQueryDTO_1.SearchQueryTypes.file_name));
214
+ }
215
+ if (type === SearchQueryDTO_1.SearchQueryTypes.any_text ||
216
+ type === SearchQueryDTO_1.SearchQueryTypes.caption) {
217
+ const q = photoRepository
218
+ .createQueryBuilder('media')
219
+ .select('DISTINCT(media.metadata.caption) as caption')
220
+ .where(SearchManager.like('media.metadata.caption', 'value'), { value: SearchManager.likeValue('%' + value + '%') });
221
+ if (session.projectionQuery) {
222
+ if (session.hasDirectoryProjection) {
223
+ q.leftJoin('media.directory', 'directory');
224
+ }
225
+ q.andWhere(session.projectionQuery);
226
+ }
227
+ q.limit(Config_1.Config.Search.AutoComplete.ItemsPerCategory.caption);
228
+ partialResult.push(this.encapsulateAutoComplete((await q.getRawMany()).map((r) => r.caption), SearchQueryDTO_1.SearchQueryTypes.caption));
229
+ }
230
+ if (type === SearchQueryDTO_1.SearchQueryTypes.any_text ||
231
+ type === SearchQueryDTO_1.SearchQueryTypes.directory) {
232
+ const dirQ = directoryRepository
233
+ .createQueryBuilder('directory')
234
+ .leftJoinAndSelect('directory.cache', 'cache', 'cache.projectionKey = :pk AND cache.valid = 1', { pk: session.user.projectionKey })
235
+ .where(SearchManager.like('directory.name', 'value'), {
236
+ value: SearchManager.likeValue('%' + value + '%'),
237
+ })
238
+ .andWhere('(cache.recursiveMediaCount > 0 OR cache.id is NULL)');
239
+ session.directoryAccess.filterDirectoryQuery(dirQ, 'directory');
240
+ const dirs = await dirQ
241
+ .limit(Config_1.Config.Search.AutoComplete.ItemsPerCategory.directory)
242
+ .getMany();
243
+ // fill cache as we need it for this autocomplete search
244
+ for (const dir of dirs) {
245
+ if (!dir.cache?.valid) {
246
+ dir.cache = await ObjectManagers_1.ObjectManagers.getInstance().ProjectedCacheManager.setAndGetCacheForDirectory(connection, session, dir);
247
+ }
248
+ }
249
+ partialResult.push(this.encapsulateAutoComplete(dirs.filter(d => d.cache.valid && session.directoryAccess.isListedInSearch(d.cache)).map((r) => r.name), SearchQueryDTO_1.SearchQueryTypes.directory));
250
+ }
251
+ const result = [];
252
+ while (result.length < Config_1.Config.Search.AutoComplete.ItemsPerCategory.maxItems) {
253
+ let adding = false;
254
+ for (let i = 0; i < partialResult.length; ++i) {
255
+ const item = partialResult[i].shift(); // first elements are more important
256
+ if (!item) {
257
+ continue;
258
+ }
259
+ result.push(item);
260
+ adding = true;
261
+ }
262
+ if (!adding) {
263
+ break;
264
+ }
265
+ }
266
+ return SearchManager.autoCompleteItemsUnique(result);
267
+ }
268
+ async search(session, queryIN) {
269
+ const query = await this.prepareQuery(queryIN);
270
+ const connection = await SQLConnection_1.SQLConnection.getConnection();
271
+ const result = {
272
+ searchQuery: queryIN,
273
+ directories: [],
274
+ media: [],
275
+ metaFile: [],
276
+ resultOverflow: false,
277
+ };
278
+ const q = connection
279
+ .getRepository(MediaEntity_1.MediaEntity)
280
+ .createQueryBuilder('media')
281
+ .select(['media', ...this.DIRECTORY_SELECT])
282
+ .where(this.buildWhereQuery(query))
283
+ .leftJoin('media.directory', 'directory')
284
+ .limit(Config_1.Config.Search.maxMediaResult + 1);
285
+ if (session.projectionQuery) {
286
+ q.andWhere(session.projectionQuery);
287
+ }
288
+ result.media = await q.getMany();
289
+ if (result.media.length > Config_1.Config.Search.maxMediaResult) {
290
+ result.resultOverflow = true;
291
+ }
292
+ if (Config_1.Config.Search.listMetafiles === true) {
293
+ const dIds = Array.from(new Set(result.media.map(m => m.directory.id)));
294
+ result.metaFile = [];
295
+ if (dIds.length > 0) {
296
+ result.metaFile = await connection
297
+ .getRepository(FileEntity_1.FileEntity)
298
+ .createQueryBuilder('file')
299
+ .select(['file', ...this.DIRECTORY_SELECT])
300
+ .where(`file.directoryId IN(${dIds.join(',')})`)
301
+ .leftJoin('file.directory', 'directory')
302
+ .getMany();
303
+ }
304
+ }
305
+ if (Config_1.Config.Search.listDirectories === true) {
306
+ const dirQuery = this.filterDirectoryQuery(query);
307
+ if (dirQuery !== null) {
308
+ const dirSQLQuery = connection
309
+ .getRepository(DirectoryEntity_1.DirectoryEntity)
310
+ .createQueryBuilder('directory')
311
+ .where(this.buildWhereQuery(dirQuery, true));
312
+ session.directoryAccess.filterDirectoryQuery(dirSQLQuery, 'directory');
313
+ result.directories = await dirSQLQuery
314
+ .leftJoin('directory.cache', 'cache', 'cache.projectionKey = :pk AND cache.valid = 1', { pk: session.user.projectionKey })
315
+ .leftJoin('cache.cover', 'cover')
316
+ .leftJoin('cover.directory', 'coverDirectory')
317
+ .limit(Config_1.Config.Search.maxDirectoryResult + 1)
318
+ .select([
319
+ 'directory',
320
+ 'cache.valid',
321
+ 'cache.oldestMedia',
322
+ 'cache.youngestMedia',
323
+ 'cache.mediaCount',
324
+ 'cache.recursiveMediaCount',
325
+ 'cover.name',
326
+ 'coverDirectory.name',
327
+ 'coverDirectory.path',
328
+ ])
329
+ .getMany();
330
+ // setting covers
331
+ if (result.directories) {
332
+ for (const item of result.directories) {
333
+ await ObjectManagers_1.ObjectManagers.getInstance().GalleryManager.fillCacheForSubDir(connection, session, item);
334
+ }
335
+ }
336
+ // do not show empty directories in search results
337
+ result.directories = result.directories.filter(d => session.directoryAccess.isListedInSearch(d.cache));
338
+ if (result.directories.length > Config_1.Config.Search.maxDirectoryResult) {
339
+ result.resultOverflow = true;
340
+ }
341
+ }
342
+ }
343
+ return result;
344
+ }
345
+ async getNMedia(session, query, sortings, take, photoOnly = false) {
346
+ const connection = await SQLConnection_1.SQLConnection.getConnection();
347
+ const sqlQuery = connection
348
+ .getRepository(photoOnly ? PhotoEntity_1.PhotoEntity : MediaEntity_1.MediaEntity)
349
+ .createQueryBuilder('media')
350
+ .select(['media', ...this.DIRECTORY_SELECT])
351
+ .innerJoin('media.directory', 'directory')
352
+ .where(await this.prepareAndBuildWhereQuery(query));
353
+ if (session.projectionQuery) {
354
+ sqlQuery.andWhere(session.projectionQuery);
355
+ }
356
+ SearchManager.setSorting(sqlQuery, sortings);
357
+ return sqlQuery.limit(take).getMany();
358
+ }
359
+ async getCount(session, query) {
360
+ const connection = await SQLConnection_1.SQLConnection.getConnection();
361
+ const q = connection
362
+ .getRepository(MediaEntity_1.MediaEntity)
363
+ .createQueryBuilder('media')
364
+ .innerJoin('media.directory', 'directory')
365
+ .where(await this.prepareAndBuildWhereQuery(query));
366
+ if (session.projectionQuery) {
367
+ q.andWhere(session.projectionQuery);
368
+ }
369
+ return await q.getCount();
370
+ }
371
+ async prepareAndBuildWhereQuery(queryIN, directoryOnly = false, aliases = {}) {
372
+ let query = await this.prepareQuery(queryIN);
373
+ if (directoryOnly) {
374
+ const dirQuery = this.filterDirectoryQuery(query);
375
+ if (dirQuery === null) {
376
+ return null;
377
+ }
378
+ query = dirQuery;
379
+ }
380
+ return this.buildWhereQuery(query, directoryOnly, aliases);
381
+ }
382
+ async prepareQuery(queryIN) {
383
+ let query = this.expandDirectoryGlobs(Utils_1.Utils.clone(queryIN));
384
+ query = this.assignQueryIDs(query); // assign local ids before flattening SOME_OF queries
385
+ query = this.flattenSameOfQueries(query);
386
+ query = await this.getGPSData(query);
387
+ query = this.convertMatchTypeToGlob(query);
388
+ return query;
389
+ }
390
+ /**
391
+ * Builds the SQL Where query from search query
392
+ * @param query input search query
393
+ * @param directoryOnly Only builds directory related queries
394
+ * @param aliases for SQL alias mapping
395
+ * @private
396
+ */
397
+ buildWhereQuery(query, directoryOnly = false, aliases = {}) {
398
+ const queryId = query.queryId;
399
+ switch (query.type) {
400
+ case SearchQueryDTO_1.SearchQueryTypes.AND:
401
+ return new typeorm_1.Brackets((q) => {
402
+ query.list.forEach((sq) => {
403
+ q.andWhere(this.buildWhereQuery(sq, directoryOnly, aliases));
404
+ });
405
+ return q;
406
+ });
407
+ case SearchQueryDTO_1.SearchQueryTypes.OR:
408
+ return new typeorm_1.Brackets((q) => {
409
+ query.list.forEach((sq) => {
410
+ q.orWhere(this.buildWhereQuery(sq, directoryOnly, aliases));
411
+ });
412
+ return q;
413
+ });
414
+ case SearchQueryDTO_1.SearchQueryTypes.distance:
415
+ if (directoryOnly) {
416
+ throw new Error('not supported in directoryOnly mode');
417
+ }
418
+ /**
419
+ * This is a best effort calculation, not fully accurate in order to have higher performance.
420
+ * see: https://stackoverflow.com/a/50506609
421
+ */
422
+ const earth = 6378.137; // radius of the earth in kilometer
423
+ const latDelta = 1 / (((2 * Math.PI) / 360) * earth); // 1 km in degree
424
+ const lonDelta = 1 / (((2 * Math.PI) / 360) * earth); // 1 km in degree
425
+ const gps = query.from.GPSData;
426
+ if (gps?.latitude == null || gps.longitude == null) {
427
+ throw new Error('Distance search query has no GPS coordinates');
428
+ }
429
+ // TODO: properly handle latitude / longitude boundaries
430
+ const trimRange = (value, min, max) => {
431
+ return Math.min(Math.max(value, min), max);
432
+ };
433
+ const minLat = trimRange(gps.latitude -
434
+ query.distance * latDelta, -90, 90);
435
+ const maxLat = trimRange(gps.latitude +
436
+ query.distance * latDelta, -90, 90);
437
+ const minLon = trimRange(gps.longitude -
438
+ (query.distance * lonDelta) /
439
+ Math.cos(minLat * (Math.PI / 180)), -180, 180);
440
+ const maxLon = trimRange(gps.longitude +
441
+ (query.distance * lonDelta) /
442
+ Math.cos(maxLat * (Math.PI / 180)), -180, 180);
443
+ return new typeorm_1.Brackets((q) => {
444
+ const textParam = {};
445
+ textParam['maxLat' + queryId] = maxLat;
446
+ textParam['minLat' + queryId] = minLat;
447
+ textParam['maxLon' + queryId] = maxLon;
448
+ textParam['minLon' + queryId] = minLon;
449
+ if (!query.negate) {
450
+ q.where(`media.metadata.positionData.GPSData.latitude < :maxLat${queryId}`, textParam);
451
+ q.andWhere(`media.metadata.positionData.GPSData.latitude > :minLat${queryId}`, textParam);
452
+ q.andWhere(`media.metadata.positionData.GPSData.longitude < :maxLon${queryId}`, textParam);
453
+ q.andWhere(`media.metadata.positionData.GPSData.longitude > :minLon${queryId}`, textParam);
454
+ }
455
+ else {
456
+ q.where(`media.metadata.positionData.GPSData.latitude > :maxLat${queryId}`, textParam);
457
+ q.orWhere(`media.metadata.positionData.GPSData.latitude < :minLat${queryId}`, textParam);
458
+ q.orWhere(`media.metadata.positionData.GPSData.longitude > :maxLon${queryId}`, textParam);
459
+ q.orWhere(`media.metadata.positionData.GPSData.longitude < :minLon${queryId}`, textParam);
460
+ }
461
+ return q;
462
+ });
463
+ case SearchQueryDTO_1.SearchQueryTypes.rating:
464
+ case SearchQueryDTO_1.SearchQueryTypes.date:
465
+ case SearchQueryDTO_1.SearchQueryTypes.person_count:
466
+ case SearchQueryDTO_1.SearchQueryTypes.resolution:
467
+ if (directoryOnly) {
468
+ throw new Error('not supported in directoryOnly mode');
469
+ }
470
+ if (typeof query.min === 'undefined' && typeof query.max === 'undefined') {
471
+ throw new Error(`Invalid search query: ${SearchQueryDTO_1.SearchQueryTypes[query.type]}(type: ${query.type}) query should contain min or max value. Query got: ${JSON.stringify(query)}`);
472
+ }
473
+ let field = '';
474
+ let timeOffset = '';
475
+ let min = query.min;
476
+ let max = query.max;
477
+ switch (query.type) {
478
+ case SearchQueryDTO_1.SearchQueryTypes.date:
479
+ timeOffset = Config_1.Config.Gallery.ignoreTimestampOffset === true ? ' + (coalesce(media.metadata.creationDateOffset,0) * 60000)' : '';
480
+ field = 'media.metadata.creationDate';
481
+ break;
482
+ case SearchQueryDTO_1.SearchQueryTypes.rating:
483
+ field = 'media.metadata.rating';
484
+ break;
485
+ case SearchQueryDTO_1.SearchQueryTypes.person_count:
486
+ field = 'media.metadata.personsLength';
487
+ break;
488
+ case SearchQueryDTO_1.SearchQueryTypes.resolution:
489
+ field = 'media.metadata.size.width * media.metadata.size.height';
490
+ if (min) {
491
+ min *= 1000 * 1000;
492
+ }
493
+ if (max) {
494
+ max *= 1000 * 1000;
495
+ }
496
+ break;
497
+ }
498
+ return new typeorm_1.Brackets((q) => {
499
+ const textParam = {};
500
+ if (min === max) {
501
+ textParam['eql' + queryId] = min;
502
+ q.where(`${field} ${timeOffset} = :eql${queryId}`, textParam);
503
+ return q;
504
+ }
505
+ const minRelation = query.negate ? '<' : '>=';
506
+ const maxRelation = query.negate ? '>' : '<=';
507
+ if (typeof min !== 'undefined') {
508
+ textParam['min' + queryId] = min;
509
+ q.where(`${field} ${timeOffset} ${minRelation} :min${queryId}`, textParam);
510
+ }
511
+ if (typeof max !== 'undefined') {
512
+ textParam['max' + queryId] = max;
513
+ q.andWhere(`${field} ${timeOffset} ${maxRelation} :max${queryId}`, textParam);
514
+ }
515
+ return q;
516
+ });
517
+ case SearchQueryDTO_1.SearchQueryTypes.orientation:
518
+ if (directoryOnly) {
519
+ throw new Error('not supported in directoryOnly mode');
520
+ }
521
+ return new typeorm_1.Brackets((q) => {
522
+ if (query.landscape) {
523
+ q.where('media.metadata.size.width >= media.metadata.size.height');
524
+ }
525
+ else {
526
+ q.where('media.metadata.size.width <= media.metadata.size.height');
527
+ }
528
+ return q;
529
+ });
530
+ case SearchQueryDTO_1.SearchQueryTypes.date_pattern: {
531
+ if (directoryOnly) {
532
+ throw new Error('not supported in directoryOnly mode');
533
+ }
534
+ const tq = query;
535
+ return new typeorm_1.Brackets((q) => {
536
+ // Fixed frequency
537
+ if ((tq.frequency === SearchQueryDTO_1.DatePatternFrequency.years_ago ||
538
+ tq.frequency === SearchQueryDTO_1.DatePatternFrequency.months_ago ||
539
+ tq.frequency === SearchQueryDTO_1.DatePatternFrequency.weeks_ago ||
540
+ tq.frequency === SearchQueryDTO_1.DatePatternFrequency.days_ago)) {
541
+ if (tq.agoNumber == null || isNaN(tq.agoNumber)) {
542
+ throw new Error('ago number is missing on date pattern search query with frequency: ' + SearchQueryDTO_1.DatePatternFrequency[tq.frequency] + ', ago number: ' + tq.agoNumber);
543
+ }
544
+ const to = new Date();
545
+ to.setHours(0, 0, 0, 0);
546
+ to.setUTCDate(to.getUTCDate() + 1);
547
+ switch (tq.frequency) {
548
+ case SearchQueryDTO_1.DatePatternFrequency.days_ago:
549
+ to.setUTCDate(to.getUTCDate() - tq.agoNumber);
550
+ break;
551
+ case SearchQueryDTO_1.DatePatternFrequency.weeks_ago:
552
+ to.setUTCDate(to.getUTCDate() - tq.agoNumber * 7);
553
+ break;
554
+ case SearchQueryDTO_1.DatePatternFrequency.months_ago:
555
+ to.setTime(Utils_1.Utils.addMonthToDate(to, -1 * tq.agoNumber).getTime());
556
+ break;
557
+ case SearchQueryDTO_1.DatePatternFrequency.years_ago:
558
+ to.setUTCFullYear(to.getUTCFullYear() - tq.agoNumber);
559
+ break;
560
+ }
561
+ const from = new Date(to);
562
+ from.setUTCDate(from.getUTCDate() - tq.daysLength);
563
+ const textParam = {};
564
+ textParam['to' + queryId] = to.getTime();
565
+ textParam['from' + queryId] = from.getTime();
566
+ if (tq.negate) {
567
+ if (Config_1.Config.Gallery.ignoreTimestampOffset === true) {
568
+ q.where(`(media.metadata.creationDate + (coalesce(media.metadata.creationDateOffset,0) * 60000)) >= :to${queryId}`, textParam).orWhere(`(media.metadata.creationDate + (coalesce(media.metadata.creationDateOffset,0) * 60000)) < :from${queryId}`, textParam);
569
+ }
570
+ else {
571
+ q.where(`media.metadata.creationDate >= :to${queryId}`, textParam).orWhere(`media.metadata.creationDate < :from${queryId}`, textParam);
572
+ }
573
+ }
574
+ else {
575
+ if (Config_1.Config.Gallery.ignoreTimestampOffset === true) {
576
+ q.where(`(media.metadata.creationDate + (coalesce(media.metadata.creationDateOffset,0) * 60000)) < :to${queryId}`, textParam).andWhere(`(media.metadata.creationDate + (coalesce(media.metadata.creationDateOffset,0) * 60000)) >= :from${queryId}`, textParam);
577
+ }
578
+ else {
579
+ q.where(`media.metadata.creationDate < :to${queryId}`, textParam).andWhere(`media.metadata.creationDate >= :from${queryId}`, textParam);
580
+ }
581
+ }
582
+ }
583
+ else {
584
+ // recurring
585
+ const textParam = {};
586
+ textParam['diff' + queryId] = tq.daysLength;
587
+ const addWhere = (duration, crossesDateBoundary) => {
588
+ const relationEql = tq.negate ? '!=' : '=';
589
+ // reminder: !(a&&b) = (!a || !b), that is what happening here if negate is true
590
+ const relationTop = tq.negate ? '>' : '<=';
591
+ const relationBottom = tq.negate ? '<=' : '>';
592
+ // this is an XoR. during date boundary crossing we swap boolean logic again
593
+ const whereFN = !!tq.negate !== crossesDateBoundary ? 'orWhere' : 'andWhere';
594
+ if (Config_1.Config.Database.type === PrivateConfig_1.DatabaseType.sqlite) {
595
+ if (tq.daysLength == 0) {
596
+ if (Config_1.Config.Gallery.ignoreTimestampOffset === true) {
597
+ q.where(`CAST(strftime('${duration}',(media.metadataCreationDate + (media.metadataCreationDateOffset * 60000))/1000, 'unixepoch') AS INTEGER) ${relationEql} CAST(strftime('${duration}','now') AS INTEGER)`);
598
+ }
599
+ else {
600
+ q.where(`CAST(strftime('${duration}',media.metadataCreationDate/1000, 'unixepoch') AS INTEGER) ${relationEql} CAST(strftime('${duration}','now') AS INTEGER)`);
601
+ }
602
+ }
603
+ else {
604
+ if (Config_1.Config.Gallery.ignoreTimestampOffset === true) {
605
+ q.where(`CAST(strftime('${duration}',(media.metadataCreationDate + (media.metadataCreationDateOffset * 60000))/1000, 'unixepoch') AS INTEGER) ${relationTop} CAST(strftime('${duration}','now') AS INTEGER)`)[whereFN](`CAST(strftime('${duration}',(media.metadataCreationDate + (media.metadataCreationDateOffset * 60000))/1000, 'unixepoch') AS INTEGER) ${relationBottom} CAST(strftime('${duration}','now','-:diff${queryId} day') AS INTEGER)`, textParam);
606
+ }
607
+ else {
608
+ q.where(`CAST(strftime('${duration}',media.metadataCreationDate/1000, 'unixepoch') AS INTEGER) ${relationTop} CAST(strftime('${duration}','now') AS INTEGER)`)[whereFN](`CAST(strftime('${duration}',media.metadataCreationDate/1000, 'unixepoch') AS INTEGER) ${relationBottom} CAST(strftime('${duration}','now','-:diff${queryId} day') AS INTEGER)`, textParam);
609
+ }
610
+ }
611
+ }
612
+ else {
613
+ if (tq.daysLength == 0) {
614
+ if (Config_1.Config.Gallery.ignoreTimestampOffset === true) {
615
+ q.where(`CAST(FROM_UNIXTIME((media.metadataCreationDate + (media.metadataCreationDateOffset * 60000))/1000, '${duration}') AS SIGNED) ${relationEql} CAST(DATE_FORMAT(CURDATE(),'${duration}') AS SIGNED)`);
616
+ }
617
+ else {
618
+ q.where(`CAST(FROM_UNIXTIME(media.metadataCreationDate/1000, '${duration}') AS SIGNED) ${relationEql} CAST(DATE_FORMAT(CURDATE(),'${duration}') AS SIGNED)`);
619
+ }
620
+ }
621
+ else {
622
+ if (Config_1.Config.Gallery.ignoreTimestampOffset === true) {
623
+ q.where(`CAST(FROM_UNIXTIME((media.metadataCreationDate + (media.metadataCreationDateOffset * 60000))/1000, '${duration}') AS SIGNED) ${relationTop} CAST(DATE_FORMAT(CURDATE(),'${duration}') AS SIGNED)`)[whereFN](`CAST(FROM_UNIXTIME((media.metadataCreationDate + (media.metadataCreationDateOffset * 60000))/1000, '${duration}') AS SIGNED) ${relationBottom} CAST(DATE_FORMAT((DATE_ADD(curdate(), INTERVAL -:diff${queryId} DAY)),'${duration}') AS SIGNED)`, textParam);
624
+ }
625
+ else {
626
+ q.where(`CAST(FROM_UNIXTIME(media.metadataCreationDate/1000, '${duration}') AS SIGNED) ${relationTop} CAST(DATE_FORMAT(CURDATE(),'${duration}') AS SIGNED)`)[whereFN](`CAST(FROM_UNIXTIME(media.metadataCreationDate/1000, '${duration}') AS SIGNED) ${relationBottom} CAST(DATE_FORMAT((DATE_ADD(curdate(), INTERVAL -:diff${queryId} DAY)),'${duration}') AS SIGNED)`, textParam);
627
+ }
628
+ }
629
+ }
630
+ };
631
+ switch (tq.frequency) {
632
+ case SearchQueryDTO_1.DatePatternFrequency.every_year:
633
+ const d = new Date();
634
+ if (tq.daysLength >= (Utils_1.Utils.isDateFromLeapYear(d) ? 366 : 365)) { // trivial result includes all photos
635
+ if (tq.negate) {
636
+ q.andWhere('FALSE');
637
+ }
638
+ return q;
639
+ }
640
+ const dayOfYear = Utils_1.Utils.getDayOfYear(d);
641
+ addWhere('%m%d', dayOfYear - tq.daysLength < 0);
642
+ break;
643
+ case SearchQueryDTO_1.DatePatternFrequency.every_month:
644
+ if (tq.daysLength >= 31) { // trivial result includes all photos
645
+ if (tq.negate) {
646
+ q.andWhere('FALSE');
647
+ }
648
+ return q;
649
+ }
650
+ addWhere('%d', (new Date()).getUTCDate() - tq.daysLength < 0);
651
+ break;
652
+ case SearchQueryDTO_1.DatePatternFrequency.every_week:
653
+ if (tq.daysLength >= 7) { // trivial result includes all photos
654
+ if (tq.negate) {
655
+ q.andWhere('FALSE');
656
+ }
657
+ return q;
658
+ }
659
+ addWhere('%w', (new Date()).getUTCDay() - tq.daysLength < 0);
660
+ break;
661
+ }
662
+ }
663
+ return q;
664
+ });
665
+ }
666
+ case SearchQueryDTO_1.SearchQueryTypes.SOME_OF:
667
+ throw new Error('Some of not supported');
668
+ }
669
+ // this should be a text search from here on
670
+ if (!SearchQueryDTO_1.TextSearchQueryTypes.includes(query.type)) {
671
+ throw new Error(`Invalid search query: Unknown query type: ${SearchQueryDTO_1.SearchQueryTypes[query.type]}(type: ${query.type})`);
672
+ }
673
+ const matchType = query.matchType;
674
+ if (matchType !== SearchQueryDTO_1.TextSearchQueryMatchTypes.globMatch) {
675
+ throw new Error(`Invalid text search query match type: ${matchType === undefined ? matchType : SearchQueryDTO_1.TextSearchQueryMatchTypes[matchType]}, it should be glob`);
676
+ }
677
+ // it should be only glob-matched text searches
678
+ if (typeof query.value === 'undefined') {
679
+ throw new Error(`Invalid search query: ${SearchQueryDTO_1.SearchQueryTypes[query.type]}(type: ${query.type}) query should contain 'value' property. Query got: ${JSON.stringify(query)}`);
680
+ }
681
+ return new typeorm_1.Brackets((q) => {
682
+ const convertGlobToLike = (str) => {
683
+ // Match either an escaped character \\(.) or any unescaped SQL/glob special character
684
+ return str.replace(/\\(.)|([*?%_])/g, (_, escaped, special) => {
685
+ if (escaped) {
686
+ if (escaped === '*' || escaped === '?') {
687
+ return escaped;
688
+ } // \* -> *, \? -> ?
689
+ if (escaped === '\\') {
690
+ return '\\\\';
691
+ } // \\ -> \\
692
+ return '\\' + escaped; // e.g., \% -> \%
693
+ }
694
+ // Handle unescaped special characters
695
+ if (special === '*') {
696
+ return '%';
697
+ }
698
+ if (special === '?') {
699
+ return '_';
700
+ }
701
+ return '\\' + special; // % -> \%, _ -> \_
702
+ });
703
+ };
704
+ const createMatchString = (str) => {
705
+ return convertGlobToLike(str);
706
+ // MySQL uses C escape syntax in strings, details:
707
+ // https://stackoverflow.com/questions/14926386/how-to-search-for-slash-in-mysql-and-why-escaping-not-required-for-wher
708
+ /*
709
+ if (Config.Database.type === DatabaseType.mysql) {
710
+ /// this reqExp replaces the "\\" to "\\\\\"
711
+ return '%' + str.replace(new RegExp('\\\\', 'g'), '\\\\') + '%';
712
+ }
713
+ return `%${str}%`;*/
714
+ };
715
+ // if the expression is negated, we use AND instead of OR as nowhere should that match
716
+ const whereFN = query.negate ? 'andWhere' : 'orWhere';
717
+ const whereFNRev = query.negate ? 'orWhere' : 'andWhere';
718
+ // A double space in a name is usually a typo, and the search query parser collapses it (#1309),
719
+ // so runs of spaces are collapsed on both sides. The three REPLACEs collapse up to 8 spaces.
720
+ const collapseSpaces = (fieldName) => `REPLACE(REPLACE(REPLACE(${fieldName}, ' ', ' '), ' ', ' '), ' ', ' ')`;
721
+ const textValue = query.value.replace(/ {2,}/g, ' ');
722
+ const likeValue = (value) => SearchManager.likeValue(value);
723
+ // convertGlobToLike escapes with '\', that is the default in MySQL but SQLite has no default escape character
724
+ const likeExpr = (field, paramName, wrap) => SearchManager.like(field, paramName + queryId, { negate: query.negate, escape: true, wrap });
725
+ const getLikeExpr = (fieldName, paramName) => likeExpr(fieldName, paramName, collapseSpaces);
726
+ const textParam = {};
727
+ textParam['text' + queryId] = likeValue(createMatchString(textValue));
728
+ if (query.type === SearchQueryDTO_1.SearchQueryTypes.any_text ||
729
+ query.type === SearchQueryDTO_1.SearchQueryTypes.directory) {
730
+ const dirPathStr = textValue.replace(new RegExp('\\\\', 'g'), '/');
731
+ const alias = aliases['directory'] ?? 'directory';
732
+ // Glob conversion uses '\' as escape character, so the path is processed with '/' separators,
733
+ // and only the final LIKE pattern is converted to the OS specific separator that is stored in the DB.
734
+ const toDBSeparator = (likeStr) => {
735
+ if (path.sep === '/') {
736
+ return likeStr;
737
+ }
738
+ // '\' is the LIKE escape character in both DBs (see getLikeExpr), so it needs to be escaped
739
+ return likeStr.replace(/\//g, '\\\\');
740
+ };
741
+ const fullDirPath = path.posix.normalize(path.posix.join('./', dirPathStr));
742
+ textParam['fullPath' + queryId] = likeValue(toDBSeparator(createMatchString(fullDirPath)));
743
+ q[whereFN](getLikeExpr(`${alias}.path`, 'fullPath'), textParam);
744
+ const directoryPath = {
745
+ name: path.posix.basename(fullDirPath),
746
+ parent: path.posix.join(path.posix.dirname(fullDirPath), '/'),
747
+ };
748
+ q[whereFN](new typeorm_1.Brackets((dq) => {
749
+ textParam['dirName' + queryId] = likeValue(createMatchString(directoryPath.name));
750
+ dq[whereFNRev](getLikeExpr(`${alias}.name`, 'dirName'), textParam);
751
+ if (dirPathStr.includes('/')) {
752
+ textParam['parentName' + queryId] = likeValue(toDBSeparator(createMatchString(directoryPath.parent)));
753
+ dq[whereFNRev](getLikeExpr(`${alias}.path`, 'parentName'), textParam);
754
+ }
755
+ return dq;
756
+ }));
757
+ }
758
+ if ((query.type === SearchQueryDTO_1.SearchQueryTypes.any_text && !directoryOnly) ||
759
+ query.type === SearchQueryDTO_1.SearchQueryTypes.file_name) {
760
+ q[whereFN](getLikeExpr('media.name', 'text'), textParam);
761
+ }
762
+ if ((query.type === SearchQueryDTO_1.SearchQueryTypes.any_text && !directoryOnly) ||
763
+ query.type === SearchQueryDTO_1.SearchQueryTypes.caption) {
764
+ q[whereFN](getLikeExpr('media.metadata.caption', 'text'), textParam);
765
+ }
766
+ if ((query.type === SearchQueryDTO_1.SearchQueryTypes.any_text && !directoryOnly) ||
767
+ query.type === SearchQueryDTO_1.SearchQueryTypes.position) {
768
+ q[whereFN](getLikeExpr('media.metadata.positionData.country', 'text'), textParam)[whereFN](getLikeExpr('media.metadata.positionData.state', 'text'), textParam)[whereFN](getLikeExpr('media.metadata.positionData.city', 'text'), textParam);
769
+ }
770
+ // Matching for array type fields
771
+ const matchArrayField = (fieldName) => {
772
+ q[whereFN](new typeorm_1.Brackets((qbr) => {
773
+ qbr[whereFN](new typeorm_1.Brackets((qb) => {
774
+ const globPattern = convertGlobToLike(query.value);
775
+ textParam['CtextC' + queryId] = likeValue(`%,${globPattern},%`);
776
+ if ((0, EntityUtils_1.sqlFoldsText)()) {
777
+ // with a comma on both ends one pattern covers all four cases: one fold() call per row instead of four
778
+ qb[whereFN](likeExpr(fieldName, 'CtextC', (expr) => `(',' || ${expr} || ',')`), textParam);
779
+ return;
780
+ }
781
+ textParam['Ctext' + queryId] = likeValue(`%,${globPattern}`);
782
+ textParam['textC' + queryId] = likeValue(`${globPattern},%`);
783
+ textParam['text_exact' + queryId] = likeValue(globPattern);
784
+ qb[whereFN](likeExpr(fieldName, 'CtextC'), textParam);
785
+ qb[whereFN](likeExpr(fieldName, 'Ctext'), textParam);
786
+ qb[whereFN](likeExpr(fieldName, 'textC'), textParam);
787
+ qb[whereFN](likeExpr(fieldName, 'text_exact'), textParam);
788
+ }));
789
+ if (query.negate) {
790
+ qbr.orWhere(`${fieldName} IS NULL`);
791
+ }
792
+ }));
793
+ };
794
+ if ((query.type === SearchQueryDTO_1.SearchQueryTypes.any_text && !directoryOnly) ||
795
+ query.type === SearchQueryDTO_1.SearchQueryTypes.person) {
796
+ matchArrayField('media.metadata.persons');
797
+ }
798
+ if ((query.type === SearchQueryDTO_1.SearchQueryTypes.any_text && !directoryOnly) ||
799
+ query.type === SearchQueryDTO_1.SearchQueryTypes.keyword) {
800
+ matchArrayField('media.metadata.keywords');
801
+ }
802
+ return q;
803
+ });
804
+ }
805
+ hasDirectoryQuery(query) {
806
+ switch (query.type) {
807
+ case SearchQueryDTO_1.SearchQueryTypes.AND:
808
+ case SearchQueryDTO_1.SearchQueryTypes.OR:
809
+ case SearchQueryDTO_1.SearchQueryTypes.SOME_OF:
810
+ return query.list.some(q => this.hasDirectoryQuery(q));
811
+ case SearchQueryDTO_1.SearchQueryTypes.any_text:
812
+ case SearchQueryDTO_1.SearchQueryTypes.directory:
813
+ return true;
814
+ }
815
+ return false;
816
+ }
817
+ flattenSameOfQueries(query) {
818
+ switch (query.type) {
819
+ case SearchQueryDTO_1.SearchQueryTypes.AND:
820
+ case SearchQueryDTO_1.SearchQueryTypes.OR:
821
+ return {
822
+ type: query.type,
823
+ list: (query.list || []).map((q) => this.flattenSameOfQueries(q)),
824
+ };
825
+ case SearchQueryDTO_1.SearchQueryTypes.SOME_OF:
826
+ const someOfQ = query;
827
+ someOfQ.min = someOfQ.min || 1;
828
+ if (someOfQ.min === 1) {
829
+ return this.flattenSameOfQueries({
830
+ type: SearchQueryDTO_1.SearchQueryTypes.OR,
831
+ list: someOfQ.list,
832
+ });
833
+ }
834
+ if (someOfQ.min === (query.list || []).length) {
835
+ return this.flattenSameOfQueries({
836
+ type: SearchQueryDTO_1.SearchQueryTypes.AND,
837
+ list: someOfQ.list,
838
+ });
839
+ }
840
+ const getAllCombinations = (num, arr, start = 0) => {
841
+ if (num <= 0 || num > arr.length || start >= arr.length) {
842
+ return null;
843
+ }
844
+ if (num <= 1) {
845
+ return arr.slice(start);
846
+ }
847
+ if (num === arr.length - start) {
848
+ return [
849
+ {
850
+ type: SearchQueryDTO_1.SearchQueryTypes.AND,
851
+ list: arr.slice(start),
852
+ },
853
+ ];
854
+ }
855
+ const ret = [];
856
+ for (let i = start; i < arr.length; ++i) {
857
+ const subRes = getAllCombinations(num - 1, arr, i + 1);
858
+ if (subRes === null) {
859
+ break;
860
+ }
861
+ const and = {
862
+ type: SearchQueryDTO_1.SearchQueryTypes.AND,
863
+ list: [arr[i]],
864
+ };
865
+ if (subRes.length === 1) {
866
+ if (subRes[0].type === SearchQueryDTO_1.SearchQueryTypes.AND) {
867
+ and.list.push(...subRes[0].list);
868
+ }
869
+ else {
870
+ and.list.push(subRes[0]);
871
+ }
872
+ }
873
+ else {
874
+ and.list.push({
875
+ type: SearchQueryDTO_1.SearchQueryTypes.OR,
876
+ list: subRes,
877
+ });
878
+ }
879
+ ret.push(and);
880
+ }
881
+ if (ret.length === 0) {
882
+ return null;
883
+ }
884
+ return ret;
885
+ };
886
+ return this.flattenSameOfQueries({
887
+ type: SearchQueryDTO_1.SearchQueryTypes.OR,
888
+ list: getAllCombinations(someOfQ.min, query.list),
889
+ });
890
+ }
891
+ return query;
892
+ }
893
+ /**
894
+ * A directory glob with a trailing '/*' means the directory itself and everything below it.
895
+ * The SQL glob only matches below the directory, so the directory itself is added as an exact match.
896
+ * See SearchQueryUtils.matchDirectorySearch for the same logic without DB.
897
+ */
898
+ expandDirectoryGlobs(query) {
899
+ if (Array.isArray(query.list)) {
900
+ query.list = query.list.map(q => this.expandDirectoryGlobs(q));
901
+ return query;
902
+ }
903
+ const tq = query;
904
+ if (query.type !== SearchQueryDTO_1.SearchQueryTypes.directory ||
905
+ tq.matchType !== SearchQueryDTO_1.TextSearchQueryMatchTypes.globMatch ||
906
+ typeof tq.value !== 'string') {
907
+ return query;
908
+ }
909
+ const value = tq.value.replace(/\\/g, '/');
910
+ if (!value.endsWith('/*')) {
911
+ return query;
912
+ }
913
+ const dir = value.slice(0, -2);
914
+ if (path.posix.normalize(path.posix.join('./', dir)) === '.') {
915
+ return query; // root and below is everything, the glob already matches it
916
+ }
917
+ return {
918
+ type: tq.negate ? SearchQueryDTO_1.SearchQueryTypes.AND : SearchQueryDTO_1.SearchQueryTypes.OR,
919
+ list: [
920
+ {
921
+ type: SearchQueryDTO_1.SearchQueryTypes.directory,
922
+ value: dir,
923
+ matchType: SearchQueryDTO_1.TextSearchQueryMatchTypes.exact_match,
924
+ ...(tq.negate && { negate: true })
925
+ },
926
+ query
927
+ ]
928
+ };
929
+ }
930
+ convertMatchTypeToGlob(query) {
931
+ const list = query.list;
932
+ if (Array.isArray(list)) {
933
+ for (let i = 0; i < list.length; ++i) {
934
+ list[i] = this.convertMatchTypeToGlob(list[i]);
935
+ }
936
+ }
937
+ if (SearchQueryDTO_1.TextSearchQueryTypes.includes(query.type) &&
938
+ query.matchType !== SearchQueryDTO_1.TextSearchQueryMatchTypes.globMatch) {
939
+ if (typeof query.value !== 'string') {
940
+ throw new Error(`Invalid search query: ${SearchQueryDTO_1.SearchQueryTypes[query.type]}(type: ${query.type}) query should contain 'value' property. Query got: ${JSON.stringify(query)}`);
941
+ }
942
+ query.value = query.value.replace(/([\\*?])/g, '\\$1');
943
+ if (query.matchType != SearchQueryDTO_1.TextSearchQueryMatchTypes.exact_match) {
944
+ query.value = `*${query.value}*`;
945
+ }
946
+ query.matchType = SearchQueryDTO_1.TextSearchQueryMatchTypes.globMatch;
947
+ }
948
+ return query;
949
+ }
950
+ /**
951
+ * Assigning IDs to search queries. It is a help / simplification to typeorm,
952
+ * so less parameters are needed to pass down to SQL.
953
+ * Witch SOME_OF query the number of WHERE constrains have O(N!) complexity
954
+ */
955
+ assignQueryIDs(queryIN, id = { value: 1 }) {
956
+ // It is possible that one SQL query contains multiple searchQueries
957
+ // (like: where (<searchQuery1> AND (<searchQuery2>))
958
+ // lets make params unique across multiple queries
959
+ if (id.value === 1) {
960
+ this.queryIdBase++;
961
+ if (this.queryIdBase > 10000) {
962
+ this.queryIdBase = 0;
963
+ }
964
+ }
965
+ if (Array.isArray(queryIN.list)) {
966
+ queryIN.list.forEach((q) => this.assignQueryIDs(q, id));
967
+ return queryIN;
968
+ }
969
+ queryIN.queryId =
970
+ this.queryIdBase + '_' + id.value;
971
+ id.value++;
972
+ return queryIN;
973
+ }
974
+ /**
975
+ * Returns only those parts of a query tree that only contains directory-related search queries
976
+ */
977
+ filterDirectoryQuery(query) {
978
+ switch (query.type) {
979
+ case SearchQueryDTO_1.SearchQueryTypes.AND:
980
+ const andList = query.list.map((q) => this.filterDirectoryQuery(q));
981
+ // if any of the queries contain non dir query the whole and query is a non dir query
982
+ if (andList.indexOf(null) !== -1) {
983
+ return null;
984
+ }
985
+ return {
986
+ type: SearchQueryDTO_1.SearchQueryTypes.AND,
987
+ list: andList.filter((q) => q !== null),
988
+ };
989
+ case SearchQueryDTO_1.SearchQueryTypes.OR:
990
+ const orRet = {
991
+ type: SearchQueryDTO_1.SearchQueryTypes.OR,
992
+ list: query.list
993
+ .map((q) => this.filterDirectoryQuery(q))
994
+ .filter((q) => q !== null),
995
+ };
996
+ if (orRet.list.length === 0) {
997
+ return null;
998
+ }
999
+ return orRet;
1000
+ case SearchQueryDTO_1.SearchQueryTypes.any_text:
1001
+ case SearchQueryDTO_1.SearchQueryTypes.directory:
1002
+ return query;
1003
+ case SearchQueryDTO_1.SearchQueryTypes.SOME_OF:
1004
+ throw new Error('"Some of" queries should have been already flattened');
1005
+ }
1006
+ // of none of the above, its not a directory search
1007
+ return null;
1008
+ }
1009
+ async getGPSData(query) {
1010
+ const list = query.list;
1011
+ if (Array.isArray(list)) {
1012
+ for (let i = 0; i < list.length; ++i) {
1013
+ list[i] = await this.getGPSData(list[i]);
1014
+ }
1015
+ }
1016
+ if (query.type === SearchQueryDTO_1.SearchQueryTypes.distance) {
1017
+ const from = query.from;
1018
+ if (from.value) {
1019
+ from.GPSData = await ObjectManagers_1.ObjectManagers.getInstance().LocationManager.getGPSData(from.value);
1020
+ }
1021
+ }
1022
+ return query;
1023
+ }
1024
+ encapsulateAutoComplete(values, type) {
1025
+ const res = [];
1026
+ values.forEach((value) => {
1027
+ res.push(new AutoCompleteItem_1.AutoCompleteItem(value, type));
1028
+ });
1029
+ return res;
1030
+ }
1031
+ }
1032
+ exports.SearchManager = SearchManager;