ProjectEntityMongoUpdateHandler.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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 = await ProjectGetter.promises.getProjectWithOnlyFolders(
  258. projectId
  259. )
  260. if (path === '/') {
  261. return { newFolders: [], folder: project.rootFolder[0] }
  262. }
  263. const newFolders = []
  264. let builtUpPath = ''
  265. let lastFolder = null
  266. for (const folderName of folders) {
  267. builtUpPath += `/${folderName}`
  268. try {
  269. const { element: foundFolder, folder: parentFolder } =
  270. await ProjectLocator.promises.findElementByPath({
  271. project,
  272. path: builtUpPath,
  273. exactCaseMatch: options.exactCaseMatch,
  274. })
  275. lastFolder = foundFolder
  276. lastFolder.parentFolder_id = parentFolder._id
  277. } catch (err) {
  278. // Folder couldn't be found. Create it.
  279. const parentFolderId = lastFolder && lastFolder._id
  280. const { folder: newFolder, parentFolderId: newParentFolderId } =
  281. await addFolder(projectId, parentFolderId, folderName)
  282. newFolder.parentFolder_id = newParentFolderId
  283. lastFolder = newFolder
  284. newFolders.push(newFolder)
  285. }
  286. }
  287. return { folder: lastFolder, newFolders }
  288. }
  289. async function moveEntity(projectId, entityId, destFolderId, entityType) {
  290. const project = await ProjectGetter.promises.getProjectWithoutLock(
  291. projectId,
  292. { rootFolder: true, name: true, overleaf: true }
  293. )
  294. const { element: entity, path: entityPath } =
  295. await ProjectLocator.promises.findElement({
  296. project,
  297. element_id: entityId,
  298. type: entityType,
  299. })
  300. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  301. if (_blockedFilename(entityPath, entityType)) {
  302. throw new Errors.InvalidNameError('blocked element name')
  303. }
  304. await _checkValidMove(project, entityType, entity, entityPath, destFolderId)
  305. const { docs: oldDocs, files: oldFiles } =
  306. ProjectEntityHandler.getAllEntitiesFromProject(project)
  307. // For safety, insert the entity in the destination
  308. // location first, and then remove the original. If
  309. // there is an error the entity may appear twice. This
  310. // will cause some breakage but is better than being
  311. // lost, which is what happens if this is done in the
  312. // opposite order.
  313. const { result } = await _putElement(
  314. project,
  315. destFolderId,
  316. entity,
  317. entityType
  318. )
  319. // Note: putElement always pushes onto the end of an
  320. // array so it will never change an existing mongo
  321. // path. Therefore it is safe to remove an element
  322. // from the project with an existing path after
  323. // calling putElement. But we must be sure that we
  324. // have not moved a folder subfolder of itself (which
  325. // is done by _checkValidMove above) because that
  326. // would lead to it being deleted.
  327. const newProject = await _removeElementFromMongoArray(
  328. Project,
  329. projectId,
  330. entityPath.mongo,
  331. entityId
  332. )
  333. const { docs: newDocs, files: newFiles } =
  334. ProjectEntityHandler.getAllEntitiesFromProject(newProject)
  335. const startPath = entityPath.fileSystem
  336. const endPath = result.path.fileSystem
  337. const changes = {
  338. oldDocs,
  339. newDocs,
  340. oldFiles,
  341. newFiles,
  342. newProject,
  343. }
  344. // check that no files have been lost (or duplicated)
  345. if (
  346. oldFiles.length !== newFiles.length ||
  347. oldDocs.length !== newDocs.length
  348. ) {
  349. logger.warn(
  350. {
  351. projectId,
  352. oldDocs: oldDocs.length,
  353. newDocs: newDocs.length,
  354. oldFiles: oldFiles.length,
  355. newFiles: newFiles.length,
  356. origProject: project,
  357. newProject,
  358. },
  359. "project corrupted moving files - shouldn't happen"
  360. )
  361. throw new Error('unexpected change in project structure')
  362. }
  363. return { project, startPath, endPath, rev: entity.rev, changes }
  364. }
  365. async function deleteEntity(projectId, entityId, entityType, callback) {
  366. const project = await ProjectGetter.promises.getProjectWithoutLock(
  367. projectId,
  368. { name: true, rootFolder: true, overleaf: true, rootDoc_id: true }
  369. )
  370. const deleteRootDoc =
  371. project.rootDoc_id &&
  372. entityId &&
  373. project.rootDoc_id.toString() === entityId.toString()
  374. const { element: entity, path } = await ProjectLocator.promises.findElement({
  375. project,
  376. element_id: entityId,
  377. type: entityType,
  378. })
  379. const newProject = await _removeElementFromMongoArray(
  380. Project,
  381. projectId,
  382. path.mongo,
  383. entityId,
  384. deleteRootDoc
  385. )
  386. return { entity, path, projectBeforeDeletion: project, newProject }
  387. }
  388. async function renameEntity(
  389. projectId,
  390. entityId,
  391. entityType,
  392. newName,
  393. callback
  394. ) {
  395. const project = await ProjectGetter.promises.getProjectWithoutLock(
  396. projectId,
  397. { rootFolder: true, name: true, overleaf: true }
  398. )
  399. const {
  400. element: entity,
  401. path: entPath,
  402. folder: parentFolder,
  403. } = await ProjectLocator.promises.findElement({
  404. project,
  405. element_id: entityId,
  406. type: entityType,
  407. })
  408. const startPath = entPath.fileSystem
  409. const endPath = path.join(path.dirname(entPath.fileSystem), newName)
  410. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  411. if (_blockedFilename({ fileSystem: endPath }, entityType)) {
  412. throw new Errors.InvalidNameError('blocked element name')
  413. }
  414. // check if the new name already exists in the current folder
  415. _checkValidElementName(parentFolder, newName)
  416. const { docs: oldDocs, files: oldFiles } =
  417. ProjectEntityHandler.getAllEntitiesFromProject(project)
  418. // we need to increment the project version number for any structure change
  419. const newProject = await Project.findOneAndUpdate(
  420. { _id: projectId, [entPath.mongo]: { $exists: true } },
  421. { $set: { [`${entPath.mongo}.name`]: newName }, $inc: { version: 1 } },
  422. { new: true }
  423. ).exec()
  424. if (newProject == null) {
  425. throw new OError('Project not found or path not found in filetree', {
  426. projectId,
  427. path: entPath,
  428. })
  429. }
  430. const { docs: newDocs, files: newFiles } =
  431. ProjectEntityHandler.getAllEntitiesFromProject(newProject)
  432. return {
  433. project,
  434. startPath,
  435. endPath,
  436. rev: entity.rev,
  437. changes: { oldDocs, newDocs, oldFiles, newFiles, newProject },
  438. }
  439. }
  440. async function _insertDeletedFileReference(projectId, fileRef) {
  441. await DeletedFile.create({
  442. projectId,
  443. _id: fileRef._id,
  444. name: fileRef.name,
  445. linkedFileData: fileRef.linkedFileData,
  446. hash: fileRef.hash,
  447. deletedAt: new Date(),
  448. })
  449. }
  450. async function _removeElementFromMongoArray(
  451. model,
  452. modelId,
  453. path,
  454. elementId,
  455. deleteRootDoc = false
  456. ) {
  457. const nonArrayPath = path.slice(0, path.lastIndexOf('.'))
  458. const options = { new: true }
  459. const query = { _id: modelId }
  460. const update = {
  461. $pull: { [nonArrayPath]: { _id: elementId } },
  462. $inc: { version: 1 },
  463. }
  464. if (deleteRootDoc) {
  465. update.$unset = { rootDoc_id: 1 }
  466. }
  467. return model.findOneAndUpdate(query, update, options).exec()
  468. }
  469. function _countElements(project) {
  470. function countFolder(folder) {
  471. if (folder == null) {
  472. return 0
  473. }
  474. let total = 0
  475. if (folder.folders) {
  476. total += folder.folders.length
  477. for (const subfolder of iterablePaths(folder, 'folders')) {
  478. total += countFolder(subfolder)
  479. }
  480. }
  481. if (folder.docs) {
  482. total += folder.docs.length
  483. }
  484. if (folder.fileRefs) {
  485. total += folder.fileRefs.length
  486. }
  487. return total
  488. }
  489. return countFolder(project.rootFolder[0])
  490. }
  491. async function _putElement(project, folderId, element, type) {
  492. if (element == null || element._id == null) {
  493. logger.warn(
  494. { projectId: project._id, folderId, element, type },
  495. 'failed trying to insert element as it was null'
  496. )
  497. throw new Error('no element passed to be inserted')
  498. }
  499. const pathSegment = _getMongoPathSegmentFromType(type)
  500. // original check path.resolve("/", element.name) isnt "/#{element.name}" or element.name.match("/")
  501. // check if name is allowed
  502. if (!SafePath.isCleanFilename(element.name)) {
  503. logger.warn(
  504. { projectId: project._id, folderId, element, type },
  505. 'failed trying to insert element as name was invalid'
  506. )
  507. throw new Errors.InvalidNameError('invalid element name')
  508. }
  509. if (folderId == null) {
  510. folderId = project.rootFolder[0]._id
  511. }
  512. if (_countElements(project) > Settings.maxEntitiesPerProject) {
  513. logger.warn(
  514. { projectId: project._id },
  515. 'project too big, stopping insertions'
  516. )
  517. CooldownManager.putProjectOnCooldown(project._id)
  518. throw new Error('project_has_too_many_files')
  519. }
  520. const { element: folder, path } = await ProjectLocator.promises.findElement({
  521. project,
  522. element_id: folderId,
  523. type: 'folder',
  524. })
  525. const newPath = {
  526. fileSystem: `${path.fileSystem}/${element.name}`,
  527. mongo: path.mongo,
  528. }
  529. // check if the path would be too long
  530. if (!SafePath.isAllowedLength(newPath.fileSystem)) {
  531. throw new Errors.InvalidNameError('path too long')
  532. }
  533. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  534. if (_blockedFilename(newPath, type)) {
  535. throw new Errors.InvalidNameError('blocked element name')
  536. }
  537. _checkValidElementName(folder, element.name)
  538. element._id = new ObjectId(element._id.toString())
  539. const mongoPath = `${path.mongo}.${pathSegment}`
  540. const newProject = await Project.findOneAndUpdate(
  541. { _id: project._id, [path.mongo]: { $exists: true } },
  542. { $push: { [mongoPath]: element }, $inc: { version: 1 } },
  543. { new: true }
  544. ).exec()
  545. if (newProject == null) {
  546. throw new OError('Project not found or path not found in filetree', {
  547. projectId: project._id,
  548. path,
  549. })
  550. }
  551. return { result: { path: newPath }, project: newProject }
  552. }
  553. function _blockedFilename(entityPath, entityType) {
  554. // check if name would be blocked in v1
  555. // javascript reserved names are forbidden for docs and files
  556. // at the top-level (but folders with reserved names are allowed).
  557. const isFolder = entityType === 'folder'
  558. const dir = path.dirname(entityPath.fileSystem)
  559. const file = path.basename(entityPath.fileSystem)
  560. const isTopLevel = dir === '/'
  561. if (isTopLevel && !isFolder && SafePath.isBlockedFilename(file)) {
  562. return true
  563. } else {
  564. return false
  565. }
  566. }
  567. function _getMongoPathSegmentFromType(type) {
  568. const pathSegment = ENTITY_TYPE_TO_MONGO_PATH_SEGMENT[type]
  569. if (pathSegment == null) {
  570. throw new Error(`Unknown entity type: ${type}`)
  571. }
  572. return pathSegment
  573. }
  574. /**
  575. * Check if the name is already taken by a doc, file or folder. If so, return an
  576. * error "file already exists".
  577. */
  578. function _checkValidElementName(folder, name) {
  579. if (folder == null) {
  580. return
  581. }
  582. const elements = []
  583. .concat(folder.docs || [])
  584. .concat(folder.fileRefs || [])
  585. .concat(folder.folders || [])
  586. for (const element of elements) {
  587. if (element.name === name) {
  588. throw new Errors.InvalidNameError('file already exists')
  589. }
  590. }
  591. }
  592. function _confirmFolder(project, folderId) {
  593. if (folderId == null) {
  594. return project.rootFolder[0]._id
  595. } else {
  596. return folderId
  597. }
  598. }
  599. function _checkValidFolderPath(folderPath, destinationFolderPath) {
  600. if (!folderPath.endsWith('/')) {
  601. folderPath += '/'
  602. }
  603. if (!destinationFolderPath.endsWith('/')) {
  604. destinationFolderPath += '/'
  605. }
  606. if (destinationFolderPath === folderPath) {
  607. throw new Errors.InvalidNameError('destination folder is the same as me')
  608. }
  609. if (destinationFolderPath.startsWith(folderPath)) {
  610. throw new Errors.InvalidNameError(
  611. 'destination folder is a child folder of me'
  612. )
  613. }
  614. }
  615. async function _checkValidMove(
  616. project,
  617. entityType,
  618. entity,
  619. entityPath,
  620. destFolderId
  621. ) {
  622. const { element: destEntity, path: destFolderPath } =
  623. await ProjectLocator.promises.findElement({
  624. project,
  625. element_id: destFolderId,
  626. type: 'folder',
  627. })
  628. // check if there is already a doc/file/folder with the same name
  629. // in the destination folder
  630. _checkValidElementName(destEntity, entity.name)
  631. // check if the folder being moved is a parent of the destination folder
  632. if (/folder/.test(entityType)) {
  633. _checkValidFolderPath(entityPath.fileSystem, destFolderPath.fileSystem)
  634. }
  635. }
  636. /**
  637. * Create an initial file tree out of a list of doc and file entries
  638. *
  639. * Each entry specifies a path to the doc or file. Folders are automatically
  640. * created.
  641. *
  642. * @param {ObjectId} projectId - id of the project
  643. * @param {DocEntry[]} docEntries - list of docs to add
  644. * @param {FileEntry[]} fileEntries - list of files to add
  645. * @return {Promise<string>} the project version after the operation
  646. */
  647. async function createNewFolderStructure(projectId, docEntries, fileEntries) {
  648. try {
  649. const rootFolder = FolderStructureBuilder.buildFolderStructure(
  650. docEntries,
  651. fileEntries
  652. )
  653. const project = await Project.findOneAndUpdate(
  654. {
  655. _id: projectId,
  656. 'rootFolder.0.folders.0': { $exists: false },
  657. 'rootFolder.0.docs.0': { $exists: false },
  658. 'rootFolder.0.files.0': { $exists: false },
  659. },
  660. {
  661. $set: { rootFolder: [rootFolder] },
  662. $inc: { version: 1 },
  663. },
  664. {
  665. new: true,
  666. lean: true,
  667. fields: { version: 1 },
  668. }
  669. ).exec()
  670. if (project == null) {
  671. throw new OError('project not found or folder structure already exists', {
  672. projectId,
  673. })
  674. }
  675. return project.version
  676. } catch (err) {
  677. throw OError.tag(err, 'failed to create folder structure', { projectId })
  678. }
  679. }
  680. /**
  681. * Given a Mongo path to an entity, return the Mongo path to the parent folder
  682. */
  683. function _getParentMongoPath(mongoPath) {
  684. const segments = mongoPath.split('.')
  685. if (segments.length <= 2) {
  686. throw new Error('Root folder has no parents')
  687. }
  688. return segments.slice(0, -2).join('.')
  689. }