ProjectEntityMongoUpdateHandler.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. const { callbackify } = require('util')
  2. const { callbackifyMultiResult } = require('@overleaf/promise-utils')
  3. const logger = require('@overleaf/logger')
  4. const path = require('path')
  5. const { ObjectId } = require('mongodb')
  6. const Settings = require('@overleaf/settings')
  7. const OError = require('@overleaf/o-error')
  8. const CooldownManager = require('../Cooldown/CooldownManager')
  9. const Errors = require('../Errors/Errors')
  10. const { Folder } = require('../../models/Folder')
  11. const LockManager = require('../../infrastructure/LockManager')
  12. const { Project } = require('../../models/Project')
  13. const ProjectEntityHandler = require('./ProjectEntityHandler')
  14. const ProjectGetter = require('./ProjectGetter')
  15. const ProjectLocator = require('./ProjectLocator')
  16. const FolderStructureBuilder = require('./FolderStructureBuilder')
  17. const SafePath = require('./SafePath')
  18. const { DeletedFile } = require('../../models/DeletedFile')
  19. const { iterablePaths } = require('./IterablePath')
  20. const LOCK_NAMESPACE = 'mongoTransaction'
  21. const ENTITY_TYPE_TO_MONGO_PATH_SEGMENT = {
  22. doc: 'docs',
  23. docs: 'docs',
  24. file: 'fileRefs',
  25. files: 'fileRefs',
  26. fileRefs: 'fileRefs',
  27. folder: 'folders',
  28. folders: 'folders',
  29. }
  30. module.exports = {
  31. LOCK_NAMESPACE,
  32. addDoc: callbackifyMultiResult(wrapWithLock(addDoc), ['result', 'project']),
  33. addFile: callbackifyMultiResult(wrapWithLock(addFile), ['result', 'project']),
  34. addFolder: callbackifyMultiResult(wrapWithLock(addFolder), [
  35. 'folder',
  36. 'parentFolderId',
  37. ]),
  38. replaceFileWithNew: callbackifyMultiResult(wrapWithLock(replaceFileWithNew), [
  39. 'oldFileRef',
  40. 'project',
  41. 'path',
  42. 'newProject',
  43. 'newFileRef',
  44. ]),
  45. replaceDocWithFile: callbackify(replaceDocWithFile),
  46. replaceFileWithDoc: callbackify(replaceFileWithDoc),
  47. mkdirp: callbackifyMultiResult(wrapWithLock(mkdirp), [
  48. 'newFolders',
  49. 'folder',
  50. 'parentFolder',
  51. ]),
  52. moveEntity: callbackifyMultiResult(wrapWithLock(moveEntity), [
  53. 'project',
  54. 'startPath',
  55. 'endPath',
  56. 'rev',
  57. 'changes',
  58. ]),
  59. deleteEntity: callbackifyMultiResult(wrapWithLock(deleteEntity), [
  60. 'entity',
  61. 'path',
  62. 'projectBeforeDeletion',
  63. 'newProject',
  64. ]),
  65. renameEntity: callbackifyMultiResult(wrapWithLock(renameEntity), [
  66. 'project',
  67. 'startPath',
  68. 'endPath',
  69. 'rev',
  70. 'changes',
  71. ]),
  72. createNewFolderStructure: callbackify(wrapWithLock(createNewFolderStructure)),
  73. _insertDeletedFileReference: callbackify(_insertDeletedFileReference),
  74. _putElement: callbackifyMultiResult(_putElement, ['result', 'project']),
  75. _confirmFolder,
  76. promises: {
  77. addDoc: wrapWithLock(addDoc),
  78. addFile: wrapWithLock(addFile),
  79. addFolder: wrapWithLock(addFolder),
  80. replaceFileWithNew: wrapWithLock(replaceFileWithNew),
  81. replaceDocWithFile: wrapWithLock(replaceDocWithFile),
  82. replaceFileWithDoc: wrapWithLock(replaceFileWithDoc),
  83. mkdirp: wrapWithLock(mkdirp),
  84. moveEntity: wrapWithLock(moveEntity),
  85. deleteEntity: wrapWithLock(deleteEntity),
  86. renameEntity: wrapWithLock(renameEntity),
  87. createNewFolderStructure: wrapWithLock(createNewFolderStructure),
  88. _insertDeletedFileReference,
  89. _putElement,
  90. },
  91. }
  92. function wrapWithLock(methodWithoutLock) {
  93. // This lock is used whenever we read or write to an existing project's
  94. // structure. Some operations to project structure cannot be done atomically
  95. // in mongo, this lock is used to prevent reading the structure between two
  96. // parts of a staged update.
  97. async function methodWithLock(projectId, ...rest) {
  98. return LockManager.promises.runWithLock(LOCK_NAMESPACE, projectId, () =>
  99. methodWithoutLock(projectId, ...rest)
  100. )
  101. }
  102. return methodWithLock
  103. }
  104. async function addDoc(projectId, folderId, doc) {
  105. const project = await ProjectGetter.promises.getProjectWithoutLock(
  106. projectId,
  107. {
  108. rootFolder: true,
  109. name: true,
  110. overleaf: true,
  111. }
  112. )
  113. folderId = _confirmFolder(project, folderId)
  114. const { result, project: newProject } = await _putElement(
  115. project,
  116. folderId,
  117. doc,
  118. 'doc'
  119. )
  120. return { result, project: newProject }
  121. }
  122. async function addFile(projectId, folderId, fileRef) {
  123. const project = await ProjectGetter.promises.getProjectWithoutLock(
  124. projectId,
  125. { rootFolder: true, name: true, overleaf: true }
  126. )
  127. folderId = _confirmFolder(project, folderId)
  128. const { result, project: newProject } = await _putElement(
  129. project,
  130. folderId,
  131. fileRef,
  132. 'file'
  133. )
  134. return { result, project: newProject }
  135. }
  136. async function addFolder(projectId, parentFolderId, folderName) {
  137. const project = await ProjectGetter.promises.getProjectWithoutLock(
  138. projectId,
  139. { rootFolder: true, name: true, overleaf: true }
  140. )
  141. parentFolderId = _confirmFolder(project, parentFolderId)
  142. const folder = new Folder({ name: folderName })
  143. await _putElement(project, parentFolderId, folder, 'folder')
  144. return { folder, parentFolderId }
  145. }
  146. async function replaceFileWithNew(projectId, fileId, newFileRef) {
  147. const project = await ProjectGetter.promises.getProjectWithoutLock(
  148. projectId,
  149. { rootFolder: true, name: true, overleaf: true }
  150. )
  151. const { element: fileRef, path } = await ProjectLocator.promises.findElement({
  152. project,
  153. element_id: fileId,
  154. type: 'file',
  155. })
  156. await _insertDeletedFileReference(projectId, fileRef)
  157. const newProject = await Project.findOneAndUpdate(
  158. { _id: project._id, [path.mongo]: { $exists: true } },
  159. {
  160. $set: {
  161. [`${path.mongo}._id`]: newFileRef._id,
  162. [`${path.mongo}.created`]: new Date(),
  163. [`${path.mongo}.linkedFileData`]: newFileRef.linkedFileData,
  164. [`${path.mongo}.hash`]: newFileRef.hash,
  165. },
  166. $inc: {
  167. version: 1,
  168. [`${path.mongo}.rev`]: 1,
  169. },
  170. },
  171. // Note: Mongoose uses new:true to return the modified document
  172. // https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
  173. // but Mongo uses returnNewDocument:true instead
  174. // https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/
  175. // We are using Mongoose here, but if we ever switch to a direct mongo call
  176. // the next line will need to be updated.
  177. { new: true }
  178. ).exec()
  179. if (newProject == null) {
  180. throw new OError('Project not found or path not found in filetree', {
  181. projectId,
  182. path,
  183. })
  184. }
  185. // Refresh newFileRef with the version returned from the database
  186. newFileRef = ProjectLocator.findElementByMongoPath(newProject, path.mongo)
  187. return { oldFileRef: fileRef, project, path, newProject, newFileRef }
  188. }
  189. async function replaceDocWithFile(projectId, docId, fileRef) {
  190. const project = await ProjectGetter.promises.getProjectWithoutLock(
  191. projectId,
  192. { rootFolder: true, name: true, overleaf: true }
  193. )
  194. const { path } = await ProjectLocator.promises.findElement({
  195. project,
  196. element_id: docId,
  197. type: 'doc',
  198. })
  199. const folderMongoPath = _getParentMongoPath(path.mongo)
  200. const newProject = await Project.findOneAndUpdate(
  201. { _id: project._id, [folderMongoPath]: { $exists: true } },
  202. {
  203. $pull: {
  204. [`${folderMongoPath}.docs`]: { _id: docId },
  205. },
  206. $push: {
  207. [`${folderMongoPath}.fileRefs`]: fileRef,
  208. },
  209. $inc: { version: 1 },
  210. },
  211. { new: true }
  212. ).exec()
  213. if (newProject == null) {
  214. throw new OError('Project not found or path not found in filetree', {
  215. projectId,
  216. path,
  217. })
  218. }
  219. return newProject
  220. }
  221. async function replaceFileWithDoc(projectId, fileId, newDoc) {
  222. const project = await ProjectGetter.promises.getProjectWithoutLock(
  223. projectId,
  224. { rootFolder: true, name: true, overleaf: true }
  225. )
  226. const { path } = await ProjectLocator.promises.findElement({
  227. project,
  228. element_id: fileId,
  229. type: 'file',
  230. })
  231. const folderMongoPath = _getParentMongoPath(path.mongo)
  232. const newProject = await Project.findOneAndUpdate(
  233. { _id: project._id, [folderMongoPath]: { $exists: true } },
  234. {
  235. $pull: {
  236. [`${folderMongoPath}.fileRefs`]: { _id: fileId },
  237. },
  238. $push: {
  239. [`${folderMongoPath}.docs`]: newDoc,
  240. },
  241. $inc: { version: 1 },
  242. },
  243. { new: true }
  244. ).exec()
  245. if (newProject == null) {
  246. throw new OError('Project not found or path not found in filetree', {
  247. projectId,
  248. path,
  249. })
  250. }
  251. return newProject
  252. }
  253. async function mkdirp(projectId, path, options = {}) {
  254. // defaults to case insensitive paths, use options {exactCaseMatch:true}
  255. // to make matching case-sensitive
  256. const folders = path.split('/').filter(folder => folder.length !== 0)
  257. const project =
  258. await ProjectGetter.promises.getProjectWithOnlyFolders(projectId)
  259. if (path === '/') {
  260. return { newFolders: [], folder: project.rootFolder[0] }
  261. }
  262. const newFolders = []
  263. let builtUpPath = ''
  264. let lastFolder = null
  265. for (const folderName of folders) {
  266. builtUpPath += `/${folderName}`
  267. try {
  268. const { element: foundFolder, folder: parentFolder } =
  269. await ProjectLocator.promises.findElementByPath({
  270. project,
  271. path: builtUpPath,
  272. exactCaseMatch: options.exactCaseMatch,
  273. })
  274. lastFolder = foundFolder
  275. lastFolder.parentFolder_id = parentFolder._id
  276. } catch (err) {
  277. // Folder couldn't be found. Create it.
  278. const parentFolderId = lastFolder && lastFolder._id
  279. const { folder: newFolder, parentFolderId: newParentFolderId } =
  280. await addFolder(projectId, parentFolderId, folderName)
  281. newFolder.parentFolder_id = newParentFolderId
  282. lastFolder = newFolder
  283. newFolders.push(newFolder)
  284. }
  285. }
  286. return { folder: lastFolder, newFolders }
  287. }
  288. async function moveEntity(projectId, entityId, destFolderId, entityType) {
  289. const project = await ProjectGetter.promises.getProjectWithoutLock(
  290. projectId,
  291. { rootFolder: true, name: true, overleaf: true }
  292. )
  293. const { element: entity, path: entityPath } =
  294. await ProjectLocator.promises.findElement({
  295. project,
  296. element_id: entityId,
  297. type: entityType,
  298. })
  299. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  300. if (_blockedFilename(entityPath, entityType)) {
  301. throw new Errors.InvalidNameError('blocked element name')
  302. }
  303. await _checkValidMove(project, entityType, entity, entityPath, destFolderId)
  304. const { docs: oldDocs, files: oldFiles } =
  305. ProjectEntityHandler.getAllEntitiesFromProject(project)
  306. // For safety, insert the entity in the destination
  307. // location first, and then remove the original. If
  308. // there is an error the entity may appear twice. This
  309. // will cause some breakage but is better than being
  310. // lost, which is what happens if this is done in the
  311. // opposite order.
  312. const { result } = await _putElement(
  313. project,
  314. destFolderId,
  315. entity,
  316. entityType
  317. )
  318. // Note: putElement always pushes onto the end of an
  319. // array so it will never change an existing mongo
  320. // path. Therefore it is safe to remove an element
  321. // from the project with an existing path after
  322. // calling putElement. But we must be sure that we
  323. // have not moved a folder subfolder of itself (which
  324. // is done by _checkValidMove above) because that
  325. // would lead to it being deleted.
  326. const newProject = await _removeElementFromMongoArray(
  327. Project,
  328. projectId,
  329. entityPath.mongo,
  330. entityId
  331. )
  332. const { docs: newDocs, files: newFiles } =
  333. ProjectEntityHandler.getAllEntitiesFromProject(newProject)
  334. const startPath = entityPath.fileSystem
  335. const endPath = result.path.fileSystem
  336. const changes = {
  337. oldDocs,
  338. newDocs,
  339. oldFiles,
  340. newFiles,
  341. newProject,
  342. }
  343. // check that no files have been lost (or duplicated)
  344. if (
  345. oldFiles.length !== newFiles.length ||
  346. oldDocs.length !== newDocs.length
  347. ) {
  348. logger.warn(
  349. {
  350. projectId,
  351. oldDocs: oldDocs.length,
  352. newDocs: newDocs.length,
  353. oldFiles: oldFiles.length,
  354. newFiles: newFiles.length,
  355. origProject: project,
  356. newProject,
  357. },
  358. "project corrupted moving files - shouldn't happen"
  359. )
  360. throw new Error('unexpected change in project structure')
  361. }
  362. return { project, startPath, endPath, rev: entity.rev, changes }
  363. }
  364. async function deleteEntity(projectId, entityId, entityType, callback) {
  365. const project = await ProjectGetter.promises.getProjectWithoutLock(
  366. projectId,
  367. { name: true, rootFolder: true, overleaf: true, rootDoc_id: true }
  368. )
  369. const deleteRootDoc =
  370. project.rootDoc_id &&
  371. entityId &&
  372. project.rootDoc_id.toString() === entityId.toString()
  373. const { element: entity, path } = await ProjectLocator.promises.findElement({
  374. project,
  375. element_id: entityId,
  376. type: entityType,
  377. })
  378. const newProject = await _removeElementFromMongoArray(
  379. Project,
  380. projectId,
  381. path.mongo,
  382. entityId,
  383. deleteRootDoc
  384. )
  385. return { entity, path, projectBeforeDeletion: project, newProject }
  386. }
  387. async function renameEntity(
  388. projectId,
  389. entityId,
  390. entityType,
  391. newName,
  392. callback
  393. ) {
  394. const project = await ProjectGetter.promises.getProjectWithoutLock(
  395. projectId,
  396. { rootFolder: true, name: true, overleaf: true }
  397. )
  398. const {
  399. element: entity,
  400. path: entPath,
  401. folder: parentFolder,
  402. } = await ProjectLocator.promises.findElement({
  403. project,
  404. element_id: entityId,
  405. type: entityType,
  406. })
  407. const startPath = entPath.fileSystem
  408. const endPath = path.join(path.dirname(entPath.fileSystem), newName)
  409. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  410. if (_blockedFilename({ fileSystem: endPath }, entityType)) {
  411. throw new Errors.InvalidNameError('blocked element name')
  412. }
  413. // check if the new name already exists in the current folder
  414. _checkValidElementName(parentFolder, newName)
  415. const { docs: oldDocs, files: oldFiles } =
  416. ProjectEntityHandler.getAllEntitiesFromProject(project)
  417. // we need to increment the project version number for any structure change
  418. const newProject = await Project.findOneAndUpdate(
  419. { _id: projectId, [entPath.mongo]: { $exists: true } },
  420. { $set: { [`${entPath.mongo}.name`]: newName }, $inc: { version: 1 } },
  421. { new: true }
  422. ).exec()
  423. if (newProject == null) {
  424. throw new OError('Project not found or path not found in filetree', {
  425. projectId,
  426. path: entPath,
  427. })
  428. }
  429. const { docs: newDocs, files: newFiles } =
  430. ProjectEntityHandler.getAllEntitiesFromProject(newProject)
  431. return {
  432. project,
  433. startPath,
  434. endPath,
  435. rev: entity.rev,
  436. changes: { oldDocs, newDocs, oldFiles, newFiles, newProject },
  437. }
  438. }
  439. async function _insertDeletedFileReference(projectId, fileRef) {
  440. await DeletedFile.create({
  441. projectId,
  442. _id: fileRef._id,
  443. name: fileRef.name,
  444. linkedFileData: fileRef.linkedFileData,
  445. hash: fileRef.hash,
  446. deletedAt: new Date(),
  447. })
  448. }
  449. async function _removeElementFromMongoArray(
  450. model,
  451. modelId,
  452. path,
  453. elementId,
  454. deleteRootDoc = false
  455. ) {
  456. const nonArrayPath = path.slice(0, path.lastIndexOf('.'))
  457. const options = { new: true }
  458. const query = { _id: modelId }
  459. const update = {
  460. $pull: { [nonArrayPath]: { _id: elementId } },
  461. $inc: { version: 1 },
  462. }
  463. if (deleteRootDoc) {
  464. update.$unset = { rootDoc_id: 1 }
  465. }
  466. return model.findOneAndUpdate(query, update, options).exec()
  467. }
  468. function _countElements(project) {
  469. function countFolder(folder) {
  470. if (folder == null) {
  471. return 0
  472. }
  473. let total = 0
  474. if (folder.folders) {
  475. total += folder.folders.length
  476. for (const subfolder of iterablePaths(folder, 'folders')) {
  477. total += countFolder(subfolder)
  478. }
  479. }
  480. if (folder.docs) {
  481. total += folder.docs.length
  482. }
  483. if (folder.fileRefs) {
  484. total += folder.fileRefs.length
  485. }
  486. return total
  487. }
  488. return countFolder(project.rootFolder[0])
  489. }
  490. async function _putElement(project, folderId, element, type) {
  491. if (element == null || element._id == null) {
  492. logger.warn(
  493. { projectId: project._id, folderId, element, type },
  494. 'failed trying to insert element as it was null'
  495. )
  496. throw new Error('no element passed to be inserted')
  497. }
  498. const pathSegment = _getMongoPathSegmentFromType(type)
  499. // original check path.resolve("/", element.name) isnt "/#{element.name}" or element.name.match("/")
  500. // check if name is allowed
  501. if (!SafePath.isCleanFilename(element.name)) {
  502. logger.warn(
  503. { projectId: project._id, folderId, element, type },
  504. 'failed trying to insert element as name was invalid'
  505. )
  506. throw new Errors.InvalidNameError('invalid element name')
  507. }
  508. if (folderId == null) {
  509. folderId = project.rootFolder[0]._id
  510. }
  511. if (_countElements(project) > Settings.maxEntitiesPerProject) {
  512. logger.warn(
  513. { projectId: project._id },
  514. 'project too big, stopping insertions'
  515. )
  516. CooldownManager.putProjectOnCooldown(project._id)
  517. throw new Error('project_has_too_many_files')
  518. }
  519. const { element: folder, path } = await ProjectLocator.promises.findElement({
  520. project,
  521. element_id: folderId,
  522. type: 'folder',
  523. })
  524. const newPath = {
  525. fileSystem: `${path.fileSystem}/${element.name}`,
  526. mongo: path.mongo,
  527. }
  528. // check if the path would be too long
  529. if (!SafePath.isAllowedLength(newPath.fileSystem)) {
  530. throw new Errors.InvalidNameError('path too long')
  531. }
  532. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  533. if (_blockedFilename(newPath, type)) {
  534. throw new Errors.InvalidNameError('blocked element name')
  535. }
  536. _checkValidElementName(folder, element.name)
  537. element._id = new ObjectId(element._id.toString())
  538. const mongoPath = `${path.mongo}.${pathSegment}`
  539. const newProject = await Project.findOneAndUpdate(
  540. { _id: project._id, [path.mongo]: { $exists: true } },
  541. { $push: { [mongoPath]: element }, $inc: { version: 1 } },
  542. { new: true }
  543. ).exec()
  544. if (newProject == null) {
  545. throw new OError('Project not found or path not found in filetree', {
  546. projectId: project._id,
  547. path,
  548. })
  549. }
  550. return { result: { path: newPath }, project: newProject }
  551. }
  552. function _blockedFilename(entityPath, entityType) {
  553. // check if name would be blocked in v1
  554. // javascript reserved names are forbidden for docs and files
  555. // at the top-level (but folders with reserved names are allowed).
  556. const isFolder = entityType === 'folder'
  557. const dir = path.dirname(entityPath.fileSystem)
  558. const file = path.basename(entityPath.fileSystem)
  559. const isTopLevel = dir === '/'
  560. if (isTopLevel && !isFolder && SafePath.isBlockedFilename(file)) {
  561. return true
  562. } else {
  563. return false
  564. }
  565. }
  566. function _getMongoPathSegmentFromType(type) {
  567. const pathSegment = ENTITY_TYPE_TO_MONGO_PATH_SEGMENT[type]
  568. if (pathSegment == null) {
  569. throw new Error(`Unknown entity type: ${type}`)
  570. }
  571. return pathSegment
  572. }
  573. /**
  574. * Check if the name is already taken by a doc, file or folder. If so, return an
  575. * error "file already exists".
  576. */
  577. function _checkValidElementName(folder, name) {
  578. if (folder == null) {
  579. return
  580. }
  581. const elements = []
  582. .concat(folder.docs || [])
  583. .concat(folder.fileRefs || [])
  584. .concat(folder.folders || [])
  585. for (const element of elements) {
  586. if (element.name === name) {
  587. throw new Errors.InvalidNameError('file already exists')
  588. }
  589. }
  590. }
  591. function _confirmFolder(project, folderId) {
  592. if (folderId == null) {
  593. return project.rootFolder[0]._id
  594. } else {
  595. return folderId
  596. }
  597. }
  598. function _checkValidFolderPath(folderPath, destinationFolderPath) {
  599. if (!folderPath.endsWith('/')) {
  600. folderPath += '/'
  601. }
  602. if (!destinationFolderPath.endsWith('/')) {
  603. destinationFolderPath += '/'
  604. }
  605. if (destinationFolderPath === folderPath) {
  606. throw new Errors.InvalidNameError('destination folder is the same as me')
  607. }
  608. if (destinationFolderPath.startsWith(folderPath)) {
  609. throw new Errors.InvalidNameError(
  610. 'destination folder is a child folder of me'
  611. )
  612. }
  613. }
  614. async function _checkValidMove(
  615. project,
  616. entityType,
  617. entity,
  618. entityPath,
  619. destFolderId
  620. ) {
  621. const { element: destEntity, path: destFolderPath } =
  622. await ProjectLocator.promises.findElement({
  623. project,
  624. element_id: destFolderId,
  625. type: 'folder',
  626. })
  627. // check if there is already a doc/file/folder with the same name
  628. // in the destination folder
  629. _checkValidElementName(destEntity, entity.name)
  630. // check if the folder being moved is a parent of the destination folder
  631. if (/folder/.test(entityType)) {
  632. _checkValidFolderPath(entityPath.fileSystem, destFolderPath.fileSystem)
  633. }
  634. }
  635. /**
  636. * Create an initial file tree out of a list of doc and file entries
  637. *
  638. * Each entry specifies a path to the doc or file. Folders are automatically
  639. * created.
  640. *
  641. * @param {ObjectId} projectId - id of the project
  642. * @param {DocEntry[]} docEntries - list of docs to add
  643. * @param {FileEntry[]} fileEntries - list of files to add
  644. * @return {Promise<string>} the project version after the operation
  645. */
  646. async function createNewFolderStructure(projectId, docEntries, fileEntries) {
  647. try {
  648. const rootFolder = FolderStructureBuilder.buildFolderStructure(
  649. docEntries,
  650. fileEntries
  651. )
  652. const project = await Project.findOneAndUpdate(
  653. {
  654. _id: projectId,
  655. 'rootFolder.0.folders.0': { $exists: false },
  656. 'rootFolder.0.docs.0': { $exists: false },
  657. 'rootFolder.0.files.0': { $exists: false },
  658. },
  659. {
  660. $set: { rootFolder: [rootFolder] },
  661. $inc: { version: 1 },
  662. },
  663. {
  664. new: true,
  665. lean: true,
  666. fields: { version: 1 },
  667. }
  668. ).exec()
  669. if (project == null) {
  670. throw new OError('project not found or folder structure already exists', {
  671. projectId,
  672. })
  673. }
  674. return project.version
  675. } catch (err) {
  676. throw OError.tag(err, 'failed to create folder structure', { projectId })
  677. }
  678. }
  679. /**
  680. * Given a Mongo path to an entity, return the Mongo path to the parent folder
  681. */
  682. function _getParentMongoPath(mongoPath) {
  683. const segments = mongoPath.split('.')
  684. if (segments.length <= 2) {
  685. throw new Error('Root folder has no parents')
  686. }
  687. return segments.slice(0, -2).join('.')
  688. }