ProjectEntityUpdateHandler.test.mjs 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284
  1. import { vi, expect } from 'vitest'
  2. import sinon from 'sinon'
  3. import Errors from '../../../../app/src/Features/Errors/Errors.js'
  4. import mongodb from 'mongodb-legacy'
  5. vi.mock('../../../../app/src/Features/Errors/Errors.js', () =>
  6. vi.importActual('../../../../app/src/Features/Errors/Errors.js')
  7. )
  8. const { ObjectId } = mongodb
  9. const MODULE_PATH =
  10. '../../../../app/src/Features/Project/ProjectEntityUpdateHandler'
  11. describe('ProjectEntityUpdateHandler', function () {
  12. const projectId = '4eecb1c1bffa66588e0000a1'
  13. const projectHistoryId = '123456'
  14. const docId = '4eecb1c1bffa66588e0000a2'
  15. const fileId = '4eecaffcbffa66588e000009'
  16. const folderId = '4eecaffcbffa66588e000008'
  17. const newFileId = '4eecaffcbffa66588e000099'
  18. const userId = 1234
  19. beforeEach(async function (ctx) {
  20. ctx.project = {
  21. _id: projectId,
  22. name: 'project name',
  23. overleaf: {
  24. history: {
  25. id: projectHistoryId,
  26. },
  27. },
  28. }
  29. ctx.user = { _id: new ObjectId() }
  30. ctx.DocModel = class Doc {
  31. constructor(options) {
  32. this.name = options.name
  33. this.lines = options.lines
  34. this._id = docId
  35. this.rev = options.rev ?? 0
  36. }
  37. }
  38. ctx.FileModel = class File {
  39. constructor(options) {
  40. this.name = options.name
  41. // use a new id for replacement files
  42. if (this.name === 'dummy-upload-filename') {
  43. this._id = newFileId
  44. } else {
  45. this._id = fileId
  46. }
  47. this.rev = 0
  48. if (options.linkedFileData != null) {
  49. this.linkedFileData = options.linkedFileData
  50. }
  51. if (options.hash != null) {
  52. this.hash = options.hash
  53. }
  54. }
  55. }
  56. ctx.docName = 'doc-name'
  57. ctx.docLines = ['1234', 'abc']
  58. ctx.doc = { _id: new ObjectId(), name: ctx.docName }
  59. ctx.fileName = 'something.jpg'
  60. ctx.fileSystemPath = 'somehintg'
  61. ctx.file = { _id: new ObjectId(), name: ctx.fileName, rev: 2 }
  62. ctx.linkedFileData = { provider: 'url' }
  63. ctx.source = 'editor'
  64. ctx.callback = sinon.stub()
  65. ctx.DocstoreManager = {
  66. promises: {
  67. getDoc: sinon.stub(),
  68. isDocDeleted: sinon.stub(),
  69. updateDoc: sinon.stub(),
  70. deleteDoc: sinon.stub(),
  71. },
  72. }
  73. ctx.DocumentUpdaterHandler = {
  74. promises: {
  75. flushDocToMongo: sinon.stub().resolves(),
  76. flushProjectToMongo: sinon.stub().resolves(),
  77. updateProjectStructure: sinon.stub().resolves(),
  78. setDocument: sinon.stub(),
  79. resyncProjectHistory: sinon.stub().resolves(),
  80. deleteDoc: sinon.stub().resolves(),
  81. },
  82. }
  83. ctx.fs = {
  84. promises: {
  85. unlink: sinon.stub().resolves(),
  86. },
  87. }
  88. ctx.LockManager = {
  89. promises: {
  90. runWithLock: sinon.spy((namespace, id, runner, callback) =>
  91. runner(callback)
  92. ),
  93. },
  94. withTimeout: sinon.stub().returns(ctx.LockManager),
  95. }
  96. ctx.ProjectModel = {
  97. updateOne: sinon.stub().returns({ exec: sinon.stub().resolves() }),
  98. }
  99. ctx.ProjectGetter = {
  100. promises: {
  101. getProject: sinon.stub(),
  102. },
  103. }
  104. ctx.ProjectLocator = {
  105. promises: {
  106. findElement: sinon.stub(),
  107. findElementByPath: sinon.stub(),
  108. },
  109. }
  110. ctx.ProjectUpdater = {
  111. promises: {
  112. markAsUpdated: sinon.stub().resolves(),
  113. },
  114. }
  115. ctx.ProjectEntityHandler = {
  116. getAllEntitiesFromProject: sinon.stub(),
  117. promises: {
  118. getDoc: sinon.stub(),
  119. getDocPathByProjectIdAndDocId: sinon.stub(),
  120. },
  121. }
  122. ctx.ProjectEntityMongoUpdateHandler = {
  123. promises: {
  124. addDoc: sinon.stub(),
  125. addFile: sinon.stub(),
  126. addFolder: sinon.stub(),
  127. _confirmFolder: sinon.stub(),
  128. _putElement: sinon.stub(),
  129. replaceFileWithNew: sinon.stub(),
  130. mkdirp: sinon.stub(),
  131. moveEntity: sinon.stub(),
  132. renameEntity: sinon.stub().resolves({}),
  133. deleteEntity: sinon.stub(),
  134. replaceDocWithFile: sinon.stub(),
  135. replaceFileWithDoc: sinon.stub(),
  136. },
  137. }
  138. ctx.TpdsUpdateSender = {
  139. promises: {
  140. addFile: sinon.stub().resolves(),
  141. addDoc: sinon.stub(),
  142. deleteEntity: sinon.stub().resolves(),
  143. moveEntity: sinon.stub().resolves(),
  144. },
  145. }
  146. ctx.FileStoreHandler = {
  147. promises: {
  148. uploadFileFromDisk: sinon.stub(),
  149. },
  150. }
  151. ctx.FileWriter = {
  152. promises: {
  153. writeLinesToDisk: sinon.stub(),
  154. },
  155. }
  156. ctx.EditorRealTimeController = {
  157. emitToRoom: sinon.stub(),
  158. }
  159. ctx.ProjectOptionsHandler = {
  160. setHistoryRangesSupport: sinon.stub().resolves(),
  161. }
  162. vi.doMock('@overleaf/settings', () => ({
  163. default: { validRootDocExtensions: ['tex'] },
  164. }))
  165. vi.doMock('fs', () => ({
  166. default: ctx.fs,
  167. }))
  168. vi.doMock('../../../../app/src/models/Doc', () => ({
  169. Doc: ctx.DocModel,
  170. }))
  171. vi.doMock('../../../../app/src/Features/Docstore/DocstoreManager', () => ({
  172. default: ctx.DocstoreManager,
  173. }))
  174. vi.doMock(
  175. '../../../../app/src/Features/DocumentUpdater/DocumentUpdaterHandler',
  176. () => ({
  177. default: ctx.DocumentUpdaterHandler,
  178. })
  179. )
  180. vi.doMock('../../../../app/src/models/File', () => ({
  181. File: ctx.FileModel,
  182. }))
  183. vi.doMock(
  184. '../../../../app/src/Features/FileStore/FileStoreHandler',
  185. () => ({
  186. default: ctx.FileStoreHandler,
  187. })
  188. )
  189. vi.doMock('../../../../app/src/infrastructure/LockManager', () => ({
  190. default: ctx.LockManager,
  191. }))
  192. vi.doMock('../../../../app/src/models/Project', () => ({
  193. Project: ctx.ProjectModel,
  194. }))
  195. vi.doMock('../../../../app/src/Features/Project/ProjectGetter', () => ({
  196. default: ctx.ProjectGetter,
  197. }))
  198. vi.doMock('../../../../app/src/Features/Project/ProjectLocator', () => ({
  199. default: ctx.ProjectLocator,
  200. }))
  201. vi.doMock(
  202. '../../../../app/src/Features/Project/ProjectUpdateHandler',
  203. () => ({
  204. default: ctx.ProjectUpdater,
  205. })
  206. )
  207. vi.doMock(
  208. '../../../../app/src/Features/Project/ProjectEntityHandler',
  209. () => ({
  210. default: ctx.ProjectEntityHandler,
  211. })
  212. )
  213. vi.doMock(
  214. '../../../../app/src/Features/Project/ProjectEntityMongoUpdateHandler',
  215. () => ({
  216. default: ctx.ProjectEntityMongoUpdateHandler,
  217. })
  218. )
  219. vi.doMock(
  220. '../../../../app/src/Features/Project/ProjectOptionsHandler',
  221. () => ({
  222. default: ctx.ProjectOptionsHandler,
  223. })
  224. )
  225. vi.doMock(
  226. '../../../../app/src/Features/ThirdPartyDataStore/TpdsUpdateSender',
  227. () => ({
  228. default: ctx.TpdsUpdateSender,
  229. })
  230. )
  231. vi.doMock(
  232. '../../../../app/src/Features/Editor/EditorRealTimeController',
  233. () => ({
  234. default: ctx.EditorRealTimeController,
  235. })
  236. )
  237. vi.doMock('../../../../app/src/infrastructure/FileWriter', () => ({
  238. default: ctx.FileWriter,
  239. }))
  240. ctx.ProjectEntityUpdateHandler = (await import(MODULE_PATH)).default
  241. })
  242. describe('updateDocLines', function () {
  243. beforeEach(function (ctx) {
  244. ctx.path = '/somewhere/something.tex'
  245. ctx.doc = {
  246. _id: docId,
  247. }
  248. ctx.version = 42
  249. ctx.ranges = { mock: 'ranges' }
  250. ctx.lastUpdatedAt = new Date().getTime()
  251. ctx.lastUpdatedBy = 'fake-last-updater-id'
  252. ctx.parentFolder = { _id: new ObjectId() }
  253. ctx.DocstoreManager.promises.isDocDeleted.resolves(false)
  254. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  255. ctx.ProjectLocator.promises.findElement.resolves({
  256. element: ctx.doc,
  257. path: {
  258. fileSystem: ctx.path,
  259. },
  260. folder: ctx.parentFolder,
  261. })
  262. ctx.TpdsUpdateSender.promises.addDoc.resolves()
  263. })
  264. describe('when the doc has been modified', function () {
  265. beforeEach(async function (ctx) {
  266. ctx.DocstoreManager.promises.updateDoc.resolves({
  267. modified: true,
  268. rev: (ctx.rev = 5),
  269. })
  270. await ctx.ProjectEntityUpdateHandler.promises.updateDocLines(
  271. projectId,
  272. docId,
  273. ctx.docLines,
  274. ctx.version,
  275. ctx.ranges,
  276. ctx.lastUpdatedAt,
  277. ctx.lastUpdatedBy
  278. )
  279. })
  280. it('should get the project with very few fields', function (ctx) {
  281. ctx.ProjectGetter.promises.getProject
  282. .calledWith(projectId, {
  283. name: true,
  284. rootFolder: true,
  285. })
  286. .should.equal(true)
  287. })
  288. it('should find the doc', function (ctx) {
  289. ctx.ProjectLocator.promises.findElement
  290. .calledWith({
  291. project: ctx.project,
  292. type: 'docs',
  293. element_id: docId,
  294. })
  295. .should.equal(true)
  296. })
  297. it('should update the doc in the docstore', function (ctx) {
  298. ctx.DocstoreManager.promises.updateDoc
  299. .calledWith(projectId, docId, ctx.docLines, ctx.version, ctx.ranges)
  300. .should.equal(true)
  301. })
  302. it('should mark the project as updated', function (ctx) {
  303. sinon.assert.calledWith(
  304. ctx.ProjectUpdater.promises.markAsUpdated,
  305. projectId,
  306. ctx.lastUpdatedAt,
  307. ctx.lastUpdatedBy
  308. )
  309. })
  310. it('should send the doc to the TPDS', function (ctx) {
  311. ctx.TpdsUpdateSender.promises.addDoc.should.have.been.calledWith({
  312. projectId,
  313. projectName: ctx.project.name,
  314. docId,
  315. rev: ctx.rev,
  316. path: ctx.path,
  317. folderId: ctx.parentFolder._id,
  318. })
  319. })
  320. })
  321. describe('when the doc has not been modified', function () {
  322. beforeEach(async function (ctx) {
  323. ctx.DocstoreManager.promises.updateDoc.resolves({
  324. modified: false,
  325. rev: (ctx.rev = 5),
  326. })
  327. await ctx.ProjectEntityUpdateHandler.promises.updateDocLines(
  328. projectId,
  329. docId,
  330. ctx.docLines,
  331. ctx.version,
  332. ctx.ranges,
  333. ctx.lastUpdatedAt,
  334. ctx.lastUpdatedBy
  335. )
  336. })
  337. it('should not mark the project as updated', function (ctx) {
  338. ctx.ProjectUpdater.promises.markAsUpdated.called.should.equal(false)
  339. })
  340. it('should not send the doc the to the TPDS', function (ctx) {
  341. ctx.TpdsUpdateSender.promises.addDoc.called.should.equal(false)
  342. })
  343. })
  344. describe('when the doc has been deleted', function () {
  345. beforeEach(async function (ctx) {
  346. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  347. ctx.ProjectLocator.promises.findElement.rejects(
  348. new Errors.NotFoundError()
  349. )
  350. ctx.DocstoreManager.promises.isDocDeleted.resolves(true)
  351. ctx.DocstoreManager.promises.updateDoc.resolves({})
  352. await ctx.ProjectEntityUpdateHandler.promises.updateDocLines(
  353. projectId,
  354. docId,
  355. ctx.docLines,
  356. ctx.version,
  357. ctx.ranges,
  358. ctx.lastUpdatedAt,
  359. ctx.lastUpdatedBy
  360. )
  361. })
  362. it('should update the doc in the docstore', function (ctx) {
  363. ctx.DocstoreManager.promises.updateDoc
  364. .calledWith(projectId, docId, ctx.docLines, ctx.version, ctx.ranges)
  365. .should.equal(true)
  366. })
  367. it('should not mark the project as updated', function (ctx) {
  368. ctx.ProjectUpdater.promises.markAsUpdated.called.should.equal(false)
  369. })
  370. it('should not send the doc the to the TPDS', function (ctx) {
  371. ctx.TpdsUpdateSender.promises.addDoc.called.should.equal(false)
  372. })
  373. })
  374. describe('when projects and docs collection are de-synced', function () {
  375. beforeEach(async function (ctx) {
  376. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  377. // The doc is not in the file-tree, but also not marked as deleted.
  378. // This should not happen, but web should handle it.
  379. ctx.ProjectLocator.promises.findElement.rejects(
  380. new Errors.NotFoundError()
  381. )
  382. ctx.DocstoreManager.promises.isDocDeleted.resolves(false)
  383. ctx.DocstoreManager.promises.updateDoc.resolves({})
  384. await ctx.ProjectEntityUpdateHandler.promises.updateDocLines(
  385. projectId,
  386. docId,
  387. ctx.docLines,
  388. ctx.version,
  389. ctx.ranges,
  390. ctx.lastUpdatedAt,
  391. ctx.lastUpdatedBy
  392. )
  393. })
  394. it('should update the doc in the docstore', function (ctx) {
  395. ctx.DocstoreManager.promises.updateDoc
  396. .calledWith(projectId, docId, ctx.docLines, ctx.version, ctx.ranges)
  397. .should.equal(true)
  398. })
  399. it('should not mark the project as updated', function (ctx) {
  400. ctx.ProjectUpdater.promises.markAsUpdated.called.should.equal(false)
  401. })
  402. it('should not send the doc the to the TPDS', function (ctx) {
  403. ctx.TpdsUpdateSender.promises.addDoc.called.should.equal(false)
  404. })
  405. })
  406. describe('when the doc is not related to the project', function () {
  407. let updateDocLinesPromise
  408. beforeEach(function (ctx) {
  409. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  410. ctx.ProjectLocator.promises.findElement.rejects(
  411. new Errors.NotFoundError()
  412. )
  413. ctx.DocstoreManager.promises.isDocDeleted.rejects(
  414. new Errors.NotFoundError()
  415. )
  416. updateDocLinesPromise =
  417. ctx.ProjectEntityUpdateHandler.promises.updateDocLines(
  418. projectId,
  419. docId,
  420. ctx.docLines,
  421. ctx.version,
  422. ctx.ranges,
  423. ctx.lastUpdatedAt,
  424. ctx.lastUpdatedBy
  425. )
  426. })
  427. it('should return a not found error', async function () {
  428. let error
  429. try {
  430. await updateDocLinesPromise
  431. } catch (err) {
  432. error = err
  433. }
  434. expect(error).to.be.instanceOf(Errors.NotFoundError)
  435. })
  436. it('should not update the doc', async function (ctx) {
  437. let error
  438. try {
  439. await updateDocLinesPromise
  440. } catch (err) {
  441. error = err
  442. }
  443. expect(error).to.exist
  444. ctx.DocstoreManager.promises.updateDoc.called.should.equal(false)
  445. })
  446. it('should not send the doc the to the TPDS', async function (ctx) {
  447. let error
  448. try {
  449. await updateDocLinesPromise
  450. } catch (err) {
  451. error = err
  452. }
  453. expect(error).to.exist
  454. ctx.TpdsUpdateSender.promises.addDoc.called.should.equal(false)
  455. })
  456. })
  457. describe('when the project is not found', function () {
  458. let error
  459. beforeEach(async function (ctx) {
  460. ctx.ProjectGetter.promises.getProject.rejects(
  461. new Errors.NotFoundError()
  462. )
  463. try {
  464. await ctx.ProjectEntityUpdateHandler.promises.updateDocLines(
  465. projectId,
  466. docId,
  467. ctx.docLines,
  468. ctx.version,
  469. ctx.ranges,
  470. ctx.lastUpdatedAt,
  471. ctx.lastUpdatedBy
  472. )
  473. } catch (err) {
  474. error = err
  475. }
  476. })
  477. it('should return a not found error', async function () {
  478. expect(error).to.be.instanceOf(Errors.NotFoundError)
  479. })
  480. it('should not update the doc', async function (ctx) {
  481. ctx.DocstoreManager.promises.updateDoc.called.should.equal(false)
  482. })
  483. it('should not send the doc the to the TPDS', function (ctx) {
  484. ctx.TpdsUpdateSender.promises.addDoc.called.should.equal(false)
  485. })
  486. })
  487. })
  488. describe('setRootDoc', function () {
  489. beforeEach(function (ctx) {
  490. ctx.rootDocId = 'root-doc-id-123123'
  491. })
  492. it('should call Project.updateOne when the doc exists and has a valid extension', async function (ctx) {
  493. ctx.ProjectEntityHandler.promises.getDocPathByProjectIdAndDocId.resolves(
  494. `/main.tex`
  495. )
  496. await ctx.ProjectEntityUpdateHandler.promises.setRootDoc(
  497. projectId,
  498. ctx.rootDocId
  499. )
  500. ctx.ProjectModel.updateOne
  501. .calledWith({ _id: projectId }, { rootDoc_id: ctx.rootDocId })
  502. .should.equal(true)
  503. })
  504. it("should not call Project.updateOne when the doc doesn't exist", async function (ctx) {
  505. ctx.ProjectEntityHandler.promises.getDocPathByProjectIdAndDocId.rejects(
  506. Errors.NotFoundError
  507. )
  508. let error
  509. try {
  510. await ctx.ProjectEntityUpdateHandler.promises.setRootDoc(
  511. projectId,
  512. ctx.rootDocId
  513. )
  514. } catch (err) {
  515. error = err
  516. }
  517. expect(error).to.exist
  518. ctx.ProjectModel.updateOne
  519. .calledWith({ _id: projectId }, { rootDoc_id: ctx.rootDocId })
  520. .should.equal(false)
  521. })
  522. it('should call the callback with an UnsupportedFileTypeError when the doc has an unaccepted file extension', function (ctx) {
  523. ctx.ProjectEntityHandler.promises.getDocPathByProjectIdAndDocId.resolves(
  524. `/foo/bar.baz`
  525. )
  526. ctx.ProjectEntityUpdateHandler.setRootDoc(
  527. projectId,
  528. ctx.rootDocId,
  529. error => {
  530. expect(error).to.be.an.instanceof(Errors.UnsupportedFileTypeError)
  531. }
  532. )
  533. })
  534. })
  535. describe('unsetRootDoc', function () {
  536. it('should call Project.updateOne', async function (ctx) {
  537. await ctx.ProjectEntityUpdateHandler.promises.unsetRootDoc(projectId)
  538. ctx.ProjectModel.updateOne
  539. .calledWith({ _id: projectId }, { $unset: { rootDoc_id: true } })
  540. .should.equal(true)
  541. })
  542. })
  543. describe('addDoc', function () {
  544. describe('adding a doc', function () {
  545. beforeEach(async function (ctx) {
  546. ctx.path = '/path/to/doc'
  547. ctx.rev = 5
  548. ctx.newDoc = new ctx.DocModel({
  549. name: ctx.docName,
  550. lines: undefined,
  551. _id: docId,
  552. rev: ctx.rev,
  553. })
  554. ctx.DocstoreManager.promises.updateDoc.resolves({
  555. lines: false,
  556. rev: ctx.rev,
  557. })
  558. ctx.TpdsUpdateSender.promises.addDoc.resolves()
  559. ctx.ProjectEntityMongoUpdateHandler.promises.addDoc.resolves({
  560. result: { path: { fileSystem: ctx.path } },
  561. project: ctx.project,
  562. })
  563. await ctx.ProjectEntityUpdateHandler.promises.addDoc(
  564. projectId,
  565. docId,
  566. ctx.docName,
  567. ctx.docLines,
  568. userId,
  569. ctx.source
  570. )
  571. })
  572. it('creates the doc without history', function (ctx) {
  573. ctx.DocstoreManager.promises.updateDoc
  574. .calledWith(projectId, docId, ctx.docLines, 0, {})
  575. .should.equal(true)
  576. })
  577. it('sends the change in project structure to the doc updater', function (ctx) {
  578. const newDocs = [
  579. {
  580. doc: ctx.newDoc,
  581. path: ctx.path,
  582. docLines: ctx.docLines.join('\n'),
  583. ranges: {},
  584. },
  585. ]
  586. ctx.DocumentUpdaterHandler.promises.updateProjectStructure.should.have.been.calledWith(
  587. projectId,
  588. projectHistoryId,
  589. userId,
  590. {
  591. newDocs,
  592. newProject: ctx.project,
  593. },
  594. ctx.source
  595. )
  596. })
  597. })
  598. describe('adding a doc with an invalid name', function () {
  599. beforeEach(function (ctx) {
  600. ctx.path = '/path/to/doc'
  601. ctx.newDoc = { _id: docId }
  602. })
  603. it('returns an error', async function (ctx) {
  604. let error
  605. try {
  606. await ctx.ProjectEntityUpdateHandler.promises.addDoc(
  607. projectId,
  608. folderId,
  609. `*${ctx.docName}`,
  610. ctx.docLines,
  611. userId,
  612. ctx.source
  613. )
  614. } catch (err) {
  615. error = err
  616. }
  617. expect(error).to.be.instanceOf(Errors.InvalidNameError)
  618. })
  619. })
  620. })
  621. describe('addFile', function () {
  622. describe('adding a file', function () {
  623. beforeEach(async function (ctx) {
  624. ctx.path = '/path/to/file'
  625. ctx.newFile = {
  626. _id: fileId,
  627. hash: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
  628. rev: 0,
  629. name: ctx.fileName,
  630. linkedFileData: ctx.linkedFileData,
  631. }
  632. ctx.FileStoreHandler.promises.uploadFileFromDisk.resolves({
  633. fileRef: ctx.newFile,
  634. createdBlob: true,
  635. })
  636. ctx.TpdsUpdateSender.promises.addFile.resolves()
  637. ctx.ProjectEntityMongoUpdateHandler.promises.addFile.resolves({
  638. result: { path: { fileSystem: ctx.path } },
  639. project: ctx.project,
  640. })
  641. await ctx.ProjectEntityUpdateHandler.promises.addFile(
  642. projectId,
  643. folderId,
  644. ctx.fileName,
  645. ctx.fileSystemPath,
  646. ctx.linkedFileData,
  647. userId,
  648. ctx.source
  649. )
  650. })
  651. it('updates the file in the filestore', function (ctx) {
  652. ctx.FileStoreHandler.promises.uploadFileFromDisk
  653. .calledWith(
  654. projectId,
  655. { name: ctx.fileName, linkedFileData: ctx.linkedFileData },
  656. ctx.fileSystemPath
  657. )
  658. .should.equal(true)
  659. })
  660. it('updates the file in mongo', function (ctx) {
  661. const fileMatcher = sinon.match(file => {
  662. return file.name === ctx.fileName
  663. })
  664. ctx.ProjectEntityMongoUpdateHandler.promises.addFile
  665. .calledWithMatch(projectId, folderId, fileMatcher)
  666. .should.equal(true)
  667. })
  668. it('notifies the tpds', function (ctx) {
  669. ctx.TpdsUpdateSender.promises.addFile
  670. .calledWith({
  671. projectId,
  672. historyId: ctx.project.overleaf.history.id,
  673. projectName: ctx.project.name,
  674. fileId,
  675. hash: ctx.newFile.hash,
  676. rev: 0,
  677. path: ctx.path,
  678. folderId,
  679. })
  680. .should.equal(true)
  681. })
  682. it('sends the change in project structure to the doc updater', function (ctx) {
  683. const newFiles = [
  684. {
  685. file: ctx.newFile,
  686. path: ctx.path,
  687. createdBlob: true,
  688. },
  689. ]
  690. ctx.DocumentUpdaterHandler.promises.updateProjectStructure.should.have.been.calledWith(
  691. projectId,
  692. projectHistoryId,
  693. userId,
  694. {
  695. newFiles,
  696. newProject: ctx.project,
  697. },
  698. ctx.source
  699. )
  700. })
  701. })
  702. describe('adding a file with an invalid name', function () {
  703. beforeEach(function (ctx) {
  704. ctx.path = '/path/to/file'
  705. ctx.newFile = {
  706. _id: fileId,
  707. hash: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  708. rev: 0,
  709. name: ctx.fileName,
  710. linkedFileData: ctx.linkedFileData,
  711. }
  712. ctx.TpdsUpdateSender.promises.addFile.resolves()
  713. ctx.ProjectEntityMongoUpdateHandler.promises.addFile.resolves({
  714. result: { path: { fileSystem: ctx.path } },
  715. project: ctx.project,
  716. })
  717. })
  718. it('returns an error', async function (ctx) {
  719. let error
  720. try {
  721. await ctx.ProjectEntityUpdateHandler.promises.addFile(
  722. projectId,
  723. folderId,
  724. `*${ctx.fileName}`,
  725. ctx.fileSystemPath,
  726. ctx.linkedFileData,
  727. userId,
  728. ctx.source
  729. )
  730. } catch (err) {
  731. error = err
  732. }
  733. expect(error).to.be.instanceOf(Errors.InvalidNameError)
  734. })
  735. })
  736. })
  737. describe('upsertDoc', function () {
  738. describe('upserting into an invalid folder', function () {
  739. beforeEach(function (ctx) {
  740. ctx.ProjectLocator.promises.findElement.resolves({ element: null })
  741. })
  742. it('returns an error', async function (ctx) {
  743. let error
  744. try {
  745. await ctx.ProjectEntityUpdateHandler.promises.upsertDoc(
  746. projectId,
  747. folderId,
  748. ctx.docName,
  749. ctx.docLines,
  750. ctx.source,
  751. userId
  752. )
  753. } catch (err) {
  754. error = err
  755. }
  756. expect(error).to.be.instanceOf(Error)
  757. })
  758. })
  759. describe('updating an existing doc', function () {
  760. let upsertDocResponse
  761. beforeEach(async function (ctx) {
  762. ctx.existingDoc = { _id: docId, name: ctx.docName }
  763. ctx.existingFile = {
  764. _id: fileId,
  765. name: ctx.fileName,
  766. hash: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  767. }
  768. ctx.folder = {
  769. _id: folderId,
  770. docs: [ctx.existingDoc],
  771. fileRefs: [ctx.existingFile],
  772. }
  773. ctx.ProjectLocator.promises.findElement.resolves({
  774. element: ctx.folder,
  775. })
  776. ctx.DocumentUpdaterHandler.promises.setDocument.resolves()
  777. upsertDocResponse =
  778. await ctx.ProjectEntityUpdateHandler.promises.upsertDoc(
  779. projectId,
  780. folderId,
  781. ctx.docName,
  782. ctx.docLines,
  783. ctx.source,
  784. userId
  785. )
  786. })
  787. it('tries to find the folder', function (ctx) {
  788. ctx.ProjectLocator.promises.findElement
  789. .calledWith({
  790. project_id: projectId,
  791. element_id: folderId,
  792. type: 'folder',
  793. })
  794. .should.equal(true)
  795. })
  796. it('updates the doc contents', function (ctx) {
  797. ctx.DocumentUpdaterHandler.promises.setDocument
  798. .calledWith(
  799. projectId,
  800. ctx.existingDoc._id,
  801. userId,
  802. ctx.docLines,
  803. ctx.source
  804. )
  805. .should.equal(true)
  806. })
  807. it('returns the doc', function (ctx) {
  808. expect(upsertDocResponse.isNew).to.equal(false)
  809. expect(upsertDocResponse.doc).to.eql(ctx.existingDoc)
  810. })
  811. })
  812. describe('creating a new doc', function () {
  813. let upsertDocResponse
  814. beforeEach(async function (ctx) {
  815. ctx.folder = { _id: folderId, docs: [], fileRefs: [] }
  816. ctx.newDoc = { _id: docId }
  817. ctx.ProjectLocator.promises.findElement.resolves({
  818. element: ctx.folder,
  819. })
  820. ctx.ProjectEntityUpdateHandler.promises.addDocWithRanges = {
  821. withoutLock: sinon.stub().resolves({ doc: ctx.newDoc }),
  822. }
  823. upsertDocResponse =
  824. await ctx.ProjectEntityUpdateHandler.promises.upsertDoc(
  825. projectId,
  826. folderId,
  827. ctx.docName,
  828. ctx.docLines,
  829. ctx.source,
  830. userId
  831. )
  832. })
  833. it('tries to find the folder', function (ctx) {
  834. ctx.ProjectLocator.promises.findElement
  835. .calledWith({
  836. project_id: projectId,
  837. element_id: folderId,
  838. type: 'folder',
  839. })
  840. .should.equal(true)
  841. })
  842. it('adds the doc', function (ctx) {
  843. ctx.ProjectEntityUpdateHandler.promises.addDocWithRanges.withoutLock.should.have.been.calledWith(
  844. projectId,
  845. folderId,
  846. ctx.docName,
  847. ctx.docLines,
  848. {},
  849. userId,
  850. ctx.source
  851. )
  852. })
  853. it('returns the doc', function (ctx) {
  854. expect(upsertDocResponse.isNew).to.equal(true)
  855. expect(upsertDocResponse.doc).to.equal(ctx.newDoc)
  856. })
  857. })
  858. describe('upserting a new doc with an invalid name', function () {
  859. beforeEach(function (ctx) {
  860. ctx.folder = { _id: folderId, docs: [], fileRefs: [] }
  861. ctx.newDoc = { _id: docId }
  862. ctx.ProjectLocator.promises.findElement.resolves({
  863. element: ctx.folder,
  864. })
  865. ctx.ProjectEntityUpdateHandler.promises.addDocWithRanges = {
  866. withoutLock: sinon.stub().resolves({ doc: ctx.newDoc }),
  867. }
  868. })
  869. it('returns an error', async function (ctx) {
  870. let error
  871. try {
  872. await ctx.ProjectEntityUpdateHandler.promises.upsertDoc(
  873. projectId,
  874. folderId,
  875. `*${ctx.docName}`,
  876. ctx.docLines,
  877. ctx.source,
  878. userId
  879. )
  880. } catch (err) {
  881. error = err
  882. }
  883. expect(error).to.be.instanceOf(Errors.InvalidNameError)
  884. })
  885. })
  886. describe('upserting a doc on top of a file', function () {
  887. beforeEach(async function (ctx) {
  888. ctx.newProject = {
  889. name: 'new project',
  890. overleaf: { history: { id: projectHistoryId } },
  891. }
  892. ctx.existingFile = { _id: fileId, name: 'foo.tex', rev: 12 }
  893. ctx.folder = { _id: folderId, docs: [], fileRefs: [ctx.existingFile] }
  894. ctx.newDoc = { _id: docId }
  895. ctx.docLines = ['line one', 'line two']
  896. ctx.folderPath = '/path/to/folder'
  897. ctx.filePath = '/path/to/folder/foo.tex'
  898. ctx.ProjectLocator.promises.findElement
  899. .withArgs({
  900. project_id: projectId,
  901. element_id: ctx.folder._id,
  902. type: 'folder',
  903. })
  904. .resolves({
  905. element: ctx.folder,
  906. path: {
  907. fileSystem: ctx.folderPath,
  908. },
  909. })
  910. ctx.DocstoreManager.promises.updateDoc.resolves({ rev: null })
  911. ctx.ProjectEntityMongoUpdateHandler.promises.replaceFileWithDoc.resolves(
  912. ctx.newProject
  913. )
  914. ctx.TpdsUpdateSender.promises.addDoc.resolves()
  915. await ctx.ProjectEntityUpdateHandler.promises.upsertDoc(
  916. projectId,
  917. folderId,
  918. 'foo.tex',
  919. ctx.docLines,
  920. ctx.source,
  921. userId
  922. )
  923. })
  924. it('notifies docstore of the new doc', function (ctx) {
  925. expect(ctx.DocstoreManager.promises.updateDoc).to.have.been.calledWith(
  926. projectId,
  927. ctx.newDoc._id,
  928. ctx.docLines
  929. )
  930. })
  931. it('adds the new doc and removes the file in one go', function (ctx) {
  932. expect(
  933. ctx.ProjectEntityMongoUpdateHandler.promises.replaceFileWithDoc
  934. ).to.have.been.calledWithMatch(
  935. projectId,
  936. ctx.existingFile._id,
  937. ctx.newDoc
  938. )
  939. })
  940. it('sends the doc to TPDS', function (ctx) {
  941. expect(ctx.TpdsUpdateSender.promises.addDoc).to.have.been.calledWith({
  942. projectId,
  943. docId: ctx.newDoc._id,
  944. path: ctx.filePath,
  945. projectName: ctx.newProject.name,
  946. rev: ctx.existingFile.rev + 1,
  947. folderId,
  948. })
  949. })
  950. it('sends the updates to the doc updater', function (ctx) {
  951. const oldFiles = [
  952. {
  953. file: ctx.existingFile,
  954. path: ctx.filePath,
  955. },
  956. ]
  957. const newDocs = [
  958. {
  959. doc: sinon.match(ctx.newDoc),
  960. path: ctx.filePath,
  961. docLines: ctx.docLines.join('\n'),
  962. },
  963. ]
  964. expect(
  965. ctx.DocumentUpdaterHandler.promises.updateProjectStructure
  966. ).to.have.been.calledWith(
  967. projectId,
  968. projectHistoryId,
  969. userId,
  970. {
  971. oldFiles,
  972. newDocs,
  973. newProject: ctx.newProject,
  974. },
  975. ctx.source
  976. )
  977. })
  978. it('should notify everyone of the file deletion', function (ctx) {
  979. expect(ctx.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
  980. projectId,
  981. 'removeEntity',
  982. ctx.existingFile._id,
  983. 'convertFileToDoc'
  984. )
  985. })
  986. })
  987. })
  988. describe('upsertFile', function () {
  989. beforeEach(function (ctx) {
  990. ctx.FileStoreHandler.promises.uploadFileFromDisk.resolves({
  991. fileRef: ctx.file,
  992. createdBlob: true,
  993. })
  994. })
  995. describe('upserting into an invalid folder', function () {
  996. beforeEach(function (ctx) {
  997. ctx.ProjectLocator.promises.findElement.resolves({ element: null })
  998. })
  999. it('returns an error', async function (ctx) {
  1000. let error
  1001. try {
  1002. await ctx.ProjectEntityUpdateHandler.promises.upsertFile(
  1003. projectId,
  1004. folderId,
  1005. ctx.fileName,
  1006. ctx.fileSystemPath,
  1007. ctx.linkedFileData,
  1008. userId,
  1009. ctx.source
  1010. )
  1011. } catch (err) {
  1012. error = err
  1013. }
  1014. expect(error).to.be.instanceOf(Error)
  1015. })
  1016. })
  1017. describe('updating an existing file', function () {
  1018. let upsertFileResult
  1019. beforeEach(async function (ctx) {
  1020. ctx.existingFile = { _id: fileId, name: ctx.fileName, rev: 1 }
  1021. ctx.newFile = {
  1022. _id: new ObjectId(),
  1023. name: ctx.fileName,
  1024. rev: 3,
  1025. hash: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  1026. }
  1027. ctx.folder = { _id: folderId, fileRefs: [ctx.existingFile], docs: [] }
  1028. ctx.ProjectLocator.promises.findElement.resolves({
  1029. element: ctx.folder,
  1030. })
  1031. ctx.newProject = 'new-project-stub'
  1032. ctx.ProjectEntityMongoUpdateHandler.promises.replaceFileWithNew.resolves(
  1033. {
  1034. oldFileRef: ctx.existingFile,
  1035. project: ctx.project,
  1036. path: { fileSystem: ctx.fileSystemPath },
  1037. newProject: ctx.newProject,
  1038. newFileRef: ctx.newFile,
  1039. }
  1040. )
  1041. upsertFileResult =
  1042. await ctx.ProjectEntityUpdateHandler.promises.upsertFile(
  1043. projectId,
  1044. folderId,
  1045. ctx.fileName,
  1046. ctx.fileSystemPath,
  1047. ctx.linkedFileData,
  1048. userId,
  1049. ctx.source
  1050. )
  1051. })
  1052. it('uploads a new version of the file', function (ctx) {
  1053. ctx.FileStoreHandler.promises.uploadFileFromDisk.should.have.been.calledWith(
  1054. projectId,
  1055. {
  1056. name: ctx.fileName,
  1057. linkedFileData: ctx.linkedFileData,
  1058. },
  1059. ctx.fileSystemPath
  1060. )
  1061. })
  1062. it('replaces the file in mongo', function (ctx) {
  1063. ctx.ProjectEntityMongoUpdateHandler.promises.replaceFileWithNew.should.have.been.calledWith(
  1064. projectId,
  1065. ctx.existingFile._id,
  1066. ctx.file,
  1067. userId
  1068. )
  1069. })
  1070. it('notifies the tpds', function (ctx) {
  1071. ctx.TpdsUpdateSender.promises.addFile.should.have.been.calledWith({
  1072. projectId,
  1073. historyId: ctx.project.overleaf.history.id,
  1074. projectName: ctx.project.name,
  1075. fileId: ctx.newFile._id,
  1076. hash: ctx.newFile.hash,
  1077. rev: ctx.newFile.rev,
  1078. path: ctx.fileSystemPath,
  1079. folderId,
  1080. })
  1081. })
  1082. it('updates the project structure in the doc updater', function (ctx) {
  1083. const oldFiles = [
  1084. {
  1085. file: ctx.existingFile,
  1086. path: ctx.fileSystemPath,
  1087. },
  1088. ]
  1089. const newFiles = [
  1090. {
  1091. file: ctx.newFile,
  1092. path: ctx.fileSystemPath,
  1093. createdBlob: true,
  1094. },
  1095. ]
  1096. ctx.DocumentUpdaterHandler.promises.updateProjectStructure.should.have.been.calledWith(
  1097. projectId,
  1098. projectHistoryId,
  1099. userId,
  1100. {
  1101. oldFiles,
  1102. newFiles,
  1103. newProject: ctx.newProject,
  1104. },
  1105. ctx.source
  1106. )
  1107. })
  1108. it('returns the file', function (ctx) {
  1109. expect(upsertFileResult.isNew).to.be.false
  1110. expect(upsertFileResult.fileRef.toString()).to.eql(
  1111. ctx.existingFile.toString()
  1112. )
  1113. })
  1114. })
  1115. describe('creating a new file', function () {
  1116. let upsertFileResult
  1117. beforeEach(async function (ctx) {
  1118. ctx.folder = { _id: folderId, fileRefs: [], docs: [] }
  1119. ctx.newFile = {
  1120. _id: fileId,
  1121. hash: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
  1122. }
  1123. ctx.ProjectLocator.promises.findElement.resolves({
  1124. element: ctx.folder,
  1125. })
  1126. ctx.FileStoreHandler.promises.uploadFileFromDisk.resolves({
  1127. fileRef: ctx.newFile,
  1128. createdBlob: true,
  1129. })
  1130. ctx.ProjectEntityUpdateHandler.promises.addFile = {
  1131. mainTask: sinon.stub().resolves(ctx.newFile),
  1132. }
  1133. upsertFileResult =
  1134. await ctx.ProjectEntityUpdateHandler.promises.upsertFile(
  1135. projectId,
  1136. folderId,
  1137. ctx.fileName,
  1138. ctx.fileSystemPath,
  1139. ctx.linkedFileData,
  1140. userId,
  1141. ctx.source
  1142. )
  1143. })
  1144. it('tries to find the folder', function (ctx) {
  1145. ctx.ProjectLocator.promises.findElement.should.have.been.calledWith({
  1146. project_id: projectId,
  1147. element_id: folderId,
  1148. type: 'folder',
  1149. })
  1150. })
  1151. it('adds the file', function (ctx) {
  1152. expect(
  1153. ctx.ProjectEntityUpdateHandler.promises.addFile.mainTask
  1154. ).to.have.been.calledWith({
  1155. projectId,
  1156. folderId,
  1157. userId,
  1158. fileRef: ctx.newFile,
  1159. source: ctx.source,
  1160. createdBlob: true,
  1161. })
  1162. })
  1163. it('returns the file', function (ctx) {
  1164. expect(upsertFileResult.fileRef).to.eql(ctx.newFile)
  1165. expect(upsertFileResult.isNew).to.be.true
  1166. })
  1167. })
  1168. describe('upserting a new file with an invalid name', function () {
  1169. beforeEach(function (ctx) {
  1170. ctx.folder = { _id: folderId, fileRefs: [] }
  1171. ctx.newFile = { _id: fileId }
  1172. ctx.ProjectLocator.promises.findElement.resolves({
  1173. element: ctx.folder,
  1174. })
  1175. ctx.ProjectEntityUpdateHandler.promises.addFile = {
  1176. mainTask: sinon.stub().resolves(ctx.newFile),
  1177. }
  1178. })
  1179. it('returns an error', async function (ctx) {
  1180. let error
  1181. try {
  1182. await ctx.ProjectEntityUpdateHandler.promises.upsertFile(
  1183. projectId,
  1184. folderId,
  1185. `*${ctx.fileName}`,
  1186. ctx.fileSystemPath,
  1187. ctx.linkedFileData,
  1188. userId,
  1189. ctx.source
  1190. )
  1191. } catch (err) {
  1192. error = err
  1193. }
  1194. expect(error).to.be.instanceOf(Errors.InvalidNameError)
  1195. })
  1196. })
  1197. describe('upserting file on top of a doc', function () {
  1198. beforeEach(async function (ctx) {
  1199. ctx.path = '/path/to/doc'
  1200. ctx.existingDoc = { _id: new ObjectId(), name: ctx.fileName }
  1201. ctx.folder = {
  1202. _id: folderId,
  1203. fileRefs: [],
  1204. docs: [ctx.existingDoc],
  1205. }
  1206. ctx.ProjectLocator.promises.findElement
  1207. .withArgs({
  1208. project_id: ctx.project._id.toString(),
  1209. element_id: folderId,
  1210. type: 'folder',
  1211. })
  1212. .resolves({ element: ctx.folder })
  1213. ctx.ProjectLocator.promises.findElement
  1214. .withArgs({
  1215. project_id: ctx.project._id.toString(),
  1216. element_id: ctx.existingDoc._id,
  1217. type: 'doc',
  1218. })
  1219. .resolves({
  1220. element: ctx.existingDoc,
  1221. path: { fileSystem: ctx.path },
  1222. folder: ctx.folder,
  1223. })
  1224. ctx.newFile = {
  1225. _id: newFileId,
  1226. name: 'dummy-upload-filename',
  1227. rev: 0,
  1228. linkedFileData: ctx.linkedFileData,
  1229. }
  1230. ctx.newProject = {
  1231. name: 'new project',
  1232. overleaf: { history: { id: projectHistoryId } },
  1233. }
  1234. ctx.FileStoreHandler.promises.uploadFileFromDisk.resolves({
  1235. fileRef: ctx.newFile,
  1236. createdBlob: true,
  1237. })
  1238. ctx.ProjectEntityMongoUpdateHandler.promises.replaceDocWithFile.resolves(
  1239. ctx.newProject
  1240. )
  1241. await ctx.ProjectEntityUpdateHandler.promises.upsertFile(
  1242. projectId,
  1243. folderId,
  1244. ctx.fileName,
  1245. ctx.fileSystemPath,
  1246. ctx.linkedFileData,
  1247. userId,
  1248. ctx.source
  1249. )
  1250. })
  1251. it('replaces the existing doc with a file', function (ctx) {
  1252. expect(
  1253. ctx.ProjectEntityMongoUpdateHandler.promises.replaceDocWithFile
  1254. ).to.have.been.calledWith(
  1255. projectId,
  1256. ctx.existingDoc._id,
  1257. ctx.newFile,
  1258. userId
  1259. )
  1260. })
  1261. it('updates the doc structure', function (ctx) {
  1262. const oldDocs = [
  1263. {
  1264. doc: ctx.existingDoc,
  1265. path: ctx.path,
  1266. },
  1267. ]
  1268. const newFiles = [
  1269. {
  1270. file: ctx.newFile,
  1271. path: ctx.path,
  1272. createdBlob: true,
  1273. },
  1274. ]
  1275. const updates = {
  1276. oldDocs,
  1277. newFiles,
  1278. newProject: ctx.newProject,
  1279. }
  1280. expect(
  1281. ctx.DocumentUpdaterHandler.promises.updateProjectStructure
  1282. ).to.have.been.calledWith(
  1283. projectId,
  1284. projectHistoryId,
  1285. userId,
  1286. updates,
  1287. ctx.source
  1288. )
  1289. })
  1290. it('tells everyone in the room the doc is removed', function (ctx) {
  1291. expect(ctx.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
  1292. projectId,
  1293. 'removeEntity',
  1294. ctx.existingDoc._id,
  1295. 'convertDocToFile'
  1296. )
  1297. })
  1298. })
  1299. })
  1300. describe('upsertDocWithPath', function () {
  1301. describe('upserting a doc', function () {
  1302. let upsertDocWithPathResult
  1303. beforeEach(async function (ctx) {
  1304. ctx.path = '/folder/doc.tex'
  1305. ctx.newFolders = ['mock-a', 'mock-b']
  1306. ctx.folder = { _id: folderId }
  1307. ctx.doc = { _id: docId }
  1308. ctx.isNewDoc = true
  1309. ctx.ProjectEntityUpdateHandler.promises.mkdirp = {
  1310. withoutLock: sinon
  1311. .stub()
  1312. .resolves({ newFolders: ctx.newFolders, folder: ctx.folder }),
  1313. }
  1314. ctx.ProjectEntityUpdateHandler.promises.upsertDoc = {
  1315. withoutLock: sinon
  1316. .stub()
  1317. .resolves({ doc: ctx.doc, isNew: ctx.isNewDoc }),
  1318. }
  1319. upsertDocWithPathResult =
  1320. await ctx.ProjectEntityUpdateHandler.promises.upsertDocWithPath(
  1321. projectId,
  1322. ctx.path,
  1323. ctx.docLines,
  1324. ctx.source,
  1325. userId
  1326. )
  1327. })
  1328. it('creates any necessary folders', function (ctx) {
  1329. ctx.ProjectEntityUpdateHandler.promises.mkdirp.withoutLock
  1330. .calledWith(projectId, '/folder', userId)
  1331. .should.equal(true)
  1332. })
  1333. it('upserts the doc', function (ctx) {
  1334. ctx.ProjectEntityUpdateHandler.promises.upsertDoc.withoutLock
  1335. .calledWith(
  1336. projectId,
  1337. ctx.folder._id,
  1338. 'doc.tex',
  1339. ctx.docLines,
  1340. ctx.source,
  1341. userId
  1342. )
  1343. .should.equal(true)
  1344. })
  1345. it('returns a doc, the isNewDoc flag, newFolders and a folder', function (ctx) {
  1346. expect(upsertDocWithPathResult).to.eql({
  1347. doc: ctx.doc,
  1348. isNew: ctx.isNewDoc,
  1349. newFolders: ctx.newFolders,
  1350. folder: ctx.folder,
  1351. })
  1352. })
  1353. })
  1354. describe('upserting a doc with an invalid path', function () {
  1355. beforeEach(function (ctx) {
  1356. ctx.path = '/*folder/doc.tex'
  1357. ctx.newFolders = ['mock-a', 'mock-b']
  1358. ctx.folder = { _id: folderId }
  1359. ctx.doc = { _id: docId }
  1360. ctx.isNewDoc = true
  1361. ctx.ProjectEntityUpdateHandler.promises.mkdirp = {
  1362. withoutLock: sinon
  1363. .stub()
  1364. .resolves({ newFolders: ctx.newFolders, folder: ctx.folder }),
  1365. }
  1366. ctx.ProjectEntityUpdateHandler.promises.upsertDoc = {
  1367. withoutLock: sinon
  1368. .stub()
  1369. .resolves({ doc: ctx.doc, isNew: ctx.isNewDoc }),
  1370. }
  1371. })
  1372. it('returns an error', async function (ctx) {
  1373. let error
  1374. try {
  1375. await ctx.ProjectEntityUpdateHandler.promises.upsertDocWithPath(
  1376. projectId,
  1377. ctx.path,
  1378. ctx.docLines,
  1379. ctx.source,
  1380. userId
  1381. )
  1382. } catch (err) {
  1383. error = err
  1384. }
  1385. expect(error).to.be.instanceOf(Errors.InvalidNameError)
  1386. })
  1387. })
  1388. describe('upserting a doc with an invalid name', function () {
  1389. beforeEach(function (ctx) {
  1390. ctx.path = '/folder/*doc.tex'
  1391. ctx.newFolders = ['mock-a', 'mock-b']
  1392. ctx.folder = { _id: folderId }
  1393. ctx.doc = { _id: docId }
  1394. ctx.isNewDoc = true
  1395. ctx.ProjectEntityUpdateHandler.promises.mkdirp = {
  1396. withoutLock: sinon
  1397. .stub()
  1398. .resolves({ newFolders: ctx.newFolders, folder: ctx.folder }),
  1399. }
  1400. ctx.ProjectEntityUpdateHandler.promises.upsertDoc = {
  1401. withoutLock: sinon
  1402. .stub()
  1403. .resolves({ doc: ctx.doc, isNew: ctx.isNewDoc }),
  1404. }
  1405. })
  1406. it('returns an error', async function (ctx) {
  1407. let error
  1408. try {
  1409. await ctx.ProjectEntityUpdateHandler.promises.upsertDocWithPath(
  1410. projectId,
  1411. ctx.path,
  1412. ctx.docLines,
  1413. ctx.source,
  1414. userId
  1415. )
  1416. } catch (err) {
  1417. error = err
  1418. }
  1419. expect(error).to.be.instanceOf(Errors.InvalidNameError)
  1420. })
  1421. })
  1422. })
  1423. describe('upsertFileWithPath', function () {
  1424. describe('upserting a file', function () {
  1425. let upsertFileWithPathResult
  1426. beforeEach(async function (ctx) {
  1427. ctx.path = '/folder/file.png'
  1428. ctx.newFolders = ['mock-a', 'mock-b']
  1429. ctx.folder = { _id: folderId }
  1430. ctx.file = { _id: fileId }
  1431. ctx.isNewFile = true
  1432. ctx.FileStoreHandler.promises.uploadFileFromDisk.resolves({
  1433. fileRef: ctx.newFile,
  1434. createdBlob: true,
  1435. })
  1436. ctx.ProjectEntityUpdateHandler.promises.mkdirp = {
  1437. withoutLock: sinon
  1438. .stub()
  1439. .resolves({ newFolders: ctx.newFolders, folder: ctx.folder }),
  1440. }
  1441. ctx.ProjectEntityUpdateHandler.promises.upsertFile = {
  1442. mainTask: sinon
  1443. .stub()
  1444. .resolves({ fileRef: ctx.file, isNew: ctx.isNewFile }),
  1445. }
  1446. upsertFileWithPathResult =
  1447. await ctx.ProjectEntityUpdateHandler.promises.upsertFileWithPath(
  1448. projectId,
  1449. ctx.path,
  1450. ctx.fileSystemPath,
  1451. ctx.linkedFileData,
  1452. userId,
  1453. ctx.source
  1454. )
  1455. })
  1456. it('creates any necessary folders', function (ctx) {
  1457. ctx.ProjectEntityUpdateHandler.promises.mkdirp.withoutLock
  1458. .calledWith(projectId, '/folder', userId)
  1459. .should.equal(true)
  1460. })
  1461. it('upserts the file', function (ctx) {
  1462. ctx.ProjectEntityUpdateHandler.promises.upsertFile.mainTask.should.have.been.calledWith(
  1463. {
  1464. projectId,
  1465. folderId: ctx.folder._id,
  1466. fileName: 'file.png',
  1467. fsPath: ctx.fileSystemPath,
  1468. linkedFileData: ctx.linkedFileData,
  1469. userId,
  1470. fileRef: ctx.newFile,
  1471. source: ctx.source,
  1472. createdBlob: true,
  1473. }
  1474. )
  1475. })
  1476. it('returns an object with the fileRef, isNew flag, undefined oldFileRef, newFolders, and folder', function (ctx) {
  1477. expect(upsertFileWithPathResult).to.eql({
  1478. fileRef: ctx.file,
  1479. isNew: ctx.isNewFile,
  1480. newFolders: ctx.newFolders,
  1481. folder: ctx.folder,
  1482. oldFileRef: undefined,
  1483. })
  1484. })
  1485. })
  1486. describe('upserting a file with an invalid path', function () {
  1487. beforeEach(function (ctx) {
  1488. ctx.path = '/*folder/file.png'
  1489. ctx.newFolders = ['mock-a', 'mock-b']
  1490. ctx.folder = { _id: folderId }
  1491. ctx.file = { _id: fileId }
  1492. ctx.isNewFile = true
  1493. ctx.ProjectEntityUpdateHandler.promises.mkdirp = {
  1494. withoutLock: sinon
  1495. .stub()
  1496. .resolves({ newFolders: ctx.newFolders, folder: ctx.folder }),
  1497. }
  1498. ctx.ProjectEntityUpdateHandler.promises.upsertFile = {
  1499. mainTask: sinon
  1500. .stub()
  1501. .resolves({ doc: ctx.file, isNew: ctx.isNewFile }),
  1502. }
  1503. })
  1504. it('returns an error', async function (ctx) {
  1505. let error
  1506. try {
  1507. await ctx.ProjectEntityUpdateHandler.promises.upsertFileWithPath(
  1508. projectId,
  1509. ctx.path,
  1510. ctx.fileSystemPath,
  1511. ctx.linkedFileData,
  1512. userId,
  1513. ctx.source
  1514. )
  1515. } catch (err) {
  1516. error = err
  1517. }
  1518. expect(error).to.be.instanceOf(Errors.InvalidNameError)
  1519. })
  1520. })
  1521. describe('upserting a file with an invalid name', function () {
  1522. beforeEach(function (ctx) {
  1523. ctx.path = '/folder/*file.png'
  1524. ctx.newFolders = ['mock-a', 'mock-b']
  1525. ctx.folder = { _id: folderId }
  1526. ctx.file = { _id: fileId }
  1527. ctx.isNewFile = true
  1528. ctx.ProjectEntityUpdateHandler.promises.mkdirp = {
  1529. withoutLock: sinon
  1530. .stub()
  1531. .resolves({ newFolders: ctx.newFolders, folder: ctx.folder }),
  1532. }
  1533. ctx.ProjectEntityUpdateHandler.promises.upsertFile = {
  1534. mainTask: sinon
  1535. .stub()
  1536. .resolves({ doc: ctx.file, isNew: ctx.isNewFile }),
  1537. }
  1538. })
  1539. it('returns an error', async function (ctx) {
  1540. let error
  1541. try {
  1542. await ctx.ProjectEntityUpdateHandler.promises.upsertFileWithPath(
  1543. projectId,
  1544. ctx.path,
  1545. ctx.fileSystemPath,
  1546. ctx.linkedFileData,
  1547. userId,
  1548. ctx.source
  1549. )
  1550. } catch (err) {
  1551. error = err
  1552. }
  1553. expect(error).to.be.instanceOf(Errors.InvalidNameError)
  1554. })
  1555. })
  1556. })
  1557. describe('deleteEntity', function () {
  1558. let deleteEntityResult
  1559. beforeEach(async function (ctx) {
  1560. ctx.path = '/path/to/doc.tex'
  1561. ctx.doc = { _id: docId }
  1562. ctx.projectBeforeDeletion = { _id: projectId, name: 'project' }
  1563. ctx.newProject = 'new-project'
  1564. ctx.ProjectEntityMongoUpdateHandler.promises.deleteEntity.resolves({
  1565. entity: ctx.doc,
  1566. path: { fileSystem: ctx.path },
  1567. projectBeforeDeletion: ctx.projectBeforeDeletion,
  1568. newProject: ctx.newProject,
  1569. })
  1570. ctx.ProjectEntityUpdateHandler._cleanUpEntity = sinon
  1571. .stub()
  1572. .resolves([{ type: 'doc', entity: ctx.doc, path: ctx.path }])
  1573. deleteEntityResult =
  1574. await ctx.ProjectEntityUpdateHandler.promises.deleteEntity(
  1575. projectId,
  1576. docId,
  1577. 'doc',
  1578. userId,
  1579. ctx.source
  1580. )
  1581. })
  1582. it('flushes the project to mongo', function (ctx) {
  1583. ctx.DocumentUpdaterHandler.promises.flushProjectToMongo.should.have.been.calledWith(
  1584. projectId
  1585. )
  1586. })
  1587. it('deletes the entity in mongo', function (ctx) {
  1588. ctx.ProjectEntityMongoUpdateHandler.promises.deleteEntity
  1589. .calledWith(projectId, docId, 'doc', userId)
  1590. .should.equal(true)
  1591. })
  1592. it('cleans up the doc in the docstore', function (ctx) {
  1593. ctx.ProjectEntityUpdateHandler._cleanUpEntity
  1594. .calledWith(
  1595. ctx.projectBeforeDeletion,
  1596. ctx.newProject,
  1597. ctx.doc,
  1598. 'doc',
  1599. ctx.path,
  1600. userId,
  1601. ctx.source
  1602. )
  1603. .should.equal(true)
  1604. })
  1605. it('it notifies the tpds', function (ctx) {
  1606. ctx.TpdsUpdateSender.promises.deleteEntity.should.have.been.calledWith({
  1607. projectId,
  1608. path: ctx.path,
  1609. projectName: ctx.projectBeforeDeletion.name,
  1610. entityId: docId,
  1611. entityType: 'doc',
  1612. subtreeEntityIds: [ctx.doc._id],
  1613. })
  1614. })
  1615. it('retuns the entity_id', function () {
  1616. expect(deleteEntityResult).to.equal(docId)
  1617. })
  1618. })
  1619. describe('deleteEntityWithPath', function () {
  1620. describe('when the entity exists', function () {
  1621. beforeEach(async function (ctx) {
  1622. ctx.doc = { _id: docId }
  1623. ctx.ProjectLocator.promises.findElementByPath.resolves({
  1624. element: ctx.doc,
  1625. type: 'doc',
  1626. })
  1627. ctx.ProjectEntityUpdateHandler.promises.deleteEntity = {
  1628. withoutLock: sinon.stub().resolves(),
  1629. }
  1630. ctx.path = '/path/to/doc.tex'
  1631. await ctx.ProjectEntityUpdateHandler.promises.deleteEntityWithPath(
  1632. projectId,
  1633. ctx.path,
  1634. userId,
  1635. ctx.source
  1636. )
  1637. })
  1638. it('finds the entity', function (ctx) {
  1639. ctx.ProjectLocator.promises.findElementByPath
  1640. .calledWith({
  1641. project_id: projectId,
  1642. path: ctx.path,
  1643. exactCaseMatch: true,
  1644. })
  1645. .should.equal(true)
  1646. })
  1647. it('deletes the entity', function (ctx) {
  1648. ctx.ProjectEntityUpdateHandler.promises.deleteEntity.withoutLock.should.have.been.calledWith(
  1649. projectId,
  1650. ctx.doc._id,
  1651. 'doc',
  1652. userId,
  1653. ctx.source
  1654. )
  1655. })
  1656. })
  1657. describe('when the entity does not exist', function () {
  1658. beforeEach(function (ctx) {
  1659. ctx.ProjectLocator.promises.findElementByPath.resolves({
  1660. element: null,
  1661. })
  1662. ctx.path = '/doc.tex'
  1663. })
  1664. it('returns an error', async function (ctx) {
  1665. let error
  1666. try {
  1667. await ctx.ProjectEntityUpdateHandler.promises.deleteEntityWithPath(
  1668. projectId,
  1669. ctx.path,
  1670. userId,
  1671. ctx.source
  1672. )
  1673. } catch (err) {
  1674. error = err
  1675. }
  1676. expect(error).to.be.instanceOf(Errors.NotFoundError)
  1677. })
  1678. })
  1679. })
  1680. describe('mkdirp', function () {
  1681. beforeEach(async function (ctx) {
  1682. ctx.docPath = '/folder/doc.tex'
  1683. ctx.ProjectEntityMongoUpdateHandler.promises.mkdirp.resolves({})
  1684. await ctx.ProjectEntityUpdateHandler.promises.mkdirp(
  1685. projectId,
  1686. ctx.docPath,
  1687. userId
  1688. )
  1689. })
  1690. it('calls ProjectEntityMongoUpdateHandler', function (ctx) {
  1691. ctx.ProjectEntityMongoUpdateHandler.promises.mkdirp
  1692. .calledWith(projectId, ctx.docPath, userId)
  1693. .should.equal(true)
  1694. })
  1695. })
  1696. describe('mkdirpWithExactCase', function () {
  1697. beforeEach(async function (ctx) {
  1698. ctx.docPath = '/folder/doc.tex'
  1699. ctx.ProjectEntityMongoUpdateHandler.promises.mkdirp.resolves({})
  1700. await ctx.ProjectEntityUpdateHandler.promises.mkdirpWithExactCase(
  1701. projectId,
  1702. ctx.docPath,
  1703. userId
  1704. )
  1705. })
  1706. it('calls ProjectEntityMongoUpdateHandler', function (ctx) {
  1707. ctx.ProjectEntityMongoUpdateHandler.promises.mkdirp
  1708. .calledWith(projectId, ctx.docPath, userId, { exactCaseMatch: true })
  1709. .should.equal(true)
  1710. })
  1711. })
  1712. describe('addFolder', function () {
  1713. describe('adding a folder', function () {
  1714. beforeEach(async function (ctx) {
  1715. ctx.parentFolderId = '123asdf'
  1716. ctx.folderName = 'new-folder'
  1717. ctx.ProjectEntityMongoUpdateHandler.promises.addFolder.resolves({})
  1718. await ctx.ProjectEntityUpdateHandler.promises.addFolder(
  1719. projectId,
  1720. ctx.parentFolderId,
  1721. ctx.folderName,
  1722. userId
  1723. )
  1724. })
  1725. it('calls ProjectEntityMongoUpdateHandler', function (ctx) {
  1726. ctx.ProjectEntityMongoUpdateHandler.promises.addFolder
  1727. .calledWith(projectId, ctx.parentFolderId, ctx.folderName, userId)
  1728. .should.equal(true)
  1729. })
  1730. })
  1731. describe('adding a folder with an invalid name', function () {
  1732. beforeEach(function (ctx) {
  1733. ctx.parentFolderId = '123asdf'
  1734. ctx.folderName = '*new-folder'
  1735. ctx.ProjectEntityMongoUpdateHandler.promises.addFolder.resolves({})
  1736. })
  1737. it('returns an error', async function (ctx) {
  1738. let error
  1739. try {
  1740. await ctx.ProjectEntityUpdateHandler.promises.addFolder(
  1741. projectId,
  1742. ctx.parentFolderId,
  1743. ctx.folderName
  1744. )
  1745. } catch (err) {
  1746. error = err
  1747. }
  1748. expect(error).to.be.instanceOf(Errors.InvalidNameError)
  1749. })
  1750. })
  1751. })
  1752. describe('moveEntity', function () {
  1753. beforeEach(async function (ctx) {
  1754. ctx.project_name = 'project name'
  1755. ctx.startPath = '/a.tex'
  1756. ctx.endPath = '/folder/b.tex'
  1757. ctx.rev = 2
  1758. ctx.changes = { newDocs: ['old-doc'], newFiles: ['old-file'] }
  1759. ctx.ProjectEntityMongoUpdateHandler.promises.moveEntity.resolves({
  1760. project: ctx.project,
  1761. startPath: ctx.startPath,
  1762. endPath: ctx.endPath,
  1763. rev: ctx.rev,
  1764. changes: ctx.changes,
  1765. })
  1766. await ctx.ProjectEntityUpdateHandler.promises.moveEntity(
  1767. projectId,
  1768. docId,
  1769. folderId,
  1770. 'doc',
  1771. userId,
  1772. ctx.source
  1773. )
  1774. })
  1775. it('moves the entity in mongo', function (ctx) {
  1776. ctx.ProjectEntityMongoUpdateHandler.promises.moveEntity
  1777. .calledWith(projectId, docId, folderId, 'doc', userId)
  1778. .should.equal(true)
  1779. })
  1780. it('notifies tpds', function (ctx) {
  1781. ctx.TpdsUpdateSender.promises.moveEntity
  1782. .calledWith({
  1783. projectId,
  1784. projectName: ctx.project_name,
  1785. startPath: ctx.startPath,
  1786. endPath: ctx.endPath,
  1787. rev: ctx.rev,
  1788. entityId: docId,
  1789. entityType: 'doc',
  1790. folderId,
  1791. })
  1792. .should.equal(true)
  1793. })
  1794. it('sends the changes in project structure to the doc updater', function (ctx) {
  1795. ctx.DocumentUpdaterHandler.promises.updateProjectStructure
  1796. .calledWith(
  1797. projectId,
  1798. projectHistoryId,
  1799. userId,
  1800. ctx.changes,
  1801. ctx.source
  1802. )
  1803. .should.equal(true)
  1804. })
  1805. })
  1806. describe('renameEntity', function () {
  1807. describe('renaming an entity', function () {
  1808. beforeEach(async function (ctx) {
  1809. ctx.project_name = 'project name'
  1810. ctx.startPath = '/folder/a.tex'
  1811. ctx.endPath = '/folder/b.tex'
  1812. ctx.rev = 2
  1813. ctx.changes = { newDocs: ['old-doc'], newFiles: ['old-file'] }
  1814. ctx.newDocName = 'b.tex'
  1815. ctx.ProjectEntityMongoUpdateHandler.promises.renameEntity.resolves({
  1816. project: ctx.project,
  1817. startPath: ctx.startPath,
  1818. endPath: ctx.endPath,
  1819. rev: ctx.rev,
  1820. changes: ctx.changes,
  1821. })
  1822. await ctx.ProjectEntityUpdateHandler.promises.renameEntity(
  1823. projectId,
  1824. docId,
  1825. 'doc',
  1826. ctx.newDocName,
  1827. userId,
  1828. ctx.source
  1829. )
  1830. })
  1831. it('moves the entity in mongo', function (ctx) {
  1832. ctx.ProjectEntityMongoUpdateHandler.promises.renameEntity
  1833. .calledWith(projectId, docId, 'doc', ctx.newDocName, userId)
  1834. .should.equal(true)
  1835. })
  1836. it('notifies tpds', function (ctx) {
  1837. ctx.TpdsUpdateSender.promises.moveEntity
  1838. .calledWith({
  1839. projectId,
  1840. projectName: ctx.project_name,
  1841. startPath: ctx.startPath,
  1842. endPath: ctx.endPath,
  1843. rev: ctx.rev,
  1844. entityId: docId,
  1845. entityType: 'doc',
  1846. folderId: null,
  1847. })
  1848. .should.equal(true)
  1849. })
  1850. it('flushes the project in doc updater', function (ctx) {
  1851. ctx.DocumentUpdaterHandler.promises.flushProjectToMongo.should.have.been.calledWith(
  1852. projectId
  1853. )
  1854. })
  1855. it('sends the changes in project structure to the doc updater', function (ctx) {
  1856. ctx.DocumentUpdaterHandler.promises.updateProjectStructure
  1857. .calledWith(
  1858. projectId,
  1859. projectHistoryId,
  1860. userId,
  1861. ctx.changes,
  1862. ctx.source
  1863. )
  1864. .should.equal(true)
  1865. })
  1866. })
  1867. describe('renaming an entity to an invalid name', function () {
  1868. beforeEach(function (ctx) {
  1869. ctx.project_name = 'project name'
  1870. ctx.startPath = '/folder/a.tex'
  1871. ctx.endPath = '/folder/b.tex'
  1872. ctx.rev = 2
  1873. ctx.changes = { newDocs: ['old-doc'], newFiles: ['old-file'] }
  1874. ctx.newDocName = '*b.tex'
  1875. ctx.ProjectEntityMongoUpdateHandler.promises.renameEntity.resolves({
  1876. project: ctx.project,
  1877. startPath: ctx.startPath,
  1878. endPath: ctx.endPath,
  1879. rev: ctx.rev,
  1880. changes: ctx.changes,
  1881. })
  1882. })
  1883. it('returns an error', async function (ctx) {
  1884. let error
  1885. try {
  1886. await ctx.ProjectEntityUpdateHandler.promises.renameEntity(
  1887. projectId,
  1888. docId,
  1889. 'doc',
  1890. ctx.newDocName,
  1891. userId,
  1892. ctx.source
  1893. )
  1894. } catch (err) {
  1895. error = err
  1896. }
  1897. expect(error).to.be.instanceOf(Errors.InvalidNameError)
  1898. })
  1899. })
  1900. describe('renaming an entity with a non-string value', function () {
  1901. beforeEach(function (ctx) {
  1902. ctx.project_name = 'project name'
  1903. ctx.startPath = '/folder/a.tex'
  1904. ctx.endPath = '/folder/b.tex'
  1905. ctx.rev = 2
  1906. ctx.changes = { newDocs: ['old-doc'], newFiles: ['old-file'] }
  1907. ctx.newDocName = ['hello']
  1908. ctx.ProjectEntityMongoUpdateHandler.promises.renameEntity.resolves({
  1909. project: ctx.project,
  1910. startPath: ctx.startPath,
  1911. endPath: ctx.endPath,
  1912. rev: ctx.rev,
  1913. changes: ctx.changes,
  1914. })
  1915. })
  1916. it('returns an error', async function (ctx) {
  1917. let error
  1918. try {
  1919. await ctx.ProjectEntityUpdateHandler.promises.renameEntity(
  1920. projectId,
  1921. docId,
  1922. 'doc',
  1923. ctx.newDocName,
  1924. userId,
  1925. ctx.source
  1926. )
  1927. } catch (err) {
  1928. error = err
  1929. }
  1930. expect(error).to.be.instanceOf(Error)
  1931. expect(
  1932. ctx.ProjectEntityMongoUpdateHandler.promises.renameEntity.called
  1933. ).to.equal(false)
  1934. })
  1935. })
  1936. })
  1937. describe('resyncProjectHistory', function () {
  1938. describe('a deleted project', function () {
  1939. beforeEach(function (ctx) {
  1940. ctx.ProjectGetter.promises.getProject.resolves({})
  1941. })
  1942. it('should return an error', async function (ctx) {
  1943. let error
  1944. try {
  1945. await ctx.ProjectEntityUpdateHandler.promises.resyncProjectHistory(
  1946. projectId,
  1947. {}
  1948. )
  1949. } catch (err) {
  1950. error = err
  1951. }
  1952. expect(error).to.be.instanceOf(Errors.ProjectHistoryDisabledError)
  1953. expect(error).to.have.property(
  1954. 'message',
  1955. `project history not enabled for ${projectId}`
  1956. )
  1957. })
  1958. })
  1959. describe('a project without project-history enabled', function () {
  1960. beforeEach(function (ctx) {
  1961. ctx.project.overleaf = {}
  1962. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  1963. })
  1964. it('should return an error', async function (ctx) {
  1965. let error
  1966. try {
  1967. await ctx.ProjectEntityUpdateHandler.promises.resyncProjectHistory(
  1968. projectId,
  1969. {}
  1970. )
  1971. } catch (err) {
  1972. error = err
  1973. }
  1974. expect(error).to.be.instanceOf(Errors.ProjectHistoryDisabledError)
  1975. expect(error).to.have.property(
  1976. 'message',
  1977. `project history not enabled for ${projectId}`
  1978. )
  1979. })
  1980. })
  1981. describe('a project with project-history enabled', function () {
  1982. const docs = [{ doc: { _id: docId, name: 'main.tex' }, path: 'main.tex' }]
  1983. const files = [
  1984. {
  1985. file: { _id: fileId, name: 'universe.png', hash: '123456' },
  1986. path: 'universe.png',
  1987. },
  1988. ]
  1989. beforeEach(async function (ctx) {
  1990. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  1991. const folders = []
  1992. ctx.ProjectEntityHandler.getAllEntitiesFromProject.returns({
  1993. docs,
  1994. files,
  1995. folders,
  1996. })
  1997. await ctx.ProjectEntityUpdateHandler.promises.resyncProjectHistory(
  1998. projectId,
  1999. {}
  2000. )
  2001. })
  2002. it('gets the project', function (ctx) {
  2003. ctx.ProjectGetter.promises.getProject.should.have.been.calledWith(
  2004. projectId
  2005. )
  2006. })
  2007. it('gets the entities for the project', function (ctx) {
  2008. ctx.ProjectEntityHandler.getAllEntitiesFromProject.should.have.been.calledWith(
  2009. ctx.project
  2010. )
  2011. })
  2012. it('uses an extended timeout', function (ctx) {
  2013. ctx.LockManager.withTimeout.should.have.been.calledWith(6 * 60)
  2014. })
  2015. it('tells the doc updater to sync the project', function (ctx) {
  2016. ctx.DocumentUpdaterHandler.promises.resyncProjectHistory
  2017. .calledWith(projectId, projectHistoryId, docs, files)
  2018. .should.equal(true)
  2019. })
  2020. })
  2021. describe('a project with duplicate filenames', function () {
  2022. beforeEach(async function (ctx) {
  2023. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  2024. ctx.docs = [
  2025. { doc: { _id: 'doc1', name: 'main.tex' }, path: 'main.tex' },
  2026. {
  2027. doc: { _id: 'doc2', name: 'duplicate.tex' },
  2028. path: 'a/b/c/duplicate.tex',
  2029. },
  2030. {
  2031. doc: { _id: 'doc3', name: 'duplicate.tex' },
  2032. path: 'a/b/c/duplicate.tex',
  2033. },
  2034. {
  2035. doc: { _id: 'doc4', name: 'another dupe (22)' },
  2036. path: 'another dupe (22)',
  2037. },
  2038. {
  2039. doc: { _id: 'doc5', name: 'duplicate.tex' },
  2040. path: 'a/b/c/duplicate.tex',
  2041. },
  2042. ]
  2043. ctx.files = [
  2044. {
  2045. file: { _id: 'file1', name: 'image.jpg', hash: 'hash1' },
  2046. path: 'image.jpg',
  2047. },
  2048. {
  2049. file: { _id: 'file2', name: 'duplicate.jpg', hash: 'hash2' },
  2050. path: 'duplicate.jpg',
  2051. },
  2052. {
  2053. file: { _id: 'file3', name: 'duplicate.jpg', hash: 'hash3' },
  2054. path: 'duplicate.jpg',
  2055. },
  2056. {
  2057. file: { _id: 'file4', name: 'another dupe (22)', hash: 'hash4' },
  2058. path: 'another dupe (22)',
  2059. },
  2060. ]
  2061. ctx.ProjectEntityHandler.getAllEntitiesFromProject.returns({
  2062. docs: ctx.docs,
  2063. files: ctx.files,
  2064. folders: [],
  2065. })
  2066. await ctx.ProjectEntityUpdateHandler.promises.resyncProjectHistory(
  2067. projectId,
  2068. {}
  2069. )
  2070. })
  2071. it('renames the duplicate files', function (ctx) {
  2072. const renameEntity =
  2073. ctx.ProjectEntityMongoUpdateHandler.promises.renameEntity
  2074. expect(renameEntity).to.have.callCount(4)
  2075. expect(renameEntity).to.have.been.calledWith(
  2076. projectId,
  2077. 'doc3',
  2078. 'doc',
  2079. 'duplicate.tex (1)',
  2080. null
  2081. )
  2082. expect(renameEntity).to.have.been.calledWith(
  2083. projectId,
  2084. 'doc5',
  2085. 'doc',
  2086. 'duplicate.tex (2)',
  2087. null
  2088. )
  2089. expect(renameEntity).to.have.been.calledWith(
  2090. projectId,
  2091. 'file3',
  2092. 'file',
  2093. 'duplicate.jpg (1)',
  2094. null
  2095. )
  2096. expect(renameEntity).to.have.been.calledWith(
  2097. projectId,
  2098. 'file4',
  2099. 'file',
  2100. 'another dupe (23)',
  2101. null
  2102. )
  2103. })
  2104. it('tells the doc updater to resync the project', function (ctx) {
  2105. const docs = ctx.docs.map(d => {
  2106. if (d.doc._id === 'doc3') {
  2107. return Object.assign({}, d, { path: 'a/b/c/duplicate.tex (1)' })
  2108. }
  2109. if (d.doc._id === 'doc5') {
  2110. return Object.assign({}, d, { path: 'a/b/c/duplicate.tex (2)' })
  2111. }
  2112. return d
  2113. })
  2114. const files = ctx.files.map(f => {
  2115. if (f.file._id === 'file3') {
  2116. return Object.assign({}, f, { path: 'duplicate.jpg (1)' })
  2117. }
  2118. if (f.file._id === 'file4') {
  2119. return Object.assign({}, f, { path: 'another dupe (23)' })
  2120. }
  2121. return f
  2122. })
  2123. expect(
  2124. ctx.DocumentUpdaterHandler.promises.resyncProjectHistory
  2125. ).to.have.been.calledWith(projectId, projectHistoryId, docs, files)
  2126. })
  2127. })
  2128. describe('a project with bad filenames', function () {
  2129. beforeEach(async function (ctx) {
  2130. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  2131. ctx.docs = [
  2132. {
  2133. doc: { _id: 'doc1', name: '/d/e/f/test.tex' },
  2134. path: 'a/b/c/d/e/f/test.tex',
  2135. },
  2136. {
  2137. doc: { _id: 'doc2', name: '' },
  2138. path: 'a',
  2139. },
  2140. ]
  2141. ctx.files = [
  2142. {
  2143. file: { _id: 'file1', name: 'A*.png', hash: 'hash1' },
  2144. path: 'A*.png',
  2145. },
  2146. {
  2147. file: { _id: 'file2', name: 'A_.png', hash: 'hash2' },
  2148. path: 'A_.png',
  2149. },
  2150. ]
  2151. ctx.ProjectEntityHandler.getAllEntitiesFromProject.returns({
  2152. docs: ctx.docs,
  2153. files: ctx.files,
  2154. folders: [],
  2155. })
  2156. await ctx.ProjectEntityUpdateHandler.promises.resyncProjectHistory(
  2157. projectId,
  2158. {}
  2159. )
  2160. })
  2161. it('renames the files', function (ctx) {
  2162. const renameEntity =
  2163. ctx.ProjectEntityMongoUpdateHandler.promises.renameEntity
  2164. expect(renameEntity).to.have.callCount(4)
  2165. expect(renameEntity).to.have.been.calledWith(
  2166. projectId,
  2167. 'doc1',
  2168. 'doc',
  2169. '_d_e_f_test.tex',
  2170. null
  2171. )
  2172. expect(renameEntity).to.have.been.calledWith(
  2173. projectId,
  2174. 'doc2',
  2175. 'doc',
  2176. 'untitled',
  2177. null
  2178. )
  2179. expect(renameEntity).to.have.been.calledWith(
  2180. projectId,
  2181. 'file1',
  2182. 'file',
  2183. 'A_.png',
  2184. null
  2185. )
  2186. expect(renameEntity).to.have.been.calledWith(
  2187. projectId,
  2188. 'file2',
  2189. 'file',
  2190. 'A_.png (1)',
  2191. null
  2192. )
  2193. })
  2194. it('tells the doc updater to resync the project', function (ctx) {
  2195. const docs = ctx.docs.map(d => {
  2196. if (d.doc._id === 'doc1') {
  2197. return Object.assign({}, d, { path: 'a/b/c/_d_e_f_test.tex' })
  2198. }
  2199. if (d.doc._id === 'doc2') {
  2200. return Object.assign({}, d, { path: 'a/untitled' })
  2201. }
  2202. return d
  2203. })
  2204. const files = ctx.files.map(f => {
  2205. if (f.file._id === 'file1') {
  2206. return Object.assign({}, f, { path: 'A_.png' })
  2207. }
  2208. if (f.file._id === 'file2') {
  2209. return Object.assign({}, f, { path: 'A_.png (1)' })
  2210. }
  2211. return f
  2212. })
  2213. expect(
  2214. ctx.DocumentUpdaterHandler.promises.resyncProjectHistory
  2215. ).to.have.been.calledWith(projectId, projectHistoryId, docs, files)
  2216. })
  2217. })
  2218. describe('a project with a bad folder name', function () {
  2219. const folders = [
  2220. {
  2221. folder: { _id: 'folder1', name: 'good' },
  2222. path: 'good',
  2223. },
  2224. {
  2225. folder: { _id: 'folder2', name: 'bad*' },
  2226. path: 'bad*',
  2227. },
  2228. ]
  2229. const docs = [
  2230. {
  2231. doc: { _id: 'doc1', name: 'doc1.tex' },
  2232. path: 'good/doc1.tex',
  2233. },
  2234. {
  2235. doc: { _id: 'doc2', name: 'duplicate.tex' },
  2236. path: 'bad*/doc2.tex',
  2237. },
  2238. ]
  2239. const files = []
  2240. beforeEach(async function (ctx) {
  2241. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  2242. ctx.ProjectEntityHandler.getAllEntitiesFromProject.returns({
  2243. docs,
  2244. files,
  2245. folders,
  2246. })
  2247. await ctx.ProjectEntityUpdateHandler.promises.resyncProjectHistory(
  2248. projectId,
  2249. {}
  2250. )
  2251. })
  2252. it('renames the folder', function (ctx) {
  2253. const renameEntity =
  2254. ctx.ProjectEntityMongoUpdateHandler.promises.renameEntity
  2255. expect(renameEntity).to.have.callCount(1)
  2256. expect(renameEntity).to.have.been.calledWith(
  2257. projectId,
  2258. 'folder2',
  2259. 'folder',
  2260. 'bad_',
  2261. null
  2262. )
  2263. })
  2264. it('tells the doc updater to resync the project', function (ctx) {
  2265. const fixedDocs = docs.map(d => {
  2266. if (d.doc._id === 'doc2') {
  2267. return Object.assign({}, d, { path: 'bad_/doc2.tex' })
  2268. }
  2269. return d
  2270. })
  2271. expect(
  2272. ctx.DocumentUpdaterHandler.promises.resyncProjectHistory
  2273. ).to.have.been.calledWith(projectId, projectHistoryId, fixedDocs, files)
  2274. })
  2275. })
  2276. describe('a project with duplicate names between a folder and a doc', function () {
  2277. const folders = [
  2278. {
  2279. folder: { _id: 'folder1', name: 'chapters' },
  2280. path: 'chapters',
  2281. },
  2282. ]
  2283. const docs = [
  2284. {
  2285. doc: { _id: 'doc1', name: 'chapters' },
  2286. path: 'chapters',
  2287. },
  2288. {
  2289. doc: { _id: 'doc2', name: 'chapter1.tex' },
  2290. path: 'chapters/chapter1.tex',
  2291. },
  2292. ]
  2293. const files = []
  2294. beforeEach(async function (ctx) {
  2295. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  2296. ctx.ProjectEntityHandler.getAllEntitiesFromProject.returns({
  2297. docs,
  2298. files,
  2299. folders,
  2300. })
  2301. await ctx.ProjectEntityUpdateHandler.promises.resyncProjectHistory(
  2302. projectId,
  2303. {}
  2304. )
  2305. })
  2306. it('renames the doc', function (ctx) {
  2307. const renameEntity =
  2308. ctx.ProjectEntityMongoUpdateHandler.promises.renameEntity
  2309. expect(renameEntity).to.have.callCount(1)
  2310. expect(renameEntity).to.have.been.calledWith(
  2311. projectId,
  2312. 'doc1',
  2313. 'doc',
  2314. 'chapters (1)',
  2315. null
  2316. )
  2317. })
  2318. it('tells the doc updater to resync the project', function (ctx) {
  2319. const fixedDocs = docs.map(d => {
  2320. if (d.doc._id === 'doc1') {
  2321. return Object.assign({}, d, { path: 'chapters (1)' })
  2322. }
  2323. return d
  2324. })
  2325. expect(
  2326. ctx.DocumentUpdaterHandler.promises.resyncProjectHistory
  2327. ).to.have.been.calledWith(projectId, projectHistoryId, fixedDocs, files)
  2328. })
  2329. })
  2330. describe('a project with an invalid file tree', function () {
  2331. beforeEach(function (ctx) {
  2332. ctx.callback = sinon.stub()
  2333. ctx.ProjectGetter.promises.getProject.resolves(ctx.project)
  2334. ctx.ProjectEntityHandler.getAllEntitiesFromProject.throws()
  2335. })
  2336. it('calls the callback with an error', async function (ctx) {
  2337. let error
  2338. try {
  2339. await ctx.ProjectEntityUpdateHandler.promises.resyncProjectHistory(
  2340. projectId,
  2341. {}
  2342. )
  2343. } catch (err) {
  2344. error = err
  2345. }
  2346. expect(error).to.be.instanceOf(Error)
  2347. })
  2348. })
  2349. })
  2350. describe('_cleanUpEntity', function () {
  2351. beforeEach(function (ctx) {
  2352. ctx.entityId = '4eecaffcbffa66588e000009'
  2353. ctx.ProjectEntityUpdateHandler.promises.unsetRootDoc = sinon
  2354. .stub()
  2355. .resolves()
  2356. })
  2357. describe('a file', function () {
  2358. beforeEach(async function (ctx) {
  2359. ctx.path = '/file/system/path.png'
  2360. ctx.entity = { _id: ctx.entityId }
  2361. ctx.newProject = 'new-project'
  2362. ctx.subtreeListing =
  2363. await ctx.ProjectEntityUpdateHandler._cleanUpEntity(
  2364. ctx.project,
  2365. ctx.newProject,
  2366. ctx.entity,
  2367. 'file',
  2368. ctx.path,
  2369. userId,
  2370. ctx.source
  2371. )
  2372. })
  2373. it('should not attempt to delete from the document updater', function (ctx) {
  2374. ctx.DocumentUpdaterHandler.promises.deleteDoc.called.should.equal(false)
  2375. })
  2376. it('should send the update to the doc updater', function (ctx) {
  2377. const oldFiles = [{ file: ctx.entity, path: ctx.path }]
  2378. ctx.DocumentUpdaterHandler.promises.updateProjectStructure.should.have.been.calledWith(
  2379. projectId,
  2380. projectHistoryId,
  2381. userId,
  2382. {
  2383. oldFiles,
  2384. oldDocs: [],
  2385. newProject: ctx.newProject,
  2386. },
  2387. ctx.source
  2388. )
  2389. })
  2390. it('should return a subtree listing containing only the file', function (ctx) {
  2391. expect(ctx.subtreeListing).to.deep.equal([
  2392. { type: 'file', entity: ctx.entity, path: ctx.path },
  2393. ])
  2394. })
  2395. })
  2396. describe('a doc', function () {
  2397. beforeEach(async function (ctx) {
  2398. ctx.path = '/file/system/path.tex'
  2399. ctx.ProjectEntityUpdateHandler._cleanUpDoc = sinon.stub().resolves()
  2400. ctx.entity = { _id: ctx.entityId }
  2401. ctx.newProject = 'new-project'
  2402. ctx.subtreeListing =
  2403. await ctx.ProjectEntityUpdateHandler._cleanUpEntity(
  2404. ctx.project,
  2405. ctx.newProject,
  2406. ctx.entity,
  2407. 'doc',
  2408. ctx.path,
  2409. userId,
  2410. ctx.source
  2411. )
  2412. })
  2413. it('should clean up the doc', function (ctx) {
  2414. ctx.ProjectEntityUpdateHandler._cleanUpDoc
  2415. .calledWith(ctx.project, ctx.entity, ctx.path, userId)
  2416. .should.equal(true)
  2417. })
  2418. it('should send the update to the doc updater', function (ctx) {
  2419. const oldDocs = [{ doc: ctx.entity, path: ctx.path }]
  2420. ctx.DocumentUpdaterHandler.promises.updateProjectStructure.should.have.been.calledWith(
  2421. projectId,
  2422. projectHistoryId,
  2423. userId,
  2424. {
  2425. oldDocs,
  2426. oldFiles: [],
  2427. newProject: ctx.newProject,
  2428. },
  2429. ctx.source
  2430. )
  2431. })
  2432. it('should return a subtree listing containing only the doc', function (ctx) {
  2433. expect(ctx.subtreeListing).to.deep.equal([
  2434. { type: 'doc', entity: ctx.entity, path: ctx.path },
  2435. ])
  2436. })
  2437. })
  2438. describe('a folder', function () {
  2439. beforeEach(async function (ctx) {
  2440. ctx.folder = {
  2441. folders: [
  2442. {
  2443. name: 'subfolder',
  2444. fileRefs: [
  2445. (ctx.file1 = { _id: 'file-id-1', name: 'file-name-1' }),
  2446. ],
  2447. docs: [(ctx.doc1 = { _id: 'doc-id-1', name: 'doc-name-1' })],
  2448. folders: [],
  2449. },
  2450. ],
  2451. fileRefs: [(ctx.file2 = { _id: 'file-id-2', name: 'file-name-2' })],
  2452. docs: [(ctx.doc2 = { _id: 'doc-id-2', name: 'doc-name-2' })],
  2453. }
  2454. ctx.ProjectEntityUpdateHandler._cleanUpDoc = sinon.stub().resolves()
  2455. const path = '/folder'
  2456. ctx.newProject = 'new-project'
  2457. ctx.subtreeListing =
  2458. await ctx.ProjectEntityUpdateHandler._cleanUpEntity(
  2459. ctx.project,
  2460. ctx.newProject,
  2461. ctx.folder,
  2462. 'folder',
  2463. path,
  2464. userId,
  2465. ctx.source
  2466. )
  2467. })
  2468. it('should clean up all sub docs', function (ctx) {
  2469. ctx.ProjectEntityUpdateHandler._cleanUpDoc
  2470. .calledWith(
  2471. ctx.project,
  2472. ctx.doc1,
  2473. '/folder/subfolder/doc-name-1',
  2474. userId
  2475. )
  2476. .should.equal(true)
  2477. ctx.ProjectEntityUpdateHandler._cleanUpDoc
  2478. .calledWith(ctx.project, ctx.doc2, '/folder/doc-name-2', userId)
  2479. .should.equal(true)
  2480. })
  2481. it('should should send one update to the doc updater for all docs and files', function (ctx) {
  2482. const oldFiles = [
  2483. { file: ctx.file2, path: '/folder/file-name-2' },
  2484. { file: ctx.file1, path: '/folder/subfolder/file-name-1' },
  2485. ]
  2486. const oldDocs = [
  2487. { doc: ctx.doc2, path: '/folder/doc-name-2' },
  2488. { doc: ctx.doc1, path: '/folder/subfolder/doc-name-1' },
  2489. ]
  2490. ctx.DocumentUpdaterHandler.promises.updateProjectStructure
  2491. .calledWith(
  2492. projectId,
  2493. projectHistoryId,
  2494. userId,
  2495. {
  2496. oldFiles,
  2497. oldDocs,
  2498. newProject: ctx.newProject,
  2499. },
  2500. ctx.source
  2501. )
  2502. .should.equal(true)
  2503. })
  2504. it('should return a subtree listing containing all sub-entities', function (ctx) {
  2505. expect(ctx.subtreeListing).to.have.deep.members([
  2506. { type: 'folder', entity: ctx.folder, path: '/folder' },
  2507. {
  2508. type: 'folder',
  2509. entity: ctx.folder.folders[0],
  2510. path: '/folder/subfolder',
  2511. },
  2512. {
  2513. type: 'file',
  2514. entity: ctx.file1,
  2515. path: '/folder/subfolder/file-name-1',
  2516. },
  2517. {
  2518. type: 'doc',
  2519. entity: ctx.doc1,
  2520. path: '/folder/subfolder/doc-name-1',
  2521. },
  2522. { type: 'file', entity: ctx.file2, path: '/folder/file-name-2' },
  2523. { type: 'doc', entity: ctx.doc2, path: '/folder/doc-name-2' },
  2524. ])
  2525. })
  2526. })
  2527. })
  2528. describe('_cleanUpDoc', function () {
  2529. beforeEach(function (ctx) {
  2530. ctx.doc = {
  2531. _id: new ObjectId(),
  2532. name: 'test.tex',
  2533. }
  2534. ctx.path = '/path/to/doc'
  2535. ctx.ProjectEntityUpdateHandler.promises.unsetRootDoc = sinon
  2536. .stub()
  2537. .resolves()
  2538. ctx.DocstoreManager.promises.deleteDoc.resolves()
  2539. })
  2540. describe('when the doc is the root doc', function () {
  2541. beforeEach(async function (ctx) {
  2542. ctx.project.rootDoc_id = ctx.doc._id
  2543. await ctx.ProjectEntityUpdateHandler._cleanUpDoc(
  2544. ctx.project,
  2545. ctx.doc,
  2546. ctx.path,
  2547. userId
  2548. )
  2549. })
  2550. it('should unset the root doc', function (ctx) {
  2551. ctx.ProjectEntityUpdateHandler.promises.unsetRootDoc.should.have.been.calledWith(
  2552. projectId
  2553. )
  2554. })
  2555. it('should delete the doc in the doc updater', function (ctx) {
  2556. ctx.DocumentUpdaterHandler.promises.deleteDoc
  2557. .calledWith(projectId, ctx.doc._id.toString())
  2558. .should.equal(true)
  2559. })
  2560. it('should delete the doc in the doc store', function (ctx) {
  2561. ctx.DocstoreManager.promises.deleteDoc
  2562. .calledWith(projectId, ctx.doc._id.toString(), 'test.tex')
  2563. .should.equal(true)
  2564. })
  2565. })
  2566. describe('when the doc is not the root doc', function () {
  2567. beforeEach(async function (ctx) {
  2568. ctx.project.rootDoc_id = new ObjectId()
  2569. await ctx.ProjectEntityUpdateHandler._cleanUpDoc(
  2570. ctx.project,
  2571. ctx.doc,
  2572. ctx.path,
  2573. userId
  2574. )
  2575. })
  2576. it('should not unset the root doc', function (ctx) {
  2577. ctx.ProjectEntityUpdateHandler.promises.unsetRootDoc.called.should.equal(
  2578. false
  2579. )
  2580. })
  2581. })
  2582. })
  2583. describe('convertDocToFile', function () {
  2584. beforeEach(function (ctx) {
  2585. ctx.docPath = '/folder/doc.tex'
  2586. ctx.docLines = ['line one', 'line two']
  2587. ctx.tmpFilePath = '/tmp/file'
  2588. ctx.fileStoreUrl = 'http://filestore/file'
  2589. ctx.folder = { _id: new ObjectId() }
  2590. ctx.rev = 3
  2591. ctx.ProjectLocator.promises.findElement
  2592. .withArgs({
  2593. project_id: ctx.project._id,
  2594. element_id: ctx.doc._id,
  2595. type: 'doc',
  2596. })
  2597. .resolves({
  2598. element: ctx.doc,
  2599. path: { fileSystem: ctx.path },
  2600. folder: ctx.folder,
  2601. })
  2602. ctx.ProjectLocator.promises.findElement
  2603. .withArgs({
  2604. project_id: ctx.project._id.toString(),
  2605. element_id: ctx.file._id,
  2606. type: 'file',
  2607. })
  2608. .resolves({
  2609. element: ctx.file,
  2610. path: ctx.docPath,
  2611. folder: ctx.folder,
  2612. })
  2613. ctx.DocstoreManager.promises.getDoc
  2614. .withArgs(ctx.project._id, ctx.doc._id)
  2615. .resolves({ lines: ctx.docLines, rev: ctx.rev })
  2616. ctx.FileWriter.promises.writeLinesToDisk.resolves(ctx.tmpFilePath)
  2617. ctx.FileStoreHandler.promises.uploadFileFromDisk.resolves({
  2618. fileRef: ctx.file,
  2619. createdBlob: true,
  2620. })
  2621. ctx.ProjectEntityMongoUpdateHandler.promises.replaceDocWithFile.resolves(
  2622. ctx.project
  2623. )
  2624. })
  2625. describe('successfully', function () {
  2626. beforeEach(async function (ctx) {
  2627. await ctx.ProjectEntityUpdateHandler.promises.convertDocToFile(
  2628. ctx.project._id,
  2629. ctx.doc._id,
  2630. userId,
  2631. ctx.source
  2632. )
  2633. })
  2634. it('deletes the document in doc updater', function (ctx) {
  2635. expect(
  2636. ctx.DocumentUpdaterHandler.promises.deleteDoc
  2637. ).to.have.been.calledWith(ctx.project._id, ctx.doc._id)
  2638. })
  2639. it('uploads the file to filestore', function (ctx) {
  2640. expect(
  2641. ctx.FileStoreHandler.promises.uploadFileFromDisk
  2642. ).to.have.been.calledWith(
  2643. ctx.project._id,
  2644. { name: ctx.doc.name, rev: ctx.rev + 1 },
  2645. ctx.tmpFilePath
  2646. )
  2647. })
  2648. it('cleans up the temporary file', function (ctx) {
  2649. expect(ctx.fs.promises.unlink).to.have.been.calledWith(ctx.tmpFilePath)
  2650. })
  2651. it('replaces the doc with the file', function (ctx) {
  2652. expect(
  2653. ctx.ProjectEntityMongoUpdateHandler.promises.replaceDocWithFile
  2654. ).to.have.been.calledWith(
  2655. ctx.project._id,
  2656. ctx.doc._id,
  2657. ctx.file,
  2658. userId
  2659. )
  2660. })
  2661. it('notifies document updater of changes', function (ctx) {
  2662. expect(
  2663. ctx.DocumentUpdaterHandler.promises.updateProjectStructure
  2664. ).to.have.been.calledWith(
  2665. ctx.project._id,
  2666. ctx.project.overleaf.history.id,
  2667. userId,
  2668. {
  2669. oldDocs: [{ doc: ctx.doc, path: ctx.path }],
  2670. newFiles: [
  2671. {
  2672. file: ctx.file,
  2673. path: ctx.path,
  2674. createdBlob: true,
  2675. },
  2676. ],
  2677. newProject: ctx.project,
  2678. },
  2679. ctx.source
  2680. )
  2681. })
  2682. it('should notify real-time of the doc deletion', function (ctx) {
  2683. expect(ctx.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
  2684. ctx.project._id,
  2685. 'removeEntity',
  2686. ctx.doc._id,
  2687. 'convertDocToFile'
  2688. )
  2689. })
  2690. it('should notify real-time of the file creation', function (ctx) {
  2691. expect(ctx.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
  2692. ctx.project._id,
  2693. 'reciveNewFile',
  2694. ctx.folder._id,
  2695. ctx.file,
  2696. 'convertDocToFile',
  2697. null
  2698. )
  2699. })
  2700. })
  2701. describe('when the doc has ranges', function () {
  2702. it('should throw a DocHasRangesError', async function (ctx) {
  2703. ctx.ranges = { comments: [{ id: 123 }] }
  2704. ctx.DocstoreManager.promises.getDoc
  2705. .withArgs(ctx.project._id, ctx.doc._id)
  2706. .resolves({
  2707. lines: ctx.docLines,
  2708. rev: 'rev',
  2709. version: 'version',
  2710. ranges: ctx.ranges,
  2711. })
  2712. let error
  2713. try {
  2714. await ctx.ProjectEntityUpdateHandler.promises.convertDocToFile(
  2715. ctx.project._id,
  2716. ctx.doc._id,
  2717. ctx.user._id,
  2718. ctx.source
  2719. )
  2720. } catch (err) {
  2721. error = err
  2722. }
  2723. expect(error).to.be.instanceOf(Errors.DocHasRangesError)
  2724. })
  2725. })
  2726. })
  2727. describe('isPathValidForMainBibliographyDoc', function () {
  2728. it('should not allow other endings than .bib', function (ctx) {
  2729. const endings = ['.tex', '.png', '.jpg', '.pdf', '.docx', '.doc']
  2730. endings.forEach(ending => {
  2731. expect(
  2732. ctx.ProjectEntityUpdateHandler.isPathValidForMainBibliographyDoc(
  2733. `/foo/bar/baz${ending}`
  2734. )
  2735. ).to.be.false
  2736. })
  2737. })
  2738. it('should allow a mix of lower and uppercase letters', function (ctx) {
  2739. const endings = ['.bib', '.BiB', '.BIB', '.bIB']
  2740. endings.forEach(ending => {
  2741. expect(
  2742. ctx.ProjectEntityUpdateHandler.isPathValidForMainBibliographyDoc(
  2743. `/foo/bar/baz.${ending}`
  2744. )
  2745. ).to.be.true
  2746. })
  2747. })
  2748. it('should not allow a path without an extension', function (ctx) {
  2749. expect(
  2750. ctx.ProjectEntityUpdateHandler.isPathValidForMainBibliographyDoc(
  2751. '/foo/bar/baz'
  2752. )
  2753. ).to.be.false
  2754. })
  2755. it('should not allow the empty path', function (ctx) {
  2756. expect(
  2757. ctx.ProjectEntityUpdateHandler.isPathValidForMainBibliographyDoc('')
  2758. ).to.be.false
  2759. })
  2760. })
  2761. describe('setMainBibliographyDoc', function () {
  2762. describe('on success', function () {
  2763. beforeEach(async function (ctx) {
  2764. ctx.doc = {
  2765. _id: new ObjectId(),
  2766. name: 'test.bib',
  2767. }
  2768. ctx.path = '/path/to/test.bib'
  2769. ctx.ProjectEntityHandler.promises.getDocPathByProjectIdAndDocId
  2770. .withArgs(ctx.project._id, ctx.doc._id)
  2771. .resolves(ctx.path)
  2772. await ctx.ProjectEntityUpdateHandler.promises.setMainBibliographyDoc(
  2773. ctx.project._id,
  2774. ctx.doc._id
  2775. )
  2776. })
  2777. it('should update the project with the new main bibliography doc', function (ctx) {
  2778. expect(ctx.ProjectModel.updateOne).to.have.been.calledWith(
  2779. { _id: ctx.project._id },
  2780. { mainBibliographyDoc_id: ctx.doc._id }
  2781. )
  2782. })
  2783. })
  2784. describe('on failure', function () {
  2785. describe("when document can't be found", function () {
  2786. let setMainBibliographyDocPromise
  2787. beforeEach(function (ctx) {
  2788. ctx.doc = {
  2789. _id: new ObjectId(),
  2790. name: 'test.bib',
  2791. }
  2792. ctx.ProjectEntityHandler.promises.getDocPathByProjectIdAndDocId
  2793. .withArgs(ctx.project._id, ctx.doc._id)
  2794. .rejects(new Error('error'))
  2795. setMainBibliographyDocPromise =
  2796. ctx.ProjectEntityUpdateHandler.promises.setMainBibliographyDoc(
  2797. ctx.project._id,
  2798. ctx.doc._id
  2799. )
  2800. })
  2801. it('should call the callback with an error', async function () {
  2802. let error
  2803. try {
  2804. await setMainBibliographyDocPromise
  2805. } catch (err) {
  2806. error = err
  2807. }
  2808. expect(error).to.be.instanceOf(Error)
  2809. })
  2810. it('should not update the project with the new main bibliography doc', async function (ctx) {
  2811. let error
  2812. try {
  2813. await setMainBibliographyDocPromise
  2814. } catch (err) {
  2815. error = err
  2816. }
  2817. expect(error).to.exist
  2818. expect(ctx.ProjectModel.updateOne).to.not.have.been.called
  2819. })
  2820. })
  2821. describe("when path is not a bib file can't be found", function () {
  2822. let setMainBibliographyDocPromise
  2823. beforeEach(function (ctx) {
  2824. ctx.doc = {
  2825. _id: new ObjectId(),
  2826. name: 'test.bib',
  2827. }
  2828. ctx.path = '/path/to/test.tex'
  2829. ctx.ProjectEntityHandler.promises.getDocPathByProjectIdAndDocId
  2830. .withArgs(ctx.project._id, ctx.doc._id)
  2831. .resolves(ctx.path)
  2832. setMainBibliographyDocPromise =
  2833. ctx.ProjectEntityUpdateHandler.promises.setMainBibliographyDoc(
  2834. ctx.project._id,
  2835. ctx.doc._id
  2836. )
  2837. })
  2838. it('should reject with an error', async function () {
  2839. let error
  2840. try {
  2841. await setMainBibliographyDocPromise
  2842. } catch (err) {
  2843. error = err
  2844. }
  2845. expect(error).to.be.instanceOf(Error)
  2846. })
  2847. it('should not update the project with the new main bibliography doc', async function (ctx) {
  2848. let error
  2849. try {
  2850. await setMainBibliographyDocPromise
  2851. } catch (err) {
  2852. error = err
  2853. }
  2854. expect(error).to.exist
  2855. expect(ctx.ProjectModel.updateOne).to.not.have.been.called
  2856. })
  2857. })
  2858. })
  2859. })
  2860. describe('appendToDoc', function () {
  2861. describe('when document cannot be found', function () {
  2862. let appendToDocPromise
  2863. beforeEach(function (ctx) {
  2864. ctx.appendedLines = ['5678', 'def']
  2865. ctx.DocumentUpdaterHandler.promises.appendToDocument = sinon.stub()
  2866. ctx.ProjectLocator.promises.findElement = sinon.stub()
  2867. ctx.ProjectLocator.promises.findElement
  2868. .withArgs({ project_id: projectId, element_id: docId, type: 'doc' })
  2869. .rejects(new Errors.NotFoundError())
  2870. appendToDocPromise =
  2871. ctx.ProjectEntityUpdateHandler.promises.appendToDocWithPath(
  2872. projectId,
  2873. docId,
  2874. ctx.appendedLines,
  2875. ctx.source,
  2876. userId
  2877. )
  2878. })
  2879. it('should not talk to DocumentUpdaterHandler', async function (ctx) {
  2880. let error
  2881. try {
  2882. await appendToDocPromise
  2883. } catch (err) {
  2884. error = err
  2885. }
  2886. expect(error).to.exist
  2887. ctx.DocumentUpdaterHandler.promises.appendToDocument.should.not.have
  2888. .been.called
  2889. })
  2890. it('should throw the error', async function () {
  2891. let error
  2892. try {
  2893. await appendToDocPromise
  2894. } catch (err) {
  2895. error = err
  2896. }
  2897. expect(error).to.be.instanceOf(Errors.NotFoundError)
  2898. })
  2899. })
  2900. describe('when document is found', function () {
  2901. let appendToDocResult
  2902. beforeEach(async function (ctx) {
  2903. ctx.appendedLines = ['5678', 'def']
  2904. ctx.DocumentUpdaterHandler.promises.appendToDocument = sinon.stub()
  2905. ctx.DocumentUpdaterHandler.promises.appendToDocument
  2906. .withArgs(projectId, docId, userId, ctx.appendedLines, ctx.source)
  2907. .resolves({ rev: 1 })
  2908. ctx.ProjectLocator.promises.findElement = sinon.stub()
  2909. ctx.ProjectLocator.promises.findElement
  2910. .withArgs({ project_id: projectId, element_id: docId, type: 'doc' })
  2911. .resolves({ element: { _id: docId } })
  2912. appendToDocResult =
  2913. await ctx.ProjectEntityUpdateHandler.promises.appendToDocWithPath(
  2914. projectId,
  2915. docId,
  2916. ctx.appendedLines,
  2917. ctx.source,
  2918. userId
  2919. )
  2920. })
  2921. it('should forward call to DocumentUpdaterHandler.appendToDocument', function (ctx) {
  2922. ctx.DocumentUpdaterHandler.promises.appendToDocument.should.have.been.calledWith(
  2923. projectId,
  2924. docId,
  2925. userId,
  2926. ctx.appendedLines,
  2927. ctx.source
  2928. )
  2929. })
  2930. it('should return the response from DocumentUpdaterHandler', function () {
  2931. expect(appendToDocResult).to.eql({ rev: 1 })
  2932. })
  2933. })
  2934. describe('when DocumentUpdater throws an error', function () {
  2935. beforeEach(function (ctx) {
  2936. ctx.appendedLines = ['5678', 'def']
  2937. ctx.DocumentUpdaterHandler.promises.appendToDocument = sinon.stub()
  2938. ctx.DocumentUpdaterHandler.promises.appendToDocument.rejects(
  2939. new Error()
  2940. )
  2941. ctx.ProjectLocator.promises.findElement = sinon.stub()
  2942. ctx.ProjectLocator.promises.findElement
  2943. .withArgs({ project_id: projectId, element_id: docId, type: 'doc' })
  2944. .resolves({ element: { _id: docId } })
  2945. })
  2946. it('should return the response from DocumentUpdaterHandler', async function (ctx) {
  2947. let error
  2948. try {
  2949. await ctx.ProjectEntityUpdateHandler.promises.appendToDocWithPath(
  2950. projectId,
  2951. docId,
  2952. ctx.appendedLines,
  2953. ctx.source,
  2954. userId
  2955. )
  2956. } catch (err) {
  2957. error = err
  2958. }
  2959. expect(error).to.be.instanceOf(Error)
  2960. })
  2961. })
  2962. })
  2963. })