tree.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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_INVALID_FOLDER')
  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_INVALID_FOLDER')
  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 {string[]} [args.tags] - Tags of the assets
  114. * @param {Object} [args.meta] - Extra metadata
  115. */
  116. static async addPage ({ id, parentId, parentPath, fileName, title, locale, siteId, tags = [], meta = {} }) {
  117. const folder = (parentId || parentPath) ? await WIKI.db.tree.getFolder({
  118. id: parentId,
  119. path: parentPath,
  120. locale,
  121. siteId,
  122. createIfMissing: true
  123. }) : {
  124. folderPath: '',
  125. fileName: ''
  126. }
  127. const folderPath = folder.folderPath ? `${folder.folderPath}.${folder.fileName}` : folder.fileName
  128. const fullPath = folderPath ? `${folderPath}/${fileName}` : fileName
  129. WIKI.logger.debug(`Adding page ${fullPath} to tree...`)
  130. const pageEntry = await WIKI.db.knex('tree').insert({
  131. id,
  132. folderPath: encodeFolderPath(folderPath),
  133. fileName,
  134. type: 'page',
  135. title: title,
  136. hash: generateHash(fullPath),
  137. locale: locale,
  138. siteId,
  139. tags,
  140. meta,
  141. navigationId: siteId
  142. }).returning('*')
  143. return pageEntry[0]
  144. }
  145. /**
  146. * Add Asset Entry
  147. *
  148. * @param {Object} args - New Asset Properties
  149. * @param {string} [args.parentId] - UUID of the parent folder
  150. * @param {string} [args.parentPath] - Path of the parent folder
  151. * @param {string} args.pathName - Path name of the asset to add
  152. * @param {string} args.title - Title of the asset to add
  153. * @param {string} args.locale - Locale code of the asset to add
  154. * @param {string} args.siteId - UUID of the site in which the asset will be added
  155. * @param {string[]} [args.tags] - Tags of the assets
  156. * @param {Object} [args.meta] - Extra metadata
  157. */
  158. static async addAsset ({ id, parentId, parentPath, fileName, title, locale, siteId, tags = [], meta = {} }) {
  159. const folder = (parentId || parentPath) ? await WIKI.db.tree.getFolder({
  160. id: parentId,
  161. path: parentPath,
  162. locale,
  163. siteId,
  164. createIfMissing: true
  165. }) : {
  166. folderPath: '',
  167. fileName: ''
  168. }
  169. const folderPath = folder.folderPath ? `${folder.folderPath}.${folder.fileName}` : folder.fileName
  170. const fullPath = folderPath ? `${folderPath}/${fileName}` : fileName
  171. WIKI.logger.debug(`Adding asset ${fullPath} to tree...`)
  172. const assetEntry = await WIKI.db.knex('tree').insert({
  173. id,
  174. folderPath: encodeFolderPath(folderPath),
  175. fileName,
  176. type: 'asset',
  177. title: title,
  178. hash: generateHash(fullPath),
  179. locale: locale,
  180. siteId,
  181. tags,
  182. meta
  183. }).returning('*')
  184. return assetEntry[0]
  185. }
  186. /**
  187. * Create New Folder
  188. *
  189. * @param {Object} args - New Folder Properties
  190. * @param {string} [args.parentId] - UUID of the parent folder
  191. * @param {string} [args.parentPath] - Path of the parent folder
  192. * @param {string} args.pathName - Path name of the folder to create
  193. * @param {string} args.title - Title of the folder to create
  194. * @param {string} args.locale - Locale code of the folder to create
  195. * @param {string} args.siteId - UUID of the site in which the folder will be created
  196. */
  197. static async createFolder ({ parentId, parentPath, pathName, title, locale, siteId }) {
  198. // Validate path name
  199. if (!rePathName.test(pathName)) {
  200. throw new Error('ERR_INVALID_PATH')
  201. }
  202. // Validate title
  203. if (!reTitle.test(title)) {
  204. throw new Error('ERR_FOLDER_TITLE_INVALID')
  205. }
  206. parentPath = encodeTreePath(parentPath)
  207. WIKI.logger.debug(`Creating new folder ${pathName}...`)
  208. const parentPathParts = parentPath.split('.')
  209. const parentFilter = {
  210. folderPath: encodeFolderPath(dropRight(parentPathParts).join('.')),
  211. fileName: last(parentPathParts)
  212. }
  213. // Get parent path
  214. let parent = null
  215. if (parentId) {
  216. parent = await WIKI.db.knex('tree').where('id', parentId).first()
  217. if (!parent) {
  218. throw new Error('ERR_FOLDER_PARENT_INVALID')
  219. }
  220. parentPath = parent.folderPath ? `${decodeFolderPath(parent.folderPath)}.${parent.fileName}` : parent.fileName
  221. } else if (parentPath) {
  222. parent = await WIKI.db.knex('tree').where(parentFilter).first()
  223. } else {
  224. parentPath = ''
  225. }
  226. // Check for collision
  227. const existingFolder = await WIKI.db.knex('tree').select('id').where({
  228. siteId: siteId,
  229. locale: locale,
  230. folderPath: encodeFolderPath(parentPath),
  231. fileName: pathName,
  232. type: 'folder'
  233. }).first()
  234. if (existingFolder) {
  235. throw new Error('ERR_FOLDER_DUPLICATE')
  236. }
  237. // Ensure all ancestors exist
  238. if (parentPath) {
  239. const expectedAncestors = []
  240. const existingAncestors = await WIKI.db.knex('tree').select('folderPath', 'fileName').where(builder => {
  241. const parentPathParts = parentPath.split('.')
  242. for (let i = 1; i <= parentPathParts.length; i++) {
  243. const ancestor = {
  244. folderPath: encodeFolderPath(dropRight(parentPathParts, i).join('.')),
  245. fileName: nth(parentPathParts, i * -1)
  246. }
  247. expectedAncestors.push(ancestor)
  248. builder.orWhere({
  249. ...ancestor,
  250. type: 'folder'
  251. })
  252. }
  253. })
  254. for (const ancestor of differenceWith(expectedAncestors, existingAncestors, (expAnc, exsAnc) => expAnc.folderPath === exsAnc.folderPath && expAnc.fileName === exsAnc.fileName)) {
  255. WIKI.logger.debug(`Creating missing parent folder ${ancestor.fileName} at path /${ancestor.folderPath}...`)
  256. const newAncestorFullPath = ancestor.folderPath ? `${decodeTreePath(ancestor.folderPath)}/${ancestor.fileName}` : ancestor.fileName
  257. const newAncestor = await WIKI.db.knex('tree').insert({
  258. ...ancestor,
  259. type: 'folder',
  260. title: ancestor.fileName,
  261. hash: generateHash(newAncestorFullPath),
  262. locale: locale,
  263. siteId: siteId,
  264. meta: {
  265. children: 1
  266. }
  267. }).returning('*')
  268. // Parent didn't exist until now, assign it
  269. if (!parent && ancestor.folderPath === parentFilter.folderPath && ancestor.fileName === parentFilter.fileName) {
  270. parent = newAncestor[0]
  271. }
  272. }
  273. }
  274. // Create folder
  275. const fullPath = parentPath ? `${decodeTreePath(parentPath)}/${pathName}` : pathName
  276. const folder = await WIKI.db.knex('tree').insert({
  277. folderPath: encodeFolderPath(parentPath),
  278. fileName: pathName,
  279. type: 'folder',
  280. title: title,
  281. hash: generateHash(fullPath),
  282. locale: locale,
  283. siteId: siteId,
  284. meta: {
  285. children: 0
  286. }
  287. }).returning('*')
  288. // Update parent ancestor count
  289. if (parent) {
  290. await WIKI.db.knex('tree').where('id', parent.id).update({
  291. meta: {
  292. ...(parent.meta ?? {}),
  293. children: (parent.meta?.children || 0) + 1
  294. }
  295. })
  296. }
  297. WIKI.logger.debug(`Created folder ${folder[0].id} successfully.`)
  298. return folder[0]
  299. }
  300. /**
  301. * Rename a folder
  302. *
  303. * @param {Object} args - Rename Folder Properties
  304. * @param {string} args.folderId - UUID of the folder to rename
  305. * @param {string} args.pathName - New path name of the folder
  306. * @param {string} args.title - New title of the folder
  307. */
  308. static async renameFolder ({ folderId, pathName, title }) {
  309. // Get folder
  310. const folder = await WIKI.db.knex('tree').where('id', folderId).first()
  311. if (!folder) {
  312. throw new Error('ERR_INVALID_FOLDER')
  313. }
  314. // Validate path name
  315. if (!rePathName.test(pathName)) {
  316. throw new Error('ERR_INVALID_PATH')
  317. }
  318. // Validate title
  319. if (!reTitle.test(title)) {
  320. throw new Error('ERR_FOLDER_TITLE_INVALID')
  321. }
  322. WIKI.logger.debug(`Renaming folder ${folder.id} path to ${pathName}...`)
  323. if (pathName !== folder.fileName) {
  324. // Check for collision
  325. const existingFolder = await WIKI.db.knex('tree')
  326. .whereNot('id', folder.id)
  327. .andWhere({
  328. siteId: folder.siteId,
  329. folderPath: folder.folderPath,
  330. fileName: pathName,
  331. type: 'folder'
  332. }).first()
  333. if (existingFolder) {
  334. throw new Error('ERR_FOLDER_DUPLICATE')
  335. }
  336. // Build new paths
  337. const oldFolderPath = encodeFolderPath(folder.folderPath ? `${folder.folderPath}.${folder.fileName}` : folder.fileName)
  338. const newFolderPath = encodeFolderPath(folder.folderPath ? `${folder.folderPath}.${pathName}` : pathName)
  339. // Update children nodes
  340. WIKI.logger.debug(`Updating parent path of children nodes from ${oldFolderPath} to ${newFolderPath} ...`)
  341. await WIKI.db.knex('tree').where('siteId', folder.siteId).andWhere('folderPath', oldFolderPath).update({
  342. folderPath: newFolderPath
  343. })
  344. await WIKI.db.knex('tree').where('siteId', folder.siteId).andWhere('folderPath', '<@', oldFolderPath).update({
  345. folderPath: WIKI.db.knex.raw(`'${newFolderPath}' || subpath(tree."folderPath", nlevel('${newFolderPath}'))`)
  346. })
  347. // Rename the folder itself
  348. const fullPath = folder.folderPath ? `${decodeFolderPath(folder.folderPath)}/${pathName}` : pathName
  349. await WIKI.db.knex('tree').where('id', folder.id).update({
  350. fileName: pathName,
  351. title: title,
  352. hash: generateHash(fullPath)
  353. })
  354. } else {
  355. // Update the folder title only
  356. await WIKI.db.knex('tree').where('id', folder.id).update({
  357. title: title
  358. })
  359. }
  360. WIKI.logger.debug(`Renamed folder ${folder.id} successfully.`)
  361. }
  362. /**
  363. * Delete a folder
  364. *
  365. * @param {String} folderId Folder ID
  366. */
  367. static async deleteFolder (folderId) {
  368. // Get folder
  369. const folder = await WIKI.db.knex('tree').where('id', folderId).first()
  370. if (!folder) {
  371. throw new Error('ERR_INVALID_FOLDER')
  372. }
  373. const folderPath = folder.folderPath ? `${folder.folderPath}.${folder.fileName}` : folder.fileName
  374. WIKI.logger.debug(`Deleting folder ${folder.id} at path ${folderPath}...`)
  375. // Delete all children
  376. const deletedNodes = await WIKI.db.knex('tree').where('folderPath', '<@', encodeFolderPath(folderPath)).del().returning(['id', 'type'])
  377. // Delete folders
  378. const deletedFolders = deletedNodes.filter(n => n.type === 'folder').map(n => n.id)
  379. if (deletedFolders.length > 0) {
  380. WIKI.logger.debug(`Deleted ${deletedFolders.length} children folders.`)
  381. }
  382. // Delete pages
  383. const deletedPages = deletedNodes.filter(n => n.type === 'page').map(n => n.id)
  384. if (deletedPages.length > 0) {
  385. WIKI.logger.debug(`Deleting ${deletedPages.length} children pages...`)
  386. // TODO: Delete page
  387. }
  388. // Delete assets
  389. const deletedAssets = deletedNodes.filter(n => n.type === 'asset').map(n => n.id)
  390. if (deletedAssets.length > 0) {
  391. WIKI.logger.debug(`Deleting ${deletedPages.length} children assets...`)
  392. // TODO: Delete asset
  393. }
  394. // Delete the folder itself
  395. await WIKI.db.knex('tree').where('id', folder.id).del()
  396. // Update parent children count
  397. if (folder.folderPath) {
  398. const parentPathParts = folder.folderPath.split('.')
  399. const parent = await WIKI.db.knex('tree').where({
  400. folderPath: encodeFolderPath(dropRight(parentPathParts).join('.')),
  401. fileName: last(parentPathParts)
  402. }).first()
  403. await WIKI.db.knex('tree').where('id', parent.id).update({
  404. meta: {
  405. ...(parent.meta ?? {}),
  406. children: (parent.meta?.children || 1) - 1
  407. }
  408. })
  409. }
  410. WIKI.logger.debug(`Deleted folder ${folder.id} successfully.`)
  411. }
  412. }