ProjectEntityUpdateHandler.js 54 KB

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