ProjectEntityUpdateHandler.js 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  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. userId
  290. )
  291. const docPath = result?.path?.fileSystem
  292. const projectHistoryId = project?.overleaf?.history?.id
  293. const newDocs = [
  294. {
  295. doc,
  296. path: docPath,
  297. docLines: docLines.join('\n'),
  298. ranges,
  299. },
  300. ]
  301. await DocumentUpdaterHandler.promises.updateProjectStructure(
  302. projectId,
  303. projectHistoryId,
  304. userId,
  305. { newDocs, newProject: project },
  306. source
  307. )
  308. return { doc, folderId: folderId || project.rootFolder[0]._id }
  309. },
  310. })
  311. const addFile = wrapWithLock({
  312. async beforeLock(
  313. projectId,
  314. folderId,
  315. fileName,
  316. fsPath,
  317. linkedFileData,
  318. userId,
  319. source
  320. ) {
  321. if (!SafePath.isCleanFilename(fileName)) {
  322. throw new Errors.InvalidNameError('invalid element name')
  323. }
  324. const { url, fileRef, createdBlob } =
  325. await ProjectEntityUpdateHandler._uploadFile(
  326. projectId,
  327. folderId,
  328. fileName,
  329. fsPath,
  330. linkedFileData
  331. )
  332. return {
  333. projectId,
  334. folderId,
  335. userId,
  336. fileRef,
  337. fileStoreUrl: url,
  338. createdBlob,
  339. source,
  340. }
  341. },
  342. async withLock({
  343. projectId,
  344. folderId,
  345. userId,
  346. fileRef,
  347. fileStoreUrl,
  348. createdBlob,
  349. source,
  350. }) {
  351. const { result, project } =
  352. await ProjectEntityUpdateHandler._addFileAndSendToTpds(
  353. projectId,
  354. folderId,
  355. fileRef,
  356. userId
  357. )
  358. const projectHistoryId = project.overleaf?.history?.id
  359. const newFiles = [
  360. {
  361. createdBlob,
  362. file: fileRef,
  363. path: result && result.path && result.path.fileSystem,
  364. url: fileStoreUrl,
  365. },
  366. ]
  367. await DocumentUpdaterHandler.promises.updateProjectStructure(
  368. projectId,
  369. projectHistoryId,
  370. userId,
  371. { newFiles, newProject: project },
  372. source
  373. )
  374. return { fileRef, folderId, createdBlob }
  375. },
  376. })
  377. const upsertDoc = wrapWithLock(
  378. async function (projectId, folderId, docName, docLines, source, userId) {
  379. if (!SafePath.isCleanFilename(docName)) {
  380. throw new Errors.InvalidNameError('invalid element name')
  381. }
  382. let element, folderPath
  383. try {
  384. ;({ element, path: folderPath } =
  385. await ProjectLocator.promises.findElement({
  386. project_id: projectId,
  387. element_id: folderId,
  388. type: 'folder',
  389. }))
  390. } catch (error) {
  391. if (error instanceof Errors.NotFoundError) {
  392. throw new Error('folder_not_found')
  393. }
  394. throw error
  395. }
  396. if (element == null) {
  397. throw new Error("Couldn't find folder")
  398. }
  399. const existingDoc = element.docs.find(({ name }) => name === docName)
  400. const existingFile = element.fileRefs.find(({ name }) => name === docName)
  401. if (existingFile) {
  402. const doc = new Doc({ name: docName })
  403. const filePath = `${folderPath.fileSystem}/${existingFile.name}`
  404. const { rev } = await DocstoreManager.promises.updateDoc(
  405. projectId.toString(),
  406. doc._id.toString(),
  407. docLines,
  408. 0,
  409. {}
  410. )
  411. doc.rev = rev
  412. const project =
  413. await ProjectEntityMongoUpdateHandler.promises.replaceFileWithDoc(
  414. projectId,
  415. existingFile._id,
  416. doc,
  417. userId
  418. )
  419. await TpdsUpdateSender.promises.addDoc({
  420. projectId,
  421. docId: doc._id,
  422. path: filePath,
  423. projectName: project.name,
  424. rev: existingFile.rev + 1,
  425. folderId,
  426. })
  427. const projectHistoryId =
  428. project.overleaf &&
  429. project.overleaf.history &&
  430. project.overleaf.history.id
  431. const newDocs = [
  432. {
  433. doc,
  434. path: filePath,
  435. docLines: docLines.join('\n'),
  436. },
  437. ]
  438. const oldFiles = [
  439. {
  440. file: existingFile,
  441. path: filePath,
  442. },
  443. ]
  444. await DocumentUpdaterHandler.promises.updateProjectStructure(
  445. projectId,
  446. projectHistoryId,
  447. userId,
  448. { oldFiles, newDocs, newProject: project },
  449. source
  450. )
  451. EditorRealTimeController.emitToRoom(
  452. projectId,
  453. 'removeEntity',
  454. existingFile._id,
  455. 'convertFileToDoc'
  456. )
  457. return { doc, isNew: true }
  458. } else if (existingDoc) {
  459. const result = await DocumentUpdaterHandler.promises.setDocument(
  460. projectId,
  461. existingDoc._id,
  462. userId,
  463. docLines,
  464. source
  465. )
  466. logger.debug(
  467. { projectId, docId: existingDoc._id },
  468. 'notifying users that the document has been updated'
  469. )
  470. // there is no need to flush the doc to mongo at this point as docupdater
  471. // flushes it as part of setDoc.
  472. //
  473. // combine rev from response with existing doc metadata
  474. return {
  475. doc: { ...existingDoc, ...result },
  476. isNew: existingDoc == null,
  477. }
  478. } else {
  479. const { doc } =
  480. await ProjectEntityUpdateHandler.promises.addDocWithRanges.withoutLock(
  481. projectId,
  482. folderId,
  483. docName,
  484. docLines,
  485. {},
  486. userId,
  487. source
  488. )
  489. return { doc, isNew: existingDoc == null }
  490. }
  491. }
  492. )
  493. const appendToDoc = wrapWithLock(
  494. async (projectId, docId, lines, source, userId) => {
  495. const { element } = await ProjectLocator.promises.findElement({
  496. project_id: projectId,
  497. element_id: docId,
  498. type: 'doc',
  499. })
  500. return await DocumentUpdaterHandler.promises.appendToDocument(
  501. projectId,
  502. element._id,
  503. userId,
  504. lines,
  505. source
  506. )
  507. }
  508. )
  509. const upsertFile = wrapWithLock({
  510. async beforeLock(
  511. projectId,
  512. folderId,
  513. fileName,
  514. fsPath,
  515. linkedFileData,
  516. userId,
  517. source
  518. ) {
  519. if (!SafePath.isCleanFilename(fileName)) {
  520. throw new Errors.InvalidNameError('invalid element name')
  521. }
  522. // create a new file
  523. const fileArgs = {
  524. name: fileName,
  525. linkedFileData,
  526. }
  527. const { url, fileRef, createdBlob } =
  528. await FileStoreHandler.promises.uploadFileFromDisk(
  529. projectId,
  530. fileArgs,
  531. fsPath
  532. )
  533. return {
  534. projectId,
  535. folderId,
  536. fileName,
  537. fsPath,
  538. linkedFileData,
  539. userId,
  540. fileRef,
  541. fileStoreUrl: url,
  542. createdBlob,
  543. source,
  544. }
  545. },
  546. async withLock({
  547. projectId,
  548. folderId,
  549. fileName,
  550. userId,
  551. fileRef,
  552. fileStoreUrl,
  553. createdBlob,
  554. source,
  555. }) {
  556. let element
  557. try {
  558. ;({ element } = await ProjectLocator.promises.findElement({
  559. project_id: projectId,
  560. element_id: folderId,
  561. type: 'folder',
  562. }))
  563. } catch (error) {
  564. if (error instanceof Errors.NotFoundError) {
  565. throw new Error('folder_not_found')
  566. }
  567. throw error
  568. }
  569. if (element == null) {
  570. throw new Error("Couldn't find folder")
  571. }
  572. const existingFile = element.fileRefs.find(({ name }) => name === fileName)
  573. const existingDoc = element.docs.find(({ name }) => name === fileName)
  574. if (existingDoc) {
  575. let path
  576. try {
  577. ;({ path } = await ProjectLocator.promises.findElement({
  578. project_id: projectId,
  579. element_id: existingDoc._id,
  580. type: 'doc',
  581. }))
  582. } catch (err) {
  583. throw new Error("couldn't find existing file")
  584. }
  585. const project =
  586. await ProjectEntityMongoUpdateHandler.promises.replaceDocWithFile(
  587. projectId,
  588. existingDoc._id,
  589. fileRef,
  590. userId
  591. )
  592. const projectHistoryId = project.overleaf?.history?.id
  593. await TpdsUpdateSender.promises.addFile({
  594. projectId: project._id,
  595. historyId: projectHistoryId,
  596. fileId: fileRef._id,
  597. hash: fileRef.hash,
  598. path: path.fileSystem,
  599. rev: fileRef.rev,
  600. projectName: project.name,
  601. folderId,
  602. })
  603. await DocumentUpdaterHandler.promises.updateProjectStructure(
  604. projectId,
  605. projectHistoryId,
  606. userId,
  607. {
  608. oldDocs: [{ doc: existingDoc, path: path.fileSystem }],
  609. newFiles: [
  610. {
  611. createdBlob,
  612. file: fileRef,
  613. path: path.fileSystem,
  614. url: fileStoreUrl,
  615. },
  616. ],
  617. newProject: project,
  618. },
  619. source
  620. )
  621. EditorRealTimeController.emitToRoom(
  622. projectId,
  623. 'removeEntity',
  624. existingDoc._id,
  625. 'convertDocToFile'
  626. )
  627. return { fileRef, isNew: true, oldFileRef: existingFile }
  628. } else if (existingFile) {
  629. await ProjectEntityUpdateHandler._replaceFile(
  630. projectId,
  631. existingFile._id,
  632. userId,
  633. fileRef,
  634. fileStoreUrl,
  635. folderId,
  636. source,
  637. createdBlob
  638. )
  639. return { fileRef, isNew: false, oldFileRef: existingFile }
  640. } else {
  641. // this calls directly into the addFile main task (without the beforeLock part)
  642. await ProjectEntityUpdateHandler.promises.addFile.mainTask({
  643. projectId,
  644. folderId,
  645. userId,
  646. fileRef,
  647. fileStoreUrl,
  648. createdBlob,
  649. source,
  650. })
  651. return {
  652. fileRef,
  653. isNew: existingFile == null,
  654. oldFileRef: existingFile,
  655. }
  656. }
  657. },
  658. })
  659. const upsertDocWithPath = wrapWithLock(
  660. async function (projectId, elementPath, docLines, source, userId) {
  661. if (!SafePath.isCleanPath(elementPath)) {
  662. throw new Errors.InvalidNameError('invalid element name')
  663. }
  664. const docName = Path.basename(elementPath)
  665. const folderPath = Path.dirname(elementPath)
  666. const { newFolders, folder } =
  667. await ProjectEntityUpdateHandler.promises.mkdirp.withoutLock(
  668. projectId,
  669. folderPath,
  670. userId
  671. )
  672. const { isNew, doc } =
  673. await ProjectEntityUpdateHandler.promises.upsertDoc.withoutLock(
  674. projectId,
  675. folder._id,
  676. docName,
  677. docLines,
  678. source,
  679. userId
  680. )
  681. return { doc, isNew, newFolders, folder }
  682. }
  683. )
  684. const upsertFileWithPath = wrapWithLock({
  685. async beforeLock(
  686. projectId,
  687. elementPath,
  688. fsPath,
  689. linkedFileData,
  690. userId,
  691. source
  692. ) {
  693. if (!SafePath.isCleanPath(elementPath)) {
  694. throw new Errors.InvalidNameError('invalid element name')
  695. }
  696. const fileName = Path.basename(elementPath)
  697. const folderPath = Path.dirname(elementPath)
  698. // create a new file
  699. const fileArgs = {
  700. name: fileName,
  701. linkedFileData,
  702. }
  703. const {
  704. url: fileStoreUrl,
  705. fileRef,
  706. createdBlob,
  707. } = await FileStoreHandler.promises.uploadFileFromDisk(
  708. projectId,
  709. fileArgs,
  710. fsPath
  711. )
  712. return {
  713. projectId,
  714. folderPath,
  715. fileName,
  716. fsPath,
  717. linkedFileData,
  718. userId,
  719. fileRef,
  720. fileStoreUrl,
  721. createdBlob,
  722. source,
  723. }
  724. },
  725. async withLock({
  726. projectId,
  727. folderPath,
  728. fileName,
  729. fsPath,
  730. linkedFileData,
  731. userId,
  732. fileRef,
  733. fileStoreUrl,
  734. createdBlob,
  735. source,
  736. }) {
  737. const { newFolders, folder } =
  738. await ProjectEntityUpdateHandler.promises.mkdirp.withoutLock(
  739. projectId,
  740. folderPath,
  741. userId
  742. )
  743. // this calls directly into the upsertFile main task (without the beforeLock part)
  744. const {
  745. fileRef: newFileRef,
  746. isNew,
  747. oldFileRef,
  748. } = await ProjectEntityUpdateHandler.promises.upsertFile.mainTask({
  749. projectId,
  750. folderId: folder._id,
  751. fileName,
  752. fsPath,
  753. linkedFileData,
  754. userId,
  755. fileRef,
  756. fileStoreUrl,
  757. createdBlob,
  758. source,
  759. })
  760. return {
  761. fileRef: newFileRef,
  762. isNew,
  763. oldFileRef,
  764. newFolders,
  765. folder,
  766. }
  767. },
  768. })
  769. const deleteEntity = wrapWithLock(
  770. async function (projectId, entityId, entityType, userId, source, callback) {
  771. logger.debug({ entityId, entityType, projectId }, 'deleting project entity')
  772. if (entityType == null) {
  773. logger.warn({ err: 'No entityType set', projectId, entityId })
  774. throw new Error('No entityType set')
  775. }
  776. entityType = entityType.toLowerCase()
  777. // Flush the entire project to avoid leaving partially deleted docs in redis.
  778. await DocumentUpdaterHandler.promises.flushProjectToMongo(projectId)
  779. const { entity, path, projectBeforeDeletion, newProject } =
  780. await ProjectEntityMongoUpdateHandler.promises.deleteEntity(
  781. projectId,
  782. entityId,
  783. entityType,
  784. userId
  785. )
  786. const subtreeListing = await ProjectEntityUpdateHandler._cleanUpEntity(
  787. projectBeforeDeletion,
  788. newProject,
  789. entity,
  790. entityType,
  791. path.fileSystem,
  792. userId,
  793. source
  794. )
  795. const subtreeEntityIds = subtreeListing.map(entry =>
  796. entry.entity._id.toString()
  797. )
  798. await TpdsUpdateSender.promises.deleteEntity({
  799. projectId,
  800. path: path.fileSystem,
  801. projectName: projectBeforeDeletion.name,
  802. entityId,
  803. entityType,
  804. subtreeEntityIds,
  805. })
  806. return entityId
  807. }
  808. )
  809. const deleteEntityWithPath = wrapWithLock(
  810. async (projectId, path, userId, source) => {
  811. const { element, type } = await ProjectLocator.promises.findElementByPath({
  812. project_id: projectId,
  813. path,
  814. exactCaseMatch: true,
  815. })
  816. if (element == null) {
  817. throw new Errors.NotFoundError('project not found')
  818. }
  819. return await ProjectEntityUpdateHandler.promises.deleteEntity.withoutLock(
  820. projectId,
  821. element._id,
  822. type,
  823. userId,
  824. source
  825. )
  826. }
  827. )
  828. const mkdirp = wrapWithLock(async function (projectId, path, userId) {
  829. for (const folder of path.split('/')) {
  830. if (folder.length > 0 && !SafePath.isCleanFilename(folder)) {
  831. throw new Errors.InvalidNameError('invalid element name')
  832. }
  833. }
  834. return await ProjectEntityMongoUpdateHandler.promises.mkdirp(
  835. projectId,
  836. path,
  837. userId,
  838. { exactCaseMatch: false }
  839. )
  840. })
  841. const mkdirpWithExactCase = wrapWithLock(
  842. async function (projectId, path, userId) {
  843. for (const folder of path.split('/')) {
  844. if (folder.length > 0 && !SafePath.isCleanFilename(folder)) {
  845. throw new Errors.InvalidNameError('invalid element name')
  846. }
  847. }
  848. return await ProjectEntityMongoUpdateHandler.promises.mkdirp(
  849. projectId,
  850. path,
  851. userId,
  852. { exactCaseMatch: true }
  853. )
  854. }
  855. )
  856. const addFolder = wrapWithLock(
  857. async function (projectId, parentFolderId, folderName, userId) {
  858. if (!SafePath.isCleanFilename(folderName)) {
  859. throw new Errors.InvalidNameError('invalid element name')
  860. }
  861. return await ProjectEntityMongoUpdateHandler.promises.addFolder(
  862. projectId,
  863. parentFolderId,
  864. folderName,
  865. userId
  866. )
  867. }
  868. )
  869. const moveEntity = wrapWithLock(
  870. async function (
  871. projectId,
  872. entityId,
  873. destFolderId,
  874. entityType,
  875. userId,
  876. source
  877. ) {
  878. logger.debug(
  879. { entityType, entityId, projectId, destFolderId },
  880. 'moving entity'
  881. )
  882. if (entityType == null) {
  883. logger.warn({ err: 'No entityType set', projectId, entityId })
  884. throw new Error('No entityType set')
  885. }
  886. entityType = entityType.toLowerCase()
  887. await DocumentUpdaterHandler.promises.flushProjectToMongo(projectId)
  888. const { project, startPath, endPath, rev, changes } =
  889. await ProjectEntityMongoUpdateHandler.promises.moveEntity(
  890. projectId,
  891. entityId,
  892. destFolderId,
  893. entityType,
  894. userId
  895. )
  896. const projectHistoryId = project.overleaf?.history?.id
  897. try {
  898. await TpdsUpdateSender.promises.moveEntity({
  899. projectId,
  900. projectName: project.name,
  901. startPath,
  902. endPath,
  903. rev,
  904. entityId,
  905. entityType,
  906. folderId: destFolderId,
  907. })
  908. } catch (err) {
  909. logger.error({ err }, 'error sending tpds update')
  910. }
  911. return await DocumentUpdaterHandler.promises.updateProjectStructure(
  912. projectId,
  913. projectHistoryId,
  914. userId,
  915. changes,
  916. source
  917. )
  918. }
  919. )
  920. const renameEntity = wrapWithLock(
  921. async function (projectId, entityId, entityType, newName, userId, source) {
  922. if (!newName || typeof newName !== 'string') {
  923. const err = new OError('invalid newName value', {
  924. value: newName,
  925. type: typeof newName,
  926. projectId,
  927. entityId,
  928. entityType,
  929. userId,
  930. source,
  931. })
  932. logger.error({ err }, 'Invalid newName passed to renameEntity')
  933. throw err
  934. }
  935. if (!SafePath.isCleanFilename(newName)) {
  936. throw new Errors.InvalidNameError('invalid element name')
  937. }
  938. logger.debug({ entityId, projectId }, `renaming ${entityType}`)
  939. if (entityType == null) {
  940. logger.warn({ err: 'No entityType set', projectId, entityId })
  941. throw new Error('No entityType set')
  942. }
  943. entityType = entityType.toLowerCase()
  944. await DocumentUpdaterHandler.promises.flushProjectToMongo(projectId)
  945. const { project, startPath, endPath, rev, changes } =
  946. await ProjectEntityMongoUpdateHandler.promises.renameEntity(
  947. projectId,
  948. entityId,
  949. entityType,
  950. newName,
  951. userId
  952. )
  953. const projectHistoryId = project.overleaf?.history?.id
  954. try {
  955. await TpdsUpdateSender.promises.moveEntity({
  956. projectId,
  957. projectName: project.name,
  958. startPath,
  959. endPath,
  960. rev,
  961. entityId,
  962. entityType,
  963. folderId: null, // this means the folder has not changed
  964. })
  965. } catch (err) {
  966. logger.error({ err }, 'error sending tpds update')
  967. }
  968. return await DocumentUpdaterHandler.promises.updateProjectStructure(
  969. projectId,
  970. projectHistoryId,
  971. userId,
  972. changes,
  973. source
  974. )
  975. }
  976. )
  977. // This doesn't directly update project structure, but we need to take the lock
  978. // to prevent anything else being queued before the resync update
  979. const resyncProjectHistory = wrapWithLock(
  980. async (projectId, opts) => {
  981. const project = await ProjectGetter.promises.getProject(projectId, {
  982. rootFolder: true,
  983. overleaf: true,
  984. })
  985. const projectHistoryId = project.overleaf?.history?.id
  986. if (projectHistoryId == null) {
  987. throw new Errors.ProjectHistoryDisabledError(
  988. `project history not enabled for ${projectId}`
  989. )
  990. }
  991. const { docs, files, folders } =
  992. ProjectEntityHandler.getAllEntitiesFromProject(project)
  993. // _checkFileTree() must be passed the folders before docs and
  994. // files
  995. await ProjectEntityUpdateHandler._checkFiletree(
  996. projectId,
  997. projectHistoryId,
  998. [...folders, ...docs, ...files]
  999. )
  1000. await DocumentUpdaterHandler.promises.resyncProjectHistory(
  1001. projectId,
  1002. projectHistoryId,
  1003. docs,
  1004. files,
  1005. opts
  1006. )
  1007. if (opts.historyRangesMigration) {
  1008. return await ProjectOptionsHandler.promises.setHistoryRangesSupport(
  1009. projectId,
  1010. opts.historyRangesMigration === 'forwards'
  1011. )
  1012. }
  1013. },
  1014. LockManager.withTimeout(6 * 60) // use an extended lock for the resync operations
  1015. )
  1016. const convertDocToFile = wrapWithLock({
  1017. async beforeLock(projectId, docId, userId, source) {
  1018. await DocumentUpdaterHandler.promises.flushDocToMongo(projectId, docId)
  1019. const { element: doc, path } = await ProjectLocator.promises.findElement({
  1020. project_id: projectId,
  1021. element_id: docId,
  1022. type: 'doc',
  1023. })
  1024. const docPath = path.fileSystem
  1025. const { lines, rev, ranges } = await DocstoreManager.promises.getDoc(
  1026. projectId,
  1027. docId
  1028. )
  1029. if (!_.isEmpty(ranges)) {
  1030. throw new Errors.DocHasRangesError({})
  1031. }
  1032. await DocumentUpdaterHandler.promises.deleteDoc(projectId, docId, false)
  1033. const fsPath = await FileWriter.promises.writeLinesToDisk(projectId, lines)
  1034. const {
  1035. url: fileStoreUrl,
  1036. fileRef,
  1037. createdBlob,
  1038. } = await FileStoreHandler.promises.uploadFileFromDisk(
  1039. projectId,
  1040. { name: doc.name, rev: rev + 1 },
  1041. fsPath
  1042. )
  1043. try {
  1044. await fs.promises.unlink(fsPath)
  1045. } catch (err) {
  1046. logger.warn({ err, path: fsPath }, 'failed to clean up temporary file')
  1047. }
  1048. return {
  1049. projectId,
  1050. doc,
  1051. path: docPath,
  1052. fileRef,
  1053. fileStoreUrl,
  1054. userId,
  1055. source,
  1056. createdBlob,
  1057. }
  1058. },
  1059. async withLock({
  1060. projectId,
  1061. doc,
  1062. path,
  1063. fileRef,
  1064. fileStoreUrl,
  1065. userId,
  1066. source,
  1067. createdBlob,
  1068. }) {
  1069. const project =
  1070. await ProjectEntityMongoUpdateHandler.promises.replaceDocWithFile(
  1071. projectId,
  1072. doc._id,
  1073. fileRef,
  1074. userId
  1075. )
  1076. const projectHistoryId = project.overleaf?.history?.id
  1077. await DocumentUpdaterHandler.promises.updateProjectStructure(
  1078. projectId,
  1079. projectHistoryId,
  1080. userId,
  1081. {
  1082. oldDocs: [{ doc, path }],
  1083. newFiles: [{ file: fileRef, path, url: fileStoreUrl, createdBlob }],
  1084. newProject: project,
  1085. },
  1086. source
  1087. )
  1088. const { folder } = await ProjectLocator.promises.findElement({
  1089. project_id: projectId,
  1090. element_id: fileRef._id,
  1091. type: 'file',
  1092. })
  1093. EditorRealTimeController.emitToRoom(
  1094. projectId,
  1095. 'removeEntity',
  1096. doc._id,
  1097. 'convertDocToFile'
  1098. )
  1099. EditorRealTimeController.emitToRoom(
  1100. projectId,
  1101. 'reciveNewFile',
  1102. folder._id,
  1103. fileRef,
  1104. 'convertDocToFile',
  1105. null,
  1106. userId
  1107. )
  1108. return fileRef
  1109. },
  1110. })
  1111. async function setMainBibliographyDoc(projectId, newBibliographyDocId) {
  1112. logger.debug(
  1113. { projectId, mainBibliographyDocId: newBibliographyDocId },
  1114. 'setting main bibliography doc'
  1115. )
  1116. if (projectId == null || newBibliographyDocId == null) {
  1117. throw new Errors.InvalidError('missing arguments (project or doc)')
  1118. }
  1119. const docPath =
  1120. await ProjectEntityHandler.promises.getDocPathByProjectIdAndDocId(
  1121. projectId,
  1122. newBibliographyDocId
  1123. )
  1124. if (ProjectEntityUpdateHandler.isPathValidForMainBibliographyDoc(docPath)) {
  1125. await Project.updateOne(
  1126. { _id: projectId },
  1127. { mainBibliographyDoc_id: newBibliographyDocId }
  1128. ).exec()
  1129. } else {
  1130. throw new Errors.UnsupportedFileTypeError(
  1131. 'invalid file extension for main bibliography doc'
  1132. )
  1133. }
  1134. }
  1135. const ProjectEntityUpdateHandler = {
  1136. LOCK_NAMESPACE,
  1137. addDoc: callbackifyMultiResult(addDoc, ['doc', 'folderId']),
  1138. addDocWithRanges: callbackifyMultiResult(addDocWithRanges, [
  1139. 'doc',
  1140. 'folderId',
  1141. ]),
  1142. addFile: callbackifyMultiResult(addFile, [
  1143. 'fileRef',
  1144. 'folderId',
  1145. 'createdBlob',
  1146. ]),
  1147. addFolder: callbackifyMultiResult(addFolder, ['folder', 'parentFolderId']),
  1148. convertDocToFile: callbackify(convertDocToFile),
  1149. deleteEntity: callbackify(deleteEntity),
  1150. deleteEntityWithPath: callbackify(deleteEntityWithPath),
  1151. mkdirp: callbackifyMultiResult(mkdirp, [
  1152. 'newFolders',
  1153. 'folder',
  1154. 'parentFolder',
  1155. ]),
  1156. mkdirpWithExactCase: callbackifyMultiResult(mkdirpWithExactCase, [
  1157. 'newFolders',
  1158. 'folder',
  1159. 'parentFolder',
  1160. ]),
  1161. moveEntity: callbackify(moveEntity),
  1162. renameEntity: callbackify(renameEntity),
  1163. resyncProjectHistory: callbackify(resyncProjectHistory),
  1164. setRootDoc: callbackify(setRootDoc),
  1165. unsetRootDoc: callbackify(unsetRootDoc),
  1166. setMainBibliographyDoc: callbackify(setMainBibliographyDoc),
  1167. updateDocLines: callbackify(updateDocLines),
  1168. upsertDoc: callbackifyMultiResult(upsertDoc, ['doc', 'isNew']),
  1169. appendToDoc: callbackify(appendToDoc),
  1170. upsertDocWithPath: callbackifyMultiResult(upsertDocWithPath, [
  1171. 'doc',
  1172. 'isNew',
  1173. 'newFolders',
  1174. 'folder',
  1175. ]),
  1176. upsertFile: callbackifyMultiResult(upsertFile, [
  1177. 'fileRef',
  1178. 'isNew',
  1179. 'oldFileRef',
  1180. ]),
  1181. upsertFileWithPath: callbackifyMultiResult(upsertFileWithPath, [
  1182. 'fileRef',
  1183. 'isNew',
  1184. 'oldFileRef',
  1185. 'newFolders',
  1186. 'folder',
  1187. ]),
  1188. promises: {
  1189. addDoc,
  1190. addDocWithRanges,
  1191. addFile,
  1192. addFolder,
  1193. convertDocToFile,
  1194. deleteEntity,
  1195. deleteEntityWithPath,
  1196. mkdirp,
  1197. mkdirpWithExactCase,
  1198. moveEntity,
  1199. renameEntity,
  1200. resyncProjectHistory,
  1201. setRootDoc,
  1202. unsetRootDoc,
  1203. updateDocLines,
  1204. upsertDoc,
  1205. upsertDocWithPath,
  1206. upsertFile,
  1207. upsertFileWithPath,
  1208. appendToDocWithPath: appendToDoc,
  1209. setMainBibliographyDoc,
  1210. },
  1211. async _addDocAndSendToTpds(projectId, folderId, doc, userId) {
  1212. let result, project
  1213. try {
  1214. ;({ result, project } =
  1215. await ProjectEntityMongoUpdateHandler.promises.addDoc(
  1216. projectId,
  1217. folderId,
  1218. doc,
  1219. userId
  1220. ))
  1221. } catch (err) {
  1222. throw OError.tag(err, 'error adding file with project', {
  1223. projectId,
  1224. folderId,
  1225. doc_name: doc != null ? doc.name : undefined,
  1226. doc_id: doc != null ? doc._id : undefined,
  1227. })
  1228. }
  1229. await TpdsUpdateSender.promises.addDoc({
  1230. projectId,
  1231. docId: doc != null ? doc._id : undefined,
  1232. path: result?.path?.fileSystem,
  1233. projectName: project.name,
  1234. rev: 0,
  1235. folderId,
  1236. })
  1237. return { result, project }
  1238. },
  1239. async _uploadFile(projectId, folderId, fileName, fsPath, linkedFileData) {
  1240. if (!SafePath.isCleanFilename(fileName)) {
  1241. throw new Errors.InvalidNameError('invalid element name')
  1242. }
  1243. const fileArgs = {
  1244. name: fileName,
  1245. linkedFileData,
  1246. }
  1247. try {
  1248. return await FileStoreHandler.promises.uploadFileFromDisk(
  1249. projectId,
  1250. fileArgs,
  1251. fsPath
  1252. )
  1253. } catch (err) {
  1254. throw OError.tag(err, 'error uploading image to s3', {
  1255. projectId,
  1256. folderId,
  1257. file_name: fileName,
  1258. })
  1259. }
  1260. },
  1261. async _addFileAndSendToTpds(projectId, folderId, fileRef, userId) {
  1262. let result, project
  1263. try {
  1264. ;({ result, project } =
  1265. await ProjectEntityMongoUpdateHandler.promises.addFile(
  1266. projectId,
  1267. folderId,
  1268. fileRef,
  1269. userId
  1270. ))
  1271. } catch (err) {
  1272. throw OError.tag(err, 'error adding file with project', {
  1273. projectId,
  1274. folderId,
  1275. file_name: fileRef.name,
  1276. fileRef,
  1277. })
  1278. }
  1279. const historyId = project?.overleaf?.history?.id
  1280. if (!historyId) {
  1281. throw new OError('project does not have a history id', { projectId })
  1282. }
  1283. await TpdsUpdateSender.promises.addFile({
  1284. projectId,
  1285. historyId,
  1286. fileId: fileRef._id,
  1287. hash: fileRef.hash,
  1288. path: result?.path?.fileSystem,
  1289. projectName: project.name,
  1290. rev: fileRef.rev,
  1291. folderId,
  1292. })
  1293. return { result, project }
  1294. },
  1295. async _replaceFile(
  1296. projectId,
  1297. fileId,
  1298. userId,
  1299. newFileRef,
  1300. fileStoreUrl,
  1301. folderId,
  1302. source,
  1303. createdBlob
  1304. ) {
  1305. const {
  1306. oldFileRef,
  1307. project,
  1308. path,
  1309. newProject,
  1310. newFileRef: updatedFileRef,
  1311. } = await ProjectEntityMongoUpdateHandler.promises.replaceFileWithNew(
  1312. projectId,
  1313. fileId,
  1314. newFileRef,
  1315. userId
  1316. )
  1317. const oldFiles = [
  1318. {
  1319. file: oldFileRef,
  1320. path: path.fileSystem,
  1321. },
  1322. ]
  1323. const newFiles = [
  1324. {
  1325. file: updatedFileRef,
  1326. createdBlob,
  1327. path: path.fileSystem,
  1328. url: fileStoreUrl,
  1329. },
  1330. ]
  1331. const projectHistoryId = project.overleaf?.history?.id
  1332. await TpdsUpdateSender.promises.addFile({
  1333. projectId: project._id,
  1334. historyId: projectHistoryId,
  1335. fileId: updatedFileRef._id,
  1336. hash: updatedFileRef.hash,
  1337. path: path.fileSystem,
  1338. rev: updatedFileRef.rev,
  1339. projectName: project.name,
  1340. folderId,
  1341. })
  1342. await DocumentUpdaterHandler.promises.updateProjectStructure(
  1343. projectId,
  1344. projectHistoryId,
  1345. userId,
  1346. { oldFiles, newFiles, newProject },
  1347. source
  1348. )
  1349. return updatedFileRef
  1350. },
  1351. async _checkFiletree(projectId, projectHistoryId, entities) {
  1352. const adjustPathsAfterFolderRename = (oldPath, newPath) => {
  1353. oldPath = oldPath + '/'
  1354. newPath = newPath + '/'
  1355. for (const entity of entities) {
  1356. if (entity.path.startsWith(oldPath)) {
  1357. entity.path = newPath + entity.path.slice(oldPath.length)
  1358. }
  1359. }
  1360. }
  1361. // Data structures for recording pending renames
  1362. const renames = []
  1363. const paths = new Set()
  1364. for (const entity of entities) {
  1365. const originalName = entity.folder
  1366. ? entity.folder.name
  1367. : entity.doc
  1368. ? entity.doc.name
  1369. : entity.file.name
  1370. let newPath = entity.path
  1371. let newName = originalName
  1372. // Clean the filename if necessary
  1373. if (newName === '') {
  1374. newName = 'untitled'
  1375. } else {
  1376. newName = SafePath.clean(newName)
  1377. }
  1378. if (newName !== originalName) {
  1379. newPath = Path.join(
  1380. newPath.slice(0, newPath.length - originalName.length),
  1381. newName
  1382. )
  1383. }
  1384. // Check if we've seen that path already
  1385. if (paths.has(newPath)) {
  1386. newPath = ProjectEntityUpdateHandler.findNextAvailablePath(
  1387. paths,
  1388. newPath
  1389. )
  1390. newName = newPath.split('/').pop()
  1391. }
  1392. // If we've changed the filename, schedule a rename
  1393. if (newName !== originalName) {
  1394. renames.push({ entity, newName, newPath })
  1395. if (entity.folder) {
  1396. // Here, we rely on entities being processed in the right order.
  1397. // Parent folders need to be processed before their children. This is
  1398. // the case only because getAllEntitiesFromProject() returns folders
  1399. // in that order and resyncProjectHistory() calls us with the folders
  1400. // first.
  1401. adjustPathsAfterFolderRename(entity.path, newPath)
  1402. }
  1403. }
  1404. // Remember that we've seen this path
  1405. paths.add(newPath)
  1406. }
  1407. if (renames.length === 0) {
  1408. return
  1409. }
  1410. logger.warn(
  1411. {
  1412. projectId,
  1413. renames: renames.map(rename => ({
  1414. oldPath: rename.entity.path,
  1415. newPath: rename.newPath,
  1416. })),
  1417. },
  1418. 'found conflicts or bad filenames in filetree'
  1419. )
  1420. // Avoid conflicts by processing renames in the reverse order. If we have
  1421. // the following starting situation:
  1422. //
  1423. // somefile.tex
  1424. // somefile.tex
  1425. // somefile.tex (1)
  1426. //
  1427. // somefile.tex would be processed first, and then somefile.tex (1),
  1428. // yielding the following renames:
  1429. //
  1430. // somefile.tex -> somefile.tex (1)
  1431. // somefile.tex (1) -> somefile.tex (2)
  1432. //
  1433. // When the first rename was decided, we didn't know that somefile.tex (1)
  1434. // existed, so that created a conflict. By processing renames in the
  1435. // reverse order, we start with the files that had the most extensive
  1436. // information about existing files.
  1437. renames.reverse()
  1438. for (const rename of renames) {
  1439. // rename the duplicate files
  1440. const entity = rename.entity
  1441. const entityId = entity.folder
  1442. ? entity.folder._id
  1443. : entity.doc
  1444. ? entity.doc._id
  1445. : entity.file._id
  1446. const entityType = entity.folder ? 'folder' : entity.doc ? 'doc' : 'file'
  1447. const { changes } =
  1448. await ProjectEntityMongoUpdateHandler.promises.renameEntity(
  1449. projectId,
  1450. entityId,
  1451. entityType,
  1452. rename.newName,
  1453. null // unset lastUpdatedBy
  1454. )
  1455. // update the renamed entity for the resync
  1456. entity.path = rename.newPath
  1457. if (entityType === 'folder') {
  1458. entity.folder.name = rename.newName
  1459. } else if (entityType === 'doc') {
  1460. entity.doc.name = rename.newName
  1461. } else {
  1462. entity.file.name = rename.newName
  1463. }
  1464. await DocumentUpdaterHandler.promises.updateProjectStructure(
  1465. projectId,
  1466. projectHistoryId,
  1467. null,
  1468. changes,
  1469. 'automatic-fix'
  1470. )
  1471. }
  1472. },
  1473. findNextAvailablePath(allPaths, candidatePath) {
  1474. const incrementReplacer = (match, p1) => {
  1475. return ' (' + (parseInt(p1, 10) + 1) + ')'
  1476. }
  1477. // if the filename was invalid we should normalise it here too. Currently
  1478. // this only handles renames in the same folder, so we will be out of luck
  1479. // if it is the folder name which in invalid. We could handle folder
  1480. // renames by returning the folders list from getAllEntitiesFromProject
  1481. do {
  1482. // does the filename look like "foo (1)" if so, increment the number in parentheses
  1483. if (/ \(\d+\)$/.test(candidatePath)) {
  1484. candidatePath = candidatePath.replace(/ \((\d+)\)$/, incrementReplacer)
  1485. } else {
  1486. // otherwise, add a ' (1)' suffix to the name
  1487. candidatePath = candidatePath + ' (1)'
  1488. }
  1489. } while (allPaths.has(candidatePath)) // keep going until the name is unique
  1490. // add the new name to the set
  1491. allPaths.add(candidatePath)
  1492. return candidatePath
  1493. },
  1494. isPathValidForRootDoc(docPath) {
  1495. const docExtension = Path.extname(docPath)
  1496. return VALID_ROOT_DOC_REGEXP.test(docExtension)
  1497. },
  1498. isPathValidForMainBibliographyDoc(docPath) {
  1499. const docExtension = Path.extname(docPath).toLowerCase()
  1500. return docExtension === '.bib'
  1501. },
  1502. async _cleanUpEntity(
  1503. project,
  1504. newProject,
  1505. entity,
  1506. entityType,
  1507. path,
  1508. userId,
  1509. source
  1510. ) {
  1511. const subtreeListing = _listSubtree(entity, entityType, path)
  1512. await ProjectEntityUpdateHandler._updateProjectStructureWithDeletedEntity(
  1513. project,
  1514. newProject,
  1515. subtreeListing,
  1516. userId,
  1517. source
  1518. )
  1519. for (const entry of subtreeListing) {
  1520. if (entry.type === 'doc') {
  1521. await ProjectEntityUpdateHandler._cleanUpDoc(
  1522. project,
  1523. entry.entity,
  1524. entry.path,
  1525. userId
  1526. )
  1527. } else if (entry.type === 'file') {
  1528. await ProjectEntityUpdateHandler._cleanUpFile(project, entry.entity)
  1529. }
  1530. }
  1531. return subtreeListing
  1532. },
  1533. async _updateProjectStructureWithDeletedEntity(
  1534. project,
  1535. newProject,
  1536. subtreeListing,
  1537. userId,
  1538. source
  1539. ) {
  1540. const changes = { oldDocs: [], oldFiles: [] }
  1541. for (const entry of subtreeListing) {
  1542. if (entry.type === 'doc') {
  1543. changes.oldDocs.push({ doc: entry.entity, path: entry.path })
  1544. } else if (entry.type === 'file') {
  1545. changes.oldFiles.push({ file: entry.entity, path: entry.path })
  1546. }
  1547. }
  1548. // now send the project structure changes to the docupdater
  1549. changes.newProject = newProject
  1550. const projectId = project._id.toString()
  1551. const projectHistoryId =
  1552. project.overleaf &&
  1553. project.overleaf.history &&
  1554. project.overleaf.history.id
  1555. return await DocumentUpdaterHandler.promises.updateProjectStructure(
  1556. projectId,
  1557. projectHistoryId,
  1558. userId,
  1559. changes,
  1560. source
  1561. )
  1562. },
  1563. async _cleanUpDoc(project, doc) {
  1564. const projectId = project._id.toString()
  1565. const docId = doc._id.toString()
  1566. if (project.rootDoc_id != null && project.rootDoc_id.toString() === docId) {
  1567. await ProjectEntityUpdateHandler.promises.unsetRootDoc(projectId)
  1568. }
  1569. const { name } = doc
  1570. const deletedAt = new Date()
  1571. await DocstoreManager.promises.deleteDoc(projectId, docId, name, deletedAt)
  1572. return await DocumentUpdaterHandler.promises.deleteDoc(projectId, docId)
  1573. },
  1574. async _cleanUpFile(project, file) {
  1575. return await ProjectEntityMongoUpdateHandler.promises._insertDeletedFileReference(
  1576. project._id,
  1577. file
  1578. )
  1579. },
  1580. }
  1581. /**
  1582. * List all descendants of an entity along with their type and path. Include
  1583. * the top-level entity as well.
  1584. */
  1585. function _listSubtree(entity, entityType, entityPath) {
  1586. if (entityType.indexOf('file') !== -1) {
  1587. return [{ type: 'file', entity, path: entityPath }]
  1588. } else if (entityType.indexOf('doc') !== -1) {
  1589. return [{ type: 'doc', entity, path: entityPath }]
  1590. } else if (entityType.indexOf('folder') !== -1) {
  1591. const listing = []
  1592. const _recurseFolder = (folder, folderPath) => {
  1593. listing.push({ type: 'folder', entity: folder, path: folderPath })
  1594. for (const doc of iterablePaths(folder, 'docs')) {
  1595. listing.push({
  1596. type: 'doc',
  1597. entity: doc,
  1598. path: Path.join(folderPath, doc.name),
  1599. })
  1600. }
  1601. for (const file of iterablePaths(folder, 'fileRefs')) {
  1602. listing.push({
  1603. type: 'file',
  1604. entity: file,
  1605. path: Path.join(folderPath, file.name),
  1606. })
  1607. }
  1608. for (const childFolder of iterablePaths(folder, 'folders')) {
  1609. _recurseFolder(childFolder, Path.join(folderPath, childFolder.name))
  1610. }
  1611. }
  1612. _recurseFolder(entity, entityPath)
  1613. return listing
  1614. } else {
  1615. // This shouldn't happen, but if it does, fail silently.
  1616. return []
  1617. }
  1618. }
  1619. module.exports = ProjectEntityUpdateHandler