tree.mjs 14 KB

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