| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634 |
- /* NOTE: this file is an almost exact copy of ProjectEntityUpdateHandler.js.
- * The only difference is that it imports
- * ProjectEntityMongoUpdateHandlerCanary.js. It's meant to be a short-lived
- * module, so that we can test the async/await code in production for some code
- * paths only.
- */
- /* eslint-disable
- camelcase,
- handle-callback-err,
- max-len,
- one-var,
- standard/no-callback-literal,
- */
- // TODO: This file was created by bulk-decaffeinate.
- // Fix any style issues and re-enable lint.
- /*
- * decaffeinate suggestions:
- * DS101: Remove unnecessary use of Array.from
- * DS102: Remove unnecessary code created because of implicit returns
- * DS103: Rewrite code to no longer use __guard__
- * DS201: Simplify complex destructure assignments
- * DS207: Consider shorter variations of null checks
- * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
- */
- let ProjectEntityUpdateHandler, self
- const _ = require('lodash')
- const async = require('async')
- const logger = require('logger-sharelatex')
- const Settings = require('settings-sharelatex')
- const path = require('path')
- const { Doc } = require('../../models/Doc')
- const DocstoreManager = require('../Docstore/DocstoreManager')
- const DocumentUpdaterHandler = require('../../Features/DocumentUpdater/DocumentUpdaterHandler')
- const Errors = require('../Errors/Errors')
- const { File } = require('../../models/File')
- const FileStoreHandler = require('../FileStore/FileStoreHandler')
- const LockManager = require('../../infrastructure/LockManager')
- const { Project } = require('../../models/Project')
- const ProjectEntityHandler = require('./ProjectEntityHandler')
- const ProjectGetter = require('./ProjectGetter')
- const ProjectLocator = require('./ProjectLocator')
- const ProjectUpdateHandler = require('./ProjectUpdateHandler')
- const ProjectEntityMongoUpdateHandler = require('./ProjectEntityMongoUpdateHandlerCanary')
- const SafePath = require('./SafePath')
- const TpdsUpdateSender = require('../ThirdPartyDataStore/TpdsUpdateSender')
- const LOCK_NAMESPACE = 'sequentialProjectStructureUpdateLock'
- const validRootDocExtensions = Settings.validRootDocExtensions
- const validRootDocRegExp = new RegExp(
- `^\\.(${validRootDocExtensions.join('|')})$`,
- 'i'
- )
- const wrapWithLock = function(methodWithoutLock) {
- // This lock is used to make sure that the project structure updates are made
- // sequentially. In particular the updates must be made in mongo and sent to
- // the doc-updater in the same order.
- let methodWithLock
- if (typeof methodWithoutLock === 'function') {
- methodWithLock = function(project_id, ...rest) {
- const adjustedLength = Math.max(rest.length, 1),
- args = rest.slice(0, adjustedLength - 1),
- callback = rest[adjustedLength - 1]
- return LockManager.runWithLock(
- LOCK_NAMESPACE,
- project_id,
- cb => methodWithoutLock(project_id, ...Array.from(args), cb),
- callback
- )
- }
- methodWithLock.withoutLock = methodWithoutLock
- return methodWithLock
- } else {
- // handle case with separate setup and locked stages
- const wrapWithSetup = methodWithoutLock.beforeLock // a function to set things up before the lock
- const mainTask = methodWithoutLock.withLock // function to execute inside the lock
- methodWithLock = wrapWithSetup(function(project_id, ...rest) {
- const adjustedLength = Math.max(rest.length, 1),
- args = rest.slice(0, adjustedLength - 1),
- callback = rest[adjustedLength - 1]
- return LockManager.runWithLock(
- LOCK_NAMESPACE,
- project_id,
- cb => mainTask(project_id, ...Array.from(args), cb),
- callback
- )
- })
- methodWithLock.withoutLock = wrapWithSetup(mainTask)
- methodWithLock.beforeLock = methodWithoutLock.beforeLock
- methodWithLock.mainTask = methodWithoutLock.withLock
- return methodWithLock
- }
- }
- module.exports = ProjectEntityUpdateHandler = self = {
- copyFileFromExistingProjectWithProject: wrapWithLock({
- beforeLock(next) {
- return function(
- project_id,
- project,
- folder_id,
- originalProject_id,
- origonalFileRef,
- userId,
- callback
- ) {
- if (callback == null) {
- callback = function(error, fileRef, folder_id) {}
- }
- logger.log(
- { project_id, folder_id, originalProject_id, origonalFileRef },
- 'copying file in s3 with project'
- )
- folder_id = ProjectEntityMongoUpdateHandler._confirmFolder(
- project,
- folder_id
- )
- if (origonalFileRef == null) {
- logger.err(
- { project_id, folder_id, originalProject_id, origonalFileRef },
- 'file trying to copy is null'
- )
- return callback()
- }
- // convert any invalid characters in original file to '_'
- const fileProperties = {
- name: SafePath.clean(origonalFileRef.name)
- }
- if (origonalFileRef.linkedFileData != null) {
- fileProperties.linkedFileData = origonalFileRef.linkedFileData
- }
- if (origonalFileRef.hash != null) {
- fileProperties.hash = origonalFileRef.hash
- }
- const fileRef = new File(fileProperties)
- return FileStoreHandler.copyFile(
- originalProject_id,
- origonalFileRef._id,
- project._id,
- fileRef._id,
- function(err, fileStoreUrl) {
- if (err != null) {
- logger.warn(
- {
- err,
- project_id,
- folder_id,
- originalProject_id,
- origonalFileRef
- },
- 'error coping file in s3'
- )
- return callback(err)
- }
- return next(
- project_id,
- project,
- folder_id,
- originalProject_id,
- origonalFileRef,
- userId,
- fileRef,
- fileStoreUrl,
- callback
- )
- }
- )
- }
- },
- withLock(
- project_id,
- project,
- folder_id,
- originalProject_id,
- origonalFileRef,
- userId,
- fileRef,
- fileStoreUrl,
- callback
- ) {
- if (callback == null) {
- callback = function(error, fileRef, folder_id) {}
- }
- const projectHistoryId = __guard__(
- project.overleaf != null ? project.overleaf.history : undefined,
- x => x.id
- )
- return ProjectEntityMongoUpdateHandler._putElement(
- project,
- folder_id,
- fileRef,
- 'file',
- function(err, result, newProject) {
- if (err != null) {
- logger.warn(
- { err, project_id, folder_id },
- 'error putting element as part of copy'
- )
- return callback(err)
- }
- return TpdsUpdateSender.addFile(
- {
- project_id,
- file_id: fileRef._id,
- path: __guard__(
- result != null ? result.path : undefined,
- x1 => x1.fileSystem
- ),
- rev: fileRef.rev,
- project_name: project.name
- },
- function(err) {
- if (err != null) {
- logger.err(
- {
- err,
- project_id,
- folder_id,
- originalProject_id,
- origonalFileRef
- },
- 'error sending file to tpds worker'
- )
- }
- const newFiles = [
- {
- file: fileRef,
- path: __guard__(
- result != null ? result.path : undefined,
- x2 => x2.fileSystem
- ),
- url: fileStoreUrl
- }
- ]
- return DocumentUpdaterHandler.updateProjectStructure(
- project_id,
- projectHistoryId,
- userId,
- { newFiles, newProject },
- function(error) {
- if (error != null) {
- return callback(error)
- }
- return callback(null, fileRef, folder_id)
- }
- )
- }
- )
- }
- )
- }
- }),
- updateDocLines(
- project_id,
- doc_id,
- lines,
- version,
- ranges,
- lastUpdatedAt,
- lastUpdatedBy,
- callback
- ) {
- if (callback == null) {
- callback = function(error) {}
- }
- return ProjectGetter.getProjectWithoutDocLines(project_id, function(
- err,
- project
- ) {
- if (err != null) {
- return callback(err)
- }
- if (project == null) {
- return callback(new Errors.NotFoundError('project not found'))
- }
- logger.log({ project_id, doc_id }, 'updating doc lines')
- return ProjectLocator.findElement(
- { project, element_id: doc_id, type: 'docs' },
- function(err, doc, path) {
- let isDeletedDoc = false
- if (err != null) {
- if (err instanceof Errors.NotFoundError) {
- // We need to be able to update the doclines of deleted docs. This is
- // so the doc-updater can flush a doc's content to the doc-store after
- // the doc is deleted.
- isDeletedDoc = true
- doc = _.find(
- project.deletedDocs,
- doc => doc._id.toString() === doc_id.toString()
- )
- } else {
- return callback(err)
- }
- }
- if (doc == null) {
- // Do not allow an update to a doc which has never exist on this project
- logger.warn(
- { doc_id, project_id, lines },
- 'doc not found while updating doc lines'
- )
- return callback(new Errors.NotFoundError('doc not found'))
- }
- logger.log(
- { project_id, doc_id },
- 'telling docstore manager to update doc'
- )
- return DocstoreManager.updateDoc(
- project_id,
- doc_id,
- lines,
- version,
- ranges,
- function(err, modified, rev) {
- if (err != null) {
- logger.warn(
- { err, doc_id, project_id, lines },
- 'error sending doc to docstore'
- )
- return callback(err)
- }
- logger.log(
- { project_id, doc_id, modified },
- 'finished updating doc lines'
- )
- // path will only be present if the doc is not deleted
- if (modified && !isDeletedDoc) {
- // Don't need to block for marking as updated
- ProjectUpdateHandler.markAsUpdated(
- project_id,
- lastUpdatedAt,
- lastUpdatedBy
- )
- return TpdsUpdateSender.addDoc(
- {
- project_id,
- path: path.fileSystem,
- doc_id,
- project_name: project.name,
- rev
- },
- callback
- )
- } else {
- return callback()
- }
- }
- )
- }
- )
- })
- },
- setRootDoc(project_id, newRootDocID, callback) {
- if (callback == null) {
- callback = function(error) {}
- }
- logger.log({ project_id, rootDocId: newRootDocID }, 'setting root doc')
- if (project_id == null || newRootDocID == null) {
- return callback(
- new Errors.InvalidError('missing arguments (project or doc)')
- )
- }
- ProjectEntityHandler.getDocPathByProjectIdAndDocId(
- project_id,
- newRootDocID,
- function(err, docPath) {
- if (err != null) {
- return callback(err)
- }
- if (ProjectEntityUpdateHandler.isPathValidForRootDoc(docPath)) {
- return Project.update(
- { _id: project_id },
- { rootDoc_id: newRootDocID },
- {},
- callback
- )
- } else {
- return callback(
- new Errors.UnsupportedFileTypeError(
- 'invalid file extension for root doc'
- )
- )
- }
- }
- )
- },
- unsetRootDoc(project_id, callback) {
- if (callback == null) {
- callback = function(error) {}
- }
- logger.log({ project_id }, 'removing root doc')
- return Project.update(
- { _id: project_id },
- { $unset: { rootDoc_id: true } },
- {},
- callback
- )
- },
- _addDocAndSendToTpds(project_id, folder_id, doc, callback) {
- if (callback == null) {
- callback = function(error, result, project) {}
- }
- return ProjectEntityMongoUpdateHandler.addDoc(
- project_id,
- folder_id,
- doc,
- function(err, result, project) {
- if (err != null) {
- logger.warn(
- {
- err,
- project_id,
- folder_id,
- doc_name: doc != null ? doc.name : undefined,
- doc_id: doc != null ? doc._id : undefined
- },
- 'error adding file with project'
- )
- return callback(err)
- }
- return TpdsUpdateSender.addDoc(
- {
- project_id,
- doc_id: doc != null ? doc._id : undefined,
- path: __guard__(
- result != null ? result.path : undefined,
- x => x.fileSystem
- ),
- project_name: project.name,
- rev: 0
- },
- function(err) {
- if (err != null) {
- return callback(err)
- }
- return callback(null, result, project)
- }
- )
- }
- )
- },
- addDoc(project_id, folder_id, docName, docLines, userId, callback) {
- return self.addDocWithRanges(
- project_id,
- folder_id,
- docName,
- docLines,
- {},
- userId,
- callback
- )
- },
- addDocWithRanges: wrapWithLock({
- beforeLock(next) {
- return function(
- project_id,
- folder_id,
- docName,
- docLines,
- ranges,
- userId,
- callback
- ) {
- if (callback == null) {
- callback = function(error, doc, folder_id) {}
- }
- if (!SafePath.isCleanFilename(docName)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- // Put doc in docstore first, so that if it errors, we don't have a doc_id in the project
- // which hasn't been created in docstore.
- const doc = new Doc({ name: docName })
- return DocstoreManager.updateDoc(
- project_id.toString(),
- doc._id.toString(),
- docLines,
- 0,
- ranges,
- function(err, modified, rev) {
- if (err != null) {
- return callback(err)
- }
- return next(
- project_id,
- folder_id,
- doc,
- docName,
- docLines,
- ranges,
- userId,
- callback
- )
- }
- )
- }
- },
- withLock(
- project_id,
- folder_id,
- doc,
- docName,
- docLines,
- ranges,
- userId,
- callback
- ) {
- if (callback == null) {
- callback = function(error, doc, folder_id) {}
- }
- return ProjectEntityUpdateHandler._addDocAndSendToTpds(
- project_id,
- folder_id,
- doc,
- function(err, result, project) {
- if (err != null) {
- return callback(err)
- }
- const docPath = __guard__(
- result != null ? result.path : undefined,
- x => x.fileSystem
- )
- const projectHistoryId = __guard__(
- project.overleaf != null ? project.overleaf.history : undefined,
- x1 => x1.id
- )
- const newDocs = [
- {
- doc,
- path: docPath,
- docLines: docLines.join('\n')
- }
- ]
- return DocumentUpdaterHandler.updateProjectStructure(
- project_id,
- projectHistoryId,
- userId,
- { newDocs, newProject: project },
- function(error) {
- if (error != null) {
- return callback(error)
- }
- return callback(null, doc, folder_id)
- }
- )
- }
- )
- }
- }),
- _uploadFile(
- project_id,
- folder_id,
- fileName,
- fsPath,
- linkedFileData,
- callback
- ) {
- if (callback == null) {
- callback = function(error, fileStoreUrl, fileRef) {}
- }
- if (!SafePath.isCleanFilename(fileName)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- const fileArgs = {
- name: fileName,
- linkedFileData
- }
- return FileStoreHandler.uploadFileFromDisk(
- project_id,
- fileArgs,
- fsPath,
- function(err, fileStoreUrl, fileRef) {
- if (err != null) {
- logger.warn(
- { err, project_id, folder_id, file_name: fileName, fileRef },
- 'error uploading image to s3'
- )
- return callback(err)
- }
- return callback(null, fileStoreUrl, fileRef)
- }
- )
- },
- _addFileAndSendToTpds(project_id, folder_id, fileRef, callback) {
- if (callback == null) {
- callback = function(error) {}
- }
- return ProjectEntityMongoUpdateHandler.addFile(
- project_id,
- folder_id,
- fileRef,
- function(err, result, project) {
- if (err != null) {
- logger.warn(
- { err, project_id, folder_id, file_name: fileRef.name, fileRef },
- 'error adding file with project'
- )
- return callback(err)
- }
- return TpdsUpdateSender.addFile(
- {
- project_id,
- file_id: fileRef._id,
- path: __guard__(
- result != null ? result.path : undefined,
- x => x.fileSystem
- ),
- project_name: project.name,
- rev: fileRef.rev
- },
- function(err) {
- if (err != null) {
- return callback(err)
- }
- return callback(null, result, project)
- }
- )
- }
- )
- },
- addFile: wrapWithLock({
- beforeLock(next) {
- return function(
- project_id,
- folder_id,
- fileName,
- fsPath,
- linkedFileData,
- userId,
- callback
- ) {
- if (!SafePath.isCleanFilename(fileName)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- return ProjectEntityUpdateHandler._uploadFile(
- project_id,
- folder_id,
- fileName,
- fsPath,
- linkedFileData,
- function(error, fileStoreUrl, fileRef) {
- if (error != null) {
- return callback(error)
- }
- return next(
- project_id,
- folder_id,
- fileName,
- fsPath,
- linkedFileData,
- userId,
- fileRef,
- fileStoreUrl,
- callback
- )
- }
- )
- }
- },
- withLock(
- project_id,
- folder_id,
- fileName,
- fsPath,
- linkedFileData,
- userId,
- fileRef,
- fileStoreUrl,
- callback
- ) {
- if (callback == null) {
- callback = function(error, fileRef, folder_id) {}
- }
- return ProjectEntityUpdateHandler._addFileAndSendToTpds(
- project_id,
- folder_id,
- fileRef,
- function(err, result, project) {
- if (err != null) {
- return callback(err)
- }
- const projectHistoryId = __guard__(
- project.overleaf != null ? project.overleaf.history : undefined,
- x => x.id
- )
- const newFiles = [
- {
- file: fileRef,
- path: __guard__(
- result != null ? result.path : undefined,
- x1 => x1.fileSystem
- ),
- url: fileStoreUrl
- }
- ]
- return DocumentUpdaterHandler.updateProjectStructure(
- project_id,
- projectHistoryId,
- userId,
- { newFiles, newProject: project },
- function(error) {
- if (error != null) {
- return callback(error)
- }
- return callback(null, fileRef, folder_id)
- }
- )
- }
- )
- }
- }),
- replaceFile: wrapWithLock({
- beforeLock(next) {
- return function(
- project_id,
- file_id,
- fsPath,
- linkedFileData,
- userId,
- callback
- ) {
- // create a new file
- const fileArgs = {
- name: 'dummy-upload-filename',
- linkedFileData
- }
- return FileStoreHandler.uploadFileFromDisk(
- project_id,
- fileArgs,
- fsPath,
- function(err, fileStoreUrl, fileRef) {
- if (err != null) {
- return callback(err)
- }
- return next(
- project_id,
- file_id,
- fsPath,
- linkedFileData,
- userId,
- fileRef,
- fileStoreUrl,
- callback
- )
- }
- )
- }
- },
- withLock(
- project_id,
- file_id,
- fsPath,
- linkedFileData,
- userId,
- newFileRef,
- fileStoreUrl,
- callback
- ) {
- return ProjectEntityMongoUpdateHandler.replaceFileWithNew(
- project_id,
- file_id,
- newFileRef,
- function(err, oldFileRef, project, path, newProject) {
- if (err != null) {
- return callback(err)
- }
- const oldFiles = [
- {
- file: oldFileRef,
- path: path.fileSystem
- }
- ]
- const newFiles = [
- {
- file: newFileRef,
- path: path.fileSystem,
- url: fileStoreUrl
- }
- ]
- const projectHistoryId = __guard__(
- project.overleaf != null ? project.overleaf.history : undefined,
- x => x.id
- )
- // Increment the rev for an in-place update (with the same path) so the third-party-datastore
- // knows this is a new file.
- // Ideally we would get this from ProjectEntityMongoUpdateHandler.replaceFileWithNew
- // but it returns the original oldFileRef (after incrementing the rev value in mongo),
- // so we add 1 to the rev from that. This isn't atomic and relies on the lock
- // but it is acceptable for now.
- return TpdsUpdateSender.addFile(
- {
- project_id: project._id,
- file_id: newFileRef._id,
- path: path.fileSystem,
- rev: oldFileRef.rev + 1,
- project_name: project.name
- },
- function(err) {
- if (err != null) {
- return callback(err)
- }
- return DocumentUpdaterHandler.updateProjectStructure(
- project_id,
- projectHistoryId,
- userId,
- { oldFiles, newFiles, newProject },
- callback
- )
- }
- )
- }
- )
- }
- }),
- upsertDoc: wrapWithLock(function(
- project_id,
- folder_id,
- docName,
- docLines,
- source,
- userId,
- callback
- ) {
- if (callback == null) {
- callback = function(err, doc, folder_id, isNewDoc) {}
- }
- if (!SafePath.isCleanFilename(docName)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- return ProjectLocator.findElement(
- { project_id, element_id: folder_id, type: 'folder' },
- function(error, folder) {
- if (error != null) {
- return callback(error)
- }
- if (folder == null) {
- return callback(new Error("Couldn't find folder"))
- }
- let existingDoc = null
- for (let doc of Array.from(folder.docs)) {
- if (doc.name === docName) {
- existingDoc = doc
- break
- }
- }
- if (existingDoc != null) {
- return DocumentUpdaterHandler.setDocument(
- project_id,
- existingDoc._id,
- userId,
- docLines,
- source,
- err => {
- logger.log(
- { project_id, doc_id: existingDoc._id },
- 'notifying users that the document has been updated'
- )
- return DocumentUpdaterHandler.flushDocToMongo(
- project_id,
- existingDoc._id,
- function(err) {
- if (err != null) {
- return callback(err)
- }
- return callback(null, existingDoc, existingDoc == null)
- }
- )
- }
- )
- } else {
- return self.addDocWithRanges.withoutLock(
- project_id,
- folder_id,
- docName,
- docLines,
- {},
- userId,
- function(err, doc) {
- if (err != null) {
- return callback(err)
- }
- return callback(null, doc, existingDoc == null)
- }
- )
- }
- }
- )
- }),
- upsertFile: wrapWithLock({
- beforeLock(next) {
- return function(
- project_id,
- folder_id,
- fileName,
- fsPath,
- linkedFileData,
- userId,
- callback
- ) {
- if (!SafePath.isCleanFilename(fileName)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- // create a new file
- const fileArgs = {
- name: fileName,
- linkedFileData
- }
- return FileStoreHandler.uploadFileFromDisk(
- project_id,
- fileArgs,
- fsPath,
- function(err, fileStoreUrl, fileRef) {
- if (err != null) {
- return callback(err)
- }
- return next(
- project_id,
- folder_id,
- fileName,
- fsPath,
- linkedFileData,
- userId,
- fileRef,
- fileStoreUrl,
- callback
- )
- }
- )
- }
- },
- withLock(
- project_id,
- folder_id,
- fileName,
- fsPath,
- linkedFileData,
- userId,
- newFileRef,
- fileStoreUrl,
- callback
- ) {
- if (callback == null) {
- callback = function(err, file, isNewFile, existingFile) {}
- }
- return ProjectLocator.findElement(
- { project_id, element_id: folder_id, type: 'folder' },
- function(error, folder) {
- if (error != null) {
- return callback(error)
- }
- if (folder == null) {
- return callback(new Error("Couldn't find folder"))
- }
- let existingFile = null
- for (let fileRef of Array.from(folder.fileRefs)) {
- if (fileRef.name === fileName) {
- existingFile = fileRef
- break
- }
- }
- if (existingFile != null) {
- // this calls directly into the replaceFile main task (without the beforeLock part)
- return self.replaceFile.mainTask(
- project_id,
- existingFile._id,
- fsPath,
- linkedFileData,
- userId,
- newFileRef,
- fileStoreUrl,
- function(err) {
- if (err != null) {
- return callback(err)
- }
- return callback(
- null,
- newFileRef,
- existingFile == null,
- existingFile
- )
- }
- )
- } else {
- // this calls directly into the addFile main task (without the beforeLock part)
- return self.addFile.mainTask(
- project_id,
- folder_id,
- fileName,
- fsPath,
- linkedFileData,
- userId,
- newFileRef,
- fileStoreUrl,
- function(err) {
- if (err != null) {
- return callback(err)
- }
- return callback(
- null,
- newFileRef,
- existingFile == null,
- existingFile
- )
- }
- )
- }
- }
- )
- }
- }),
- upsertDocWithPath: wrapWithLock(function(
- project_id,
- elementPath,
- docLines,
- source,
- userId,
- callback
- ) {
- if (!SafePath.isCleanPath(elementPath)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- const docName = path.basename(elementPath)
- const folderPath = path.dirname(elementPath)
- return self.mkdirp.withoutLock(project_id, folderPath, function(
- err,
- newFolders,
- folder
- ) {
- if (err != null) {
- return callback(err)
- }
- return self.upsertDoc.withoutLock(
- project_id,
- folder._id,
- docName,
- docLines,
- source,
- userId,
- function(err, doc, isNewDoc) {
- if (err != null) {
- return callback(err)
- }
- return callback(null, doc, isNewDoc, newFolders, folder)
- }
- )
- })
- }),
- upsertFileWithPath: wrapWithLock({
- beforeLock(next) {
- return function(
- project_id,
- elementPath,
- fsPath,
- linkedFileData,
- userId,
- callback
- ) {
- if (!SafePath.isCleanPath(elementPath)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- const fileName = path.basename(elementPath)
- const folderPath = path.dirname(elementPath)
- // create a new file
- const fileArgs = {
- name: fileName,
- linkedFileData
- }
- return FileStoreHandler.uploadFileFromDisk(
- project_id,
- fileArgs,
- fsPath,
- function(err, fileStoreUrl, fileRef) {
- if (err != null) {
- return callback(err)
- }
- return next(
- project_id,
- folderPath,
- fileName,
- fsPath,
- linkedFileData,
- userId,
- fileRef,
- fileStoreUrl,
- callback
- )
- }
- )
- }
- },
- withLock(
- project_id,
- folderPath,
- fileName,
- fsPath,
- linkedFileData,
- userId,
- fileRef,
- fileStoreUrl,
- callback
- ) {
- return self.mkdirp.withoutLock(project_id, folderPath, function(
- err,
- newFolders,
- folder
- ) {
- if (err != null) {
- return callback(err)
- }
- // this calls directly into the upsertFile main task (without the beforeLock part)
- return self.upsertFile.mainTask(
- project_id,
- folder._id,
- fileName,
- fsPath,
- linkedFileData,
- userId,
- fileRef,
- fileStoreUrl,
- function(err, newFile, isNewFile, existingFile) {
- if (err != null) {
- return callback(err)
- }
- return callback(
- null,
- newFile,
- isNewFile,
- existingFile,
- newFolders,
- folder
- )
- }
- )
- })
- }
- }),
- deleteEntity: wrapWithLock(function(
- project_id,
- entity_id,
- entityType,
- userId,
- callback
- ) {
- if (callback == null) {
- callback = function(error) {}
- }
- logger.log({ entity_id, entityType, project_id }, 'deleting project entity')
- if (entityType == null) {
- logger.warn({ err: 'No entityType set', project_id, entity_id })
- return callback(new Error('No entityType set'))
- }
- entityType = entityType.toLowerCase()
- return ProjectEntityMongoUpdateHandler.deleteEntity(
- project_id,
- entity_id,
- entityType,
- function(error, entity, path, projectBeforeDeletion, newProject) {
- if (error != null) {
- return callback(error)
- }
- return self._cleanUpEntity(
- projectBeforeDeletion,
- newProject,
- entity,
- entityType,
- path.fileSystem,
- userId,
- function(error) {
- if (error != null) {
- return callback(error)
- }
- return TpdsUpdateSender.deleteEntity(
- {
- project_id,
- path: path.fileSystem,
- project_name: projectBeforeDeletion.name
- },
- function(error) {
- if (error != null) {
- return callback(error)
- }
- return callback(null, entity_id)
- }
- )
- }
- )
- }
- )
- }),
- deleteEntityWithPath: wrapWithLock((project_id, path, userId, callback) =>
- ProjectLocator.findElementByPath({ project_id, path }, function(
- err,
- element,
- type
- ) {
- if (err != null) {
- return callback(err)
- }
- if (element == null) {
- return callback(new Errors.NotFoundError('project not found'))
- }
- return self.deleteEntity.withoutLock(
- project_id,
- element._id,
- type,
- userId,
- callback
- )
- })
- ),
- mkdirp: wrapWithLock(function(project_id, path, callback) {
- if (callback == null) {
- callback = function(err, newlyCreatedFolders, lastFolderInPath) {}
- }
- for (let folder of Array.from(path.split('/'))) {
- if (folder.length > 0 && !SafePath.isCleanFilename(folder)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- }
- return ProjectEntityMongoUpdateHandler.mkdirp(
- project_id,
- path,
- { exactCaseMatch: false },
- callback
- )
- }),
- mkdirpWithExactCase: wrapWithLock(function(project_id, path, callback) {
- if (callback == null) {
- callback = function(err, newlyCreatedFolders, lastFolderInPath) {}
- }
- for (let folder of Array.from(path.split('/'))) {
- if (folder.length > 0 && !SafePath.isCleanFilename(folder)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- }
- return ProjectEntityMongoUpdateHandler.mkdirp(
- project_id,
- path,
- { exactCaseMatch: true },
- callback
- )
- }),
- addFolder: wrapWithLock(function(
- project_id,
- parentFolder_id,
- folderName,
- callback
- ) {
- if (!SafePath.isCleanFilename(folderName)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- return ProjectEntityMongoUpdateHandler.addFolder(
- project_id,
- parentFolder_id,
- folderName,
- callback
- )
- }),
- moveEntity: wrapWithLock(function(
- project_id,
- entity_id,
- destFolderId,
- entityType,
- userId,
- callback
- ) {
- if (callback == null) {
- callback = function(error) {}
- }
- logger.log(
- { entityType, entity_id, project_id, destFolderId },
- 'moving entity'
- )
- if (entityType == null) {
- logger.warn({ err: 'No entityType set', project_id, entity_id })
- return callback(new Error('No entityType set'))
- }
- entityType = entityType.toLowerCase()
- return ProjectEntityMongoUpdateHandler.moveEntity(
- project_id,
- entity_id,
- destFolderId,
- entityType,
- function(err, project, startPath, endPath, rev, changes) {
- if (err != null) {
- return callback(err)
- }
- const projectHistoryId = __guard__(
- project.overleaf != null ? project.overleaf.history : undefined,
- x => x.id
- )
- TpdsUpdateSender.moveEntity({
- project_id,
- project_name: project.name,
- startPath,
- endPath,
- rev
- })
- return DocumentUpdaterHandler.updateProjectStructure(
- project_id,
- projectHistoryId,
- userId,
- changes,
- callback
- )
- }
- )
- }),
- renameEntity: wrapWithLock(function(
- project_id,
- entity_id,
- entityType,
- newName,
- userId,
- callback
- ) {
- if (!SafePath.isCleanFilename(newName)) {
- return callback(new Errors.InvalidNameError('invalid element name'))
- }
- logger.log({ entity_id, project_id }, `renaming ${entityType}`)
- if (entityType == null) {
- logger.warn({ err: 'No entityType set', project_id, entity_id })
- return callback(new Error('No entityType set'))
- }
- entityType = entityType.toLowerCase()
- return ProjectEntityMongoUpdateHandler.renameEntity(
- project_id,
- entity_id,
- entityType,
- newName,
- function(err, project, startPath, endPath, rev, changes) {
- if (err != null) {
- return callback(err)
- }
- const projectHistoryId = __guard__(
- project.overleaf != null ? project.overleaf.history : undefined,
- x => x.id
- )
- TpdsUpdateSender.moveEntity({
- project_id,
- project_name: project.name,
- startPath,
- endPath,
- rev
- })
- return DocumentUpdaterHandler.updateProjectStructure(
- project_id,
- projectHistoryId,
- userId,
- changes,
- callback
- )
- }
- )
- }),
- // This doesn't directly update project structure but we need to take the lock
- // to prevent anything else being queued before the resync update
- resyncProjectHistory: wrapWithLock((project_id, callback) =>
- ProjectGetter.getProject(
- project_id,
- { rootFolder: true, overleaf: true },
- function(error, project) {
- if (error != null) {
- return callback(error)
- }
- const projectHistoryId = __guard__(
- __guard__(
- project != null ? project.overleaf : undefined,
- x1 => x1.history
- ),
- x => x.id
- )
- if (projectHistoryId == null) {
- error = new Errors.ProjectHistoryDisabledError(
- `project history not enabled for ${project_id}`
- )
- return callback(error)
- }
- return ProjectEntityHandler.getAllEntitiesFromProject(project, function(
- error,
- docs,
- files
- ) {
- if (error != null) {
- return callback(error)
- }
- docs = _.map(docs, doc => ({
- doc: doc.doc._id,
- path: doc.path
- }))
- files = _.map(files, file => ({
- file: file.file._id,
- path: file.path,
- url: FileStoreHandler._buildUrl(project_id, file.file._id)
- }))
- return DocumentUpdaterHandler.resyncProjectHistory(
- project_id,
- projectHistoryId,
- docs,
- files,
- callback
- )
- })
- }
- )
- ),
- isPathValidForRootDoc(docPath) {
- let docExtension = path.extname(docPath)
- return validRootDocRegExp.test(docExtension)
- },
- _cleanUpEntity(
- project,
- newProject,
- entity,
- entityType,
- path,
- userId,
- callback
- ) {
- if (callback == null) {
- callback = function(error) {}
- }
- return self._updateProjectStructureWithDeletedEntity(
- project,
- newProject,
- entity,
- entityType,
- path,
- userId,
- function(error) {
- if (error != null) {
- return callback(error)
- }
- if (entityType.indexOf('file') !== -1) {
- return self._cleanUpFile(project, entity, path, userId, callback)
- } else if (entityType.indexOf('doc') !== -1) {
- return self._cleanUpDoc(project, entity, path, userId, callback)
- } else if (entityType.indexOf('folder') !== -1) {
- return self._cleanUpFolder(project, entity, path, userId, callback)
- } else {
- return callback()
- }
- }
- )
- },
- // Note: the _cleanUpEntity code and _updateProjectStructureWithDeletedEntity
- // methods both need to recursively iterate over the entities in folder.
- // These are currently using separate implementations of the recursion. In
- // future, these could be simplified using a common project entity iterator.
- _updateProjectStructureWithDeletedEntity(
- project,
- newProject,
- entity,
- entityType,
- entityPath,
- userId,
- callback
- ) {
- // compute the changes to the project structure
- let changes
- if (callback == null) {
- callback = function(error) {}
- }
- if (entityType.indexOf('file') !== -1) {
- changes = { oldFiles: [{ file: entity, path: entityPath }] }
- } else if (entityType.indexOf('doc') !== -1) {
- changes = { oldDocs: [{ doc: entity, path: entityPath }] }
- } else if (entityType.indexOf('folder') !== -1) {
- changes = { oldDocs: [], oldFiles: [] }
- var _recurseFolder = function(folder, folderPath) {
- for (let doc of Array.from(folder.docs)) {
- changes.oldDocs.push({ doc, path: path.join(folderPath, doc.name) })
- }
- for (let file of Array.from(folder.fileRefs)) {
- changes.oldFiles.push({
- file,
- path: path.join(folderPath, file.name)
- })
- }
- return Array.from(folder.folders).map(childFolder =>
- _recurseFolder(childFolder, path.join(folderPath, childFolder.name))
- )
- }
- _recurseFolder(entity, entityPath)
- }
- // now send the project structure changes to the docupdater
- changes.newProject = newProject
- const project_id = project._id.toString()
- const projectHistoryId = __guard__(
- project.overleaf != null ? project.overleaf.history : undefined,
- x => x.id
- )
- return DocumentUpdaterHandler.updateProjectStructure(
- project_id,
- projectHistoryId,
- userId,
- changes,
- callback
- )
- },
- _cleanUpDoc(project, doc, path, userId, callback) {
- if (callback == null) {
- callback = function(error) {}
- }
- const project_id = project._id.toString()
- const doc_id = doc._id.toString()
- const unsetRootDocIfRequired = callback => {
- if (
- project.rootDoc_id != null &&
- project.rootDoc_id.toString() === doc_id
- ) {
- return this.unsetRootDoc(project_id, callback)
- } else {
- return callback()
- }
- }
- return unsetRootDocIfRequired(function(error) {
- if (error != null) {
- return callback(error)
- }
- return ProjectEntityMongoUpdateHandler._insertDeletedDocReference(
- project._id,
- doc,
- function(error) {
- if (error != null) {
- return callback(error)
- }
- return DocumentUpdaterHandler.deleteDoc(project_id, doc_id, function(
- error
- ) {
- if (error != null) {
- return callback(error)
- }
- return DocstoreManager.deleteDoc(project_id, doc_id, callback)
- })
- }
- )
- })
- },
- _cleanUpFile(project, file, path, userId, callback) {
- if (callback == null) {
- callback = function(error) {}
- }
- return ProjectEntityMongoUpdateHandler._insertDeletedFileReference(
- project._id,
- file,
- callback
- )
- },
- _cleanUpFolder(project, folder, folderPath, userId, callback) {
- if (callback == null) {
- callback = function(error) {}
- }
- const jobs = []
- for (let doc of Array.from(folder.docs)) {
- ;(function(doc) {
- const docPath = path.join(folderPath, doc.name)
- return jobs.push(callback =>
- self._cleanUpDoc(project, doc, docPath, userId, callback)
- )
- })(doc)
- }
- for (let file of Array.from(folder.fileRefs)) {
- ;(function(file) {
- const filePath = path.join(folderPath, file.name)
- return jobs.push(callback =>
- self._cleanUpFile(project, file, filePath, userId, callback)
- )
- })(file)
- }
- for (let childFolder of Array.from(folder.folders)) {
- ;(function(childFolder) {
- folderPath = path.join(folderPath, childFolder.name)
- return jobs.push(callback =>
- self._cleanUpFolder(
- project,
- childFolder,
- folderPath,
- userId,
- callback
- )
- )
- })(childFolder)
- }
- return async.series(jobs, callback)
- }
- }
- function __guard__(value, transform) {
- return typeof value !== 'undefined' && value !== null
- ? transform(value)
- : undefined
- }
|