tree.mjs 15 KB

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