ProjectEntityUpdateHandler.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  1. const _ = require('lodash')
  2. const OError = require('@overleaf/o-error')
  3. const logger = require('@overleaf/logger')
  4. const Settings = require('@overleaf/settings')
  5. const Path = require('path')
  6. const fs = require('fs')
  7. const { Doc } = require('../../models/Doc')
  8. const DocstoreManager = require('../Docstore/DocstoreManager')
  9. const DocumentUpdaterHandler = require('../../Features/DocumentUpdater/DocumentUpdaterHandler')
  10. const Errors = require('../Errors/Errors')
  11. const FileStoreHandler = require('../FileStore/FileStoreHandler')
  12. const LockManager = require('../../infrastructure/LockManager')
  13. const { Project } = require('../../models/Project')
  14. const ProjectEntityHandler = require('./ProjectEntityHandler')
  15. const ProjectGetter = require('./ProjectGetter')
  16. const ProjectLocator = require('./ProjectLocator')
  17. const ProjectOptionsHandler = require('./ProjectOptionsHandler')
  18. const ProjectUpdateHandler = require('./ProjectUpdateHandler')
  19. const ProjectEntityMongoUpdateHandler = require('./ProjectEntityMongoUpdateHandler')
  20. const SafePath = require('./SafePath')
  21. const TpdsUpdateSender = require('../ThirdPartyDataStore/TpdsUpdateSender')
  22. const FileWriter = require('../../infrastructure/FileWriter')
  23. const EditorRealTimeController = require('../Editor/EditorRealTimeController')
  24. const {
  25. callbackifyMultiResult,
  26. callbackify,
  27. } = require('@overleaf/promise-utils')
  28. const { iterablePaths } = require('./IterablePath')
  29. const LOCK_NAMESPACE = 'sequentialProjectStructureUpdateLock'
  30. const VALID_ROOT_DOC_EXTENSIONS = Settings.validRootDocExtensions
  31. const VALID_ROOT_DOC_REGEXP = new RegExp(
  32. `^\\.(${VALID_ROOT_DOC_EXTENSIONS.join('|')})$`,
  33. 'i'
  34. )
  35. function wrapWithLock(methodWithoutLock, lockManager = LockManager) {
  36. // This lock is used to make sure that the project structure updates are made
  37. // sequentially. In particular the updates must be made in mongo and sent to
  38. // the doc-updater in the same order.
  39. if (typeof methodWithoutLock === 'function') {
  40. const methodWithLock = async (projectId, ...rest) => {
  41. return lockManager.promises.runWithLock(LOCK_NAMESPACE, projectId, () =>
  42. methodWithoutLock(projectId, ...rest)
  43. )
  44. }
  45. methodWithLock.withoutLock = methodWithoutLock
  46. return methodWithLock
  47. } else {
  48. // handle case with separate setup and locked stages
  49. const mainTask = methodWithoutLock.withLock
  50. const methodWithLock = async (projectId, ...rest) => {
  51. const arg = await methodWithoutLock.beforeLock(projectId, ...rest)
  52. return lockManager.promises.runWithLock(LOCK_NAMESPACE, projectId, () =>
  53. mainTask(arg)
  54. )
  55. }
  56. methodWithLock.withoutLock = async (...args) => {
  57. return await mainTask(await methodWithoutLock.beforeLock(...args))
  58. }
  59. methodWithLock.beforeLock = methodWithoutLock.beforeLock
  60. methodWithLock.mainTask = methodWithoutLock.withLock
  61. return methodWithLock
  62. }
  63. }
  64. async function getDocContext(projectId, docId) {
  65. let project
  66. try {
  67. project = await ProjectGetter.promises.getProject(projectId, {
  68. name: true,
  69. rootFolder: true,
  70. })
  71. } catch (err) {
  72. throw OError.tag(err, 'error fetching project', {
  73. projectId,
  74. })
  75. }
  76. if (!project) {
  77. throw new Errors.NotFoundError('project not found')
  78. }
  79. try {
  80. const { path, folder } = await ProjectLocator.promises.findElement({
  81. project,
  82. element_id: docId,
  83. type: 'docs',
  84. })
  85. return {
  86. projectName: project.name,
  87. isDeletedDoc: false,
  88. path: path.fileSystem,
  89. folder,
  90. }
  91. } catch (err) {
  92. if (err instanceof Errors.NotFoundError) {
  93. // (Soft-)Deleted docs are removed from the file-tree (rootFolder).
  94. // docstore can tell whether it exists and is (soft)-deleted.
  95. let isDeletedDoc
  96. try {
  97. isDeletedDoc = await DocstoreManager.promises.isDocDeleted(
  98. projectId,
  99. docId
  100. )
  101. if (!isDeletedDoc) {
  102. // NOTE: This can happen while we delete a doc:
  103. // 1. web will update the projects entry
  104. // 2. web triggers flushes to tpds/doc-updater
  105. // 3. web triggers (soft)-delete in docstore
  106. // Specifically when an update comes in after 1
  107. // and before 3 completes.
  108. logger.debug(
  109. { projectId, docId },
  110. 'updating doc that is in process of getting soft-deleted'
  111. )
  112. }
  113. return {
  114. projectName: project.name,
  115. isDeletedDoc: true,
  116. path: null,
  117. folder: null,
  118. }
  119. } catch (error) {
  120. if (error instanceof Errors.NotFoundError) {
  121. logger.warn(
  122. { projectId, docId },
  123. 'doc not found while updating doc lines'
  124. )
  125. throw error
  126. }
  127. throw OError.tag(
  128. error,
  129. 'error checking deletion status with docstore',
  130. {
  131. projectId,
  132. docId,
  133. }
  134. )
  135. }
  136. } else {
  137. throw OError.tag(err, 'error finding doc in rootFolder', {
  138. docId,
  139. projectId,
  140. })
  141. }
  142. }
  143. }
  144. async function updateDocLines(
  145. projectId,
  146. docId,
  147. lines,
  148. version,
  149. ranges,
  150. lastUpdatedAt,
  151. lastUpdatedBy
  152. ) {
  153. let ctx
  154. try {
  155. ctx = await getDocContext(projectId, docId)
  156. } catch (error) {
  157. if (error instanceof Errors.NotFoundError) {
  158. // Do not allow an update to a doc which has never exist on this project
  159. logger.warn(
  160. { docId, projectId },
  161. 'project or doc not found while updating doc lines'
  162. )
  163. }
  164. throw error
  165. }
  166. const { projectName, isDeletedDoc, path, folder } = ctx
  167. logger.debug({ projectId, docId }, 'telling docstore manager to update doc')
  168. let modified, rev
  169. try {
  170. ;({ modified, rev } = await DocstoreManager.promises.updateDoc(
  171. projectId,
  172. docId,
  173. lines,
  174. version,
  175. ranges
  176. ))
  177. } catch (err) {
  178. throw OError.tag(err, 'error sending doc to docstore', { docId, projectId })
  179. }
  180. // path will only be present if the doc is not deleted
  181. if (!modified || isDeletedDoc) {
  182. return { rev }
  183. }
  184. // Don't need to block for marking as updated
  185. ProjectUpdateHandler.promises
  186. .markAsUpdated(projectId, lastUpdatedAt, lastUpdatedBy)
  187. .catch(error => {
  188. logger.error({ error }, 'failed to mark project as updated')
  189. })
  190. await TpdsUpdateSender.promises.addDoc({
  191. projectId,
  192. path,
  193. docId,
  194. projectName,
  195. rev,
  196. folderId: folder?._id,
  197. })
  198. return { rev, modified }
  199. }
  200. async function setRootDoc(projectId, newRootDocID) {
  201. logger.debug({ projectId, rootDocId: newRootDocID }, 'setting root doc')
  202. if (projectId == null || newRootDocID == null) {
  203. throw new Errors.InvalidError('missing arguments (project or doc)')
  204. }
  205. const docPath =
  206. await ProjectEntityHandler.promises.getDocPathByProjectIdAndDocId(
  207. projectId,
  208. newRootDocID
  209. )
  210. if (ProjectEntityUpdateHandler.isPathValidForRootDoc(docPath)) {
  211. await Project.updateOne(
  212. { _id: projectId },
  213. { rootDoc_id: newRootDocID }
  214. ).exec()
  215. } else {
  216. throw new Errors.UnsupportedFileTypeError(
  217. 'invalid file extension for root doc'
  218. )
  219. }
  220. }
  221. async function unsetRootDoc(projectId) {
  222. logger.debug({ projectId }, 'removing root doc')
  223. await Project.updateOne(
  224. { _id: projectId },
  225. { $unset: { rootDoc_id: true } }
  226. ).exec()
  227. }
  228. async function addDoc(projectId, folderId, docName, docLines, userId, source) {
  229. return await ProjectEntityUpdateHandler.promises.addDocWithRanges(
  230. projectId,
  231. folderId,
  232. docName,
  233. docLines,
  234. {},
  235. userId,
  236. source
  237. )
  238. }
  239. const addDocWithRanges = wrapWithLock({
  240. async beforeLock(
  241. projectId,
  242. folderId,
  243. docName,
  244. docLines,
  245. ranges,
  246. userId,
  247. source
  248. ) {
  249. if (!SafePath.isCleanFilename(docName)) {
  250. throw new Errors.InvalidNameError('invalid element name')
  251. }
  252. // Put doc in docstore first, so that if it errors, we don't have a doc_id in the project
  253. // which hasn't been created in docstore.
  254. const doc = new Doc({ name: docName })
  255. const { rev } = await DocstoreManager.promises.updateDoc(
  256. projectId.toString(),
  257. doc._id.toString(),
  258. docLines,
  259. 0,
  260. ranges
  261. )
  262. doc.rev = rev
  263. return {
  264. projectId,
  265. folderId,
  266. doc,
  267. docName,
  268. docLines,
  269. ranges,
  270. userId,
  271. source,
  272. }
  273. },
  274. async withLock({
  275. projectId,
  276. folderId,
  277. doc,
  278. docName,
  279. docLines,
  280. ranges,
  281. userId,
  282. source,
  283. }) {
  284. const { result, project } =
  285. await ProjectEntityUpdateHandler._addDocAndSendToTpds(
  286. projectId,
  287. folderId,
  288. doc
  289. )
  290. const docPath = result?.path?.fileSystem
  291. const projectHistoryId = project?.overleaf?.history?.id
  292. const newDocs = [
  293. {
  294. doc,
  295. path: docPath,
  296. docLines: docLines.join('\n'),
  297. ranges,
  298. },
  299. ]
  300. await DocumentUpdaterHandler.promises.updateProjectStructure(
  301. projectId,
  302. projectHistoryId,
  303. userId,
  304. { newDocs, newProject: project },
  305. source
  306. )
  307. return { doc, folderId: folderId || project.rootFolder[0]._id }
  308. },
  309. })
  310. const addFile = wrapWithLock({
  311. async beforeLock(
  312. projectId,
  313. folderId,
  314. fileName,
  315. fsPath,
  316. linkedFileData,
  317. userId,
  318. source
  319. ) {
  320. if (!SafePath.isCleanFilename(fileName)) {
  321. throw new Errors.InvalidNameError('invalid element name')
  322. }
  323. const { url, fileRef } = await ProjectEntityUpdateHandler._uploadFile(
  324. projectId,
  325. folderId,
  326. fileName,
  327. fsPath,
  328. linkedFileData
  329. )
  330. return {
  331. projectId,
  332. folderId,
  333. userId,
  334. fileRef,
  335. fileStoreUrl: url,
  336. source,
  337. }
  338. },
  339. async withLock({
  340. projectId,
  341. folderId,
  342. userId,
  343. fileRef,
  344. fileStoreUrl,
  345. source,
  346. }) {
  347. const { result, project } =
  348. await ProjectEntityUpdateHandler._addFileAndSendToTpds(
  349. projectId,
  350. folderId,
  351. fileRef
  352. )
  353. const projectHistoryId = project.overleaf?.history?.id
  354. const newFiles = [
  355. {
  356. file: fileRef,
  357. path: result && result.path && result.path.fileSystem,
  358. url: fileStoreUrl,
  359. },
  360. ]
  361. await DocumentUpdaterHandler.promises.updateProjectStructure(
  362. projectId,
  363. projectHistoryId,
  364. userId,
  365. { newFiles, newProject: project },
  366. source
  367. )
  368. ProjectUpdateHandler.promises
  369. .markAsUpdated(projectId, new Date(), userId)
  370. .catch(error => {
  371. logger.error({ error }, 'failed to mark project as updated')
  372. })
  373. return { fileRef, folderId }
  374. },
  375. })
  376. const upsertDoc = wrapWithLock(
  377. async function (projectId, folderId, docName, docLines, source, userId) {
  378. if (!SafePath.isCleanFilename(docName)) {
  379. throw new Errors.InvalidNameError('invalid element name')
  380. }
  381. let element, folderPath
  382. try {
  383. ;({ element, path: folderPath } =
  384. await ProjectLocator.promises.findElement({
  385. project_id: projectId,
  386. element_id: folderId,
  387. type: 'folder',
  388. }))
  389. } catch (error) {
  390. if (error instanceof Errors.NotFoundError) {
  391. throw new Error('folder_not_found')
  392. }
  393. throw error
  394. }
  395. if (element == null) {
  396. throw new Error("Couldn't find folder")
  397. }
  398. const existingDoc = element.docs.find(({ name }) => name === docName)
  399. const existingFile = element.fileRefs.find(({ name }) => name === docName)
  400. if (existingFile) {
  401. const doc = new Doc({ name: docName })
  402. const filePath = `${folderPath.fileSystem}/${existingFile.name}`
  403. const { rev } = await DocstoreManager.promises.updateDoc(
  404. projectId.toString(),
  405. doc._id.toString(),
  406. docLines,
  407. 0,
  408. {}
  409. )
  410. doc.rev = rev
  411. const project =
  412. await ProjectEntityMongoUpdateHandler.promises.replaceFileWithDoc(
  413. projectId,
  414. existingFile._id,
  415. doc
  416. )
  417. await TpdsUpdateSender.promises.addDoc({
  418. projectId,
  419. docId: doc._id,
  420. path: filePath,
  421. projectName: project.name,
  422. rev: existingFile.rev + 1,
  423. folderId,
  424. })
  425. const projectHistoryId =
  426. project.overleaf &&
  427. project.overleaf.history &&
  428. project.overleaf.history.id
  429. const newDocs = [
  430. {
  431. doc,
  432. path: filePath,
  433. docLines: docLines.join('\n'),
  434. },
  435. ]
  436. const oldFiles = [
  437. {
  438. file: existingFile,
  439. path: filePath,
  440. },
  441. ]
  442. await DocumentUpdaterHandler.promises.updateProjectStructure(
  443. projectId,
  444. projectHistoryId,
  445. userId,
  446. { oldFiles, newDocs, newProject: project },
  447. source
  448. )
  449. EditorRealTimeController.emitToRoom(
  450. projectId,
  451. 'removeEntity',
  452. existingFile._id,
  453. 'convertFileToDoc'
  454. )
  455. return { doc, isNew: true }
  456. } else if (existingDoc) {
  457. const result = await DocumentUpdaterHandler.promises.setDocument(
  458. projectId,
  459. existingDoc._id,
  460. userId,
  461. docLines,
  462. source
  463. )
  464. logger.debug(
  465. { projectId, docId: existingDoc._id },
  466. 'notifying users that the document has been updated'
  467. )
  468. // there is no need to flush the doc to mongo at this point as docupdater
  469. // flushes it as part of setDoc.
  470. //
  471. // combine rev from response with existing doc metadata
  472. return {
  473. doc: { ...existingDoc, ...result },
  474. isNew: existingDoc == null,
  475. }
  476. } else {
  477. const { doc } =
  478. await ProjectEntityUpdateHandler.promises.addDocWithRanges.withoutLock(
  479. projectId,
  480. folderId,
  481. docName,
  482. docLines,
  483. {},
  484. userId,
  485. source
  486. )
  487. return { doc, isNew: existingDoc == null }
  488. }
  489. }
  490. )
  491. const upsertFile = wrapWithLock({
  492. async beforeLock(
  493. projectId,
  494. folderId,
  495. fileName,
  496. fsPath,
  497. linkedFileData,
  498. userId,
  499. source
  500. ) {
  501. if (!SafePath.isCleanFilename(fileName)) {
  502. throw new Errors.InvalidNameError('invalid element name')
  503. }
  504. // create a new file
  505. const fileArgs = {
  506. name: fileName,
  507. linkedFileData,
  508. }
  509. const { url, fileRef } = await FileStoreHandler.promises.uploadFileFromDisk(
  510. projectId,
  511. fileArgs,
  512. fsPath
  513. )
  514. return {
  515. projectId,
  516. folderId,
  517. fileName,
  518. fsPath,
  519. linkedFileData,
  520. userId,
  521. fileRef,
  522. fileStoreUrl: url,
  523. source,
  524. }
  525. },
  526. async withLock({
  527. projectId,
  528. folderId,
  529. fileName,
  530. userId,
  531. fileRef,
  532. fileStoreUrl,
  533. source,
  534. }) {
  535. let element
  536. try {
  537. ;({ element } = await ProjectLocator.promises.findElement({
  538. project_id: projectId,
  539. element_id: folderId,
  540. type: 'folder',
  541. }))
  542. } catch (error) {
  543. if (error instanceof Errors.NotFoundError) {
  544. throw new Error('folder_not_found')
  545. }
  546. throw error
  547. }
  548. if (element == null) {
  549. throw new Error("Couldn't find folder")
  550. }
  551. const existingFile = element.fileRefs.find(({ name }) => name === fileName)
  552. const existingDoc = element.docs.find(({ name }) => name === fileName)
  553. if (existingDoc) {
  554. let path
  555. try {
  556. ;({ path } = await ProjectLocator.promises.findElement({
  557. project_id: projectId,
  558. element_id: existingDoc._id,
  559. type: 'doc',
  560. }))
  561. } catch (err) {
  562. throw new Error("couldn't find existing file")
  563. }
  564. const project =
  565. await ProjectEntityMongoUpdateHandler.promises.replaceDocWithFile(
  566. projectId,
  567. existingDoc._id,
  568. fileRef
  569. )
  570. const projectHistoryId = project.overleaf?.history?.id
  571. await TpdsUpdateSender.promises.addFile({
  572. projectId: project._id,
  573. fileId: fileRef._id,
  574. path: path.fileSystem,
  575. rev: fileRef.rev,
  576. projectName: project.name,
  577. folderId,
  578. })
  579. await DocumentUpdaterHandler.promises.updateProjectStructure(
  580. projectId,
  581. projectHistoryId,
  582. userId,
  583. {
  584. oldDocs: [{ doc: existingDoc, path: path.fileSystem }],
  585. newFiles: [
  586. {
  587. file: fileRef,
  588. path: path.fileSystem,
  589. url: fileStoreUrl,
  590. },
  591. ],
  592. newProject: project,
  593. },
  594. source
  595. )
  596. EditorRealTimeController.emitToRoom(
  597. projectId,
  598. 'removeEntity',
  599. existingDoc._id,
  600. 'convertDocToFile'
  601. )
  602. return { fileRef, isNew: true, oldFileRef: existingFile }
  603. } else if (existingFile) {
  604. await ProjectEntityUpdateHandler._replaceFile(
  605. projectId,
  606. existingFile._id,
  607. userId,
  608. fileRef,
  609. fileStoreUrl,
  610. folderId,
  611. source
  612. )
  613. return { fileRef, isNew: false, oldFileRef: existingFile }
  614. } else {
  615. // this calls directly into the addFile main task (without the beforeLock part)
  616. await ProjectEntityUpdateHandler.promises.addFile.mainTask({
  617. projectId,
  618. folderId,
  619. userId,
  620. fileRef,
  621. fileStoreUrl,
  622. source,
  623. })
  624. return {
  625. fileRef,
  626. isNew: existingFile == null,
  627. oldFileRef: existingFile,
  628. }
  629. }
  630. },
  631. })
  632. const upsertDocWithPath = wrapWithLock(
  633. async function (projectId, elementPath, docLines, source, userId) {
  634. if (!SafePath.isCleanPath(elementPath)) {
  635. throw new Errors.InvalidNameError('invalid element name')
  636. }
  637. const docName = Path.basename(elementPath)
  638. const folderPath = Path.dirname(elementPath)
  639. const { newFolders, folder } =
  640. await ProjectEntityUpdateHandler.promises.mkdirp.withoutLock(
  641. projectId,
  642. folderPath
  643. )
  644. const { isNew, doc } =
  645. await ProjectEntityUpdateHandler.promises.upsertDoc.withoutLock(
  646. projectId,
  647. folder._id,
  648. docName,
  649. docLines,
  650. source,
  651. userId
  652. )
  653. return { doc, isNew, newFolders, folder }
  654. }
  655. )
  656. const upsertFileWithPath = wrapWithLock({
  657. async beforeLock(
  658. projectId,
  659. elementPath,
  660. fsPath,
  661. linkedFileData,
  662. userId,
  663. source
  664. ) {
  665. if (!SafePath.isCleanPath(elementPath)) {
  666. throw new Errors.InvalidNameError('invalid element name')
  667. }
  668. const fileName = Path.basename(elementPath)
  669. const folderPath = Path.dirname(elementPath)
  670. // create a new file
  671. const fileArgs = {
  672. name: fileName,
  673. linkedFileData,
  674. }
  675. const { url: fileStoreUrl, fileRef } =
  676. await FileStoreHandler.promises.uploadFileFromDisk(
  677. projectId,
  678. fileArgs,
  679. fsPath
  680. )
  681. return {
  682. projectId,
  683. folderPath,
  684. fileName,
  685. fsPath,
  686. linkedFileData,
  687. userId,
  688. fileRef,
  689. fileStoreUrl,
  690. source,
  691. }
  692. },
  693. async withLock({
  694. projectId,
  695. folderPath,
  696. fileName,
  697. fsPath,
  698. linkedFileData,
  699. userId,
  700. fileRef,
  701. fileStoreUrl,
  702. source,
  703. }) {
  704. const { newFolders, folder } =
  705. await ProjectEntityUpdateHandler.promises.mkdirp.withoutLock(
  706. projectId,
  707. folderPath
  708. )
  709. // this calls directly into the upsertFile main task (without the beforeLock part)
  710. const {
  711. fileRef: newFileRef,
  712. isNew,
  713. oldFileRef,
  714. } = await ProjectEntityUpdateHandler.promises.upsertFile.mainTask({
  715. projectId,
  716. folderId: folder._id,
  717. fileName,
  718. fsPath,
  719. linkedFileData,
  720. userId,
  721. fileRef,
  722. fileStoreUrl,
  723. source,
  724. })
  725. return {
  726. fileRef: newFileRef,
  727. isNew,
  728. oldFileRef,
  729. newFolders,
  730. folder,
  731. }
  732. },
  733. })
  734. const deleteEntity = wrapWithLock(
  735. async function (projectId, entityId, entityType, userId, source, callback) {
  736. logger.debug({ entityId, entityType, projectId }, 'deleting project entity')
  737. if (entityType == null) {
  738. logger.warn({ err: 'No entityType set', projectId, entityId })
  739. throw new Error('No entityType set')
  740. }
  741. entityType = entityType.toLowerCase()
  742. // Flush the entire project to avoid leaving partially deleted docs in redis.
  743. await DocumentUpdaterHandler.promises.flushProjectToMongo(projectId)
  744. const { entity, path, projectBeforeDeletion, newProject } =
  745. await ProjectEntityMongoUpdateHandler.promises.deleteEntity(
  746. projectId,
  747. entityId,
  748. entityType
  749. )
  750. const subtreeListing = await ProjectEntityUpdateHandler._cleanUpEntity(
  751. projectBeforeDeletion,
  752. newProject,
  753. entity,
  754. entityType,
  755. path.fileSystem,
  756. userId,
  757. source
  758. )
  759. const subtreeEntityIds = subtreeListing.map(entry =>
  760. entry.entity._id.toString()
  761. )
  762. await TpdsUpdateSender.promises.deleteEntity({
  763. projectId,
  764. path: path.fileSystem,
  765. projectName: projectBeforeDeletion.name,
  766. entityId,
  767. entityType,
  768. subtreeEntityIds,
  769. })
  770. return entityId
  771. }
  772. )
  773. const deleteEntityWithPath = wrapWithLock(
  774. async (projectId, path, userId, source) => {
  775. const { element, type } = await ProjectLocator.promises.findElementByPath({
  776. project_id: projectId,
  777. path,
  778. exactCaseMatch: true,
  779. })
  780. if (element == null) {
  781. throw new Errors.NotFoundError('project not found')
  782. }
  783. return await ProjectEntityUpdateHandler.promises.deleteEntity.withoutLock(
  784. projectId,
  785. element._id,
  786. type,
  787. userId,
  788. source
  789. )
  790. }
  791. )
  792. const mkdirp = wrapWithLock(async function (projectId, path) {
  793. for (const folder of path.split('/')) {
  794. if (folder.length > 0 && !SafePath.isCleanFilename(folder)) {
  795. throw new Errors.InvalidNameError('invalid element name')
  796. }
  797. }
  798. return await ProjectEntityMongoUpdateHandler.promises.mkdirp(
  799. projectId,
  800. path,
  801. { exactCaseMatch: false }
  802. )
  803. })
  804. const mkdirpWithExactCase = wrapWithLock(async function (projectId, path) {
  805. for (const folder of path.split('/')) {
  806. if (folder.length > 0 && !SafePath.isCleanFilename(folder)) {
  807. throw new Errors.InvalidNameError('invalid element name')
  808. }
  809. }
  810. return await ProjectEntityMongoUpdateHandler.promises.mkdirp(
  811. projectId,
  812. path,
  813. { exactCaseMatch: true }
  814. )
  815. })
  816. const addFolder = wrapWithLock(
  817. async function (projectId, parentFolderId, folderName) {
  818. if (!SafePath.isCleanFilename(folderName)) {
  819. throw new Errors.InvalidNameError('invalid element name')
  820. }
  821. return await ProjectEntityMongoUpdateHandler.promises.addFolder(
  822. projectId,
  823. parentFolderId,
  824. folderName
  825. )
  826. }
  827. )
  828. const moveEntity = wrapWithLock(
  829. async function (
  830. projectId,
  831. entityId,
  832. destFolderId,
  833. entityType,
  834. userId,
  835. source
  836. ) {
  837. logger.debug(
  838. { entityType, entityId, projectId, destFolderId },
  839. 'moving entity'
  840. )
  841. if (entityType == null) {
  842. logger.warn({ err: 'No entityType set', projectId, entityId })
  843. throw new Error('No entityType set')
  844. }
  845. entityType = entityType.toLowerCase()
  846. await DocumentUpdaterHandler.promises.flushProjectToMongo(projectId)
  847. const { project, startPath, endPath, rev, changes } =
  848. await ProjectEntityMongoUpdateHandler.promises.moveEntity(
  849. projectId,
  850. entityId,
  851. destFolderId,
  852. entityType
  853. )
  854. const projectHistoryId = project.overleaf?.history?.id
  855. try {
  856. await TpdsUpdateSender.promises.moveEntity({
  857. projectId,
  858. projectName: project.name,
  859. startPath,
  860. endPath,
  861. rev,
  862. entityId,
  863. entityType,
  864. folderId: destFolderId,
  865. })
  866. } catch (err) {
  867. logger.error({ err }, 'error sending tpds update')
  868. }
  869. return await DocumentUpdaterHandler.promises.updateProjectStructure(
  870. projectId,
  871. projectHistoryId,
  872. userId,
  873. changes,
  874. source
  875. )
  876. }
  877. )
  878. const renameEntity = wrapWithLock(
  879. async function (projectId, entityId, entityType, newName, userId, source) {
  880. if (!newName || typeof newName !== 'string') {
  881. const err = new OError('invalid newName value', {
  882. value: newName,
  883. type: typeof newName,
  884. projectId,
  885. entityId,
  886. entityType,
  887. userId,
  888. source,
  889. })
  890. logger.error({ err }, 'Invalid newName passed to renameEntity')
  891. throw err
  892. }
  893. if (!SafePath.isCleanFilename(newName)) {
  894. throw new Errors.InvalidNameError('invalid element name')
  895. }
  896. logger.debug({ entityId, projectId }, `renaming ${entityType}`)
  897. if (entityType == null) {
  898. logger.warn({ err: 'No entityType set', projectId, entityId })
  899. throw new Error('No entityType set')
  900. }
  901. entityType = entityType.toLowerCase()
  902. await DocumentUpdaterHandler.promises.flushProjectToMongo(projectId)
  903. const { project, startPath, endPath, rev, changes } =
  904. await ProjectEntityMongoUpdateHandler.promises.renameEntity(
  905. projectId,
  906. entityId,
  907. entityType,
  908. newName
  909. )
  910. const projectHistoryId = project.overleaf?.history?.id
  911. try {
  912. await TpdsUpdateSender.promises.moveEntity({
  913. projectId,
  914. projectName: project.name,
  915. startPath,
  916. endPath,
  917. rev,
  918. entityId,
  919. entityType,
  920. folderId: null, // this means the folder has not changed
  921. })
  922. } catch (err) {
  923. logger.error({ err }, 'error sending tpds update')
  924. }
  925. return await DocumentUpdaterHandler.promises.updateProjectStructure(
  926. projectId,
  927. projectHistoryId,
  928. userId,
  929. changes,
  930. source
  931. )
  932. }
  933. )
  934. // This doesn't directly update project structure, but we need to take the lock
  935. // to prevent anything else being queued before the resync update
  936. const resyncProjectHistory = wrapWithLock(
  937. async (projectId, opts) => {
  938. const project = await ProjectGetter.promises.getProject(projectId, {
  939. rootFolder: true,
  940. overleaf: true,
  941. })
  942. const projectHistoryId = project.overleaf?.history?.id
  943. if (projectHistoryId == null) {
  944. throw new Errors.ProjectHistoryDisabledError(
  945. `project history not enabled for ${projectId}`
  946. )
  947. }
  948. const { docs, files, folders } =
  949. ProjectEntityHandler.getAllEntitiesFromProject(project)
  950. // _checkFileTree() must be passed the folders before docs and
  951. // files
  952. await ProjectEntityUpdateHandler._checkFiletree(
  953. projectId,
  954. projectHistoryId,
  955. [...folders, ...docs, ...files]
  956. )
  957. await DocumentUpdaterHandler.promises.resyncProjectHistory(
  958. projectId,
  959. projectHistoryId,
  960. docs,
  961. files,
  962. opts
  963. )
  964. if (opts.historyRangesMigration) {
  965. return await ProjectOptionsHandler.promises.setHistoryRangesSupport(
  966. projectId,
  967. opts.historyRangesMigration === 'forwards'
  968. )
  969. }
  970. },
  971. LockManager.withTimeout(6 * 60) // use an extended lock for the resync operations
  972. )
  973. const convertDocToFile = wrapWithLock({
  974. async beforeLock(projectId, docId, userId, source) {
  975. await DocumentUpdaterHandler.promises.flushDocToMongo(projectId, docId)
  976. const { element: doc, path } = await ProjectLocator.promises.findElement({
  977. project_id: projectId,
  978. element_id: docId,
  979. type: 'doc',
  980. })
  981. const docPath = path.fileSystem
  982. const { lines, rev, ranges } = await DocstoreManager.promises.getDoc(
  983. projectId,
  984. docId
  985. )
  986. if (!_.isEmpty(ranges)) {
  987. throw new Errors.DocHasRangesError({})
  988. }
  989. await DocumentUpdaterHandler.promises.deleteDoc(projectId, docId, false)
  990. const fsPath = await FileWriter.promises.writeLinesToDisk(projectId, lines)
  991. const { url: fileStoreUrl, fileRef } =
  992. await FileStoreHandler.promises.uploadFileFromDisk(
  993. projectId,
  994. { name: doc.name, rev: rev + 1 },
  995. fsPath
  996. )
  997. try {
  998. await fs.promises.unlink(fsPath)
  999. } catch (err) {
  1000. logger.warn({ err, path: fsPath }, 'failed to clean up temporary file')
  1001. }
  1002. return {
  1003. projectId,
  1004. doc,
  1005. path: docPath,
  1006. fileRef,
  1007. fileStoreUrl,
  1008. userId,
  1009. source,
  1010. }
  1011. },
  1012. async withLock({
  1013. projectId,
  1014. doc,
  1015. path,
  1016. fileRef,
  1017. fileStoreUrl,
  1018. userId,
  1019. source,
  1020. }) {
  1021. const project =
  1022. await ProjectEntityMongoUpdateHandler.promises.replaceDocWithFile(
  1023. projectId,
  1024. doc._id,
  1025. fileRef
  1026. )
  1027. const projectHistoryId = project.overleaf?.history?.id
  1028. await DocumentUpdaterHandler.promises.updateProjectStructure(
  1029. projectId,
  1030. projectHistoryId,
  1031. userId,
  1032. {
  1033. oldDocs: [{ doc, path }],
  1034. newFiles: [{ file: fileRef, path, url: fileStoreUrl }],
  1035. newProject: project,
  1036. },
  1037. source
  1038. )
  1039. const { folder } = await ProjectLocator.promises.findElement({
  1040. project_id: projectId,
  1041. element_id: fileRef._id,
  1042. type: 'file',
  1043. })
  1044. EditorRealTimeController.emitToRoom(
  1045. projectId,
  1046. 'removeEntity',
  1047. doc._id,
  1048. 'convertDocToFile'
  1049. )
  1050. EditorRealTimeController.emitToRoom(
  1051. projectId,
  1052. 'reciveNewFile',
  1053. folder._id,
  1054. fileRef,
  1055. 'convertDocToFile',
  1056. null,
  1057. userId
  1058. )
  1059. return fileRef
  1060. },
  1061. })
  1062. const ProjectEntityUpdateHandler = {
  1063. LOCK_NAMESPACE,
  1064. addDoc: callbackifyMultiResult(addDoc, ['doc', 'folderId']),
  1065. addDocWithRanges: callbackifyMultiResult(addDocWithRanges, [
  1066. 'doc',
  1067. 'folderId',
  1068. ]),
  1069. addFile: callbackifyMultiResult(addFile, ['fileRef', 'folderId']),
  1070. addFolder: callbackifyMultiResult(addFolder, ['folder', 'parentFolderId']),
  1071. convertDocToFile: callbackify(convertDocToFile),
  1072. deleteEntity: callbackify(deleteEntity),
  1073. deleteEntityWithPath: callbackify(deleteEntityWithPath),
  1074. mkdirp: callbackifyMultiResult(mkdirp, [
  1075. 'newFolders',
  1076. 'folder',
  1077. 'parentFolder',
  1078. ]),
  1079. mkdirpWithExactCase: callbackifyMultiResult(mkdirpWithExactCase, [
  1080. 'newFolders',
  1081. 'folder',
  1082. 'parentFolder',
  1083. ]),
  1084. moveEntity: callbackify(moveEntity),
  1085. renameEntity: callbackify(renameEntity),
  1086. resyncProjectHistory: callbackify(resyncProjectHistory),
  1087. setRootDoc: callbackify(setRootDoc),
  1088. unsetRootDoc: callbackify(unsetRootDoc),
  1089. updateDocLines: callbackify(updateDocLines),
  1090. upsertDoc: callbackifyMultiResult(upsertDoc, ['doc', 'isNew']),
  1091. upsertDocWithPath: callbackifyMultiResult(upsertDocWithPath, [
  1092. 'doc',
  1093. 'isNew',
  1094. 'newFolders',
  1095. 'folder',
  1096. ]),
  1097. upsertFile: callbackifyMultiResult(upsertFile, [
  1098. 'fileRef',
  1099. 'isNew',
  1100. 'oldFileRef',
  1101. ]),
  1102. upsertFileWithPath: callbackifyMultiResult(upsertFileWithPath, [
  1103. 'fileRef',
  1104. 'isNew',
  1105. 'oldFileRef',
  1106. 'newFolders',
  1107. 'folder',
  1108. ]),
  1109. promises: {
  1110. addDoc,
  1111. addDocWithRanges,
  1112. addFile,
  1113. addFolder,
  1114. convertDocToFile,
  1115. deleteEntity,
  1116. deleteEntityWithPath,
  1117. mkdirp,
  1118. mkdirpWithExactCase,
  1119. moveEntity,
  1120. renameEntity,
  1121. resyncProjectHistory,
  1122. setRootDoc,
  1123. unsetRootDoc,
  1124. updateDocLines,
  1125. upsertDoc,
  1126. upsertDocWithPath,
  1127. upsertFile,
  1128. upsertFileWithPath,
  1129. },
  1130. async _addDocAndSendToTpds(projectId, folderId, doc) {
  1131. let result, project
  1132. try {
  1133. ;({ result, project } =
  1134. await ProjectEntityMongoUpdateHandler.promises.addDoc(
  1135. projectId,
  1136. folderId,
  1137. doc
  1138. ))
  1139. } catch (err) {
  1140. throw OError.tag(err, 'error adding file with project', {
  1141. projectId,
  1142. folderId,
  1143. doc_name: doc != null ? doc.name : undefined,
  1144. doc_id: doc != null ? doc._id : undefined,
  1145. })
  1146. }
  1147. await TpdsUpdateSender.promises.addDoc({
  1148. projectId,
  1149. docId: doc != null ? doc._id : undefined,
  1150. path: result?.path?.fileSystem,
  1151. projectName: project.name,
  1152. rev: 0,
  1153. folderId,
  1154. })
  1155. return { result, project }
  1156. },
  1157. async _uploadFile(projectId, folderId, fileName, fsPath, linkedFileData) {
  1158. if (!SafePath.isCleanFilename(fileName)) {
  1159. throw new Errors.InvalidNameError('invalid element name')
  1160. }
  1161. const fileArgs = {
  1162. name: fileName,
  1163. linkedFileData,
  1164. }
  1165. try {
  1166. return await FileStoreHandler.promises.uploadFileFromDisk(
  1167. projectId,
  1168. fileArgs,
  1169. fsPath
  1170. )
  1171. } catch (err) {
  1172. throw OError.tag(err, 'error uploading image to s3', {
  1173. projectId,
  1174. folderId,
  1175. file_name: fileName,
  1176. })
  1177. }
  1178. },
  1179. async _addFileAndSendToTpds(projectId, folderId, fileRef) {
  1180. let result, project
  1181. try {
  1182. ;({ result, project } =
  1183. await ProjectEntityMongoUpdateHandler.promises.addFile(
  1184. projectId,
  1185. folderId,
  1186. fileRef
  1187. ))
  1188. } catch (err) {
  1189. throw OError.tag(err, 'error adding file with project', {
  1190. projectId,
  1191. folderId,
  1192. file_name: fileRef.name,
  1193. fileRef,
  1194. })
  1195. }
  1196. await TpdsUpdateSender.promises.addFile({
  1197. projectId,
  1198. fileId: fileRef._id,
  1199. path: result?.path?.fileSystem,
  1200. projectName: project.name,
  1201. rev: fileRef.rev,
  1202. folderId,
  1203. })
  1204. return { result, project }
  1205. },
  1206. async _replaceFile(
  1207. projectId,
  1208. fileId,
  1209. userId,
  1210. newFileRef,
  1211. fileStoreUrl,
  1212. folderId,
  1213. source
  1214. ) {
  1215. const {
  1216. oldFileRef,
  1217. project,
  1218. path,
  1219. newProject,
  1220. newFileRef: updatedFileRef,
  1221. } = await ProjectEntityMongoUpdateHandler.promises.replaceFileWithNew(
  1222. projectId,
  1223. fileId,
  1224. newFileRef
  1225. )
  1226. const oldFiles = [
  1227. {
  1228. file: oldFileRef,
  1229. path: path.fileSystem,
  1230. },
  1231. ]
  1232. const newFiles = [
  1233. {
  1234. file: updatedFileRef,
  1235. path: path.fileSystem,
  1236. url: fileStoreUrl,
  1237. },
  1238. ]
  1239. const projectHistoryId = project.overleaf?.history?.id
  1240. await TpdsUpdateSender.promises.addFile({
  1241. projectId: project._id,
  1242. fileId: updatedFileRef._id,
  1243. path: path.fileSystem,
  1244. rev: updatedFileRef.rev,
  1245. projectName: project.name,
  1246. folderId,
  1247. })
  1248. ProjectUpdateHandler.promises
  1249. .markAsUpdated(projectId, new Date(), userId)
  1250. .catch(error => {
  1251. logger.error({ error }, 'failed to mark project as updated')
  1252. })
  1253. await DocumentUpdaterHandler.promises.updateProjectStructure(
  1254. projectId,
  1255. projectHistoryId,
  1256. userId,
  1257. { oldFiles, newFiles, newProject },
  1258. source
  1259. )
  1260. return updatedFileRef
  1261. },
  1262. async _checkFiletree(projectId, projectHistoryId, entities) {
  1263. const adjustPathsAfterFolderRename = (oldPath, newPath) => {
  1264. oldPath = oldPath + '/'
  1265. newPath = newPath + '/'
  1266. for (const entity of entities) {
  1267. if (entity.path.startsWith(oldPath)) {
  1268. entity.path = newPath + entity.path.slice(oldPath.length)
  1269. }
  1270. }
  1271. }
  1272. // Data structures for recording pending renames
  1273. const renames = []
  1274. const paths = new Set()
  1275. for (const entity of entities) {
  1276. const originalName = entity.folder
  1277. ? entity.folder.name
  1278. : entity.doc
  1279. ? entity.doc.name
  1280. : entity.file.name
  1281. let newPath = entity.path
  1282. let newName = originalName
  1283. // Clean the filename if necessary
  1284. if (newName === '') {
  1285. newName = 'untitled'
  1286. } else {
  1287. newName = SafePath.clean(newName)
  1288. }
  1289. if (newName !== originalName) {
  1290. newPath = Path.join(
  1291. newPath.slice(0, newPath.length - originalName.length),
  1292. newName
  1293. )
  1294. }
  1295. // Check if we've seen that path already
  1296. if (paths.has(newPath)) {
  1297. newPath = ProjectEntityUpdateHandler.findNextAvailablePath(
  1298. paths,
  1299. newPath
  1300. )
  1301. newName = newPath.split('/').pop()
  1302. }
  1303. // If we've changed the filename, schedule a rename
  1304. if (newName !== originalName) {
  1305. renames.push({ entity, newName, newPath })
  1306. if (entity.folder) {
  1307. // Here, we rely on entities being processed in the right order.
  1308. // Parent folders need to be processed before their children. This is
  1309. // the case only because getAllEntitiesFromProject() returns folders
  1310. // in that order and resyncProjectHistory() calls us with the folders
  1311. // first.
  1312. adjustPathsAfterFolderRename(entity.path, newPath)
  1313. }
  1314. }
  1315. // Remember that we've seen this path
  1316. paths.add(newPath)
  1317. }
  1318. if (renames.length === 0) {
  1319. return
  1320. }
  1321. logger.warn(
  1322. {
  1323. projectId,
  1324. renames: renames.map(rename => ({
  1325. oldPath: rename.entity.path,
  1326. newPath: rename.newPath,
  1327. })),
  1328. },
  1329. 'found conflicts or bad filenames in filetree'
  1330. )
  1331. // Avoid conflicts by processing renames in the reverse order. If we have
  1332. // the following starting situation:
  1333. //
  1334. // somefile.tex
  1335. // somefile.tex
  1336. // somefile.tex (1)
  1337. //
  1338. // somefile.tex would be processed first, and then somefile.tex (1),
  1339. // yielding the following renames:
  1340. //
  1341. // somefile.tex -> somefile.tex (1)
  1342. // somefile.tex (1) -> somefile.tex (2)
  1343. //
  1344. // When the first rename was decided, we didn't know that somefile.tex (1)
  1345. // existed, so that created a conflict. By processing renames in the
  1346. // reverse order, we start with the files that had the most extensive
  1347. // information about existing files.
  1348. renames.reverse()
  1349. for (const rename of renames) {
  1350. // rename the duplicate files
  1351. const entity = rename.entity
  1352. const entityId = entity.folder
  1353. ? entity.folder._id
  1354. : entity.doc
  1355. ? entity.doc._id
  1356. : entity.file._id
  1357. const entityType = entity.folder ? 'folder' : entity.doc ? 'doc' : 'file'
  1358. const { changes } =
  1359. await ProjectEntityMongoUpdateHandler.promises.renameEntity(
  1360. projectId,
  1361. entityId,
  1362. entityType,
  1363. rename.newName
  1364. )
  1365. // update the renamed entity for the resync
  1366. entity.path = rename.newPath
  1367. if (entityType === 'folder') {
  1368. entity.folder.name = rename.newName
  1369. } else if (entityType === 'doc') {
  1370. entity.doc.name = rename.newName
  1371. } else {
  1372. entity.file.name = rename.newName
  1373. }
  1374. await DocumentUpdaterHandler.promises.updateProjectStructure(
  1375. projectId,
  1376. projectHistoryId,
  1377. null,
  1378. changes,
  1379. 'automatic-fix'
  1380. )
  1381. }
  1382. },
  1383. findNextAvailablePath(allPaths, candidatePath) {
  1384. const incrementReplacer = (match, p1) => {
  1385. return ' (' + (parseInt(p1, 10) + 1) + ')'
  1386. }
  1387. // if the filename was invalid we should normalise it here too. Currently
  1388. // this only handles renames in the same folder, so we will be out of luck
  1389. // if it is the folder name which in invalid. We could handle folder
  1390. // renames by returning the folders list from getAllEntitiesFromProject
  1391. do {
  1392. // does the filename look like "foo (1)" if so, increment the number in parentheses
  1393. if (/ \(\d+\)$/.test(candidatePath)) {
  1394. candidatePath = candidatePath.replace(/ \((\d+)\)$/, incrementReplacer)
  1395. } else {
  1396. // otherwise, add a ' (1)' suffix to the name
  1397. candidatePath = candidatePath + ' (1)'
  1398. }
  1399. } while (allPaths.has(candidatePath)) // keep going until the name is unique
  1400. // add the new name to the set
  1401. allPaths.add(candidatePath)
  1402. return candidatePath
  1403. },
  1404. isPathValidForRootDoc(docPath) {
  1405. const docExtension = Path.extname(docPath)
  1406. return VALID_ROOT_DOC_REGEXP.test(docExtension)
  1407. },
  1408. async _cleanUpEntity(
  1409. project,
  1410. newProject,
  1411. entity,
  1412. entityType,
  1413. path,
  1414. userId,
  1415. source
  1416. ) {
  1417. const subtreeListing = _listSubtree(entity, entityType, path)
  1418. await ProjectEntityUpdateHandler._updateProjectStructureWithDeletedEntity(
  1419. project,
  1420. newProject,
  1421. subtreeListing,
  1422. userId,
  1423. source
  1424. )
  1425. for (const entry of subtreeListing) {
  1426. if (entry.type === 'doc') {
  1427. await ProjectEntityUpdateHandler._cleanUpDoc(
  1428. project,
  1429. entry.entity,
  1430. entry.path,
  1431. userId
  1432. )
  1433. } else if (entry.type === 'file') {
  1434. await ProjectEntityUpdateHandler._cleanUpFile(project, entry.entity)
  1435. }
  1436. }
  1437. return subtreeListing
  1438. },
  1439. async _updateProjectStructureWithDeletedEntity(
  1440. project,
  1441. newProject,
  1442. subtreeListing,
  1443. userId,
  1444. source
  1445. ) {
  1446. const changes = { oldDocs: [], oldFiles: [] }
  1447. for (const entry of subtreeListing) {
  1448. if (entry.type === 'doc') {
  1449. changes.oldDocs.push({ doc: entry.entity, path: entry.path })
  1450. } else if (entry.type === 'file') {
  1451. changes.oldFiles.push({ file: entry.entity, path: entry.path })
  1452. }
  1453. }
  1454. // now send the project structure changes to the docupdater
  1455. changes.newProject = newProject
  1456. const projectId = project._id.toString()
  1457. const projectHistoryId =
  1458. project.overleaf &&
  1459. project.overleaf.history &&
  1460. project.overleaf.history.id
  1461. return await DocumentUpdaterHandler.promises.updateProjectStructure(
  1462. projectId,
  1463. projectHistoryId,
  1464. userId,
  1465. changes,
  1466. source
  1467. )
  1468. },
  1469. async _cleanUpDoc(project, doc) {
  1470. const projectId = project._id.toString()
  1471. const docId = doc._id.toString()
  1472. if (project.rootDoc_id != null && project.rootDoc_id.toString() === docId) {
  1473. await ProjectEntityUpdateHandler.promises.unsetRootDoc(projectId)
  1474. }
  1475. const { name } = doc
  1476. const deletedAt = new Date()
  1477. await DocstoreManager.promises.deleteDoc(projectId, docId, name, deletedAt)
  1478. return await DocumentUpdaterHandler.promises.deleteDoc(projectId, docId)
  1479. },
  1480. async _cleanUpFile(project, file) {
  1481. return await ProjectEntityMongoUpdateHandler.promises._insertDeletedFileReference(
  1482. project._id,
  1483. file
  1484. )
  1485. },
  1486. }
  1487. /**
  1488. * List all descendants of an entity along with their type and path. Include
  1489. * the top-level entity as well.
  1490. */
  1491. function _listSubtree(entity, entityType, entityPath) {
  1492. if (entityType.indexOf('file') !== -1) {
  1493. return [{ type: 'file', entity, path: entityPath }]
  1494. } else if (entityType.indexOf('doc') !== -1) {
  1495. return [{ type: 'doc', entity, path: entityPath }]
  1496. } else if (entityType.indexOf('folder') !== -1) {
  1497. const listing = []
  1498. const _recurseFolder = (folder, folderPath) => {
  1499. listing.push({ type: 'folder', entity: folder, path: folderPath })
  1500. for (const doc of iterablePaths(folder, 'docs')) {
  1501. listing.push({
  1502. type: 'doc',
  1503. entity: doc,
  1504. path: Path.join(folderPath, doc.name),
  1505. })
  1506. }
  1507. for (const file of iterablePaths(folder, 'fileRefs')) {
  1508. listing.push({
  1509. type: 'file',
  1510. entity: file,
  1511. path: Path.join(folderPath, file.name),
  1512. })
  1513. }
  1514. for (const childFolder of iterablePaths(folder, 'folders')) {
  1515. _recurseFolder(childFolder, Path.join(folderPath, childFolder.name))
  1516. }
  1517. }
  1518. _recurseFolder(entity, entityPath)
  1519. return listing
  1520. } else {
  1521. // This shouldn't happen, but if it does, fail silently.
  1522. return []
  1523. }
  1524. }
  1525. module.exports = ProjectEntityUpdateHandler