tree.mjs 15 KB

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