tree.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. import { Model } from 'objection'
  2. import { differenceWith, dropRight, last, nth } from 'lodash-es'
  3. import {
  4. decodeFolderPath,
  5. decodeTreePath,
  6. encodeFolderPath,
  7. encodeTreePath,
  8. generateHash
  9. } from '../helpers/common.mjs'
  10. import { Locale } from './locales.mjs'
  11. import { Site } from './sites.mjs'
  12. const rePathName = /^[a-z0-9-]+$/
  13. const reTitle = /^[^<>"]+$/
  14. /**
  15. * Tree model
  16. */
  17. export class Tree extends Model {
  18. static get tableName() { return 'tree' }
  19. static get jsonSchema () {
  20. return {
  21. type: 'object',
  22. required: ['fileName'],
  23. properties: {
  24. id: {type: 'string'},
  25. folderPath: {type: 'string'},
  26. fileName: {type: 'string'},
  27. type: {type: 'string'},
  28. title: {type: 'string'},
  29. createdAt: {type: 'string'},
  30. updatedAt: {type: 'string'}
  31. }
  32. }
  33. }
  34. static get jsonAttributes() {
  35. return ['meta']
  36. }
  37. static get relationMappings() {
  38. return {
  39. site: {
  40. relation: Model.BelongsToOneRelation,
  41. modelClass: Site,
  42. join: {
  43. from: 'tree.siteId',
  44. to: 'sites.id'
  45. }
  46. }
  47. }
  48. }
  49. $beforeUpdate() {
  50. this.updatedAt = new Date().toISOString()
  51. }
  52. $beforeInsert() {
  53. this.createdAt = new Date().toISOString()
  54. this.updatedAt = new Date().toISOString()
  55. }
  56. /**
  57. * Get a Folder
  58. *
  59. * @param {Object} args - Fetch Properties
  60. * @param {string} [args.id] - UUID of the folder
  61. * @param {string} [args.path] - Path of the folder
  62. * @param {string} [args.locale] - Locale code of the folder (when using path)
  63. * @param {string} [args.siteId] - UUID of the site in which the folder is (when using path)
  64. * @param {boolean} [args.createIfMissing] - Create the folder and its ancestor if it's missing (when using path)
  65. */
  66. static async getFolder ({ id, path, locale, siteId, createIfMissing = false }) {
  67. // Get by ID
  68. if (id) {
  69. const parent = await WIKI.db.knex('tree').where('id', id).first()
  70. if (!parent) {
  71. throw new Error('ERR_NONEXISTING_FOLDER_ID')
  72. }
  73. return parent
  74. } else {
  75. // Get by path
  76. const parentPath = encodeTreePath(path)
  77. const parentPathParts = parentPath.split('.')
  78. const parentFilter = {
  79. folderPath: encodeFolderPath(dropRight(parentPathParts).join('.')),
  80. fileName: last(parentPathParts)
  81. }
  82. const parent = await WIKI.db.knex('tree').where({
  83. ...parentFilter,
  84. type: 'folder',
  85. locale: locale,
  86. siteId
  87. }).first()
  88. if (parent) {
  89. return parent
  90. } else if (createIfMissing) {
  91. return WIKI.db.tree.createFolder({
  92. parentPath: parentFilter.folderPath,
  93. pathName: parentFilter.fileName,
  94. title: parentFilter.fileName,
  95. locale,
  96. siteId
  97. })
  98. } else {
  99. throw new Error('ERR_NONEXISTING_FOLDER_PATH')
  100. }
  101. }
  102. }
  103. /**
  104. * Add Page Entry
  105. *
  106. * @param {Object} args - New Page Properties
  107. * @param {string} [args.parentId] - UUID of the parent folder
  108. * @param {string} [args.parentPath] - Path of the parent folder
  109. * @param {string} args.pathName - Path name of the page to add
  110. * @param {string} args.title - Title of the page to add
  111. * @param {string} args.locale - Locale code of the page to add
  112. * @param {string} args.siteId - UUID of the site in which the page will be added
  113. * @param {Object} [args.meta] - Extra metadata
  114. */
  115. static async addPage ({ id, parentId, parentPath, fileName, title, locale, siteId, meta = {} }) {
  116. const folder = (parentId || parentPath) ? await WIKI.db.tree.getFolder({
  117. id: parentId,
  118. path: parentPath,
  119. locale,
  120. siteId,
  121. createIfMissing: true
  122. }) : {
  123. folderPath: '',
  124. fileName: ''
  125. }
  126. const folderPath = folder.folderPath ? `${folder.folderPath}.${folder.fileName}` : folder.fileName
  127. const fullPath = folderPath ? `${folderPath}/${fileName}` : fileName
  128. WIKI.logger.debug(`Adding page ${fullPath} to tree...`)
  129. const pageEntry = await WIKI.db.knex('tree').insert({
  130. id,
  131. folderPath: encodeFolderPath(folderPath),
  132. fileName,
  133. type: 'page',
  134. title: title,
  135. hash: generateHash(fullPath),
  136. locale: locale,
  137. siteId,
  138. meta,
  139. navigationId: siteId,
  140. }).returning('*')
  141. return pageEntry[0]
  142. }
  143. /**
  144. * Add Asset Entry
  145. *
  146. * @param {Object} args - New Asset Properties
  147. * @param {string} [args.parentId] - UUID of the parent folder
  148. * @param {string} [args.parentPath] - Path of the parent folder
  149. * @param {string} args.pathName - Path name of the asset to add
  150. * @param {string} args.title - Title of the asset to add
  151. * @param {string} args.locale - Locale code of the asset to add
  152. * @param {string} args.siteId - UUID of the site in which the asset will be added
  153. * @param {Object} [args.meta] - Extra metadata
  154. */
  155. static async addAsset ({ id, parentId, parentPath, fileName, title, locale, siteId, meta = {} }) {
  156. const folder = (parentId || parentPath) ? await WIKI.db.tree.getFolder({
  157. id: parentId,
  158. path: parentPath,
  159. locale,
  160. siteId,
  161. createIfMissing: true
  162. }) : {
  163. folderPath: '',
  164. fileName: ''
  165. }
  166. const folderPath = folder.folderPath ? `${folder.folderPath}.${folder.fileName}` : folder.fileName
  167. const fullPath = folderPath ? `${folderPath}/${fileName}` : fileName
  168. WIKI.logger.debug(`Adding asset ${fullPath} to tree...`)
  169. const assetEntry = await WIKI.db.knex('tree').insert({
  170. id,
  171. folderPath: encodeFolderPath(folderPath),
  172. fileName,
  173. type: 'asset',
  174. title: title,
  175. hash: generateHash(fullPath),
  176. locale: locale,
  177. siteId,
  178. meta
  179. }).returning('*')
  180. return assetEntry[0]
  181. }
  182. /**
  183. * Create New Folder
  184. *
  185. * @param {Object} args - New Folder Properties
  186. * @param {string} [args.parentId] - UUID of the parent folder
  187. * @param {string} [args.parentPath] - Path of the parent folder
  188. * @param {string} args.pathName - Path name of the folder to create
  189. * @param {string} args.title - Title of the folder to create
  190. * @param {string} args.locale - Locale code of the folder to create
  191. * @param {string} args.siteId - UUID of the site in which the folder will be created
  192. */
  193. static async createFolder ({ parentId, parentPath, pathName, title, locale, siteId }) {
  194. // Validate path name
  195. if (!rePathName.test(pathName)) {
  196. throw new Error('ERR_INVALID_PATH_NAME')
  197. }
  198. // Validate title
  199. if (!reTitle.test(title)) {
  200. throw new Error('ERR_INVALID_TITLE')
  201. }
  202. parentPath = encodeTreePath(parentPath)
  203. WIKI.logger.debug(`Creating new folder ${pathName}...`)
  204. const parentPathParts = parentPath.split('.')
  205. const parentFilter = {
  206. folderPath: encodeFolderPath(dropRight(parentPathParts).join('.')),
  207. fileName: last(parentPathParts)
  208. }
  209. // Get parent path
  210. let parent = null
  211. if (parentId) {
  212. parent = await WIKI.db.knex('tree').where('id', parentId).first()
  213. if (!parent) {
  214. throw new Error('ERR_NONEXISTING_PARENT_ID')
  215. }
  216. parentPath = parent.folderPath ? `${decodeFolderPath(parent.folderPath)}.${parent.fileName}` : parent.fileName
  217. } else if (parentPath) {
  218. parent = await WIKI.db.knex('tree').where(parentFilter).first()
  219. } else {
  220. parentPath = ''
  221. }
  222. // Check for collision
  223. const existingFolder = await WIKI.db.knex('tree').select('id').where({
  224. siteId: siteId,
  225. locale: locale,
  226. folderPath: encodeFolderPath(parentPath),
  227. fileName: pathName,
  228. type: 'folder'
  229. }).first()
  230. if (existingFolder) {
  231. throw new Error('ERR_FOLDER_ALREADY_EXISTS')
  232. }
  233. // Ensure all ancestors exist
  234. if (parentPath) {
  235. const expectedAncestors = []
  236. const existingAncestors = await WIKI.db.knex('tree').select('folderPath', 'fileName').where(builder => {
  237. const parentPathParts = parentPath.split('.')
  238. for (let i = 1; i <= parentPathParts.length; i++) {
  239. const ancestor = {
  240. folderPath: encodeFolderPath(dropRight(parentPathParts, i).join('.')),
  241. fileName: nth(parentPathParts, i * -1)
  242. }
  243. expectedAncestors.push(ancestor)
  244. builder.orWhere({
  245. ...ancestor,
  246. type: 'folder'
  247. })
  248. }
  249. })
  250. for (const ancestor of differenceWith(expectedAncestors, existingAncestors, (expAnc, exsAnc) => expAnc.folderPath === exsAnc.folderPath && expAnc.fileName === exsAnc.fileName)) {
  251. WIKI.logger.debug(`Creating missing parent folder ${ancestor.fileName} at path /${ancestor.folderPath}...`)
  252. const newAncestorFullPath = ancestor.folderPath ? `${decodeTreePath(ancestor.folderPath)}/${ancestor.fileName}` : ancestor.fileName
  253. const newAncestor = await WIKI.db.knex('tree').insert({
  254. ...ancestor,
  255. type: 'folder',
  256. title: ancestor.fileName,
  257. hash: generateHash(newAncestorFullPath),
  258. locale: locale,
  259. siteId: siteId,
  260. meta: {
  261. children: 1
  262. }
  263. }).returning('*')
  264. // Parent didn't exist until now, assign it
  265. if (!parent && ancestor.folderPath === parentFilter.folderPath && ancestor.fileName === parentFilter.fileName) {
  266. parent = newAncestor[0]
  267. }
  268. }
  269. }
  270. // Create folder
  271. const fullPath = parentPath ? `${decodeTreePath(parentPath)}/${pathName}` : pathName
  272. const folder = await WIKI.db.knex('tree').insert({
  273. folderPath: encodeFolderPath(parentPath),
  274. fileName: pathName,
  275. type: 'folder',
  276. title: title,
  277. hash: generateHash(fullPath),
  278. locale: locale,
  279. siteId: siteId,
  280. meta: {
  281. children: 0
  282. }
  283. }).returning('*')
  284. // Update parent ancestor count
  285. if (parent) {
  286. await WIKI.db.knex('tree').where('id', parent.id).update({
  287. meta: {
  288. ...(parent.meta ?? {}),
  289. children: (parent.meta?.children || 0) + 1
  290. }
  291. })
  292. }
  293. WIKI.logger.debug(`Created folder ${folder[0].id} successfully.`)
  294. return folder[0]
  295. }
  296. /**
  297. * Rename a folder
  298. *
  299. * @param {Object} args - Rename Folder Properties
  300. * @param {string} args.folderId - UUID of the folder to rename
  301. * @param {string} args.pathName - New path name of the folder
  302. * @param {string} args.title - New title of the folder
  303. */
  304. static async renameFolder ({ folderId, pathName, title }) {
  305. // Get folder
  306. const folder = await WIKI.db.knex('tree').where('id', folderId).first()
  307. if (!folder) {
  308. throw new Error('ERR_NONEXISTING_FOLDER_ID')
  309. }
  310. // Validate path name
  311. if (!rePathName.test(pathName)) {
  312. throw new Error('ERR_INVALID_PATH_NAME')
  313. }
  314. // Validate title
  315. if (!reTitle.test(title)) {
  316. throw new Error('ERR_INVALID_TITLE')
  317. }
  318. WIKI.logger.debug(`Renaming folder ${folder.id} path to ${pathName}...`)
  319. if (pathName !== folder.fileName) {
  320. // Check for collision
  321. const existingFolder = await WIKI.db.knex('tree')
  322. .whereNot('id', folder.id)
  323. .andWhere({
  324. siteId: folder.siteId,
  325. folderPath: folder.folderPath,
  326. fileName: pathName,
  327. type: 'folder'
  328. }).first()
  329. if (existingFolder) {
  330. throw new Error('ERR_FOLDER_ALREADY_EXISTS')
  331. }
  332. // Build new paths
  333. const oldFolderPath = encodeFolderPath(folder.folderPath ? `${folder.folderPath}.${folder.fileName}` : folder.fileName)
  334. const newFolderPath = encodeFolderPath(folder.folderPath ? `${folder.folderPath}.${pathName}` : pathName)
  335. // Update children nodes
  336. WIKI.logger.debug(`Updating parent path of children nodes from ${oldFolderPath} to ${newFolderPath} ...`)
  337. await WIKI.db.knex('tree').where('siteId', folder.siteId).andWhere('folderPath', oldFolderPath).update({
  338. folderPath: newFolderPath
  339. })
  340. await WIKI.db.knex('tree').where('siteId', folder.siteId).andWhere('folderPath', '<@', oldFolderPath).update({
  341. folderPath: WIKI.db.knex.raw(`'${newFolderPath}' || subpath(tree."folderPath", nlevel('${newFolderPath}'))`)
  342. })
  343. // Rename the folder itself
  344. const fullPath = folder.folderPath ? `${decodeFolderPath(folder.folderPath)}/${pathName}` : pathName
  345. await WIKI.db.knex('tree').where('id', folder.id).update({
  346. fileName: pathName,
  347. title: title,
  348. hash: generateHash(fullPath)
  349. })
  350. } else {
  351. // Update the folder title only
  352. await WIKI.db.knex('tree').where('id', folder.id).update({
  353. title: title
  354. })
  355. }
  356. WIKI.logger.debug(`Renamed folder ${folder.id} successfully.`)
  357. }
  358. /**
  359. * Delete a folder
  360. *
  361. * @param {String} folderId Folder ID
  362. */
  363. static async deleteFolder (folderId) {
  364. // Get folder
  365. const folder = await WIKI.db.knex('tree').where('id', folderId).first()
  366. if (!folder) {
  367. throw new Error('ERR_NONEXISTING_FOLDER_ID')
  368. }
  369. const folderPath = folder.folderPath ? `${folder.folderPath}.${folder.fileName}` : folder.fileName
  370. WIKI.logger.debug(`Deleting folder ${folder.id} at path ${folderPath}...`)
  371. // Delete all children
  372. const deletedNodes = await WIKI.db.knex('tree').where('folderPath', '<@', encodeFolderPath(folderPath)).del().returning(['id', 'type'])
  373. // Delete folders
  374. const deletedFolders = deletedNodes.filter(n => n.type === 'folder').map(n => n.id)
  375. if (deletedFolders.length > 0) {
  376. WIKI.logger.debug(`Deleted ${deletedFolders.length} children folders.`)
  377. }
  378. // Delete pages
  379. const deletedPages = deletedNodes.filter(n => n.type === 'page').map(n => n.id)
  380. if (deletedPages.length > 0) {
  381. WIKI.logger.debug(`Deleting ${deletedPages.length} children pages...`)
  382. // TODO: Delete page
  383. }
  384. // Delete assets
  385. const deletedAssets = deletedNodes.filter(n => n.type === 'asset').map(n => n.id)
  386. if (deletedAssets.length > 0) {
  387. WIKI.logger.debug(`Deleting ${deletedPages.length} children assets...`)
  388. // TODO: Delete asset
  389. }
  390. // Delete the folder itself
  391. await WIKI.db.knex('tree').where('id', folder.id).del()
  392. // Update parent children count
  393. if (folder.folderPath) {
  394. const parentPathParts = folder.folderPath.split('.')
  395. const parent = await WIKI.db.knex('tree').where({
  396. folderPath: encodeFolderPath(dropRight(parentPathParts).join('.')),
  397. fileName: last(parentPathParts)
  398. }).first()
  399. await WIKI.db.knex('tree').where('id', parent.id).update({
  400. meta: {
  401. ...(parent.meta ?? {}),
  402. children: (parent.meta?.children || 1) - 1
  403. }
  404. })
  405. }
  406. WIKI.logger.debug(`Deleted folder ${folder.id} successfully.`)
  407. }
  408. }