From 1ebc8a79cb7dd10f14aa0d0c8812e2abe63a7ae6 Mon Sep 17 00:00:00 2001
From: Alf Eaton <75253002+aeaton-overleaf@users.noreply.github.com>
Date: Wed, 14 Apr 2021 14:17:21 +0100
Subject: [PATCH] Merge pull request #3495 from overleaf/ae-prettier-2
Upgrade Prettier to v2
GitOrigin-RevId: 85aa3fa1acb6332c4f58c46165a43d1a51471f33
---
services/web/.prettierignore | 1 +
services/web/app.js | 4 +-
.../Features/Analytics/AnalyticsController.js | 6 +-
.../AuthenticationController.js | 204 +-
.../Authentication/AuthenticationManager.js | 12 +-
.../Authorization/AuthorizationManager.js | 153 +-
.../Authorization/AuthorizationMiddleware.js | 279 +-
.../BetaProgram/BetaProgramController.js | 6 +-
.../BrandVariations/BrandVariationsHandler.js | 6 +-
.../src/Features/Captcha/CaptchaMiddleware.js | 4 +-
.../app/src/Features/Chat/ChatApiHandler.js | 18 +-
.../app/src/Features/Chat/ChatController.js | 40 +-
.../CollaboratorsEmailHandler.js | 2 +-
.../CollaboratorsInviteController.js | 112 +-
.../CollaboratorsInviteHandler.js | 233 +-
.../src/Features/Compile/ClsiCookieManager.js | 16 +-
.../src/Features/Compile/ClsiFormatChecker.js | 10 +-
.../src/Features/Compile/ClsiStateManager.js | 76 +-
.../src/Features/Compile/CompileController.js | 170 +-
.../src/Features/Compile/CompileManager.js | 193 +-
.../Features/Contacts/ContactController.js | 103 +-
.../src/Features/Contacts/ContactManager.js | 8 +-
.../src/Features/Cooldown/CooldownManager.js | 20 +-
.../Features/Cooldown/CooldownMiddleware.js | 30 +-
.../src/Features/Docstore/DocstoreManager.js | 100 +-
.../DocumentUpdater/DocumentUpdaterHandler.js | 6 +-
.../Features/Documents/DocumentController.js | 84 +-
.../Downloads/ProjectDownloadsController.js | 44 +-
.../Downloads/ProjectZipStreamManager.js | 134 +-
.../src/Features/Editor/EditorController.js | 161 +-
.../src/Features/Exports/ExportsController.js | 77 +-
.../src/Features/Exports/ExportsHandler.js | 49 +-
.../src/Features/FileStore/FileHashManager.js | 10 +-
.../Features/FileStore/FileStoreController.js | 38 +-
.../Features/FileStore/FileStoreHandler.js | 18 +-
.../HealthCheck/HealthCheckController.js | 34 +-
.../src/Features/History/HistoryController.js | 34 +-
.../src/Features/History/RestoreManager.js | 77 +-
.../InactiveData/InactiveProjectController.js | 4 +-
.../InactiveData/InactiveProjectManager.js | 57 +-
.../Features/Institutions/InstitutionsAPI.js | 8 +-
.../Institutions/InstitutionsController.js | 14 +-
.../Institutions/InstitutionsFeatures.js | 21 +-
.../Institutions/InstitutionsGetter.js | 2 +-
.../Institutions/InstitutionsManager.js | 18 +-
.../LinkedFiles/LinkedFilesController.js | 81 +-
.../LinkedFiles/LinkedFilesHandler.js | 104 +-
.../Features/LinkedFiles/ProjectFileAgent.js | 24 +-
.../LinkedFiles/ProjectOutputFileAgent.js | 87 +-
.../app/src/Features/LinkedFiles/UrlAgent.js | 70 +-
.../src/Features/Metadata/MetaController.js | 73 +-
.../app/src/Features/Metadata/MetaHandler.js | 56 +-
.../Features/Newsletter/NewsletterManager.js | 5 +-
.../Notifications/NotificationsBuilder.js | 28 +-
.../Notifications/NotificationsController.js | 27 +-
.../Notifications/NotificationsHandler.js | 4 +-
.../Features/Project/ProjectApiController.js | 16 +-
.../ProjectCollabratecDetailsHandler.js | 14 +-
.../src/Features/Project/ProjectController.js | 13 +-
.../Project/ProjectCreationHandler.js | 197 +-
.../Project/ProjectEntityUpdateHandler.js | 28 +-
.../app/src/Features/Project/ProjectGetter.js | 66 +-
.../app/src/Features/Project/ProjectHelper.js | 2 +-
.../Features/Project/ProjectHistoryHandler.js | 111 +-
.../src/Features/Project/ProjectLocator.js | 7 +-
.../Features/Project/ProjectRootDocManager.js | 152 +-
.../Features/Project/ProjectUpdateHandler.js | 8 +-
.../web/app/src/Features/Project/SafePath.js | 2 +-
.../Features/Publishers/PublishersGetter.js | 2 +-
.../src/Features/Referal/ReferalAllocator.js | 6 +-
.../src/Features/Referal/ReferalFeatures.js | 6 +-
.../src/Features/Referal/ReferalHandler.js | 2 +-
.../References/ReferencesController.js | 4 +-
.../Features/References/ReferencesHandler.js | 51 +-
.../src/Features/Security/LoginRateLimiter.js | 2 +-
.../Features/Security/OneTimeTokenHandler.js | 8 +-
.../Security/RateLimiterMiddleware.js | 6 +-
.../Features/ServerAdmin/AdminController.js | 23 +-
.../Features/Spelling/SpellingController.js | 2 +-
.../Features/StaticPages/HomeController.js | 6 +-
.../Features/Subscription/FeaturesUpdater.js | 76 +-
.../Subscription/LimitationsManager.js | 122 +-
.../Features/Subscription/RecurlyWrapper.js | 205 +-
.../Subscription/SubscriptionController.js | 382 +--
.../SubscriptionGroupController.js | 46 +-
.../Subscription/SubscriptionGroupHandler.js | 14 +-
.../Subscription/SubscriptionHandler.js | 373 ++-
.../Subscription/SubscriptionLocator.js | 18 +-
.../Subscription/SubscriptionUpdater.js | 152 +-
.../Subscription/TeamInvitesController.js | 84 +-
.../Subscription/TeamInvitesHandler.js | 234 +-
.../Subscription/V1SubscriptionManager.js | 45 +-
.../SystemMessages/SystemMessageManager.js | 8 +-
.../app/src/Features/Tags/TagsController.js | 25 +-
.../web/app/src/Features/Tags/TagsHandler.js | 16 +-
.../Features/Templates/TemplatesController.js | 2 +-
.../Features/Templates/TemplatesManager.js | 14 +-
.../ThirdPartyDataStore/TpdsController.js | 2 +-
.../ThirdPartyDataStore/UpdateMerger.js | 307 +--
.../TokenAccess/TokenAccessHandler.js | 8 +-
.../Features/TokenGenerator/TokenGenerator.js | 6 +-
.../src/Features/Uploads/ArchiveManager.js | 134 +-
.../Uploads/ProjectUploadController.js | 10 +-
.../User/ThirdPartyIdentityManager.js | 41 +-
.../web/app/src/Features/User/UserCreator.js | 6 +-
.../User/UserEmailsConfirmationHandler.js | 6 +-
.../src/Features/User/UserEmailsController.js | 47 +-
.../web/app/src/Features/User/UserGetter.js | 10 +-
.../src/Features/User/UserInfoController.js | 4 +-
.../src/Features/User/UserSessionsManager.js | 30 +-
.../web/app/src/Features/User/UserUpdater.js | 6 +-
.../UserMembershipController.js | 141 +-
.../UserMembership/UserMembershipHandler.js | 26 +-
.../UserMembership/UserMembershipViewModel.js | 6 +-
.../UserMembership/UserMembershipsHandler.js | 36 +-
services/web/app/src/Features/V1/V1Handler.js | 8 +-
services/web/app/src/infrastructure/CSP.js | 4 +-
services/web/app/src/infrastructure/Csrf.js | 2 +-
.../app/src/infrastructure/ExpressLocals.js | 64 +-
.../web/app/src/infrastructure/FileWriter.js | 26 +-
.../web/app/src/infrastructure/GeoIpLookup.js | 4 +-
.../web/app/src/infrastructure/Modules.js | 2 +-
.../app/src/infrastructure/ProxyManager.js | 8 +-
.../app/src/infrastructure/RandomLogging.js | 2 +-
.../web/app/src/infrastructure/RateLimiter.js | 4 +-
.../app/src/infrastructure/RedirectManager.js | 4 +-
services/web/app/src/infrastructure/Server.js | 10 +-
.../src/infrastructure/SessionStoreManager.js | 2 +-
.../app/src/infrastructure/Translations.js | 2 +-
services/web/app/src/models/Institution.js | 2 +-
services/web/app/src/models/Project.js | 2 +-
services/web/app/src/models/ProjectInvite.js | 2 +-
services/web/app/src/models/Publisher.js | 2 +-
services/web/app/src/models/Subscription.js | 4 +-
services/web/app/src/router.js | 64 +-
services/web/frontend/js/base.js | 2 +-
.../web/frontend/js/directives/asyncForm.js | 12 +-
.../frontend/js/directives/autoSubmitForm.js | 2 +-
.../js/directives/bookmarkableTabset.js | 11 +-
.../frontend/js/directives/complexPassword.js | 7 +-
services/web/frontend/js/directives/equals.js | 2 +-
.../frontend/js/directives/eventTracking.js | 6 +-
.../js/directives/expandableTextArea.js | 2 +-
.../web/frontend/js/directives/fineUpload.js | 12 +-
services/web/frontend/js/directives/focus.js | 10 +-
.../web/frontend/js/directives/mathjax.js | 2 +-
.../web/frontend/js/directives/maxHeight.js | 2 +-
.../web/frontend/js/directives/onEnter.js | 2 +-
.../web/frontend/js/directives/rightClick.js | 2 +-
.../web/frontend/js/directives/selectAll.js | 14 +-
.../frontend/js/directives/videoPlayState.js | 2 +-
.../chat/controllers/chat-controller.js | 2 +-
...eft-menu-clone-project-modal-controller.js | 66 +-
.../editor-navigation-toolbar-controller.js | 2 +-
.../file-tree/contexts/file-tree-main.js | 2 +-
.../file-tree/contexts/file-tree-mutable.js | 2 +-
.../controllers/file-tree-controller.js | 2 +-
.../controllers/hotkeys-modal-controller.js | 2 +-
.../outline/controllers/outline-controller.js | 2 +-
.../react-share-project-modal-controller.js | 107 +-
.../word-count-modal-controller.js | 36 +-
.../web/frontend/js/filters/formatDate.js | 10 +-
services/web/frontend/js/ide.js | 529 ++--
.../controllers/BinaryFileController.js | 347 ++-
.../chat/controllers/ChatButtonController.js | 10 +-
.../CloneProjectModalController.js | 77 +-
.../ide/cobranding/CobrandingDataService.js | 2 +-
.../js/ide/connection/ConnectionManager.js | 2 +-
.../js/ide/connection/SocketIoShim.js | 2 +-
.../web/frontend/js/ide/directives/layout.js | 22 +-
.../web/frontend/js/ide/editor/Document.js | 15 +-
.../frontend/js/ide/editor/EditorManager.js | 4 +-
.../web/frontend/js/ide/editor/ShareJsDoc.js | 4 +-
.../SavingNotificationController.js | 143 +-
.../js/ide/editor/directives/aceEditor.js | 1580 +++++------
.../auto-complete/AutoCompleteManager.js | 6 +-
.../aceEditor/auto-complete/CommandManager.js | 6 +-
.../auto-complete/EnvironmentManager.js | 8 +-
.../cursor-position/CursorPositionAdapter.js | 5 +-
.../aceEditor/highlights/HighlightsManager.js | 2 +-
.../aceEditor/metadata/MetadataManager.js | 2 +-
.../spell-check/SpellCheckManager.js | 2 +-
.../track-changes/TrackChangesAdapter.js | 9 +-
.../track-changes/TrackChangesManager.js | 5 +-
.../directives/aceEditor/undo/UndoManager.js | 5 +-
.../js/ide/file-tree/FileTreeManager.js | 23 +-
.../controllers/FileTreeController.js | 1173 +++++----
.../controllers/FileTreeEntityController.js | 248 +-
.../controllers/FileTreeFolderController.js | 213 +-
.../FileTreeRootFolderController.js | 67 +-
.../js/ide/file-tree/directives/draggable.js | 2 +-
.../js/ide/file-tree/directives/droppable.js | 2 +-
.../js/ide/file-tree/directives/fileEntity.js | 36 +-
.../js/ide/file-tree/util/iconTypeFromName.js | 2 +-
.../frontend/js/ide/files/services/files.js | 4 +-
.../js/ide/graphics/services/graphics.js | 4 +-
.../frontend/js/ide/history/HistoryManager.js | 4 +-
.../js/ide/history/HistoryV2Manager.js | 10 +-
.../history/components/historyEntriesList.js | 8 +-
.../js/ide/history/components/historyEntry.js | 12 +-
.../history/components/historyFileEntity.js | 8 +-
.../ide/history/components/historyFileTree.js | 4 +-
.../js/ide/history/components/historyLabel.js | 2 +-
.../history/components/historyLabelsList.js | 10 +-
.../controllers/HistoryDiffController.js | 97 +-
.../controllers/HistoryListController.js | 109 +-
.../HistoryV2AddLabelModalController.js | 68 +-
.../HistoryV2DeleteLabelModalController.js | 58 +-
.../HistoryV2FileTreeController.js | 14 +-
.../controllers/HistoryV2ListController.js | 75 +-
.../controllers/HistoryV2ToolbarController.js | 8 +-
.../ide/history/directives/infiniteScroll.js | 6 +-
.../js/ide/history/util/displayNameForUser.js | 2 +-
.../js/ide/hotkeys/BackspaceHighjack.js | 2 +-
.../human-readable-logs/HumanReadableLogs.js | 2 +-
.../js/ide/metadata/services/metadata.js | 16 +-
.../js/ide/online-users/OnlineUsersManager.js | 2 +-
.../controllers/OnlineUsersController.js | 6 +-
.../js/ide/pdf/controllers/PdfController.js | 1774 ++++++-------
.../controllers/PdfViewToggleController.js | 6 +-
.../js/ide/pdfng/directives/pdfAnnotations.js | 2 +-
.../js/ide/pdfng/directives/pdfHighlights.js | 2 +-
.../frontend/js/ide/pdfng/directives/pdfJs.js | 24 +-
.../js/ide/pdfng/directives/pdfPage.js | 33 +-
.../js/ide/pdfng/directives/pdfRenderer.js | 898 +++----
.../js/ide/pdfng/directives/pdfSpinner.js | 2 +-
.../js/ide/pdfng/directives/pdfTextLayer.js | 4 +-
.../js/ide/pdfng/directives/pdfViewer.js | 626 +++--
.../js/ide/preamble/services/preamble.js | 2 +-
.../js/ide/review-panel/RangesTracker.js | 4 +-
.../controllers/BulkActionsModalController.js | 20 +-
.../controllers/ReviewPanelController.js | 2309 +++++++++--------
.../directives/addCommentEntry.js | 10 +-
.../directives/aggregateChangeEntry.js | 6 +-
.../review-panel/directives/changeEntry.js | 4 +-
.../review-panel/directives/commentEntry.js | 18 +-
.../directives/resolvedCommentsDropdown.js | 10 +-
.../directives/reviewPanelCollapseHeight.js | 2 +-
.../directives/reviewPanelSorted.js | 10 +-
.../directives/reviewPanelToggle.js | 4 +-
.../js/ide/review-panel/filters/numKeys.js | 2 +-
.../filters/orderOverviewEntries.js | 2 +-
services/web/frontend/js/ide/services/ide.js | 278 +-
.../controllers/ProjectNameController.js | 114 +-
.../controllers/SettingsController.js | 391 ++-
...OwnershipTransferConfirmModalController.js | 62 +-
.../ide/share/controllers/ShareController.js | 4 +-
.../ShareProjectModalController.js | 42 +-
.../ShareProjectModalMemberRowController.js | 79 +-
.../js/infrastructure/error-boundary.js | 6 +-
.../js/infrastructure/local-storage.js | 10 +-
services/web/frontend/js/main.js | 2 +-
.../web/frontend/js/main/account-settings.js | 125 +-
.../js/main/account-upgrade-angular.js | 4 +-
.../web/frontend/js/main/account-upgrade.js | 4 +-
.../components/affiliationForm.js | 64 +-
.../components/inputSuggestions.js | 12 +-
.../controllers/UserAffiliationsController.js | 582 +++--
.../UserAffiliationsReconfirmController.js | 111 +-
.../factories/UserAffiliationsDataService.js | 8 +-
.../web/frontend/js/main/annual-upgrade.js | 59 +-
.../web/frontend/js/main/clear-sessions.js | 46 +-
services/web/frontend/js/main/event.js | 14 +-
services/web/frontend/js/main/importing.js | 32 +-
services/web/frontend/js/main/learn.js | 163 +-
.../web/frontend/js/main/new-subscription.js | 1207 +++++----
.../oauth/controllers/UserOauthController.js | 93 +-
services/web/frontend/js/main/plans.js | 403 +--
services/web/frontend/js/main/post-gateway.js | 4 +-
.../left-hand-menu-promo-controller.js | 45 +-
.../js/main/project-list/modal-controllers.js | 317 ++-
.../project-list/notifications-controller.js | 118 +-
.../js/main/project-list/project-list.js | 246 +-
.../project-list/services/project-list.js | 2 +-
.../js/main/project-list/tag-controllers.js | 225 +-
.../web/frontend/js/main/register-users.js | 64 +-
.../js/main/subscription-dashboard.js | 271 +-
.../subscription/team-invite-controller.js | 10 +-
.../main/subscription/upgrade-subscription.js | 14 +-
.../web/frontend/js/main/system-messages.js | 32 +-
services/web/frontend/js/main/translations.js | 45 +-
.../web/frontend/js/main/user-membership.js | 20 +-
.../web/frontend/js/modules/errorCatcher.js | 2 +-
.../frontend/js/modules/recursionHelper.js | 4 +-
.../web/frontend/js/modules/sessionStorage.js | 20 +-
.../frontend/js/services/algolia-search.js | 2 +-
.../web/frontend/js/services/queued-http.js | 14 +-
.../frontend/js/services/validateCaptcha.js | 6 +-
.../frontend/js/services/validateCaptchaV3.js | 4 +-
services/web/frontend/js/services/wait-for.js | 8 +-
.../js/shared/hooks/use-resize-observer.js | 2 +-
.../web/frontend/stories/file-tree.stories.js | 4 +-
.../stories/fixtures/file-tree-limit.js | 4 +-
.../frontend/stylesheets/app/editor/pdf.less | 2 +
.../stylesheets/components/carousel.less | 2 +
.../stylesheets/components/modals.less | 2 +-
.../stylesheets/components/theme.less | 13 +
.../web/frontend/stylesheets/core/type.less | 2 +-
services/web/karma.conf.js | 4 +-
.../launchpad/app/src/LaunchpadController.js | 194 +-
.../main/controllers/LaunchpadController.js | 269 +-
.../test/unit/src/LaunchpadControllerTests.js | 260 +-
services/web/modules/modules-ide.js | 2 +-
services/web/modules/modules-main.js | 2 +-
.../unit/src/UserActivateControllerTests.js | 20 +-
services/web/package-lock.json | 6 +-
services/web/package.json | 2 +-
.../web/scripts/check_institution_users.js | 20 +-
.../recurly/get_paypal_accounts_csv.js | 5 +-
.../web/scripts/refresh_institution_users.js | 20 +-
.../test/acceptance/src/AdminEmailTests.js | 16 +-
.../web/test/acceptance/src/ApiClsiTests.js | 28 +-
.../acceptance/src/AuthenticationTests.js | 16 +-
.../test/acceptance/src/AuthorizationTests.js | 118 +-
.../src/BackFillDeletedFilesTests.js | 34 +-
.../src/BackFillDocNameForDeletedDocsTests.js | 24 +-
.../test/acceptance/src/BetaProgramTests.js | 8 +-
.../acceptance/src/BodyParserErrorsTest.js | 22 +-
.../web/test/acceptance/src/BonusTests.js | 6 +-
.../web/test/acceptance/src/CloseSiteTests.js | 20 +-
.../acceptance/src/ConvertArchivedState.js | 14 +-
.../web/test/acceptance/src/DeletionTests.js | 100 +-
.../web/test/acceptance/src/DocUpdateTests.js | 30 +-
.../src/EditorHttpControllerTests.js | 18 +-
.../web/test/acceptance/src/ExportsTests.js | 14 +-
.../acceptance/src/FeatureUpdaterTests.js | 82 +-
.../src/HealthCheckControllerTests.js | 26 +-
.../web/test/acceptance/src/HistoryTests.js | 22 +-
.../web/test/acceptance/src/LabelsTests.js | 12 +-
.../test/acceptance/src/LinkedFilesTests.js | 42 +-
.../web/test/acceptance/src/ModelTests.js | 16 +-
.../web/test/acceptance/src/MongoHelper.js | 50 +-
.../test/acceptance/src/PasswordResetTests.js | 60 +-
.../acceptance/src/PasswordUpdateTests.js | 52 +-
.../test/acceptance/src/ProjectCRUDTests.js | 34 +-
.../src/ProjectDuplicateNameTests.js | 164 +-
.../acceptance/src/ProjectFeaturesTests.js | 24 +-
.../test/acceptance/src/ProjectInviteTests.js | 76 +-
.../src/ProjectOwnershipTransferTests.js | 24 +-
.../src/ProjectStructureMongoLockTest.js | 30 +-
.../acceptance/src/ProjectStructureTests.js | 156 +-
services/web/test/acceptance/src/ProxyUrls.js | 12 +-
.../src/RecurlySubscriptionUpdateTests.js | 8 +-
.../test/acceptance/src/RedirectUrlsTests.js | 18 +-
.../test/acceptance/src/RegistrationTests.js | 62 +-
.../test/acceptance/src/RestoringFilesTest.js | 44 +-
.../acceptance/src/SecurityHeadersTests.js | 26 +-
.../web/test/acceptance/src/SessionTests.js | 26 +-
.../web/test/acceptance/src/SettingsTests.js | 14 +-
.../web/test/acceptance/src/SharingTests.js | 24 +-
.../src/SubscriptionDashboardTests.js | 94 +-
.../src/SubscriptionDeletionTests.js | 12 +-
.../src/SubscriptionFeaturesTests.js | 18 +-
services/web/test/acceptance/src/TagsTests.js | 46 +-
.../test/acceptance/src/TokenAccessTests.js | 110 +-
.../test/acceptance/src/TpdsUpdateTests.js | 30 +-
.../test/acceptance/src/UserEmailsTests.js | 90 +-
.../test/acceptance/src/UserHelperTests.js | 74 +-
.../src/UserMembershipAuthorizationTests.js | 42 +-
.../test/acceptance/src/UserReconfirmTests.js | 12 +-
.../src/UserThirdPartyIdentityTests.js | 48 +-
.../test/acceptance/src/helpers/InitApp.js | 4 +-
.../acceptance/src/helpers/MongoHelper.js | 4 +-
.../src/helpers/RecurlySubscription.js | 2 +-
.../test/acceptance/src/helpers/UserHelper.js | 4 +-
.../web/test/acceptance/src/helpers/redis.js | 4 +-
.../test/acceptance/src/helpers/request.js | 2 +-
.../chat/components/chat-pane.test.js | 16 +-
.../chat/components/message-input.test.js | 10 +-
.../chat/components/message-list.test.js | 14 +-
.../features/chat/components/message.test.js | 22 +-
.../features/chat/store/chat-store.test.js | 58 +-
.../chat/store/message-list-appender.test.js | 48 +-
.../components/clone-project-modal.test.js | 12 +-
.../file-tree-create-name-input.test.js | 14 +-
.../file-tree-modal-create-file.test.js | 20 +-
.../components/file-tree-doc.test.js | 12 +-
.../components/file-tree-folder-list.test.js | 12 +-
.../components/file-tree-folder.test.js | 12 +-
.../file-tree-item-inner.test.js | 22 +-
.../file-tree-item-menu.test.js | 8 +-
.../file-tree-item-name.test.js | 20 +-
.../components/file-tree-root.test.js | 16 +-
.../components/file-tree-toolbar.test.js | 10 +-
.../file-tree/flows/context-menu.test.js | 6 +-
.../file-tree/flows/create-folder.test.js | 18 +-
.../file-tree/flows/delete-entity.test.js | 32 +-
.../file-tree/flows/rename-entity.test.js | 28 +-
.../util/icon-type-from-name.test.js | 8 +-
.../components/hotkeys-modal.test.js | 14 +-
.../outline/components/outline-item.test.js | 14 +-
.../outline/components/outline-list.test.js | 8 +-
.../outline/components/outline-pane.test.js | 14 +-
.../outline/components/outline-root.test.js | 6 +-
.../features/outline/outline-parser.test.js | 28 +-
.../preview-download-button.test.js | 34 +-
.../preview-download-file-list.test.js | 21 +-
.../preview-logs-pane-entry.test.js | 36 +-
.../components/preview-logs-pane.test.js | 32 +-
.../preview-logs-toggle-button.test.js | 26 +-
.../preview/components/preview-pane.test.js | 28 +-
.../preview-recompile-button.test.js | 26 +-
.../components/preview-toolbar.test.js | 10 +-
.../components/share-project-modal.test.js | 50 +-
.../components/word-count-modal.test.js | 14 +-
.../history/util/displayNameForUserTests.js | 16 +-
.../infrastructure/fetch-json.test.js | 18 +-
.../infrastructure/local-storage.test.js | 18 +-
services/web/test/frontend/prop-types.test.js | 4 +-
.../frontend/shared/components/icon.test.js | 16 +-
.../shared/hooks/use-expand-collapse.test.js | 28 +-
.../test/frontend/utils/EventEmitterTests.js | 16 +-
.../spell-check/SpellCheckManagerTests.js | 54 +-
.../ide/history/HistoryV2ManagerTests.js | 86 +-
services/web/test/karma/import_tests.js | 2 +-
.../src/Analytics/AnalyticsControllerTests.js | 24 +-
.../src/Analytics/AnalyticsManagerTests.js | 18 +-
.../AuthenticationControllerTests.js | 390 ++-
.../AuthenticationManagerTests.js | 198 +-
.../AuthorizationManagerTests.js | 292 +--
.../AuthorizationMiddlewareTests.js | 189 +-
.../BetaProgram/BetaProgramControllerTests.js | 54 +-
.../BetaProgram/BetaProgramHandlerTests.js | 32 +-
.../BrandVariationsHandlerTests.js | 14 +-
.../test/unit/src/Chat/ChatApiHandlerTests.js | 38 +-
.../test/unit/src/Chat/ChatControllerTests.js | 34 +-
.../CollaboratorsControllerTests.js | 68 +-
.../Collaborators/CollaboratorsGetterTests.js | 76 +-
.../CollaboratorsHandlerTests.js | 86 +-
.../CollaboratorsInviteControllerTests.js | 372 +--
.../CollaboratorsInviteHandlerTests.js | 316 +--
.../OwnershipTransferHandlerTests.js | 30 +-
.../src/Compile/ClsiCookieManagerTests.js | 42 +-
.../src/Compile/ClsiFormatCheckerTests.js | 32 +-
.../test/unit/src/Compile/ClsiManagerTests.js | 250 +-
.../unit/src/Compile/ClsiStateManagerTests.js | 80 +-
.../src/Compile/CompileControllerTests.js | 196 +-
.../unit/src/Compile/CompileManagerTests.js | 92 +-
.../src/Contact/ContactControllerTests.js | 18 +-
.../unit/src/Contact/ContactManagerTests.js | 36 +-
.../unit/src/Cooldown/CooldownManagerTests.js | 60 +-
.../src/Cooldown/CooldownMiddlewareTests.js | 40 +-
.../unit/src/Docstore/DocstoreManagerTests.js | 176 +-
.../DocumentUpdaterHandlerTests.js | 272 +-
.../src/Documents/DocumentControllerTests.js | 60 +-
.../unit/src/Documents/DocumentHelperTests.js | 46 +-
.../ProjectDownloadsControllerTests.js | 38 +-
.../Downloads/ProjectZipStreamManagerTests.js | 70 +-
.../unit/src/Editor/EditorControllerTests.js | 216 +-
.../src/Editor/EditorHttpControllerTests.js | 144 +-
.../Editor/EditorRealTimeControllerTests.js | 18 +-
.../test/unit/src/Email/EmailBuilderTests.js | 192 +-
.../test/unit/src/Email/EmailHandlerTests.js | 22 +-
.../unit/src/Email/EmailMessageHelperTests.js | 12 +-
.../test/unit/src/Email/EmailSenderTests.js | 28 +-
.../web/test/unit/src/Email/SpamSafeTests.js | 4 +-
.../unit/src/Errors/HttpErrorHandlerTests.js | 94 +-
.../src/Exports/ExportsControllerTests.js | 24 +-
.../unit/src/Exports/ExportsHandlerTests.js | 142 +-
.../src/FileStore/FileStoreControllerTests.js | 54 +-
.../src/FileStore/FileStoreHandlerTests.js | 86 +-
.../HelperFiles/AuthorizationHelperTests.js | 16 +-
.../unit/src/HelperFiles/NewLogsUITests.js | 48 +-
.../HelperFiles/SafeHTMLSubstituteTests.js | 52 +-
.../unit/src/HelperFiles/UrlHelperTests.js | 8 +-
.../src/History/HistoryControllerTests.js | 102 +-
.../unit/src/History/HistoryManagerTests.js | 58 +-
.../unit/src/History/RestoreManagerTests.js | 60 +-
.../InactiveProjectManagerTests.js | 20 +-
.../Institutions/InstitutionHelperTests.js | 14 +-
.../src/Institutions/InstitutionsAPITests.js | 56 +-
.../InstitutionsControllerTests.js | 15 +-
.../Institutions/InstitutionsFeaturesTests.js | 32 +-
.../Institutions/InstitutionsGetterTests.js | 12 +-
.../Institutions/InstitutionsManagerTests.js | 22 +-
.../unit/src/Metadata/MetaControllerTests.js | 62 +-
.../unit/src/Metadata/MetaHandlerTests.js | 42 +-
.../src/Newsletter/NewsletterManagerTests.js | 36 +-
.../NotificationsBuilderTests.js | 18 +-
.../NotificationsControllerTests.js | 8 +-
.../NotificationsHandlerTests.js | 34 +-
.../PasswordResetControllerTests.js | 94 +-
.../PasswordResetHandlerTests.js | 114 +-
.../src/Project/DocLinesComparitorTests.js | 24 +-
.../Project/FolderStructureBuilderTests.js | 22 +-
.../src/Project/ProjectApiControllerTests.js | 10 +-
.../Project/ProjectAuditLogHandlerTests.js | 20 +-
.../Project/ProjectCollabratecDetailsTest.js | 166 +-
.../src/Project/ProjectControllerTests.js | 300 +--
.../Project/ProjectCreationHandlerTests.js | 112 +-
.../unit/src/Project/ProjectDeleterTests.js | 148 +-
.../src/Project/ProjectDetailsHandlerTests.js | 126 +-
.../src/Project/ProjectDuplicatorTests.js | 48 +-
.../src/Project/ProjectEditorHandlerTests.js | 94 +-
.../src/Project/ProjectEntityHandlerTests.js | 72 +-
.../ProjectEntityMongoUpdateHandlerTests.js | 212 +-
.../ProjectEntityUpdateHandlerTests.js | 478 ++--
.../unit/src/Project/ProjectGetterTests.js | 136 +-
.../unit/src/Project/ProjectHelperTests.js | 76 +-
.../src/Project/ProjectHistoryHandlerTests.js | 42 +-
.../unit/src/Project/ProjectLocatorTests.js | 92 +-
.../src/Project/ProjectOptionsHandlerTests.js | 74 +-
.../src/Project/ProjectRootDocManagerTests.js | 182 +-
.../src/Project/ProjectUpdateHandlerTests.js | 26 +-
.../test/unit/src/Project/SafePathTests.js | 106 +-
.../src/Publishers/PublishersGetterTests.js | 8 +-
.../unit/src/Referal/ReferalAllocatorTests.js | 42 +-
.../unit/src/Referal/ReferalConnectTests.js | 26 +-
.../src/Referal/ReferalControllerTests.js | 4 +-
.../unit/src/Referal/ReferalFeaturesTests.js | 20 +-
.../unit/src/Referal/ReferalHandlerTests.js | 16 +-
.../References/ReferencesControllerTests.js | 92 +-
.../src/References/ReferencesHandlerTests.js | 146 +-
.../unit/src/SamlLog/SamlLogHandlerTests.js | 24 +-
.../src/Security/LoginRateLimiterTests.js | 34 +-
.../src/Security/OneTimeTokenHandlerTests.js | 42 +-
.../Security/RateLimiterMiddlewareTests.js | 50 +-
.../SessionAutostartMiddlewareTests.js | 26 +-
.../src/Security/SessionStoreManagerTests.js | 34 +-
.../test/unit/src/Settings/SettingsTests.js | 4 +-
.../src/Spelling/SpellingControllerTests.js | 56 +-
.../unit/src/Spelling/SpellingHandlerTests.js | 28 +-
.../src/Subscription/FeaturesUpdaterTests.js | 82 +-
.../Subscription/LimitationsManagerTests.js | 146 +-
.../src/Subscription/RecurlyClientTests.js | 24 +-
.../src/Subscription/RecurlyWrapperTests.js | 394 +--
.../SubscriptionControllerTests.js | 178 +-
.../SubscriptionGroupControllerTests.js | 12 +-
.../SubscriptionGroupHandlerTests.js | 38 +-
.../Subscription/SubscriptionHandlerTests.js | 136 +-
.../Subscription/SubscriptionLocatorTests.js | 12 +-
.../Subscription/SubscriptionUpdaterTests.js | 94 +-
.../Subscription/TeamInvitesHandlerTests.js | 54 +-
.../Subscription/UserFeaturesUpdaterTests.js | 8 +-
.../V1SusbcriptionManagerTests.js | 106 +-
.../SystemMessageManagerTests.js | 20 +-
.../test/unit/src/Tags/TagsControllerTests.js | 60 +-
.../test/unit/src/Tags/TagsHandlerTests.js | 58 +-
.../src/Templates/TemplatesControllerTests.js | 24 +-
.../src/Templates/TemplatesManagerTests.js | 30 +-
.../TpdsControllerTests.js | 60 +-
.../TpdsProjectFlusherTests.js | 59 +-
.../TpdsUpdateHandlerTests.js | 96 +-
.../TpdsUpdateSenderTests.js | 28 +-
.../ThirdPartyDataStore/UpdateMergerTests.js | 92 +-
.../TokenAccess/TokenAccessHandlerTests.js | 198 +-
.../unit/src/Uploads/ArchiveManagerTests.js | 146 +-
.../Uploads/FileSystemImportManagerTests.js | 82 +-
.../unit/src/Uploads/FileTypeManagerTests.js | 66 +-
.../Uploads/ProjectUploadControllerTests.js | 74 +-
.../src/Uploads/ProjectUploadManagerTests.js | 62 +-
.../unit/src/User/SAMLIdentityManagerTests.js | 94 +-
.../User/ThirdPartyIdentityManagerTests.js | 48 +-
.../unit/src/User/UserAuditLogHandlerTests.js | 32 +-
.../test/unit/src/User/UserControllerTests.js | 224 +-
.../test/unit/src/User/UserCreatorTests.js | 72 +-
.../test/unit/src/User/UserDeleterTests.js | 108 +-
.../UserEmailsConfirmationHandlerTests.js | 74 +-
.../src/User/UserEmailsControllerTests.js | 116 +-
.../web/test/unit/src/User/UserGetterTests.js | 97 +-
.../test/unit/src/User/UserHandlerTests.js | 10 +-
.../unit/src/User/UserInfoControllerTests.js | 52 +-
.../User/UserOnboardingEmailManagerTests.js | 12 +-
.../unit/src/User/UserPagesControllerTests.js | 70 +-
.../src/User/UserRegistrationHandlerTests.js | 78 +-
.../unit/src/User/UserSessionsManagerTests.js | 222 +-
.../test/unit/src/User/UserUpdaterTests.js | 124 +-
.../UserMembershipControllerTests.js | 68 +-
.../UserMembershipHandlerTests.js | 50 +-
.../UserMembershipViewModelTests.js | 22 +-
.../UserMembershipsHandlerTests.js | 8 +-
.../test/unit/src/infrastructure/CsrfTests.js | 58 +-
.../unit/src/infrastructure/FeaturesTests.js | 62 +-
.../src/infrastructure/GeoIpLookupTests.js | 30 +-
.../LockManager/ReleasingTheLock.js | 4 +-
.../LockManager/getLockTests.js | 42 +-
.../LockManager/tryLockTests.js | 18 +-
.../src/infrastructure/ProxyManagerTests.js | 36 +-
.../src/infrastructure/RateLimterTests.js | 30 +-
.../RequestContentTypeDetectionTests.js | 14 +-
.../src/infrastructure/TranslationsTests.js | 32 +-
.../web/test/unit/src/util/promisesTests.js | 36 +-
582 files changed, 20382 insertions(+), 20374 deletions(-)
diff --git a/services/web/.prettierignore b/services/web/.prettierignore
index 4c6c6dc3da..04ecd4764c 100644
--- a/services/web/.prettierignore
+++ b/services/web/.prettierignore
@@ -5,3 +5,4 @@ frontend/js/vendor
modules/**/frontend/js/vendor
public/js
public/minjs
+frontend/stylesheets/components/nvd3.less
diff --git a/services/web/app.js b/services/web/app.js
index 04555ef362..f1ee079cd3 100644
--- a/services/web/app.js
+++ b/services/web/app.js
@@ -45,7 +45,7 @@ if (!module.parent) {
}
Promise.all([mongodb.waitForDb(), mongoose.connectionPromise])
.then(() => {
- Server.server.listen(port, host, function() {
+ Server.server.listen(port, host, function () {
logger.info(`web starting up, listening on ${host}:${port}`)
logger.info(`${require('http').globalAgent.maxSockets} sockets enabled`)
// wait until the process is ready before monitoring the event loop
@@ -59,7 +59,7 @@ if (!module.parent) {
}
// handle SIGTERM for graceful shutdown in kubernetes
-process.on('SIGTERM', function(signal) {
+process.on('SIGTERM', function (signal) {
logger.warn({ signal: signal }, 'received signal, shutting down')
Settings.shuttingDown = true
})
diff --git a/services/web/app/src/Features/Analytics/AnalyticsController.js b/services/web/app/src/Features/Analytics/AnalyticsController.js
index 063bb1b64f..c0ce26ca06 100644
--- a/services/web/app/src/Features/Analytics/AnalyticsController.js
+++ b/services/web/app/src/Features/Analytics/AnalyticsController.js
@@ -15,7 +15,7 @@ module.exports = {
let countryCode = null
if (userId) {
- GeoIpLookup.getDetails(req.ip, function(err, geoDetails) {
+ GeoIpLookup.getDetails(req.ip, function (err, geoDetails) {
if (err) {
metrics.inc('analytics_geo_ip_lookup_errors')
} else if (geoDetails && geoDetails.country_code) {
@@ -43,7 +43,7 @@ module.exports = {
req.query.start_date,
req.query.end_date,
req.query.lag,
- function(error, licences) {
+ function (error, licences) {
if (error) {
return next(error)
}
@@ -58,7 +58,7 @@ module.exports = {
req.query.start_date,
req.query.end_date,
req.query.lag,
- function(error, licences) {
+ function (error, licences) {
if (error) {
return next(error)
}
diff --git a/services/web/app/src/Features/Authentication/AuthenticationController.js b/services/web/app/src/Features/Authentication/AuthenticationController.js
index 9a41b33de1..5b71b0294d 100644
--- a/services/web/app/src/Features/Authentication/AuthenticationController.js
+++ b/services/web/app/src/Features/Authentication/AuthenticationController.js
@@ -58,7 +58,7 @@ const AuthenticationController = {
// This function is middleware which wraps the passport.authenticate middleware,
// so we can send back our custom `{message: {text: "", type: ""}}` responses on failure,
// and send a `{redir: ""}` response on success
- passport.authenticate('local', function(err, user, info) {
+ passport.authenticate('local', function (err, user, info) {
if (err) {
return next(err)
}
@@ -81,86 +81,96 @@ const AuthenticationController = {
} // OAuth2 'state' mismatch
const Modules = require('../../infrastructure/Modules')
- Modules.hooks.fire('preFinishLogin', req, res, user, function(
- error,
- results
- ) {
- if (error) {
- return next(error)
- }
- if (results.some(result => result && result.doNotFinish)) {
- return
- }
-
- if (user.must_reconfirm) {
- return AuthenticationController._redirectToReconfirmPage(req, res, user)
- }
-
- const redir =
- AuthenticationController._getRedirectFromSession(req) || '/project'
- _loginAsyncHandlers(req, user)
- const userId = user._id
- UserAuditLogHandler.addEntry(userId, 'login', userId, req.ip, err => {
- if (err) {
- return next(err)
+ Modules.hooks.fire(
+ 'preFinishLogin',
+ req,
+ res,
+ user,
+ function (error, results) {
+ if (error) {
+ return next(error)
}
- _afterLoginSessionSetup(req, user, function(err) {
+ if (results.some(result => result && result.doNotFinish)) {
+ return
+ }
+
+ if (user.must_reconfirm) {
+ return AuthenticationController._redirectToReconfirmPage(
+ req,
+ res,
+ user
+ )
+ }
+
+ const redir =
+ AuthenticationController._getRedirectFromSession(req) || '/project'
+ _loginAsyncHandlers(req, user)
+ const userId = user._id
+ UserAuditLogHandler.addEntry(userId, 'login', userId, req.ip, err => {
if (err) {
return next(err)
}
- AuthenticationController._clearRedirectFromSession(req)
- AsyncFormHelper.redirect(req, res, redir)
+ _afterLoginSessionSetup(req, user, function (err) {
+ if (err) {
+ return next(err)
+ }
+ AuthenticationController._clearRedirectFromSession(req)
+ AsyncFormHelper.redirect(req, res, redir)
+ })
})
- })
- })
+ }
+ )
},
doPassportLogin(req, username, password, done) {
const email = username.toLowerCase()
const Modules = require('../../infrastructure/Modules')
- Modules.hooks.fire('preDoPassportLogin', req, email, function(
- err,
- infoList
- ) {
- if (err) {
- return done(err)
- }
- const info = infoList.find(i => i != null)
- if (info != null) {
- return done(null, false, info)
- }
- LoginRateLimiter.processLoginRequest(email, function(err, isAllowed) {
+ Modules.hooks.fire(
+ 'preDoPassportLogin',
+ req,
+ email,
+ function (err, infoList) {
if (err) {
return done(err)
}
- if (!isAllowed) {
- logger.log({ email }, 'too many login requests')
- return done(null, null, {
- text: req.i18n.translate('to_many_login_requests_2_mins'),
- type: 'error'
- })
+ const info = infoList.find(i => i != null)
+ if (info != null) {
+ return done(null, false, info)
}
- AuthenticationManager.authenticate({ email }, password, function(
- error,
- user
- ) {
- if (error != null) {
- return done(error)
+ LoginRateLimiter.processLoginRequest(email, function (err, isAllowed) {
+ if (err) {
+ return done(err)
}
- if (user != null) {
- // async actions
- done(null, user)
- } else {
- AuthenticationController._recordFailedLogin()
- logger.log({ email }, 'failed log in')
- done(null, false, {
- text: req.i18n.translate('email_or_password_wrong_try_again'),
+ if (!isAllowed) {
+ logger.log({ email }, 'too many login requests')
+ return done(null, null, {
+ text: req.i18n.translate('to_many_login_requests_2_mins'),
type: 'error'
})
}
+ AuthenticationManager.authenticate(
+ { email },
+ password,
+ function (error, user) {
+ if (error != null) {
+ return done(error)
+ }
+ if (user != null) {
+ // async actions
+ done(null, user)
+ } else {
+ AuthenticationController._recordFailedLogin()
+ logger.log({ email }, 'failed log in')
+ done(null, false, {
+ text: req.i18n.translate('email_or_password_wrong_try_again'),
+ type: 'error'
+ })
+ }
+ }
+ )
})
- })
- })
+ }
+ )
},
ipMatchCheck(req, user) {
@@ -215,9 +225,9 @@ const AuthenticationController = {
},
requireLogin() {
- const doRequest = function(req, res, next) {
+ const doRequest = function (req, res, next) {
if (next == null) {
- next = function() {}
+ next = function () {}
}
if (!AuthenticationController.isUserLoggedIn(req)) {
if (acceptsJson(req)) return send401WithChallenge(res)
@@ -234,45 +244,47 @@ const AuthenticationController = {
requireOauth() {
// require this here because module may not be included in some versions
const Oauth2Server = require('../../../../modules/oauth2-server/app/src/Oauth2Server')
- return function(req, res, next) {
+ return function (req, res, next) {
if (next == null) {
- next = function() {}
+ next = function () {}
}
const request = new Oauth2Server.Request(req)
const response = new Oauth2Server.Response(res)
- return Oauth2Server.server.authenticate(request, response, {}, function(
- err,
- token
- ) {
- if (err) {
- // use a 401 status code for malformed header for git-bridge
- if (
- err.code === 400 &&
- err.message === 'Invalid request: malformed authorization header'
- ) {
- err.code = 401
+ return Oauth2Server.server.authenticate(
+ request,
+ response,
+ {},
+ function (err, token) {
+ if (err) {
+ // use a 401 status code for malformed header for git-bridge
+ if (
+ err.code === 400 &&
+ err.message === 'Invalid request: malformed authorization header'
+ ) {
+ err.code = 401
+ }
+ // send all other errors
+ return res
+ .status(err.code)
+ .json({ error: err.name, error_description: err.message })
}
- // send all other errors
- return res
- .status(err.code)
- .json({ error: err.name, error_description: err.message })
+ req.oauth = { access_token: token.accessToken }
+ req.oauth_token = token
+ req.oauth_user = token.user
+ return next()
}
- req.oauth = { access_token: token.accessToken }
- req.oauth_token = token
- req.oauth_user = token.user
- return next()
- })
+ )
}
},
- validateUserSession: function() {
+ validateUserSession: function () {
// Middleware to check that the user's session is still good on key actions,
// such as opening a a project. Could be used to check that session has not
// exceeded a maximum lifetime (req.session.session_created), or for session
// hijacking checks (e.g. change of ip address, req.session.ip_address). For
// now, just check that the session has been loaded from the session store
// correctly.
- return function(req, res, next) {
+ return function (req, res, next) {
// check that the session store is returning valid results
if (req.session && !SessionStoreManager.hasValidationToken(req)) {
// force user to update session
@@ -349,7 +361,7 @@ const AuthenticationController = {
return next()
},
- httpAuth: basicAuth(function(user, pass) {
+ httpAuth: basicAuth(function (user, pass) {
let expectedPassword = Settings.httpAuthUsers[user]
const isValid =
expectedPassword &&
@@ -424,7 +436,7 @@ const AuthenticationController = {
_recordSuccessfulLogin(userId, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
UserUpdater.updateUser(
userId.toString(),
@@ -432,7 +444,7 @@ const AuthenticationController = {
$set: { lastLoggedIn: new Date() },
$inc: { loginCount: 1 }
},
- function(error) {
+ function (error) {
if (error != null) {
callback(error)
}
@@ -465,9 +477,9 @@ const AuthenticationController = {
function _afterLoginSessionSetup(req, user, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
- req.login(user, function(err) {
+ req.login(user, function (err) {
if (err) {
OError.tag(err, 'error from req.login', {
user_id: user._id
@@ -477,7 +489,7 @@ function _afterLoginSessionSetup(req, user, callback) {
// Regenerate the session to get a new sessionID (cookie value) to
// protect against session fixation attacks
const oldSession = req.session
- req.session.destroy(function(err) {
+ req.session.destroy(function (err) {
if (err) {
OError.tag(err, 'error when trying to destroy old session', {
user_id: user._id
@@ -493,14 +505,14 @@ function _afterLoginSessionSetup(req, user, callback) {
req.session[key] = value
}
}
- req.session.save(function(err) {
+ req.session.save(function (err) {
if (err) {
OError.tag(err, 'error saving regenerated session after login', {
user_id: user._id
})
return callback(err)
}
- UserSessionsManager.trackSession(user, req.sessionID, function() {})
+ UserSessionsManager.trackSession(user, req.sessionID, function () {})
callback(null)
})
})
diff --git a/services/web/app/src/Features/Authentication/AuthenticationManager.js b/services/web/app/src/Features/Authentication/AuthenticationManager.js
index 2be8abd9d1..b9250ce4c3 100644
--- a/services/web/app/src/Features/Authentication/AuthenticationManager.js
+++ b/services/web/app/src/Features/Authentication/AuthenticationManager.js
@@ -12,7 +12,7 @@ const util = require('util')
const BCRYPT_ROUNDS = Settings.security.bcryptRounds || 12
const BCRYPT_MINOR_VERSION = Settings.security.bcryptMinorVersion || 'a'
-const _checkWriteResult = function(result, callback) {
+const _checkWriteResult = function (result, callback) {
// for MongoDB
if (result && result.modifiedCount === 1) {
callback(null, true)
@@ -33,7 +33,7 @@ const AuthenticationManager = {
if (!user || !user.hashedPassword) {
return callback(null, null)
}
- bcrypt.compare(password, user.hashedPassword, function(error, match) {
+ bcrypt.compare(password, user.hashedPassword, function (error, match) {
if (error) {
return callback(error)
}
@@ -44,7 +44,7 @@ const AuthenticationManager = {
user,
user.hashedPassword,
password,
- function(err) {
+ function (err) {
if (err) {
return callback(err)
}
@@ -146,7 +146,7 @@ const AuthenticationManager = {
},
hashPassword(password, callback) {
- bcrypt.genSalt(BCRYPT_ROUNDS, BCRYPT_MINOR_VERSION, function(error, salt) {
+ bcrypt.genSalt(BCRYPT_ROUNDS, BCRYPT_MINOR_VERSION, function (error, salt) {
if (error) {
return callback(error)
}
@@ -162,7 +162,7 @@ const AuthenticationManager = {
if (validationError) {
return callback(validationError)
}
- this.hashPassword(password, function(error, hash) {
+ this.hashPassword(password, function (error, hash) {
if (error) {
return callback(error)
}
@@ -178,7 +178,7 @@ const AuthenticationManager = {
password: true
}
},
- function(updateError, result) {
+ function (updateError, result) {
if (updateError) {
return callback(updateError)
}
diff --git a/services/web/app/src/Features/Authorization/AuthorizationManager.js b/services/web/app/src/Features/Authorization/AuthorizationManager.js
index 57ce7a3034..5ed8f3a0ef 100644
--- a/services/web/app/src/Features/Authorization/AuthorizationManager.js
+++ b/services/web/app/src/Features/Authorization/AuthorizationManager.js
@@ -54,20 +54,21 @@ const AuthorizationManager = {
return callback(new Error('invalid project id'))
}
// Note, the Project property in the DB is `publicAccesLevel`, without the second `s`
- ProjectGetter.getProject(projectId, { publicAccesLevel: 1 }, function(
- error,
- project
- ) {
- if (error) {
- return callback(error)
+ ProjectGetter.getProject(
+ projectId,
+ { publicAccesLevel: 1 },
+ function (error, project) {
+ if (error) {
+ return callback(error)
+ }
+ if (!project) {
+ return callback(
+ new Errors.NotFoundError(`no project found with id ${projectId}`)
+ )
+ }
+ callback(null, project.publicAccesLevel)
}
- if (!project) {
- return callback(
- new Errors.NotFoundError(`no project found with id ${projectId}`)
- )
- }
- callback(null, project.publicAccesLevel)
- })
+ )
},
// Get the privilege level that the user has for the project
@@ -95,72 +96,78 @@ const AuthorizationManager = {
// User is present, get their privilege level from database
getPrivilegeLevelForProjectWithUser(userId, projectId, token, callback) {
- CollaboratorsGetter.getMemberIdPrivilegeLevel(userId, projectId, function(
- error,
- privilegeLevel
- ) {
- if (error) {
- return callback(error)
- }
- if (privilegeLevel && privilegeLevel !== PrivilegeLevels.NONE) {
- // The user has direct access
- return callback(null, privilegeLevel, false, false)
- }
- AuthorizationManager.isUserSiteAdmin(userId, function(error, isAdmin) {
+ CollaboratorsGetter.getMemberIdPrivilegeLevel(
+ userId,
+ projectId,
+ function (error, privilegeLevel) {
if (error) {
return callback(error)
}
- if (isAdmin) {
- return callback(null, PrivilegeLevels.OWNER, false, true)
+ if (privilegeLevel && privilegeLevel !== PrivilegeLevels.NONE) {
+ // The user has direct access
+ return callback(null, privilegeLevel, false, false)
}
- // Legacy public-access system
- // User is present (not anonymous), but does not have direct access
- AuthorizationManager.getPublicAccessLevel(projectId, function(
- err,
- publicAccessLevel
- ) {
- if (err) {
- return callback(err)
+ AuthorizationManager.isUserSiteAdmin(userId, function (error, isAdmin) {
+ if (error) {
+ return callback(error)
}
- if (publicAccessLevel === PublicAccessLevels.READ_ONLY) {
- return callback(null, PrivilegeLevels.READ_ONLY, true, false)
+ if (isAdmin) {
+ return callback(null, PrivilegeLevels.OWNER, false, true)
}
- if (publicAccessLevel === PublicAccessLevels.READ_AND_WRITE) {
- return callback(null, PrivilegeLevels.READ_AND_WRITE, true, false)
- }
- callback(null, PrivilegeLevels.NONE, false, false)
+ // Legacy public-access system
+ // User is present (not anonymous), but does not have direct access
+ AuthorizationManager.getPublicAccessLevel(
+ projectId,
+ function (err, publicAccessLevel) {
+ if (err) {
+ return callback(err)
+ }
+ if (publicAccessLevel === PublicAccessLevels.READ_ONLY) {
+ return callback(null, PrivilegeLevels.READ_ONLY, true, false)
+ }
+ if (publicAccessLevel === PublicAccessLevels.READ_AND_WRITE) {
+ return callback(
+ null,
+ PrivilegeLevels.READ_AND_WRITE,
+ true,
+ false
+ )
+ }
+ callback(null, PrivilegeLevels.NONE, false, false)
+ }
+ )
})
- })
- })
+ }
+ )
},
// User is Anonymous, Try Token-based access
getPrivilegeLevelForProjectWithoutUser(projectId, token, callback) {
- AuthorizationManager.getPublicAccessLevel(projectId, function(
- err,
- publicAccessLevel
- ) {
- if (err) {
- return callback(err)
+ AuthorizationManager.getPublicAccessLevel(
+ projectId,
+ function (err, publicAccessLevel) {
+ if (err) {
+ return callback(err)
+ }
+ if (publicAccessLevel === PublicAccessLevels.READ_ONLY) {
+ // Legacy public read-only access for anonymous user
+ return callback(null, PrivilegeLevels.READ_ONLY, true, false)
+ }
+ if (publicAccessLevel === PublicAccessLevels.READ_AND_WRITE) {
+ // Legacy public read-write access for anonymous user
+ return callback(null, PrivilegeLevels.READ_AND_WRITE, true, false)
+ }
+ if (publicAccessLevel === PublicAccessLevels.TOKEN_BASED) {
+ return AuthorizationManager.getPrivilegeLevelForProjectWithToken(
+ projectId,
+ token,
+ callback
+ )
+ }
+ // Deny anonymous user access
+ callback(null, PrivilegeLevels.NONE, false, false)
}
- if (publicAccessLevel === PublicAccessLevels.READ_ONLY) {
- // Legacy public read-only access for anonymous user
- return callback(null, PrivilegeLevels.READ_ONLY, true, false)
- }
- if (publicAccessLevel === PublicAccessLevels.READ_AND_WRITE) {
- // Legacy public read-write access for anonymous user
- return callback(null, PrivilegeLevels.READ_AND_WRITE, true, false)
- }
- if (publicAccessLevel === PublicAccessLevels.TOKEN_BASED) {
- return AuthorizationManager.getPrivilegeLevelForProjectWithToken(
- projectId,
- token,
- callback
- )
- }
- // Deny anonymous user access
- callback(null, PrivilegeLevels.NONE, false, false)
- })
+ )
},
getPrivilegeLevelForProjectWithToken(projectId, token, callback) {
@@ -170,7 +177,7 @@ const AuthorizationManager = {
TokenAccessHandler.validateTokenForAnonymousAccess(
projectId,
token,
- function(err, isValidReadAndWrite, isValidReadOnly) {
+ function (err, isValidReadAndWrite, isValidReadOnly) {
if (err) {
return callback(err)
}
@@ -193,7 +200,7 @@ const AuthorizationManager = {
userId,
projectId,
token,
- function(error, privilegeLevel) {
+ function (error, privilegeLevel) {
if (error) {
return callback(error)
}
@@ -214,7 +221,7 @@ const AuthorizationManager = {
userId,
projectId,
token,
- function(error, privilegeLevel) {
+ function (error, privilegeLevel) {
if (error) {
return callback(error)
}
@@ -233,7 +240,7 @@ const AuthorizationManager = {
userId,
projectId,
token,
- function(error, privilegeLevel, becausePublic) {
+ function (error, privilegeLevel, becausePublic) {
if (error) {
return callback(error)
}
@@ -256,7 +263,7 @@ const AuthorizationManager = {
userId,
projectId,
token,
- function(error, privilegeLevel, becausePublic, becauseSiteAdmin) {
+ function (error, privilegeLevel, becausePublic, becauseSiteAdmin) {
if (error) {
return callback(error)
}
@@ -273,7 +280,7 @@ const AuthorizationManager = {
if (!userId) {
return callback(null, false)
}
- User.findOne({ _id: userId }, { isAdmin: 1 }, function(error, user) {
+ User.findOne({ _id: userId }, { isAdmin: 1 }, function (error, user) {
if (error) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js b/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js
index 11ddd1d899..2d37a0c61c 100644
--- a/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js
+++ b/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js
@@ -11,7 +11,7 @@ const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
module.exports = AuthorizationMiddleware = {
ensureUserCanReadMultipleProjects(req, res, next) {
const projectIds = (req.query.project_ids || '').split(',')
- AuthorizationMiddleware._getUserId(req, function(error, userId) {
+ AuthorizationMiddleware._getUserId(req, function (error, userId) {
if (error) {
return next(error)
}
@@ -19,13 +19,13 @@ module.exports = AuthorizationMiddleware = {
// errors in callbacks
async.rejectSeries(
projectIds,
- function(projectId, cb) {
+ function (projectId, cb) {
const token = TokenAccessHandler.getRequestToken(req, projectId)
AuthorizationManager.canUserReadProject(
userId,
projectId,
token,
- function(error, canRead) {
+ function (error, canRead) {
if (error) {
return next(error)
}
@@ -33,7 +33,7 @@ module.exports = AuthorizationMiddleware = {
}
)
},
- function(unauthorizedProjectIds) {
+ function (unauthorizedProjectIds) {
if (unauthorizedProjectIds.length > 0) {
return AuthorizationMiddleware.redirectToRestricted(req, res, next)
}
@@ -44,178 +44,173 @@ module.exports = AuthorizationMiddleware = {
},
blockRestrictedUserFromProject(req, res, next) {
- AuthorizationMiddleware._getUserAndProjectId(req, function(
- error,
- userId,
- projectId
- ) {
- if (error) {
- return next(error)
- }
- const token = TokenAccessHandler.getRequestToken(req, projectId)
- AuthorizationManager.isRestrictedUserForProject(
- userId,
- projectId,
- token,
- (err, isRestrictedUser) => {
- if (err) {
- return next(err)
- }
- if (isRestrictedUser) {
- return res.sendStatus(403)
- }
- next()
+ AuthorizationMiddleware._getUserAndProjectId(
+ req,
+ function (error, userId, projectId) {
+ if (error) {
+ return next(error)
}
- )
- })
+ const token = TokenAccessHandler.getRequestToken(req, projectId)
+ AuthorizationManager.isRestrictedUserForProject(
+ userId,
+ projectId,
+ token,
+ (err, isRestrictedUser) => {
+ if (err) {
+ return next(err)
+ }
+ if (isRestrictedUser) {
+ return res.sendStatus(403)
+ }
+ next()
+ }
+ )
+ }
+ )
},
ensureUserCanReadProject(req, res, next) {
- AuthorizationMiddleware._getUserAndProjectId(req, function(
- error,
- userId,
- projectId
- ) {
- if (error) {
- return next(error)
- }
- const token = TokenAccessHandler.getRequestToken(req, projectId)
- AuthorizationManager.canUserReadProject(
- userId,
- projectId,
- token,
- function(error, canRead) {
- if (error) {
- return next(error)
- }
- if (canRead) {
+ AuthorizationMiddleware._getUserAndProjectId(
+ req,
+ function (error, userId, projectId) {
+ if (error) {
+ return next(error)
+ }
+ const token = TokenAccessHandler.getRequestToken(req, projectId)
+ AuthorizationManager.canUserReadProject(
+ userId,
+ projectId,
+ token,
+ function (error, canRead) {
+ if (error) {
+ return next(error)
+ }
+ if (canRead) {
+ logger.log(
+ { userId, projectId },
+ 'allowing user read access to project'
+ )
+ return next()
+ }
logger.log(
{ userId, projectId },
- 'allowing user read access to project'
+ 'denying user read access to project'
)
- return next()
+ HttpErrorHandler.forbidden(req, res)
}
- logger.log(
- { userId, projectId },
- 'denying user read access to project'
- )
- HttpErrorHandler.forbidden(req, res)
- }
- )
- })
+ )
+ }
+ )
},
ensureUserCanWriteProjectSettings(req, res, next) {
- AuthorizationMiddleware._getUserAndProjectId(req, function(
- error,
- userId,
- projectId
- ) {
- if (error) {
- return next(error)
- }
- const token = TokenAccessHandler.getRequestToken(req, projectId)
- AuthorizationManager.canUserWriteProjectSettings(
- userId,
- projectId,
- token,
- function(error, canWrite) {
- if (error) {
- return next(error)
- }
- if (canWrite) {
+ AuthorizationMiddleware._getUserAndProjectId(
+ req,
+ function (error, userId, projectId) {
+ if (error) {
+ return next(error)
+ }
+ const token = TokenAccessHandler.getRequestToken(req, projectId)
+ AuthorizationManager.canUserWriteProjectSettings(
+ userId,
+ projectId,
+ token,
+ function (error, canWrite) {
+ if (error) {
+ return next(error)
+ }
+ if (canWrite) {
+ logger.log(
+ { userId, projectId },
+ 'allowing user write access to project settings'
+ )
+ return next()
+ }
logger.log(
{ userId, projectId },
- 'allowing user write access to project settings'
+ 'denying user write access to project settings'
)
- return next()
+ HttpErrorHandler.forbidden(req, res)
}
- logger.log(
- { userId, projectId },
- 'denying user write access to project settings'
- )
- HttpErrorHandler.forbidden(req, res)
- }
- )
- })
+ )
+ }
+ )
},
ensureUserCanWriteProjectContent(req, res, next) {
- AuthorizationMiddleware._getUserAndProjectId(req, function(
- error,
- userId,
- projectId
- ) {
- if (error) {
- return next(error)
- }
- const token = TokenAccessHandler.getRequestToken(req, projectId)
- AuthorizationManager.canUserWriteProjectContent(
- userId,
- projectId,
- token,
- function(error, canWrite) {
- if (error) {
- return next(error)
- }
- if (canWrite) {
+ AuthorizationMiddleware._getUserAndProjectId(
+ req,
+ function (error, userId, projectId) {
+ if (error) {
+ return next(error)
+ }
+ const token = TokenAccessHandler.getRequestToken(req, projectId)
+ AuthorizationManager.canUserWriteProjectContent(
+ userId,
+ projectId,
+ token,
+ function (error, canWrite) {
+ if (error) {
+ return next(error)
+ }
+ if (canWrite) {
+ logger.log(
+ { userId, projectId },
+ 'allowing user write access to project content'
+ )
+ return next()
+ }
logger.log(
{ userId, projectId },
- 'allowing user write access to project content'
+ 'denying user write access to project settings'
)
- return next()
+ HttpErrorHandler.forbidden(req, res)
}
- logger.log(
- { userId, projectId },
- 'denying user write access to project settings'
- )
- HttpErrorHandler.forbidden(req, res)
- }
- )
- })
+ )
+ }
+ )
},
ensureUserCanAdminProject(req, res, next) {
- AuthorizationMiddleware._getUserAndProjectId(req, function(
- error,
- userId,
- projectId
- ) {
- if (error) {
- return next(error)
- }
- const token = TokenAccessHandler.getRequestToken(req, projectId)
- AuthorizationManager.canUserAdminProject(
- userId,
- projectId,
- token,
- function(error, canAdmin) {
- if (error) {
- return next(error)
- }
- if (canAdmin) {
+ AuthorizationMiddleware._getUserAndProjectId(
+ req,
+ function (error, userId, projectId) {
+ if (error) {
+ return next(error)
+ }
+ const token = TokenAccessHandler.getRequestToken(req, projectId)
+ AuthorizationManager.canUserAdminProject(
+ userId,
+ projectId,
+ token,
+ function (error, canAdmin) {
+ if (error) {
+ return next(error)
+ }
+ if (canAdmin) {
+ logger.log(
+ { userId, projectId },
+ 'allowing user admin access to project'
+ )
+ return next()
+ }
logger.log(
{ userId, projectId },
- 'allowing user admin access to project'
+ 'denying user admin access to project'
)
- return next()
+ HttpErrorHandler.forbidden(req, res)
}
- logger.log(
- { userId, projectId },
- 'denying user admin access to project'
- )
- HttpErrorHandler.forbidden(req, res)
- }
- )
- })
+ )
+ }
+ )
},
ensureUserIsSiteAdmin(req, res, next) {
- AuthorizationMiddleware._getUserId(req, function(error, userId) {
+ AuthorizationMiddleware._getUserId(req, function (error, userId) {
if (error) {
return next(error)
}
- AuthorizationManager.isUserSiteAdmin(userId, function(error, isAdmin) {
+ AuthorizationManager.isUserSiteAdmin(userId, function (error, isAdmin) {
if (error) {
return next(error)
}
@@ -239,7 +234,7 @@ module.exports = AuthorizationMiddleware = {
new Errors.NotFoundError(`invalid projectId: ${projectId}`)
)
}
- AuthorizationMiddleware._getUserId(req, function(error, userId) {
+ AuthorizationMiddleware._getUserId(req, function (error, userId) {
if (error) {
return callback(error)
}
diff --git a/services/web/app/src/Features/BetaProgram/BetaProgramController.js b/services/web/app/src/Features/BetaProgram/BetaProgramController.js
index 7354f35d3d..1d6116cc1d 100644
--- a/services/web/app/src/Features/BetaProgram/BetaProgramController.js
+++ b/services/web/app/src/Features/BetaProgram/BetaProgramController.js
@@ -12,7 +12,7 @@ const BetaProgramController = {
if (userId == null) {
return next(new Error('no user id in session'))
}
- BetaProgramHandler.optIn(userId, function(err) {
+ BetaProgramHandler.optIn(userId, function (err) {
if (err) {
return next(err)
}
@@ -26,7 +26,7 @@ const BetaProgramController = {
if (userId == null) {
return next(new Error('no user id in session'))
}
- BetaProgramHandler.optOut(userId, function(err) {
+ BetaProgramHandler.optOut(userId, function (err) {
if (err) {
return next(err)
}
@@ -37,7 +37,7 @@ const BetaProgramController = {
optInPage(req, res, next) {
const userId = AuthenticationController.getLoggedInUserId(req)
logger.log({ user_id: userId }, 'showing beta participation page for user')
- UserGetter.getUser(userId, function(err, user) {
+ UserGetter.getUser(userId, function (err, user) {
if (err) {
OError.tag(err, 'error fetching user', {
userId
diff --git a/services/web/app/src/Features/BrandVariations/BrandVariationsHandler.js b/services/web/app/src/Features/BrandVariations/BrandVariationsHandler.js
index 4fb26ab97e..fa02fba9dc 100644
--- a/services/web/app/src/Features/BrandVariations/BrandVariationsHandler.js
+++ b/services/web/app/src/Features/BrandVariations/BrandVariationsHandler.js
@@ -22,7 +22,7 @@ const V1Api = require('../V1/V1Api')
module.exports = BrandVariationsHandler = {
getBrandVariationById(brandVariationId, callback) {
if (callback == null) {
- callback = function(error, brandVariationDetails) {}
+ callback = function (error, brandVariationDetails) {}
}
if (brandVariationId == null || brandVariationId === '') {
return callback(new Error('Branding variation id not provided'))
@@ -32,7 +32,7 @@ module.exports = BrandVariationsHandler = {
{
uri: `/api/v2/brand_variations/${brandVariationId}`
},
- function(error, response, brandVariationDetails) {
+ function (error, response, brandVariationDetails) {
if (error != null) {
OError.tag(error, 'error getting brand variation details', {
brandVariationId
@@ -46,7 +46,7 @@ module.exports = BrandVariationsHandler = {
}
}
-var _formatBrandVariationDetails = function(details) {
+var _formatBrandVariationDetails = function (details) {
if (details.export_url != null) {
details.export_url = _setV1AsHostIfRelativeURL(details.export_url)
}
diff --git a/services/web/app/src/Features/Captcha/CaptchaMiddleware.js b/services/web/app/src/Features/Captcha/CaptchaMiddleware.js
index a0b8805269..ae7ec399ee 100644
--- a/services/web/app/src/Features/Captcha/CaptchaMiddleware.js
+++ b/services/web/app/src/Features/Captcha/CaptchaMiddleware.js
@@ -17,7 +17,7 @@ const Settings = require('settings-sharelatex')
module.exports = CaptchaMiddleware = {
validateCaptcha(action) {
- return function(req, res, next) {
+ return function (req, res, next) {
if (
(Settings.recaptcha != null ? Settings.recaptcha.siteKey : undefined) ==
null
@@ -42,7 +42,7 @@ module.exports = CaptchaMiddleware = {
return request.post(
'https://www.google.com/recaptcha/api/siteverify',
options,
- function(error, response, body) {
+ function (error, response, body) {
if (error != null) {
return next(error)
}
diff --git a/services/web/app/src/Features/Chat/ChatApiHandler.js b/services/web/app/src/Features/Chat/ChatApiHandler.js
index 4a81c5b66e..9e4e8538fd 100644
--- a/services/web/app/src/Features/Chat/ChatApiHandler.js
+++ b/services/web/app/src/Features/Chat/ChatApiHandler.js
@@ -19,9 +19,9 @@ const settings = require('settings-sharelatex')
module.exports = ChatApiHandler = {
_apiRequest(opts, callback) {
if (callback == null) {
- callback = function(error, data) {}
+ callback = function (error, data) {}
}
- return request(opts, function(error, response, data) {
+ return request(opts, function (error, response, data) {
if (error != null) {
return callback(error)
}
@@ -71,7 +71,7 @@ module.exports = ChatApiHandler = {
sendComment(project_id, thread_id, user_id, content, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
@@ -85,7 +85,7 @@ module.exports = ChatApiHandler = {
getThreads(project_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
@@ -99,7 +99,7 @@ module.exports = ChatApiHandler = {
resolveThread(project_id, thread_id, user_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
@@ -113,7 +113,7 @@ module.exports = ChatApiHandler = {
reopenThread(project_id, thread_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
@@ -126,7 +126,7 @@ module.exports = ChatApiHandler = {
deleteThread(project_id, thread_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
@@ -139,7 +139,7 @@ module.exports = ChatApiHandler = {
editMessage(project_id, thread_id, message_id, content, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
@@ -155,7 +155,7 @@ module.exports = ChatApiHandler = {
deleteMessage(project_id, thread_id, message_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return ChatApiHandler._apiRequest(
{
diff --git a/services/web/app/src/Features/Chat/ChatController.js b/services/web/app/src/Features/Chat/ChatController.js
index 47ad2e9b2a..90854de79c 100644
--- a/services/web/app/src/Features/Chat/ChatController.js
+++ b/services/web/app/src/Features/Chat/ChatController.js
@@ -36,25 +36,25 @@ module.exports = ChatController = {
project_id,
user_id,
content,
- function(err, message) {
+ function (err, message) {
if (err != null) {
return next(err)
}
- return UserInfoManager.getPersonalInfo(message.user_id, function(
- err,
- user
- ) {
- if (err != null) {
- return next(err)
+ return UserInfoManager.getPersonalInfo(
+ message.user_id,
+ function (err, user) {
+ if (err != null) {
+ return next(err)
+ }
+ message.user = UserInfoController.formatPersonalInfo(user)
+ EditorRealTimeController.emitToRoom(
+ project_id,
+ 'new-chat-message',
+ message
+ )
+ return res.sendStatus(204)
}
- message.user = UserInfoController.formatPersonalInfo(user)
- EditorRealTimeController.emitToRoom(
- project_id,
- 'new-chat-message',
- message
- )
- return res.sendStatus(204)
- })
+ )
}
)
},
@@ -66,13 +66,13 @@ module.exports = ChatController = {
project_id,
query.limit,
query.before,
- function(err, messages) {
+ function (err, messages) {
if (err != null) {
return next(err)
}
return ChatController._injectUserInfoIntoThreads(
{ global: { messages } },
- function(err) {
+ function (err) {
if (err != null) {
return next(err)
}
@@ -89,7 +89,7 @@ module.exports = ChatController = {
// user fields
let message, thread, thread_id, user_id
if (callback == null) {
- callback = function(error, threads) {}
+ callback = function (error, threads) {}
}
const user_ids = {}
for (thread_id in threads) {
@@ -108,7 +108,7 @@ module.exports = ChatController = {
const _ = user_ids[user_id]
;(user_id =>
jobs.push(cb =>
- UserInfoManager.getPersonalInfo(user_id, function(error, user) {
+ UserInfoManager.getPersonalInfo(user_id, function (error, user) {
if (error != null) return cb(error)
user = UserInfoController.formatPersonalInfo(user)
users[user_id] = user
@@ -117,7 +117,7 @@ module.exports = ChatController = {
))(user_id)
}
- return async.series(jobs, function(error) {
+ return async.series(jobs, function (error) {
if (error != null) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Collaborators/CollaboratorsEmailHandler.js b/services/web/app/src/Features/Collaborators/CollaboratorsEmailHandler.js
index 16c195cab5..3e305b7de9 100644
--- a/services/web/app/src/Features/Collaborators/CollaboratorsEmailHandler.js
+++ b/services/web/app/src/Features/Collaborators/CollaboratorsEmailHandler.js
@@ -30,7 +30,7 @@ module.exports = CollaboratorsEmailHandler = {
return Project.findOne({ _id: project_id })
.select('name owner_ref')
.populate('owner_ref')
- .exec(function(err, project) {
+ .exec(function (err, project) {
const emailOptions = {
to: email,
replyTo: project.owner_ref.email,
diff --git a/services/web/app/src/Features/Collaborators/CollaboratorsInviteController.js b/services/web/app/src/Features/Collaborators/CollaboratorsInviteController.js
index d2d87193f6..34d329da92 100644
--- a/services/web/app/src/Features/Collaborators/CollaboratorsInviteController.js
+++ b/services/web/app/src/Features/Collaborators/CollaboratorsInviteController.js
@@ -31,37 +31,38 @@ module.exports = CollaboratorsInviteController = {
getAllInvites(req, res, next) {
const projectId = req.params.Project_id
logger.log({ projectId }, 'getting all active invites for project')
- return CollaboratorsInviteHandler.getAllInvites(projectId, function(
- err,
- invites
- ) {
- if (err != null) {
- OError.tag(err, 'error getting invites for project', {
- projectId
- })
- return next(err)
+ return CollaboratorsInviteHandler.getAllInvites(
+ projectId,
+ function (err, invites) {
+ if (err != null) {
+ OError.tag(err, 'error getting invites for project', {
+ projectId
+ })
+ return next(err)
+ }
+ return res.json({ invites })
}
- return res.json({ invites })
- })
+ )
},
_checkShouldInviteEmail(email, callback) {
if (callback == null) {
- callback = function(err, shouldAllowInvite) {}
+ callback = function (err, shouldAllowInvite) {}
}
if (Settings.restrictInvitesToExistingAccounts === true) {
logger.log({ email }, 'checking if user exists with this email')
- return UserGetter.getUserByAnyEmail(email, { _id: 1 }, function(
- err,
- user
- ) {
- if (err != null) {
- return callback(err)
+ return UserGetter.getUserByAnyEmail(
+ email,
+ { _id: 1 },
+ function (err, user) {
+ if (err != null) {
+ return callback(err)
+ }
+ const userExists =
+ user != null && (user != null ? user._id : undefined) != null
+ return callback(null, userExists)
}
- const userExists =
- user != null && (user != null ? user._id : undefined) != null
- return callback(null, userExists)
- })
+ )
} else {
return callback(null, true)
}
@@ -69,11 +70,11 @@ module.exports = CollaboratorsInviteController = {
_checkRateLimit(user_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return LimitationsManager.allowedNumberOfCollaboratorsForUser(
user_id,
- function(err, collabLimit) {
+ function (err, collabLimit) {
if (collabLimit == null) {
collabLimit = 1
}
@@ -134,7 +135,7 @@ module.exports = CollaboratorsInviteController = {
}
return CollaboratorsInviteController._checkRateLimit(
sendingUserId,
- function(error, underRateLimit) {
+ function (error, underRateLimit) {
if (error != null) {
return next(error)
}
@@ -143,7 +144,7 @@ module.exports = CollaboratorsInviteController = {
}
return CollaboratorsInviteController._checkShouldInviteEmail(
email,
- function(err, shouldAllowInvite) {
+ function (err, shouldAllowInvite) {
if (err != null) {
OError.tag(
err,
@@ -171,7 +172,7 @@ module.exports = CollaboratorsInviteController = {
sendingUser,
email,
privileges,
- function(err, invite) {
+ function (err, invite) {
if (err != null) {
OError.tag(err, 'error creating project invite', {
projectId,
@@ -207,7 +208,7 @@ module.exports = CollaboratorsInviteController = {
return CollaboratorsInviteHandler.revokeInvite(
projectId,
inviteId,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'error revoking invite', {
projectId,
@@ -232,7 +233,7 @@ module.exports = CollaboratorsInviteController = {
const sendingUser = AuthenticationController.getSessionUser(req)
return CollaboratorsInviteController._checkRateLimit(
sendingUser._id,
- function(error, underRateLimit) {
+ function (error, underRateLimit) {
if (error != null) {
return next(error)
}
@@ -243,7 +244,7 @@ module.exports = CollaboratorsInviteController = {
projectId,
sendingUser,
inviteId,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'error resending invite', {
projectId,
@@ -261,7 +262,7 @@ module.exports = CollaboratorsInviteController = {
viewInvite(req, res, next) {
const projectId = req.params.Project_id
const { token } = req.params
- const _renderInvalidPage = function() {
+ const _renderInvalidPage = function () {
logger.log(
{ projectId, token },
'invite not valid, rendering not-valid page'
@@ -273,7 +274,7 @@ module.exports = CollaboratorsInviteController = {
return CollaboratorsGetter.isUserInvitedMemberOfProject(
currentUser._id,
projectId,
- function(err, isMember) {
+ function (err, isMember) {
if (err != null) {
OError.tag(err, 'error checking if user is member of project', {
projectId
@@ -291,7 +292,7 @@ module.exports = CollaboratorsInviteController = {
return CollaboratorsInviteHandler.getInviteByToken(
projectId,
token,
- function(err, invite) {
+ function (err, invite) {
if (err != null) {
OError.tag(err, 'error getting invite by token', {
projectId,
@@ -308,7 +309,7 @@ module.exports = CollaboratorsInviteController = {
return UserGetter.getUser(
{ _id: invite.sendingUserId },
{ email: 1, first_name: 1, last_name: 1 },
- function(err, owner) {
+ function (err, owner) {
if (err != null) {
OError.tag(err, 'error getting project owner', {
projectId
@@ -320,28 +321,29 @@ module.exports = CollaboratorsInviteController = {
return _renderInvalidPage()
}
// fetch the project name
- return ProjectGetter.getProject(projectId, {}, function(
- err,
- project
- ) {
- if (err != null) {
- OError.tag(err, 'error getting project', {
- projectId
+ return ProjectGetter.getProject(
+ projectId,
+ {},
+ function (err, project) {
+ if (err != null) {
+ OError.tag(err, 'error getting project', {
+ projectId
+ })
+ return next(err)
+ }
+ if (project == null) {
+ logger.log({ projectId }, 'no project found')
+ return _renderInvalidPage()
+ }
+ // finally render the invite
+ return res.render('project/invite/show', {
+ invite,
+ project,
+ owner,
+ title: 'Project Invite'
})
- return next(err)
}
- if (project == null) {
- logger.log({ projectId }, 'no project found')
- return _renderInvalidPage()
- }
- // finally render the invite
- return res.render('project/invite/show', {
- invite,
- project,
- owner,
- title: 'Project Invite'
- })
- })
+ )
}
)
}
@@ -362,7 +364,7 @@ module.exports = CollaboratorsInviteController = {
projectId,
token,
currentUser,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'error accepting invite by token', {
projectId,
diff --git a/services/web/app/src/Features/Collaborators/CollaboratorsInviteHandler.js b/services/web/app/src/Features/Collaborators/CollaboratorsInviteHandler.js
index 136e99c266..aec2d73456 100644
--- a/services/web/app/src/Features/Collaborators/CollaboratorsInviteHandler.js
+++ b/services/web/app/src/Features/Collaborators/CollaboratorsInviteHandler.js
@@ -26,10 +26,10 @@ const { promisifyAll } = require('../../util/promises')
const CollaboratorsInviteHandler = {
getAllInvites(projectId, callback) {
if (callback == null) {
- callback = function(err, invites) {}
+ callback = function (err, invites) {}
}
logger.log({ projectId }, 'fetching invites for project')
- return ProjectInvite.find({ projectId }, function(err, invites) {
+ return ProjectInvite.find({ projectId }, function (err, invites) {
if (err != null) {
OError.tag(err, 'error getting invites from mongo', {
projectId
@@ -46,10 +46,10 @@ const CollaboratorsInviteHandler = {
getInviteCount(projectId, callback) {
if (callback == null) {
- callback = function(err, count) {}
+ callback = function (err, count) {}
}
logger.log({ projectId }, 'counting invites for project')
- return ProjectInvite.countDocuments({ projectId }, function(err, count) {
+ return ProjectInvite.countDocuments({ projectId }, function (err, count) {
if (err != null) {
OError.tag(err, 'error getting invites from mongo', {
projectId
@@ -62,55 +62,57 @@ const CollaboratorsInviteHandler = {
_trySendInviteNotification(projectId, sendingUser, invite, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
const { email } = invite
- return UserGetter.getUserByAnyEmail(email, { _id: 1 }, function(
- err,
- existingUser
- ) {
- if (err != null) {
- OError.tag(err, 'error checking if user exists', {
- projectId,
- email
- })
- return callback(err)
- }
- if (existingUser == null) {
- logger.log({ projectId, email }, 'no existing user found, returning')
- return callback(null)
- }
- return ProjectGetter.getProject(projectId, { _id: 1, name: 1 }, function(
- err,
- project
- ) {
+ return UserGetter.getUserByAnyEmail(
+ email,
+ { _id: 1 },
+ function (err, existingUser) {
if (err != null) {
- OError.tag(err, 'error getting project', {
+ OError.tag(err, 'error checking if user exists', {
projectId,
email
})
return callback(err)
}
- if (project == null) {
- logger.log(
- { projectId },
- 'no project found while sending notification, returning'
- )
+ if (existingUser == null) {
+ logger.log({ projectId, email }, 'no existing user found, returning')
return callback(null)
}
- return NotificationsBuilder.projectInvite(
- invite,
- project,
- sendingUser,
- existingUser
- ).create(callback)
- })
- })
+ return ProjectGetter.getProject(
+ projectId,
+ { _id: 1, name: 1 },
+ function (err, project) {
+ if (err != null) {
+ OError.tag(err, 'error getting project', {
+ projectId,
+ email
+ })
+ return callback(err)
+ }
+ if (project == null) {
+ logger.log(
+ { projectId },
+ 'no project found while sending notification, returning'
+ )
+ return callback(null)
+ }
+ return NotificationsBuilder.projectInvite(
+ invite,
+ project,
+ sendingUser,
+ existingUser
+ ).create(callback)
+ }
+ )
+ }
+ )
},
_tryCancelInviteNotification(inviteId, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
return NotificationsBuilder.projectInvite(
{ _id: inviteId },
@@ -122,7 +124,7 @@ const CollaboratorsInviteHandler = {
_sendMessages(projectId, sendingUser, invite, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
logger.log(
{ projectId, inviteId: invite._id },
@@ -133,7 +135,7 @@ const CollaboratorsInviteHandler = {
invite.email,
invite,
sendingUser,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -141,7 +143,7 @@ const CollaboratorsInviteHandler = {
projectId,
sendingUser,
invite,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -154,13 +156,13 @@ const CollaboratorsInviteHandler = {
inviteToProject(projectId, sendingUser, email, privileges, callback) {
if (callback == null) {
- callback = function(err, invite) {}
+ callback = function (err, invite) {}
}
logger.log(
{ projectId, sendingUserId: sendingUser._id, email, privileges },
'adding invite'
)
- return Crypto.randomBytes(24, function(err, buffer) {
+ return Crypto.randomBytes(24, function (err, buffer) {
if (err != null) {
OError.tag(err, 'error generating random token', {
projectId,
@@ -177,7 +179,7 @@ const CollaboratorsInviteHandler = {
projectId,
privileges
})
- return invite.save(function(err, invite) {
+ return invite.save(function (err, invite) {
if (err != null) {
OError.tag(err, 'error saving token', {
projectId,
@@ -191,7 +193,7 @@ const CollaboratorsInviteHandler = {
projectId,
sendingUser,
invite,
- function(err) {
+ function (err) {
if (err != null) {
return logger.err(
{ err, projectId, email },
@@ -207,98 +209,101 @@ const CollaboratorsInviteHandler = {
revokeInvite(projectId, inviteId, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
logger.log({ projectId, inviteId }, 'removing invite')
- return ProjectInvite.deleteOne({ projectId, _id: inviteId }, function(err) {
- if (err != null) {
- OError.tag(err, 'error removing invite', {
- projectId,
- inviteId
- })
- return callback(err)
+ return ProjectInvite.deleteOne(
+ { projectId, _id: inviteId },
+ function (err) {
+ if (err != null) {
+ OError.tag(err, 'error removing invite', {
+ projectId,
+ inviteId
+ })
+ return callback(err)
+ }
+ CollaboratorsInviteHandler._tryCancelInviteNotification(
+ inviteId,
+ function () {}
+ )
+ return callback(null)
}
- CollaboratorsInviteHandler._tryCancelInviteNotification(
- inviteId,
- function() {}
- )
- return callback(null)
- })
+ )
},
resendInvite(projectId, sendingUser, inviteId, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
logger.log({ projectId, inviteId }, 'resending invite email')
- return ProjectInvite.findOne({ _id: inviteId, projectId }, function(
- err,
- invite
- ) {
- if (err != null) {
- OError.tag(err, 'error finding invite', {
- projectId,
- inviteId
- })
- return callback(err)
- }
- if (invite == null) {
- logger.err(
- { err, projectId, inviteId },
- 'no invite found, nothing to resend'
- )
- return callback(null)
- }
- return CollaboratorsInviteHandler._sendMessages(
- projectId,
- sendingUser,
- invite,
- function(err) {
- if (err != null) {
- OError.tag(err, 'error resending invite messages', {
- projectId,
- inviteId
- })
- return callback(err)
- }
+ return ProjectInvite.findOne(
+ { _id: inviteId, projectId },
+ function (err, invite) {
+ if (err != null) {
+ OError.tag(err, 'error finding invite', {
+ projectId,
+ inviteId
+ })
+ return callback(err)
+ }
+ if (invite == null) {
+ logger.err(
+ { err, projectId, inviteId },
+ 'no invite found, nothing to resend'
+ )
return callback(null)
}
- )
- })
+ return CollaboratorsInviteHandler._sendMessages(
+ projectId,
+ sendingUser,
+ invite,
+ function (err) {
+ if (err != null) {
+ OError.tag(err, 'error resending invite messages', {
+ projectId,
+ inviteId
+ })
+ return callback(err)
+ }
+ return callback(null)
+ }
+ )
+ }
+ )
},
getInviteByToken(projectId, tokenString, callback) {
if (callback == null) {
- callback = function(err, invite) {}
+ callback = function (err, invite) {}
}
logger.log({ projectId, tokenString }, 'fetching invite by token')
- return ProjectInvite.findOne({ projectId, token: tokenString }, function(
- err,
- invite
- ) {
- if (err != null) {
- OError.tag(err, 'error fetching invite', {
- projectId
- })
- return callback(err)
+ return ProjectInvite.findOne(
+ { projectId, token: tokenString },
+ function (err, invite) {
+ if (err != null) {
+ OError.tag(err, 'error fetching invite', {
+ projectId
+ })
+ return callback(err)
+ }
+ if (invite == null) {
+ logger.err({ err, projectId, token: tokenString }, 'no invite found')
+ return callback(null, null)
+ }
+ return callback(null, invite)
}
- if (invite == null) {
- logger.err({ err, projectId, token: tokenString }, 'no invite found')
- return callback(null, null)
- }
- return callback(null, invite)
- })
+ )
},
acceptInvite(projectId, tokenString, user, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
logger.log({ projectId, userId: user._id, tokenString }, 'accepting invite')
return CollaboratorsInviteHandler.getInviteByToken(
projectId,
tokenString,
- function(err, invite) {
+ function (err, invite) {
if (err != null) {
OError.tag(err, 'error finding invite', {
projectId,
@@ -320,7 +325,7 @@ const CollaboratorsInviteHandler = {
invite.sendingUserId,
user._id,
invite.privileges,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'error adding user to project', {
projectId,
@@ -331,7 +336,7 @@ const CollaboratorsInviteHandler = {
}
// Remove invite
logger.log({ projectId, inviteId }, 'removing invite')
- return ProjectInvite.deleteOne({ _id: inviteId }, function(err) {
+ return ProjectInvite.deleteOne({ _id: inviteId }, function (err) {
if (err != null) {
OError.tag(err, 'error removing invite', {
projectId,
@@ -341,7 +346,7 @@ const CollaboratorsInviteHandler = {
}
CollaboratorsInviteHandler._tryCancelInviteNotification(
inviteId,
- function() {}
+ function () {}
)
return callback()
})
diff --git a/services/web/app/src/Features/Compile/ClsiCookieManager.js b/services/web/app/src/Features/Compile/ClsiCookieManager.js
index 13ac423fe6..07d34247d8 100644
--- a/services/web/app/src/Features/Compile/ClsiCookieManager.js
+++ b/services/web/app/src/Features/Compile/ClsiCookieManager.js
@@ -27,7 +27,7 @@ const clsiCookiesEnabled =
(Settings.clsiCookie != null ? Settings.clsiCookie.key : undefined) != null &&
Settings.clsiCookie.key.length !== 0
-module.exports = function(backendGroup) {
+module.exports = function (backendGroup) {
return {
buildKey(project_id) {
if (backendGroup != null) {
@@ -39,7 +39,7 @@ module.exports = function(backendGroup) {
_getServerId(project_id, callback) {
if (callback == null) {
- callback = function(err, serverId) {}
+ callback = function (err, serverId) {}
}
return rclient.get(this.buildKey(project_id), (err, serverId) => {
if (err != null) {
@@ -55,7 +55,7 @@ module.exports = function(backendGroup) {
_populateServerIdViaRequest(project_id, callback) {
if (callback == null) {
- callback = function(err, serverId) {}
+ callback = function (err, serverId) {}
}
const url = `${Settings.apis.clsi.url}/project/${project_id}/status`
return request.post(url, (err, res, body) => {
@@ -65,7 +65,7 @@ module.exports = function(backendGroup) {
})
return callback(err)
}
- return this.setServerId(project_id, res, function(err, serverId) {
+ return this.setServerId(project_id, res, function (err, serverId) {
if (err != null) {
logger.warn(
{ err, project_id },
@@ -88,7 +88,7 @@ module.exports = function(backendGroup) {
setServerId(project_id, response, callback) {
if (callback == null) {
- callback = function(err, serverId) {}
+ callback = function (err, serverId) {}
}
if (!clsiCookiesEnabled) {
return callback()
@@ -112,7 +112,7 @@ module.exports = function(backendGroup) {
_setServerIdInRedis(rclient, project_id, serverId, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
rclient.setex(
this.buildKey(project_id),
@@ -124,7 +124,7 @@ module.exports = function(backendGroup) {
clearServerId(project_id, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
if (!clsiCookiesEnabled) {
return callback()
@@ -134,7 +134,7 @@ module.exports = function(backendGroup) {
getCookieJar(project_id, callback) {
if (callback == null) {
- callback = function(err, jar) {}
+ callback = function (err, jar) {}
}
if (!clsiCookiesEnabled) {
return callback(null, request.jar())
diff --git a/services/web/app/src/Features/Compile/ClsiFormatChecker.js b/services/web/app/src/Features/Compile/ClsiFormatChecker.js
index f27101bc10..aa7de53a99 100644
--- a/services/web/app/src/Features/Compile/ClsiFormatChecker.js
+++ b/services/web/app/src/Features/Compile/ClsiFormatChecker.js
@@ -26,7 +26,7 @@ module.exports = ClsiFormatChecker = {
}
}
- return async.series(jobs, function(err, problems) {
+ return async.series(jobs, function (err, problems) {
if (err != null) {
return callback(err)
}
@@ -44,7 +44,7 @@ module.exports = ClsiFormatChecker = {
_checkForConflictingPaths(resources, callback) {
const paths = resources.map(resource => resource.path)
- const conflicts = _.filter(paths, function(path) {
+ const conflicts = _.filter(paths, function (path) {
const matchingPaths = _.filter(
paths,
checkPath => checkPath.indexOf(path + '/') !== -1
@@ -63,7 +63,7 @@ module.exports = ClsiFormatChecker = {
let totalSize = 0
- let sizedResources = resources.map(function(resource) {
+ let sizedResources = resources.map(function (resource) {
const result = { path: resource.path }
if (resource.content != null) {
result.size = resource.content.replace(/\n/g, '').length
@@ -79,9 +79,7 @@ module.exports = ClsiFormatChecker = {
if (!tooLarge) {
return callback()
} else {
- sizedResources = _.sortBy(sizedResources, 'size')
- .reverse()
- .slice(0, 10)
+ sizedResources = _.sortBy(sizedResources, 'size').reverse().slice(0, 10)
return callback(null, { resources: sizedResources, totalSize })
}
}
diff --git a/services/web/app/src/Features/Compile/ClsiStateManager.js b/services/web/app/src/Features/Compile/ClsiStateManager.js
index 149d3b6e5a..8265fe9c37 100644
--- a/services/web/app/src/Features/Compile/ClsiStateManager.js
+++ b/services/web/app/src/Features/Compile/ClsiStateManager.js
@@ -34,50 +34,48 @@ const ProjectEntityHandler = require('../Project/ProjectEntityHandler')
// unsetting it if it removes any documents from the doc updater.
const buildState = s =>
- crypto
- .createHash('sha1')
- .update(s, 'utf8')
- .digest('hex')
+ crypto.createHash('sha1').update(s, 'utf8').digest('hex')
module.exports = ClsiStateManager = {
computeHash(project, options, callback) {
if (callback == null) {
- callback = function(err, hash) {}
+ callback = function (err, hash) {}
}
- return ProjectEntityHandler.getAllEntitiesFromProject(project, function(
- err,
- docs,
- files
- ) {
- const fileList = Array.from(files || []).map(
- f => `${f.file._id}:${f.file.rev}:${f.file.created}:${f.path}`
- )
- const docList = Array.from(docs || []).map(d => `${d.doc._id}:${d.path}`)
- const sortedEntityList = [
- ...Array.from(docList),
- ...Array.from(fileList)
- ].sort()
- // ignore the isAutoCompile options as it doesn't affect the
- // output, but include all other options e.g. draft
- const optionsList = (() => {
- const result = []
- const object = options || {}
- for (let key in object) {
- const value = object[key]
- if (!['isAutoCompile'].includes(key)) {
- result.push(`option ${key}:${value}`)
+ return ProjectEntityHandler.getAllEntitiesFromProject(
+ project,
+ function (err, docs, files) {
+ const fileList = Array.from(files || []).map(
+ f => `${f.file._id}:${f.file.rev}:${f.file.created}:${f.path}`
+ )
+ const docList = Array.from(docs || []).map(
+ d => `${d.doc._id}:${d.path}`
+ )
+ const sortedEntityList = [
+ ...Array.from(docList),
+ ...Array.from(fileList)
+ ].sort()
+ // ignore the isAutoCompile options as it doesn't affect the
+ // output, but include all other options e.g. draft
+ const optionsList = (() => {
+ const result = []
+ const object = options || {}
+ for (let key in object) {
+ const value = object[key]
+ if (!['isAutoCompile'].includes(key)) {
+ result.push(`option ${key}:${value}`)
+ }
}
- }
- return result
- })()
- const sortedOptionsList = optionsList.sort()
- const hash = buildState(
- [
- ...Array.from(sortedEntityList),
- ...Array.from(sortedOptionsList)
- ].join('\n')
- )
- return callback(null, hash)
- })
+ return result
+ })()
+ const sortedOptionsList = optionsList.sort()
+ const hash = buildState(
+ [
+ ...Array.from(sortedEntityList),
+ ...Array.from(sortedOptionsList)
+ ].join('\n')
+ )
+ return callback(null, hash)
+ }
+ )
}
}
diff --git a/services/web/app/src/Features/Compile/CompileController.js b/services/web/app/src/Features/Compile/CompileController.js
index 1c6e3d1867..1459ddb640 100644
--- a/services/web/app/src/Features/Compile/CompileController.js
+++ b/services/web/app/src/Features/Compile/CompileController.js
@@ -104,11 +104,11 @@ module.exports = CompileController = {
stopCompile(req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
const project_id = req.params.Project_id
const user_id = AuthenticationController.getLoggedInUserId(req)
- return CompileManager.stopCompile(project_id, user_id, function(error) {
+ return CompileManager.stopCompile(project_id, user_id, function (error) {
if (error != null) {
return next(error)
}
@@ -119,7 +119,7 @@ module.exports = CompileController = {
// Used for submissions through the public API
compileSubmission(req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
res.setTimeout(COMPILE_TIMEOUT_MS)
const { submission_id } = req.params
@@ -150,7 +150,7 @@ module.exports = CompileController = {
submission_id,
req.body,
options,
- function(error, status, outputFiles, clsiServerId, validationProblems) {
+ function (error, status, outputFiles, clsiServerId, validationProblems) {
if (error != null) {
return next(error)
}
@@ -189,13 +189,13 @@ module.exports = CompileController = {
downloadPdf(req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
Metrics.inc('pdf-downloads')
const project_id = req.params.Project_id
const isPdfjsPartialDownload =
req.query != null ? req.query.pdfng : undefined
- const rateLimit = function(callback) {
+ const rateLimit = function (callback) {
if (isPdfjsPartialDownload) {
return callback(null, true)
} else {
@@ -209,51 +209,52 @@ module.exports = CompileController = {
}
}
- return ProjectGetter.getProject(project_id, { name: 1 }, function(
- err,
- project
- ) {
- res.contentType('application/pdf')
- const filename = `${CompileController._getSafeProjectName(project)}.pdf`
+ return ProjectGetter.getProject(
+ project_id,
+ { name: 1 },
+ function (err, project) {
+ res.contentType('application/pdf')
+ const filename = `${CompileController._getSafeProjectName(project)}.pdf`
- if (req.query.popupDownload) {
- res.setContentDisposition('attachment', { filename })
- } else {
- res.setContentDisposition('', { filename })
- }
-
- return rateLimit(function(err, canContinue) {
- if (err != null) {
- logger.err({ err }, 'error checking rate limit for pdf download')
- return res.sendStatus(500)
- } else if (!canContinue) {
- logger.log(
- { project_id, ip: req.ip },
- 'rate limit hit downloading pdf'
- )
- return res.sendStatus(500)
+ if (req.query.popupDownload) {
+ res.setContentDisposition('attachment', { filename })
} else {
- return CompileController._downloadAsUser(req, function(
- error,
- user_id
- ) {
- const url = CompileController._getFileUrl(
- project_id,
- user_id,
- req.params.build_id,
- 'output.pdf'
- )
- return CompileController.proxyToClsi(
- project_id,
- url,
- req,
- res,
- next
- )
- })
+ res.setContentDisposition('', { filename })
}
- })
- })
+
+ return rateLimit(function (err, canContinue) {
+ if (err != null) {
+ logger.err({ err }, 'error checking rate limit for pdf download')
+ return res.sendStatus(500)
+ } else if (!canContinue) {
+ logger.log(
+ { project_id, ip: req.ip },
+ 'rate limit hit downloading pdf'
+ )
+ return res.sendStatus(500)
+ } else {
+ return CompileController._downloadAsUser(
+ req,
+ function (error, user_id) {
+ const url = CompileController._getFileUrl(
+ project_id,
+ user_id,
+ req.params.build_id,
+ 'output.pdf'
+ )
+ return CompileController.proxyToClsi(
+ project_id,
+ url,
+ req,
+ res,
+ next
+ )
+ }
+ )
+ }
+ })
+ }
+ )
},
_getSafeProjectName(project) {
@@ -264,18 +265,21 @@ module.exports = CompileController = {
deleteAuxFiles(req, res, next) {
const project_id = req.params.Project_id
const { clsiserverid } = req.query
- return CompileController._compileAsUser(req, function(error, user_id) {
+ return CompileController._compileAsUser(req, function (error, user_id) {
if (error != null) {
return next(error)
}
- CompileManager.deleteAuxFiles(project_id, user_id, clsiserverid, function(
- error
- ) {
- if (error != null) {
- return next(error)
+ CompileManager.deleteAuxFiles(
+ project_id,
+ user_id,
+ clsiserverid,
+ function (error) {
+ if (error != null) {
+ return next(error)
+ }
+ return res.sendStatus(200)
}
- return res.sendStatus(200)
- })
+ )
})
},
@@ -283,7 +287,7 @@ module.exports = CompileController = {
compileAndDownloadPdf(req, res, next) {
const { project_id } = req.params
// pass user_id as null, since templates are an "anonymous" compile
- return CompileManager.compile(project_id, null, {}, function(err) {
+ return CompileManager.compile(project_id, null, {}, function (err) {
if (err != null) {
logger.err(
{ err, project_id },
@@ -298,10 +302,10 @@ module.exports = CompileController = {
getFileFromClsi(req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
const project_id = req.params.Project_id
- return CompileController._downloadAsUser(req, function(error, user_id) {
+ return CompileController._downloadAsUser(req, function (error, user_id) {
if (error != null) {
return next(error)
}
@@ -317,7 +321,7 @@ module.exports = CompileController = {
getFileFromClsiWithoutUser(req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
const { submission_id } = req.params
const url = CompileController._getFileUrl(
@@ -367,7 +371,7 @@ module.exports = CompileController = {
proxySyncPdf(req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
const project_id = req.params.Project_id
const { page, h, v } = req.query
@@ -381,7 +385,7 @@ module.exports = CompileController = {
return next(new Error('invalid v parameter'))
}
// whether this request is going to a per-user container
- return CompileController._compileAsUser(req, function(error, user_id) {
+ return CompileController._compileAsUser(req, function (error, user_id) {
if (error != null) {
return next(error)
}
@@ -403,7 +407,7 @@ module.exports = CompileController = {
proxySyncCode(req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
const project_id = req.params.Project_id
const { file, line, column } = req.query
@@ -425,7 +429,7 @@ module.exports = CompileController = {
if (!(column != null ? column.match(/^\d+$/) : undefined)) {
return next(new Error('invalid column parameter'))
}
- return CompileController._compileAsUser(req, function(error, user_id) {
+ return CompileController._compileAsUser(req, function (error, user_id) {
if (error != null) {
return next(error)
}
@@ -447,7 +451,7 @@ module.exports = CompileController = {
proxyToClsi(project_id, url, req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
if (req.query != null ? req.query.compileGroup : undefined) {
return CompileController.proxyToClsiWithLimits(
@@ -459,28 +463,28 @@ module.exports = CompileController = {
next
)
} else {
- return CompileManager.getProjectCompileLimits(project_id, function(
- error,
- limits
- ) {
- if (error != null) {
- return next(error)
+ return CompileManager.getProjectCompileLimits(
+ project_id,
+ function (error, limits) {
+ if (error != null) {
+ return next(error)
+ }
+ return CompileController.proxyToClsiWithLimits(
+ project_id,
+ url,
+ limits,
+ req,
+ res,
+ next
+ )
}
- return CompileController.proxyToClsiWithLimits(
- project_id,
- url,
- limits,
- req,
- res,
- next
- )
- })
+ )
}
},
proxyToClsiWithLimits(project_id, url, limits, req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
_getPersistenceOptions(req, project_id, (err, persistenceOptions) => {
let qs
@@ -541,7 +545,7 @@ module.exports = CompileController = {
const project_id = req.params.Project_id
const file = req.query.file || false
const { clsiserverid } = req.query
- return CompileController._compileAsUser(req, function(error, user_id) {
+ return CompileController._compileAsUser(req, function (error, user_id) {
if (error != null) {
return next(error)
}
@@ -550,7 +554,7 @@ module.exports = CompileController = {
user_id,
file,
clsiserverid,
- function(error, body) {
+ function (error, body) {
if (error != null) {
return next(error)
}
diff --git a/services/web/app/src/Features/Compile/CompileManager.js b/services/web/app/src/Features/Compile/CompileManager.js
index 24f704b336..3521eec3e5 100644
--- a/services/web/app/src/Features/Compile/CompileManager.js
+++ b/services/web/app/src/Features/Compile/CompileManager.js
@@ -30,10 +30,10 @@ module.exports = CompileManager = {
options = {}
}
if (_callback == null) {
- _callback = function(error) {}
+ _callback = function (error) {}
}
const timer = new Metrics.Timer('editor.compile')
- const callback = function(...args) {
+ const callback = function (...args) {
timer.done()
return _callback(...Array.from(args || []))
}
@@ -41,7 +41,7 @@ module.exports = CompileManager = {
return CompileManager._checkIfRecentlyCompiled(
project_id,
user_id,
- function(error, recentlyCompiled) {
+ function (error, recentlyCompiled) {
if (error != null) {
return callback(error)
}
@@ -52,20 +52,20 @@ module.exports = CompileManager = {
return CompileManager._checkIfAutoCompileLimitHasBeenHit(
options.isAutoCompile,
'everyone',
- function(err, canCompile) {
+ function (err, canCompile) {
if (!canCompile) {
return callback(null, 'autocompile-backoff', [])
}
return ProjectRootDocManager.ensureRootDocumentIsSet(
project_id,
- function(error) {
+ function (error) {
if (error != null) {
return callback(error)
}
return CompileManager.getProjectCompileLimits(
project_id,
- function(error, limits) {
+ function (error, limits) {
if (error != null) {
return callback(error)
}
@@ -77,7 +77,7 @@ module.exports = CompileManager = {
return CompileManager._checkCompileGroupAutoCompileLimit(
options.isAutoCompile,
limits.compileGroup,
- function(err, canCompile) {
+ function (err, canCompile) {
if (!canCompile) {
return callback(null, 'autocompile-backoff', [])
}
@@ -89,7 +89,7 @@ module.exports = CompileManager = {
project_id,
compileAsUser,
options,
- function(
+ function (
error,
status,
outputFiles,
@@ -123,100 +123,105 @@ module.exports = CompileManager = {
stopCompile(project_id, user_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return CompileManager.getProjectCompileLimits(project_id, function(
- error,
- limits
- ) {
- if (error != null) {
- return callback(error)
+ return CompileManager.getProjectCompileLimits(
+ project_id,
+ function (error, limits) {
+ if (error != null) {
+ return callback(error)
+ }
+ return ClsiManager.stopCompile(project_id, user_id, limits, callback)
}
- return ClsiManager.stopCompile(project_id, user_id, limits, callback)
- })
+ )
},
deleteAuxFiles(project_id, user_id, clsiserverid, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return CompileManager.getProjectCompileLimits(project_id, function(
- error,
- limits
- ) {
- if (error != null) {
- return callback(error)
+ return CompileManager.getProjectCompileLimits(
+ project_id,
+ function (error, limits) {
+ if (error != null) {
+ return callback(error)
+ }
+ ClsiManager.deleteAuxFiles(
+ project_id,
+ user_id,
+ limits,
+ clsiserverid,
+ callback
+ )
}
- ClsiManager.deleteAuxFiles(
- project_id,
- user_id,
- limits,
- clsiserverid,
- callback
- )
- })
+ )
},
getProjectCompileLimits(project_id, callback) {
if (callback == null) {
- callback = function(error, limits) {}
+ callback = function (error, limits) {}
}
- return ProjectGetter.getProject(project_id, { owner_ref: 1 }, function(
- error,
- project
- ) {
- if (error != null) {
- return callback(error)
- }
- return UserGetter.getUser(
- project.owner_ref,
- { alphaProgram: 1, betaProgram: 1, features: 1 },
- function(err, owner) {
- if (error != null) {
- return callback(error)
- }
- let ownerFeatures = (owner && owner.features) || {}
- // put alpha users into their own compile group
- if (owner && owner.alphaProgram) {
- ownerFeatures.compileGroup = 'alpha'
- }
- return callback(null, {
- timeout:
- ownerFeatures.compileTimeout ||
- Settings.defaultFeatures.compileTimeout,
- compileGroup:
- ownerFeatures.compileGroup ||
- Settings.defaultFeatures.compileGroup
- })
+ return ProjectGetter.getProject(
+ project_id,
+ { owner_ref: 1 },
+ function (error, project) {
+ if (error != null) {
+ return callback(error)
}
- )
- })
+ return UserGetter.getUser(
+ project.owner_ref,
+ { alphaProgram: 1, betaProgram: 1, features: 1 },
+ function (err, owner) {
+ if (error != null) {
+ return callback(error)
+ }
+ let ownerFeatures = (owner && owner.features) || {}
+ // put alpha users into their own compile group
+ if (owner && owner.alphaProgram) {
+ ownerFeatures.compileGroup = 'alpha'
+ }
+ return callback(null, {
+ timeout:
+ ownerFeatures.compileTimeout ||
+ Settings.defaultFeatures.compileTimeout,
+ compileGroup:
+ ownerFeatures.compileGroup ||
+ Settings.defaultFeatures.compileGroup
+ })
+ }
+ )
+ }
+ )
},
COMPILE_DELAY: 1, // seconds
_checkIfRecentlyCompiled(project_id, user_id, callback) {
if (callback == null) {
- callback = function(error, recentlyCompiled) {}
+ callback = function (error, recentlyCompiled) {}
}
const key = `compile:${project_id}:${user_id}`
- return rclient.set(key, true, 'EX', this.COMPILE_DELAY, 'NX', function(
- error,
- ok
- ) {
- if (error != null) {
- return callback(error)
+ return rclient.set(
+ key,
+ true,
+ 'EX',
+ this.COMPILE_DELAY,
+ 'NX',
+ function (error, ok) {
+ if (error != null) {
+ return callback(error)
+ }
+ if (ok === 'OK') {
+ return callback(null, false)
+ } else {
+ return callback(null, true)
+ }
}
- if (ok === 'OK') {
- return callback(null, false)
- } else {
- return callback(null, true)
- }
- })
+ )
},
_checkCompileGroupAutoCompileLimit(isAutoCompile, compileGroup, callback) {
if (callback == null) {
- callback = function(err, canCompile) {}
+ callback = function (err, canCompile) {}
}
if (!isAutoCompile) {
return callback(null, true)
@@ -236,7 +241,7 @@ module.exports = CompileManager = {
_checkIfAutoCompileLimitHasBeenHit(isAutoCompile, compileGroup, callback) {
if (callback == null) {
- callback = function(err, canCompile) {}
+ callback = function (err, canCompile) {}
}
if (!isAutoCompile) {
return callback(null, true)
@@ -248,7 +253,7 @@ module.exports = CompileManager = {
subjectName: compileGroup,
throttle: Settings.rateLimit.autoCompile[compileGroup] || 25
}
- return rateLimiter.addCount(opts, function(err, canCompile) {
+ return rateLimiter.addCount(opts, function (err, canCompile) {
if (err != null) {
canCompile = false
}
@@ -261,23 +266,23 @@ module.exports = CompileManager = {
wordCount(project_id, user_id, file, clsiserverid, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return CompileManager.getProjectCompileLimits(project_id, function(
- error,
- limits
- ) {
- if (error != null) {
- return callback(error)
+ return CompileManager.getProjectCompileLimits(
+ project_id,
+ function (error, limits) {
+ if (error != null) {
+ return callback(error)
+ }
+ ClsiManager.wordCount(
+ project_id,
+ user_id,
+ file,
+ limits,
+ clsiserverid,
+ callback
+ )
}
- ClsiManager.wordCount(
- project_id,
- user_id,
- file,
- limits,
- clsiserverid,
- callback
- )
- })
+ )
}
}
diff --git a/services/web/app/src/Features/Contacts/ContactController.js b/services/web/app/src/Features/Contacts/ContactController.js
index 81e17b5ea4..ee5c186f6a 100644
--- a/services/web/app/src/Features/Contacts/ContactController.js
+++ b/services/web/app/src/Features/Contacts/ContactController.js
@@ -22,58 +22,63 @@ const Modules = require('../../infrastructure/Modules')
module.exports = ContactsController = {
getContacts(req, res, next) {
const user_id = AuthenticationController.getLoggedInUserId(req)
- return ContactManager.getContactIds(user_id, { limit: 50 }, function(
- error,
- contact_ids
- ) {
- if (error != null) {
- return next(error)
- }
- return UserGetter.getUsers(
- contact_ids,
- {
- email: 1,
- first_name: 1,
- last_name: 1,
- holdingAccount: 1
- },
- function(error, contacts) {
- if (error != null) {
- return next(error)
- }
-
- // UserGetter.getUsers may not preserve order so put them back in order
- const positions = {}
- for (let i = 0; i < contact_ids.length; i++) {
- const contact_id = contact_ids[i]
- positions[contact_id] = i
- }
- contacts.sort(
- (a, b) =>
- positions[a._id != null ? a._id.toString() : undefined] -
- positions[b._id != null ? b._id.toString() : undefined]
- )
-
- // Don't count holding accounts to discourage users from repeating mistakes (mistyped or wrong emails, etc)
- contacts = contacts.filter(c => !c.holdingAccount)
-
- contacts = contacts.map(ContactsController._formatContact)
-
- return Modules.hooks.fire('getContacts', user_id, contacts, function(
- error,
- additional_contacts
- ) {
+ return ContactManager.getContactIds(
+ user_id,
+ { limit: 50 },
+ function (error, contact_ids) {
+ if (error != null) {
+ return next(error)
+ }
+ return UserGetter.getUsers(
+ contact_ids,
+ {
+ email: 1,
+ first_name: 1,
+ last_name: 1,
+ holdingAccount: 1
+ },
+ function (error, contacts) {
if (error != null) {
return next(error)
}
- contacts = contacts.concat(...Array.from(additional_contacts || []))
- return res.send({
- contacts
- })
- })
- }
- )
- })
+
+ // UserGetter.getUsers may not preserve order so put them back in order
+ const positions = {}
+ for (let i = 0; i < contact_ids.length; i++) {
+ const contact_id = contact_ids[i]
+ positions[contact_id] = i
+ }
+ contacts.sort(
+ (a, b) =>
+ positions[a._id != null ? a._id.toString() : undefined] -
+ positions[b._id != null ? b._id.toString() : undefined]
+ )
+
+ // Don't count holding accounts to discourage users from repeating mistakes (mistyped or wrong emails, etc)
+ contacts = contacts.filter(c => !c.holdingAccount)
+
+ contacts = contacts.map(ContactsController._formatContact)
+
+ return Modules.hooks.fire(
+ 'getContacts',
+ user_id,
+ contacts,
+ function (error, additional_contacts) {
+ if (error != null) {
+ return next(error)
+ }
+ contacts = contacts.concat(
+ ...Array.from(additional_contacts || [])
+ )
+ return res.send({
+ contacts
+ })
+ }
+ )
+ }
+ )
+ }
+ )
},
_formatContact(contact) {
diff --git a/services/web/app/src/Features/Contacts/ContactManager.js b/services/web/app/src/Features/Contacts/ContactManager.js
index a54e88403d..e5aad13d65 100644
--- a/services/web/app/src/Features/Contacts/ContactManager.js
+++ b/services/web/app/src/Features/Contacts/ContactManager.js
@@ -23,7 +23,7 @@ module.exports = ContactManager = {
options = { limits: 50 }
}
if (callback == null) {
- callback = function(error, contacts) {}
+ callback = function (error, contacts) {}
}
const url = `${settings.apis.contacts.url}/user/${user_id}/contacts`
return request.get(
@@ -33,7 +33,7 @@ module.exports = ContactManager = {
json: true,
jar: false
},
- function(error, res, data) {
+ function (error, res, data) {
if (error != null) {
return callback(error)
}
@@ -55,7 +55,7 @@ module.exports = ContactManager = {
addContact(user_id, contact_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
const url = `${settings.apis.contacts.url}/user/${user_id}/contacts`
return request.post(
@@ -66,7 +66,7 @@ module.exports = ContactManager = {
},
jar: false
},
- function(error, res, data) {
+ function (error, res, data) {
if (error != null) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Cooldown/CooldownManager.js b/services/web/app/src/Features/Cooldown/CooldownManager.js
index 155375873a..a7579b62d7 100644
--- a/services/web/app/src/Features/Cooldown/CooldownManager.js
+++ b/services/web/app/src/Features/Cooldown/CooldownManager.js
@@ -24,7 +24,7 @@ module.exports = CooldownManager = {
putProjectOnCooldown(projectId, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
logger.log(
{ projectId },
@@ -41,16 +41,16 @@ module.exports = CooldownManager = {
isProjectOnCooldown(projectId, callback) {
if (callback == null) {
- callback = function(err, isOnCooldown) {}
+ callback = function (err, isOnCooldown) {}
}
- return rclient.get(CooldownManager._buildKey(projectId), function(
- err,
- result
- ) {
- if (err != null) {
- return callback(err)
+ return rclient.get(
+ CooldownManager._buildKey(projectId),
+ function (err, result) {
+ if (err != null) {
+ return callback(err)
+ }
+ return callback(null, result === '1')
}
- return callback(null, result === '1')
- })
+ )
}
}
diff --git a/services/web/app/src/Features/Cooldown/CooldownMiddleware.js b/services/web/app/src/Features/Cooldown/CooldownMiddleware.js
index 9baf008007..c82ce97f15 100644
--- a/services/web/app/src/Features/Cooldown/CooldownMiddleware.js
+++ b/services/web/app/src/Features/Cooldown/CooldownMiddleware.js
@@ -20,21 +20,21 @@ module.exports = CooldownMiddleware = {
if (projectId == null) {
return next(new Error('[Cooldown] No projectId parameter on route'))
}
- return CooldownManager.isProjectOnCooldown(projectId, function(
- err,
- projectIsOnCooldown
- ) {
- if (err != null) {
- return next(err)
+ return CooldownManager.isProjectOnCooldown(
+ projectId,
+ function (err, projectIsOnCooldown) {
+ if (err != null) {
+ return next(err)
+ }
+ if (projectIsOnCooldown) {
+ logger.log(
+ { projectId },
+ '[Cooldown] project is on cooldown, denying request'
+ )
+ return res.sendStatus(429)
+ }
+ return next()
}
- if (projectIsOnCooldown) {
- logger.log(
- { projectId },
- '[Cooldown] project is on cooldown, denying request'
- )
- return res.sendStatus(429)
- }
- return next()
- })
+ )
}
}
diff --git a/services/web/app/src/Features/Docstore/DocstoreManager.js b/services/web/app/src/Features/Docstore/DocstoreManager.js
index c85f9577d2..a4fe1820a3 100644
--- a/services/web/app/src/Features/Docstore/DocstoreManager.js
+++ b/services/web/app/src/Features/Docstore/DocstoreManager.js
@@ -24,12 +24,12 @@ const TIMEOUT = 30 * 1000 // request timeout
const DocstoreManager = {
deleteDoc(project_id, doc_id, name, deletedAt, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
const url = `${settings.apis.docstore.url}/project/${project_id}/doc/${doc_id}`
const docMetaData = { deleted: true, deletedAt, name }
const options = { url, json: docMetaData, timeout: TIMEOUT }
- request.patch(options, function(error, res) {
+ request.patch(options, function (error, res) {
if (error != null) {
return callback(error)
}
@@ -59,7 +59,7 @@ const DocstoreManager = {
getAllDocs(project_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
const url = `${settings.apis.docstore.url}/project/${project_id}/doc`
return request.get(
@@ -68,7 +68,7 @@ const DocstoreManager = {
timeout: TIMEOUT,
json: true
},
- function(error, res, docs) {
+ function (error, res, docs) {
if (error != null) {
return callback(error)
}
@@ -87,29 +87,30 @@ const DocstoreManager = {
getAllDeletedDocs(project_id, callback) {
const url = `${settings.apis.docstore.url}/project/${project_id}/doc-deleted`
- request.get({ url, timeout: TIMEOUT, json: true }, function(
- error,
- res,
- docs
- ) {
- if (error) {
- callback(OError.tag(error, 'could not get deleted docs from docstore'))
- } else if (res.statusCode === 200) {
- callback(null, docs)
- } else {
- callback(
- new OError(
- `docstore api responded with non-success code: ${res.statusCode}`,
- { project_id }
+ request.get(
+ { url, timeout: TIMEOUT, json: true },
+ function (error, res, docs) {
+ if (error) {
+ callback(
+ OError.tag(error, 'could not get deleted docs from docstore')
)
- )
+ } else if (res.statusCode === 200) {
+ callback(null, docs)
+ } else {
+ callback(
+ new OError(
+ `docstore api responded with non-success code: ${res.statusCode}`,
+ { project_id }
+ )
+ )
+ }
}
- })
+ )
},
getAllRanges(project_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
const url = `${settings.apis.docstore.url}/project/${project_id}/ranges`
return request.get(
@@ -118,7 +119,7 @@ const DocstoreManager = {
timeout: TIMEOUT,
json: true
},
- function(error, res, docs) {
+ function (error, res, docs) {
if (error != null) {
return callback(error)
}
@@ -140,7 +141,7 @@ const DocstoreManager = {
options = {}
}
if (callback == null) {
- callback = function(error, lines, rev, version) {}
+ callback = function (error, lines, rev, version) {}
}
if (typeof options === 'function') {
callback = options
@@ -156,7 +157,7 @@ const DocstoreManager = {
timeout: TIMEOUT,
json: true
},
- function(error, res, doc) {
+ function (error, res, doc) {
if (error != null) {
return callback(error)
}
@@ -191,36 +192,35 @@ const DocstoreManager = {
isDocDeleted(project_id, doc_id, callback) {
const url = `${settings.apis.docstore.url}/project/${project_id}/doc/${doc_id}/deleted`
- request.get({ url, timeout: TIMEOUT, json: true }, function(
- err,
- res,
- body
- ) {
- if (err) {
- callback(err)
- } else if (res.statusCode === 200) {
- callback(null, body.deleted)
- } else if (res.statusCode === 404) {
- callback(
- new Errors.NotFoundError({
- message: 'doc does not exist in project',
- info: { project_id, doc_id }
- })
- )
- } else {
- callback(
- new OError(
- `docstore api responded with non-success code: ${res.statusCode}`,
- { project_id, doc_id }
+ request.get(
+ { url, timeout: TIMEOUT, json: true },
+ function (err, res, body) {
+ if (err) {
+ callback(err)
+ } else if (res.statusCode === 200) {
+ callback(null, body.deleted)
+ } else if (res.statusCode === 404) {
+ callback(
+ new Errors.NotFoundError({
+ message: 'doc does not exist in project',
+ info: { project_id, doc_id }
+ })
)
- )
+ } else {
+ callback(
+ new OError(
+ `docstore api responded with non-success code: ${res.statusCode}`,
+ { project_id, doc_id }
+ )
+ )
+ }
}
- })
+ )
},
updateDoc(project_id, doc_id, lines, version, ranges, callback) {
if (callback == null) {
- callback = function(error, modified, rev) {}
+ callback = function (error, modified, rev) {}
}
const url = `${settings.apis.docstore.url}/project/${project_id}/doc/${doc_id}`
return request.post(
@@ -233,7 +233,7 @@ const DocstoreManager = {
ranges
}
},
- function(error, res, result) {
+ function (error, res, result) {
if (error != null) {
return callback(error)
}
@@ -270,7 +270,7 @@ const DocstoreManager = {
const url = `${settings.apis.docstore.url}/project/${project_id}/${method}`
logger.log({ project_id }, `calling ${method} for project in docstore`)
// use default timeout for archiving/unarchiving/destroying
- request.post(url, function(err, res, docs) {
+ request.post(url, function (err, res, docs) {
if (err != null) {
OError.tag(err, `error calling ${method} project in docstore`, {
project_id
diff --git a/services/web/app/src/Features/DocumentUpdater/DocumentUpdaterHandler.js b/services/web/app/src/Features/DocumentUpdater/DocumentUpdaterHandler.js
index 2b4027432f..e4cc3addca 100644
--- a/services/web/app/src/Features/DocumentUpdater/DocumentUpdaterHandler.js
+++ b/services/web/app/src/Features/DocumentUpdater/DocumentUpdaterHandler.js
@@ -101,7 +101,7 @@ function getDocument(projectId, docId, fromVersion, callback) {
},
projectId,
'get-document',
- function(error, doc) {
+ function (error, doc) {
if (error) {
return callback(error)
}
@@ -133,7 +133,7 @@ function getProjectDocsIfMatch(projectId, projectStateHash, callback) {
// fall back to getting them from mongo.
const timer = new metrics.Timer('get-project-docs')
const url = `${settings.apis.documentupdater.url}/project/${projectId}/get_and_flush_if_old?state=${projectStateHash}`
- request.post(url, function(error, res, body) {
+ request.post(url, function (error, res, body) {
timer.done()
if (error) {
OError.tag(error, 'error getting project docs from doc updater', {
@@ -300,7 +300,7 @@ function _makeRequest(options, projectId, metricsKey, callback) {
json: options.json,
method: options.method || 'GET'
},
- function(error, res, body) {
+ function (error, res, body) {
timer.done()
if (error) {
logger.warn(
diff --git a/services/web/app/src/Features/Documents/DocumentController.js b/services/web/app/src/Features/Documents/DocumentController.js
index 5b06673ca3..824c1badc7 100644
--- a/services/web/app/src/Features/Documents/DocumentController.js
+++ b/services/web/app/src/Features/Documents/DocumentController.js
@@ -23,7 +23,7 @@ const _ = require('lodash')
module.exports = {
getDocument(req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
const project_id = req.params.Project_id
const { doc_id } = req.params
@@ -32,7 +32,7 @@ module.exports = {
return ProjectGetter.getProject(
project_id,
{ rootFolder: true, overleaf: true },
- function(error, project) {
+ function (error, project) {
if (error != null) {
return next(error)
}
@@ -41,7 +41,7 @@ module.exports = {
}
return ProjectLocator.findElement(
{ project, element_id: doc_id, type: 'doc' },
- function(error, doc, path) {
+ function (error, doc, path) {
if (error != null) {
OError.tag(error, 'error finding element for getDocument', {
doc_id,
@@ -49,45 +49,43 @@ module.exports = {
})
return next(error)
}
- return ProjectEntityHandler.getDoc(project_id, doc_id, function(
- error,
- lines,
- rev,
- version,
- ranges
- ) {
- if (error != null) {
- OError.tag(
- error,
- 'error finding doc contents for getDocument',
- {
- doc_id,
- project_id
- }
- )
- return next(error)
+ return ProjectEntityHandler.getDoc(
+ project_id,
+ doc_id,
+ function (error, lines, rev, version, ranges) {
+ if (error != null) {
+ OError.tag(
+ error,
+ 'error finding doc contents for getDocument',
+ {
+ doc_id,
+ project_id
+ }
+ )
+ return next(error)
+ }
+ if (plain) {
+ res.type('text/plain')
+ return res.send(lines.join('\n'))
+ } else {
+ const projectHistoryId = _.get(project, 'overleaf.history.id')
+ const projectHistoryType = _.get(
+ project,
+ 'overleaf.history.display'
+ )
+ ? 'project-history'
+ : undefined // for backwards compatibility, don't send anything if the project is still on track-changes
+ return res.json({
+ lines,
+ version,
+ ranges,
+ pathname: path.fileSystem,
+ projectHistoryId,
+ projectHistoryType
+ })
+ }
}
- if (plain) {
- res.type('text/plain')
- return res.send(lines.join('\n'))
- } else {
- const projectHistoryId = _.get(project, 'overleaf.history.id')
- const projectHistoryType = _.get(
- project,
- 'overleaf.history.display'
- )
- ? 'project-history'
- : undefined // for backwards compatibility, don't send anything if the project is still on track-changes
- return res.json({
- lines,
- version,
- ranges,
- pathname: path.fileSystem,
- projectHistoryId,
- projectHistoryType
- })
- }
- })
+ )
}
)
}
@@ -96,7 +94,7 @@ module.exports = {
setDocument(req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
const project_id = req.params.Project_id
const { doc_id } = req.params
@@ -109,7 +107,7 @@ module.exports = {
ranges,
lastUpdatedAt,
lastUpdatedBy,
- function(error) {
+ function (error) {
if (error != null) {
OError.tag(error, 'error finding element for getDocument', {
doc_id,
diff --git a/services/web/app/src/Features/Downloads/ProjectDownloadsController.js b/services/web/app/src/Features/Downloads/ProjectDownloadsController.js
index 174ab71f08..9e7549c416 100644
--- a/services/web/app/src/Features/Downloads/ProjectDownloadsController.js
+++ b/services/web/app/src/Features/Downloads/ProjectDownloadsController.js
@@ -22,34 +22,36 @@ module.exports = ProjectDownloadsController = {
downloadProject(req, res, next) {
const project_id = req.params.Project_id
Metrics.inc('zip-downloads')
- return DocumentUpdaterHandler.flushProjectToMongo(project_id, function(
- error
- ) {
- if (error != null) {
- return next(error)
- }
- return ProjectGetter.getProject(project_id, { name: true }, function(
- error,
- project
- ) {
+ return DocumentUpdaterHandler.flushProjectToMongo(
+ project_id,
+ function (error) {
if (error != null) {
return next(error)
}
- return ProjectZipStreamManager.createZipStreamForProject(
+ return ProjectGetter.getProject(
project_id,
- function(error, stream) {
+ { name: true },
+ function (error, project) {
if (error != null) {
return next(error)
}
- res.setContentDisposition('attachment', {
- filename: `${project.name}.zip`
- })
- res.contentType('application/zip')
- return stream.pipe(res)
+ return ProjectZipStreamManager.createZipStreamForProject(
+ project_id,
+ function (error, stream) {
+ if (error != null) {
+ return next(error)
+ }
+ res.setContentDisposition('attachment', {
+ filename: `${project.name}.zip`
+ })
+ res.contentType('application/zip')
+ return stream.pipe(res)
+ }
+ )
}
)
- })
- })
+ }
+ )
},
downloadMultipleProjects(req, res, next) {
@@ -57,13 +59,13 @@ module.exports = ProjectDownloadsController = {
Metrics.inc('zip-downloads-multiple')
return DocumentUpdaterHandler.flushMultipleProjectsToMongo(
project_ids,
- function(error) {
+ function (error) {
if (error != null) {
return next(error)
}
return ProjectZipStreamManager.createZipStreamForMultipleProjects(
project_ids,
- function(error, stream) {
+ function (error, stream) {
if (error != null) {
return next(error)
}
diff --git a/services/web/app/src/Features/Downloads/ProjectZipStreamManager.js b/services/web/app/src/Features/Downloads/ProjectZipStreamManager.js
index 0bec0d6593..ea64cf3e6d 100644
--- a/services/web/app/src/Features/Downloads/ProjectZipStreamManager.js
+++ b/services/web/app/src/Features/Downloads/ProjectZipStreamManager.js
@@ -26,7 +26,7 @@ module.exports = ProjectZipStreamManager = {
// We'll build up a zip file that contains multiple zip files
if (callback == null) {
- callback = function(error, stream) {}
+ callback = function (error, stream) {}
}
const archive = archiver('zip')
archive.on('error', err =>
@@ -41,38 +41,39 @@ module.exports = ProjectZipStreamManager = {
for (let project_id of Array.from(project_ids || [])) {
;(project_id =>
jobs.push(callback =>
- ProjectGetter.getProject(project_id, { name: true }, function(
- error,
- project
- ) {
- if (error != null) {
- return callback(error)
- }
- logger.log(
- { project_id, name: project.name },
- 'appending project to zip stream'
- )
- return ProjectZipStreamManager.createZipStreamForProject(
- project_id,
- function(error, stream) {
- if (error != null) {
- return callback(error)
- }
- archive.append(stream, { name: `${project.name}.zip` })
- return stream.on('end', function() {
- logger.log(
- { project_id, name: project.name },
- 'zip stream ended'
- )
- return callback()
- })
+ ProjectGetter.getProject(
+ project_id,
+ { name: true },
+ function (error, project) {
+ if (error != null) {
+ return callback(error)
}
- )
- })
+ logger.log(
+ { project_id, name: project.name },
+ 'appending project to zip stream'
+ )
+ return ProjectZipStreamManager.createZipStreamForProject(
+ project_id,
+ function (error, stream) {
+ if (error != null) {
+ return callback(error)
+ }
+ archive.append(stream, { name: `${project.name}.zip` })
+ return stream.on('end', function () {
+ logger.log(
+ { project_id, name: project.name },
+ 'zip stream ended'
+ )
+ return callback()
+ })
+ }
+ )
+ }
+ )
))(project_id)
}
- return async.series(jobs, function() {
+ return async.series(jobs, function () {
logger.log(
{ project_ids },
'finished creating zip stream of multiple projects'
@@ -83,7 +84,7 @@ module.exports = ProjectZipStreamManager = {
createZipStreamForProject(project_id, callback) {
if (callback == null) {
- callback = function(error, stream) {}
+ callback = function (error, stream) {}
}
const archive = archiver('zip')
// return stream immediately before we start adding things to it
@@ -115,20 +116,20 @@ module.exports = ProjectZipStreamManager = {
addAllDocsToArchive(project_id, archive, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return ProjectEntityHandler.getAllDocs(project_id, function(error, docs) {
+ return ProjectEntityHandler.getAllDocs(project_id, function (error, docs) {
if (error != null) {
return callback(error)
}
const jobs = []
for (let path in docs) {
const doc = docs[path]
- ;(function(path, doc) {
+ ;(function (path, doc) {
if (path[0] === '/') {
path = path.slice(1)
}
- return jobs.push(function(callback) {
+ return jobs.push(function (callback) {
logger.log({ project_id }, 'Adding doc')
archive.append(doc.lines.join('\n'), { name: path })
return callback()
@@ -141,37 +142,42 @@ module.exports = ProjectZipStreamManager = {
addAllFilesToArchive(project_id, archive, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return ProjectEntityHandler.getAllFiles(project_id, function(error, files) {
- if (error != null) {
- return callback(error)
+ return ProjectEntityHandler.getAllFiles(
+ project_id,
+ function (error, files) {
+ if (error != null) {
+ return callback(error)
+ }
+ const jobs = []
+ for (let path in files) {
+ const file = files[path]
+ ;((path, file) =>
+ jobs.push(callback =>
+ FileStoreHandler.getFileStream(
+ project_id,
+ file._id,
+ {},
+ function (error, stream) {
+ if (error != null) {
+ logger.warn(
+ { err: error, project_id, file_id: file._id },
+ 'something went wrong adding file to zip archive'
+ )
+ return callback(err)
+ }
+ if (path[0] === '/') {
+ path = path.slice(1)
+ }
+ archive.append(stream, { name: path })
+ return stream.on('end', () => callback())
+ }
+ )
+ ))(path, file)
+ }
+ return async.parallelLimit(jobs, 5, callback)
}
- const jobs = []
- for (let path in files) {
- const file = files[path]
- ;((path, file) =>
- jobs.push(callback =>
- FileStoreHandler.getFileStream(project_id, file._id, {}, function(
- error,
- stream
- ) {
- if (error != null) {
- logger.warn(
- { err: error, project_id, file_id: file._id },
- 'something went wrong adding file to zip archive'
- )
- return callback(err)
- }
- if (path[0] === '/') {
- path = path.slice(1)
- }
- archive.append(stream, { name: path })
- return stream.on('end', () => callback())
- })
- ))(path, file)
- }
- return async.parallelLimit(jobs, 5, callback)
- })
+ )
}
}
diff --git a/services/web/app/src/Features/Editor/EditorController.js b/services/web/app/src/Features/Editor/EditorController.js
index f8c2142381..e9f2e31310 100644
--- a/services/web/app/src/Features/Editor/EditorController.js
+++ b/services/web/app/src/Features/Editor/EditorController.js
@@ -31,7 +31,7 @@ const { promisifyAll } = require('../../util/promises')
const EditorController = {
addDoc(project_id, folder_id, docName, docLines, source, user_id, callback) {
if (callback == null) {
- callback = function(error, doc) {}
+ callback = function (error, doc) {}
}
return EditorController.addDocWithRanges(
project_id,
@@ -56,7 +56,7 @@ const EditorController = {
callback
) {
if (callback == null) {
- callback = function(error, doc) {}
+ callback = function (error, doc) {}
}
docName = docName.trim()
Metrics.inc('editor.add-doc')
@@ -99,7 +99,7 @@ const EditorController = {
callback
) {
if (callback == null) {
- callback = function(error, file) {}
+ callback = function (error, file) {}
}
fileName = fileName.trim()
Metrics.inc('editor.add-file')
@@ -143,7 +143,7 @@ const EditorController = {
callback
) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
return ProjectEntityUpdateHandler.upsertDoc(
project_id,
@@ -152,7 +152,7 @@ const EditorController = {
docLines,
source,
user_id,
- function(err, doc, didAddNewDoc) {
+ function (err, doc, didAddNewDoc) {
if (didAddNewDoc) {
EditorRealTimeController.emitToRoom(
project_id,
@@ -179,7 +179,7 @@ const EditorController = {
callback
) {
if (callback == null) {
- callback = function(err, file) {}
+ callback = function (err, file) {}
}
return ProjectEntityUpdateHandler.upsertFile(
project_id,
@@ -188,7 +188,7 @@ const EditorController = {
fsPath,
linkedFileData,
user_id,
- function(err, newFile, didAddFile, existingFile) {
+ function (err, newFile, didAddFile, existingFile) {
if (err != null) {
return callback(err)
}
@@ -230,14 +230,14 @@ const EditorController = {
docLines,
source,
user_id,
- function(err, doc, didAddNewDoc, newFolders, lastFolder) {
+ function (err, doc, didAddNewDoc, newFolders, lastFolder) {
if (err != null) {
return callback(err)
}
return EditorController._notifyProjectUsersOfNewFolders(
project_id,
newFolders,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -273,14 +273,21 @@ const EditorController = {
fsPath,
linkedFileData,
user_id,
- function(err, newFile, didAddFile, existingFile, newFolders, lastFolder) {
+ function (
+ err,
+ newFile,
+ didAddFile,
+ existingFile,
+ newFolders,
+ lastFolder
+ ) {
if (err != null) {
return callback(err)
}
return EditorController._notifyProjectUsersOfNewFolders(
project_id,
newFolders,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -312,7 +319,7 @@ const EditorController = {
addFolder(project_id, folder_id, folderName, source, userId, callback) {
if (callback == null) {
- callback = function(error, folder) {}
+ callback = function (error, folder) {}
}
folderName = folderName.trim()
Metrics.inc('editor.add-folder')
@@ -335,7 +342,7 @@ const EditorController = {
folder_id,
folder,
userId,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -348,7 +355,7 @@ const EditorController = {
mkdirp(project_id, path, callback) {
if (callback == null) {
- callback = function(error, newFolders, lastFolder) {}
+ callback = function (error, newFolders, lastFolder) {}
}
logger.log({ project_id, path }, "making directories if they don't exist")
return ProjectEntityUpdateHandler.mkdirp(
@@ -366,7 +373,7 @@ const EditorController = {
return EditorController._notifyProjectUsersOfNewFolders(
project_id,
newFolders,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -379,7 +386,7 @@ const EditorController = {
deleteEntity(project_id, entity_id, entityType, source, userId, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
Metrics.inc('editor.delete-entity')
return ProjectEntityUpdateHandler.deleteEntity(
@@ -387,7 +394,7 @@ const EditorController = {
entity_id,
entityType,
userId,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'could not delete entity', {
project_id,
@@ -416,7 +423,7 @@ const EditorController = {
project_id,
path,
user_id,
- function(err, entity_id) {
+ function (err, entity_id) {
if (err != null) {
return callback(err)
}
@@ -433,13 +440,13 @@ const EditorController = {
updateProjectDescription(project_id, description, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
logger.log({ project_id, description }, 'updating project description')
return ProjectDetailsHandler.setProjectDescription(
project_id,
description,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(
err,
@@ -468,7 +475,7 @@ const EditorController = {
renameEntity(project_id, entity_id, entityType, newName, userId, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
newName = sanitize.escape(newName)
Metrics.inc('editor.rename-entity')
@@ -478,7 +485,7 @@ const EditorController = {
entityType,
newName,
userId,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'error renaming entity', {
project_id,
@@ -503,7 +510,7 @@ const EditorController = {
moveEntity(project_id, entity_id, folder_id, entityType, userId, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
Metrics.inc('editor.move-entity')
return ProjectEntityUpdateHandler.moveEntity(
@@ -512,7 +519,7 @@ const EditorController = {
folder_id,
entityType,
userId,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'error moving entity', {
project_id,
@@ -534,73 +541,79 @@ const EditorController = {
renameProject(project_id, newName, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
- return ProjectDetailsHandler.renameProject(project_id, newName, function(
- err
- ) {
- if (err != null) {
- OError.tag(err, 'error renaming project', {
+ return ProjectDetailsHandler.renameProject(
+ project_id,
+ newName,
+ function (err) {
+ if (err != null) {
+ OError.tag(err, 'error renaming project', {
+ project_id,
+ newName
+ })
+ return callback(err)
+ }
+ EditorRealTimeController.emitToRoom(
project_id,
+ 'projectNameUpdated',
newName
- })
- return callback(err)
+ )
+ return callback()
}
- EditorRealTimeController.emitToRoom(
- project_id,
- 'projectNameUpdated',
- newName
- )
- return callback()
- })
+ )
},
setCompiler(project_id, compiler, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
- return ProjectOptionsHandler.setCompiler(project_id, compiler, function(
- err
- ) {
- if (err != null) {
- return callback(err)
+ return ProjectOptionsHandler.setCompiler(
+ project_id,
+ compiler,
+ function (err) {
+ if (err != null) {
+ return callback(err)
+ }
+ EditorRealTimeController.emitToRoom(
+ project_id,
+ 'compilerUpdated',
+ compiler
+ )
+ return callback()
}
- EditorRealTimeController.emitToRoom(
- project_id,
- 'compilerUpdated',
- compiler
- )
- return callback()
- })
+ )
},
setImageName(project_id, imageName, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
- return ProjectOptionsHandler.setImageName(project_id, imageName, function(
- err
- ) {
- if (err != null) {
- return callback(err)
+ return ProjectOptionsHandler.setImageName(
+ project_id,
+ imageName,
+ function (err) {
+ if (err != null) {
+ return callback(err)
+ }
+ EditorRealTimeController.emitToRoom(
+ project_id,
+ 'imageNameUpdated',
+ imageName
+ )
+ return callback()
}
- EditorRealTimeController.emitToRoom(
- project_id,
- 'imageNameUpdated',
- imageName
- )
- return callback()
- })
+ )
},
setSpellCheckLanguage(project_id, languageCode, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
return ProjectOptionsHandler.setSpellCheckLanguage(
project_id,
languageCode,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -616,12 +629,12 @@ const EditorController = {
setPublicAccessLevel(project_id, newAccessLevel, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
return ProjectDetailsHandler.setPublicAccessLevel(
project_id,
newAccessLevel,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -633,7 +646,7 @@ const EditorController = {
if (newAccessLevel === PublicAccessLevels.TOKEN_BASED) {
return ProjectDetailsHandler.ensureTokensArePresent(
project_id,
- function(err, tokens) {
+ function (err, tokens) {
if (err != null) {
return callback(err)
}
@@ -654,12 +667,12 @@ const EditorController = {
setRootDoc(project_id, newRootDocID, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
return ProjectEntityUpdateHandler.setRootDoc(
project_id,
newRootDocID,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -675,7 +688,7 @@ const EditorController = {
_notifyProjectUsersOfNewFolders(project_id, folders, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return async.eachSeries(
folders,
@@ -699,7 +712,7 @@ const EditorController = {
callback
) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
EditorRealTimeController.emitToRoom(
project_id,
diff --git a/services/web/app/src/Features/Exports/ExportsController.js b/services/web/app/src/Features/Exports/ExportsController.js
index 086b9a5e30..37e9af86eb 100644
--- a/services/web/app/src/Features/Exports/ExportsController.js
+++ b/services/web/app/src/Features/Exports/ExportsController.js
@@ -49,41 +49,41 @@ module.exports = {
}
}
- return ExportsHandler.exportProject(export_params, function(
- err,
- export_data
- ) {
- if (err != null) {
- if (err.forwardResponse != null) {
- logger.log(
- { responseError: err.forwardResponse },
- 'forwarding response'
- )
- const statusCode = err.forwardResponse.status || 500
- return res.status(statusCode).json(err.forwardResponse)
- } else {
- return next(err)
+ return ExportsHandler.exportProject(
+ export_params,
+ function (err, export_data) {
+ if (err != null) {
+ if (err.forwardResponse != null) {
+ logger.log(
+ { responseError: err.forwardResponse },
+ 'forwarding response'
+ )
+ const statusCode = err.forwardResponse.status || 500
+ return res.status(statusCode).json(err.forwardResponse)
+ } else {
+ return next(err)
+ }
}
+ logger.log(
+ {
+ user_id,
+ project_id,
+ brand_variation_id,
+ export_v1_id: export_data.v1_id
+ },
+ 'exported project'
+ )
+ return res.json({
+ export_v1_id: export_data.v1_id,
+ message: export_data.message
+ })
}
- logger.log(
- {
- user_id,
- project_id,
- brand_variation_id,
- export_v1_id: export_data.v1_id
- },
- 'exported project'
- )
- return res.json({
- export_v1_id: export_data.v1_id,
- message: export_data.message
- })
- })
+ )
},
exportStatus(req, res) {
const { export_id } = req.params
- return ExportsHandler.fetchExport(export_id, function(err, export_json) {
+ return ExportsHandler.fetchExport(export_id, function (err, export_json) {
let json
if (err != null) {
json = {
@@ -112,15 +112,16 @@ module.exports = {
const { type, export_id } = req.params
AuthenticationController.getLoggedInUserId(req)
- return ExportsHandler.fetchDownload(export_id, type, function(
- err,
- export_file_url
- ) {
- if (err != null) {
- return next(err)
- }
+ return ExportsHandler.fetchDownload(
+ export_id,
+ type,
+ function (err, export_file_url) {
+ if (err != null) {
+ return next(err)
+ }
- return res.redirect(export_file_url)
- })
+ return res.redirect(export_file_url)
+ }
+ )
}
}
diff --git a/services/web/app/src/Features/Exports/ExportsHandler.js b/services/web/app/src/Features/Exports/ExportsHandler.js
index 37cac68824..7a46379bd9 100644
--- a/services/web/app/src/Features/Exports/ExportsHandler.js
+++ b/services/web/app/src/Features/Exports/ExportsHandler.js
@@ -30,13 +30,13 @@ settings = require('settings-sharelatex')
module.exports = ExportsHandler = self = {
exportProject(export_params, callback) {
if (callback == null) {
- callback = function(error, export_data) {}
+ callback = function (error, export_data) {}
}
- return self._buildExport(export_params, function(err, export_data) {
+ return self._buildExport(export_params, function (err, export_data) {
if (err != null) {
return callback(err)
}
- return self._requestExport(export_data, function(err, body) {
+ return self._requestExport(export_data, function (err, body) {
if (err != null) {
return callback(err)
}
@@ -50,7 +50,7 @@ module.exports = ExportsHandler = self = {
_buildExport(export_params, callback) {
if (callback == null) {
- callback = function(err, export_data) {}
+ callback = function (err, export_data) {}
}
const {
project_id,
@@ -70,17 +70,18 @@ module.exports = ExportsHandler = self = {
rootDoc: [
'project',
(cb, results) =>
- ProjectRootDocManager.ensureRootDocumentIsValid(project_id, function(
- error
- ) {
- if (error != null) {
- return callback(error)
+ ProjectRootDocManager.ensureRootDocumentIsValid(
+ project_id,
+ function (error) {
+ if (error != null) {
+ return callback(error)
+ }
+ return ProjectLocator.findRootDoc(
+ { project: results.project, project_id },
+ cb
+ )
}
- return ProjectLocator.findRootDoc(
- { project: results.project, project_id },
- cb
- )
- })
+ )
],
user(cb) {
return UserGetter.getUser(
@@ -92,7 +93,7 @@ module.exports = ExportsHandler = self = {
historyVersion(cb) {
return ProjectHistoryHandler.ensureHistoryExistsForProject(
project_id,
- function(error) {
+ function (error) {
if (error != null) {
return callback(error)
}
@@ -102,7 +103,7 @@ module.exports = ExportsHandler = self = {
}
}
- return async.auto(jobs, function(err, results) {
+ return async.auto(jobs, function (err, results) {
if (err != null) {
OError.tag(err, 'error building project export', {
project_id,
@@ -167,7 +168,7 @@ module.exports = ExportsHandler = self = {
_requestExport(export_data, callback) {
if (callback == null) {
- callback = function(err, export_v1_id) {}
+ callback = function (err, export_v1_id) {}
}
return request.post(
{
@@ -175,7 +176,7 @@ module.exports = ExportsHandler = self = {
auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass },
json: export_data
},
- function(err, res, body) {
+ function (err, res, body) {
if (err != null) {
OError.tag(err, 'error making request to v1 export', {
export: export_data
@@ -197,14 +198,14 @@ module.exports = ExportsHandler = self = {
_requestVersion(project_id, callback) {
if (callback == null) {
- callback = function(err, export_v1_id) {}
+ callback = function (err, export_v1_id) {}
}
return request.get(
{
url: `${settings.apis.project_history.url}/project/${project_id}/version`,
json: true
},
- function(err, res, body) {
+ function (err, res, body) {
if (err != null) {
OError.tag(err, 'error making request to project history', {
project_id
@@ -225,14 +226,14 @@ module.exports = ExportsHandler = self = {
fetchExport(export_id, callback) {
if (callback == null) {
- callback = function(err, export_json) {}
+ callback = function (err, export_json) {}
}
return request.get(
{
url: `${settings.apis.v1.url}/api/v1/sharelatex/exports/${export_id}`,
auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass }
},
- function(err, res, body) {
+ function (err, res, body) {
if (err != null) {
OError.tag(err, 'error making request to v1 export', {
export: export_id
@@ -253,14 +254,14 @@ module.exports = ExportsHandler = self = {
fetchDownload(export_id, type, callback) {
if (callback == null) {
- callback = function(err, file_url) {}
+ callback = function (err, file_url) {}
}
return request.get(
{
url: `${settings.apis.v1.url}/api/v1/sharelatex/exports/${export_id}/${type}_url`,
auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass }
},
- function(err, res, body) {
+ function (err, res, body) {
if (err != null) {
OError.tag(err, 'error making request to v1 export', {
export: export_id
diff --git a/services/web/app/src/Features/FileStore/FileHashManager.js b/services/web/app/src/Features/FileStore/FileHashManager.js
index 5a69ec1911..d52ad6f6de 100644
--- a/services/web/app/src/Features/FileStore/FileHashManager.js
+++ b/services/web/app/src/Features/FileStore/FileHashManager.js
@@ -20,7 +20,7 @@ const _ = require('underscore')
module.exports = FileHashManager = {
computeHash(filePath, callback) {
if (callback == null) {
- callback = function(error, hashValue) {}
+ callback = function (error, hashValue) {}
}
callback = _.once(callback) // avoid double callbacks
@@ -28,20 +28,20 @@ module.exports = FileHashManager = {
const getGitBlobHeader = byteLength => `blob ${byteLength}` + '\x00'
const getByteLengthOfFile = cb =>
- fs.stat(filePath, function(err, stats) {
+ fs.stat(filePath, function (err, stats) {
if (err != null) {
return cb(err)
}
return cb(null, stats.size)
})
- return getByteLengthOfFile(function(err, byteLength) {
+ return getByteLengthOfFile(function (err, byteLength) {
if (err != null) {
return callback(err)
}
const input = fs.createReadStream(filePath)
- input.on('error', function(err) {
+ input.on('error', function (err) {
logger.warn({ filePath, err }, 'error opening file in computeHash')
return callback(err)
})
@@ -49,7 +49,7 @@ module.exports = FileHashManager = {
const hash = crypto.createHash('sha1')
hash.setEncoding('hex')
hash.update(getGitBlobHeader(byteLength))
- hash.on('readable', function() {
+ hash.on('readable', function () {
const result = hash.read()
if (result != null) {
return callback(null, result.toString('hex'))
diff --git a/services/web/app/src/Features/FileStore/FileStoreController.js b/services/web/app/src/Features/FileStore/FileStoreController.js
index e05b1b1435..c16822ef57 100644
--- a/services/web/app/src/Features/FileStore/FileStoreController.js
+++ b/services/web/app/src/Features/FileStore/FileStoreController.js
@@ -12,7 +12,7 @@ module.exports = {
const userAgent = req.get('User-Agent')
ProjectLocator.findElement(
{ project_id: projectId, element_id: fileId, type: 'file' },
- function(err, file) {
+ function (err, file) {
if (err) {
logger.err(
{ err, projectId, fileId, queryString },
@@ -20,24 +20,26 @@ module.exports = {
)
return res.sendStatus(500)
}
- FileStoreHandler.getFileStream(projectId, fileId, queryString, function(
- err,
- stream
- ) {
- if (err) {
- logger.err(
- { err, projectId, fileId, queryString },
- 'error getting file stream for downloading file'
- )
- return res.sendStatus(500)
+ FileStoreHandler.getFileStream(
+ projectId,
+ fileId,
+ queryString,
+ function (err, stream) {
+ if (err) {
+ logger.err(
+ { err, projectId, fileId, queryString },
+ 'error getting file stream for downloading file'
+ )
+ return res.sendStatus(500)
+ }
+ // mobile safari will try to render html files, prevent this
+ if (isMobileSafari(userAgent) && isHtml(file)) {
+ res.setHeader('Content-Type', 'text/plain')
+ }
+ res.setContentDisposition('attachment', { filename: file.name })
+ stream.pipe(res)
}
- // mobile safari will try to render html files, prevent this
- if (isMobileSafari(userAgent) && isHtml(file)) {
- res.setHeader('Content-Type', 'text/plain')
- }
- res.setContentDisposition('attachment', { filename: file.name })
- stream.pipe(res)
- })
+ )
}
)
},
diff --git a/services/web/app/src/Features/FileStore/FileStoreHandler.js b/services/web/app/src/Features/FileStore/FileStoreHandler.js
index ad77f56f4d..62f0d4962b 100644
--- a/services/web/app/src/Features/FileStore/FileStoreHandler.js
+++ b/services/web/app/src/Features/FileStore/FileStoreHandler.js
@@ -17,7 +17,7 @@ const FileStoreHandler = {
RETRY_ATTEMPTS: 3,
uploadFileFromDisk(projectId, fileArgs, fsPath, callback) {
- fs.lstat(fsPath, function(err, stat) {
+ fs.lstat(fsPath, function (err, stat) {
if (err) {
logger.warn({ err, projectId, fileArgs, fsPath }, 'error stating file')
callback(err)
@@ -45,7 +45,7 @@ const FileStoreHandler = {
fsPath,
cb
),
- function(err, result) {
+ function (err, result) {
if (err) {
OError.tag(err, 'Error uploading file, retries failed', {
projectId,
@@ -62,21 +62,21 @@ const FileStoreHandler = {
_doUploadFileFromDisk(projectId, fileArgs, fsPath, callback) {
const callbackOnce = _.once(callback)
- FileHashManager.computeHash(fsPath, function(err, hashValue) {
+ FileHashManager.computeHash(fsPath, function (err, hashValue) {
if (err) {
return callbackOnce(err)
}
const fileRef = new File(Object.assign({}, fileArgs, { hash: hashValue }))
const fileId = fileRef._id
const readStream = fs.createReadStream(fsPath)
- readStream.on('error', function(err) {
+ readStream.on('error', function (err) {
logger.warn(
{ err, projectId, fileId, fsPath },
'something went wrong on the read stream of uploadFileFromDisk'
)
callbackOnce(err)
})
- readStream.on('open', function() {
+ readStream.on('open', function () {
const url = FileStoreHandler._buildUrl(projectId, fileId)
const opts = {
method: 'post',
@@ -87,14 +87,14 @@ const FileStoreHandler = {
} // send the hash to the filestore as a custom header so it can be checked
}
const writeStream = request(opts)
- writeStream.on('error', function(err) {
+ writeStream.on('error', function (err) {
logger.warn(
{ err, projectId, fileId, fsPath },
'something went wrong on the write stream of uploadFileFromDisk'
)
callbackOnce(err)
})
- writeStream.on('response', function(response) {
+ writeStream.on('response', function (response) {
if (![200, 201].includes(response.statusCode)) {
err = new OError(
`non-ok response from filestore for upload: ${response.statusCode}`,
@@ -168,7 +168,7 @@ const FileStoreHandler = {
uri: this._buildUrl(projectId, fileId),
timeout: FIVE_MINS_IN_MS
}
- return request(opts, function(err, response) {
+ return request(opts, function (err, response) {
if (err) {
logger.warn(
{ err, projectId, fileId },
@@ -217,7 +217,7 @@ const FileStoreHandler = {
uri: this._buildUrl(newProjectId, newFileId),
timeout: FIVE_MINS_IN_MS
}
- return request(opts, function(err, response) {
+ return request(opts, function (err, response) {
if (err) {
OError.tag(
err,
diff --git a/services/web/app/src/Features/HealthCheck/HealthCheckController.js b/services/web/app/src/Features/HealthCheck/HealthCheckController.js
index 2daa41d0f4..fb2145fc0c 100644
--- a/services/web/app/src/Features/HealthCheck/HealthCheckController.js
+++ b/services/web/app/src/Features/HealthCheck/HealthCheckController.js
@@ -61,7 +61,7 @@ module.exports = {
},
checkRedis(req, res, next) {
- return rclient.healthCheck(function(error) {
+ return rclient.healthCheck(function (error) {
if (error != null) {
logger.err({ err: error }, 'failed redis health check')
return res.sendStatus(500)
@@ -72,23 +72,23 @@ module.exports = {
},
checkMongo(req, res, next) {
- return UserGetter.getUserEmail(settings.smokeTest.userId, function(
- err,
- email
- ) {
- if (err != null) {
- logger.err({ err }, 'mongo health check failed, error present')
- return res.sendStatus(500)
- } else if (email == null) {
- logger.err(
- { err },
- 'mongo health check failed, no emai present in find result'
- )
- return res.sendStatus(500)
- } else {
- return res.sendStatus(200)
+ return UserGetter.getUserEmail(
+ settings.smokeTest.userId,
+ function (err, email) {
+ if (err != null) {
+ logger.err({ err }, 'mongo health check failed, error present')
+ return res.sendStatus(500)
+ } else if (email == null) {
+ logger.err(
+ { err },
+ 'mongo health check failed, no emai present in find result'
+ )
+ return res.sendStatus(500)
+ } else {
+ return res.sendStatus(200)
+ }
}
- })
+ )
}
}
diff --git a/services/web/app/src/Features/History/HistoryController.js b/services/web/app/src/Features/History/HistoryController.js
index 6051434668..c4767088a7 100644
--- a/services/web/app/src/Features/History/HistoryController.js
+++ b/services/web/app/src/Features/History/HistoryController.js
@@ -17,7 +17,7 @@ module.exports = HistoryController = {
selectHistoryApi(req, res, next) {
const { Project_id: projectId } = req.params
// find out which type of history service this project uses
- ProjectDetailsHandler.getDetails(projectId, function(err, project) {
+ ProjectDetailsHandler.getDetails(projectId, function (err, project) {
if (err) {
return next(err)
}
@@ -52,7 +52,7 @@ module.exports = HistoryController = {
}
})
getReq.pipe(res)
- getReq.on('error', function(err) {
+ getReq.on('error', function (err) {
logger.warn({ url, err }, 'history API error')
next(err)
})
@@ -71,11 +71,11 @@ module.exports = HistoryController = {
'X-User-Id': userId
}
},
- function(err, body) {
+ function (err, body) {
if (err) {
return next(err)
}
- HistoryManager.injectUserDetails(body, function(err, data) {
+ HistoryManager.injectUserDetails(body, function (err, data) {
if (err) {
return next(err)
}
@@ -97,7 +97,7 @@ module.exports = HistoryController = {
resyncProjectHistory(req, res, next) {
const projectId = req.params.Project_id
- ProjectEntityUpdateHandler.resyncProjectHistory(projectId, function(err) {
+ ProjectEntityUpdateHandler.resyncProjectHistory(projectId, function (err) {
if (err instanceof Errors.ProjectHistoryDisabledError) {
return res.sendStatus(404)
}
@@ -117,7 +117,7 @@ module.exports = HistoryController = {
projectId,
version,
pathname,
- function(err, entity) {
+ function (err, entity) {
if (err) {
return next(err)
}
@@ -158,7 +158,7 @@ module.exports = HistoryController = {
url: `${settings.apis.project_history.url}/project/${projectId}/labels`,
json: true
},
- function(err, labels) {
+ function (err, labels) {
if (err) {
return next(err)
}
@@ -182,7 +182,7 @@ module.exports = HistoryController = {
url: `${settings.apis.project_history.url}/project/${projectId}/user/${userId}/labels`,
json: { comment, version }
},
- function(err, label) {
+ function (err, label) {
if (err) {
return next(err)
}
@@ -230,7 +230,7 @@ module.exports = HistoryController = {
UserGetter.getUsers(
Array.from(uniqueUsers),
{ first_name: 1, last_name: 1, email: 1 },
- function(err, rawUsers) {
+ function (err, rawUsers) {
if (err) {
return callback(err)
}
@@ -274,7 +274,7 @@ module.exports = HistoryController = {
method: 'DELETE',
url: `${settings.apis.project_history.url}/project/${projectId}/user/${userId}/labels/${labelId}`
},
- function(err) {
+ function (err) {
if (err) {
return next(err)
}
@@ -284,7 +284,7 @@ module.exports = HistoryController = {
},
_makeRequest(options, callback) {
- return request(options, function(err, response, body) {
+ return request(options, function (err, response, body) {
if (err) {
return callback(err)
}
@@ -301,7 +301,7 @@ module.exports = HistoryController = {
downloadZipOfVersion(req, res, next) {
const { project_id: projectId, version } = req.params
- ProjectDetailsHandler.getDetails(projectId, function(err, project) {
+ ProjectDetailsHandler.getDetails(projectId, function (err, project) {
if (err) {
return next(err)
}
@@ -344,7 +344,7 @@ module.exports = HistoryController = {
method: 'post',
url
}
- request(options, function(err, response, body) {
+ request(options, function (err, response, body) {
if (err) {
OError.tag(err, 'history API error', {
v1ProjectId,
@@ -362,7 +362,7 @@ module.exports = HistoryController = {
async.retry(
40,
callback =>
- setTimeout(function() {
+ setTimeout(function () {
if (req.aborted) {
// client has disconnected -- skip s3 download
return callback() // stop async.retry loop
@@ -384,7 +384,7 @@ module.exports = HistoryController = {
req.off('aborted', abortS3Request)
res.off('timeout', abortS3Request)
}
- getReq.on('response', function(response) {
+ getReq.on('response', function (response) {
if (response.statusCode !== 200) {
cleanupAbortTrigger()
return callback(new Error('invalid response'))
@@ -407,7 +407,7 @@ module.exports = HistoryController = {
})
callback()
})
- getReq.on('error', function(err) {
+ getReq.on('error', function (err) {
logger.warn(
{ err, v1ProjectId, version, retryAttempt },
'history s3 download error'
@@ -416,7 +416,7 @@ module.exports = HistoryController = {
callback(err)
})
}, retryDelay),
- function(err) {
+ function (err) {
if (err) {
OError.tag(err, 'history s3 download failed', {
v1ProjectId,
diff --git a/services/web/app/src/Features/History/RestoreManager.js b/services/web/app/src/Features/History/RestoreManager.js
index 9394e95efd..5a7f82c9e4 100644
--- a/services/web/app/src/Features/History/RestoreManager.js
+++ b/services/web/app/src/Features/History/RestoreManager.js
@@ -28,13 +28,13 @@ module.exports = RestoreManager = {
// It looks up the deleted doc's contents, and then creates a new doc with the same content.
// We don't actually remove the deleted doc entry, just create a new one from its lines.
if (callback == null) {
- callback = function(error, doc, folder_id) {}
+ callback = function (error, doc, folder_id) {}
}
return ProjectEntityHandler.getDoc(
project_id,
doc_id,
{ include_deleted: true },
- function(error, lines) {
+ function (error, lines) {
if (error != null) {
return callback(error)
}
@@ -59,13 +59,13 @@ module.exports = RestoreManager = {
restoreFileFromV2(user_id, project_id, version, pathname, callback) {
if (callback == null) {
- callback = function(error, entity) {}
+ callback = function (error, entity) {}
}
return RestoreManager._writeFileVersionToDisk(
project_id,
version,
pathname,
- function(error, fsPath) {
+ function (error, fsPath) {
if (error != null) {
return callback(error)
}
@@ -75,54 +75,55 @@ module.exports = RestoreManager = {
// no directory
dirname = ''
}
- return RestoreManager._findOrCreateFolder(project_id, dirname, function(
- error,
- parent_folder_id
- ) {
- if (error != null) {
- return callback(error)
- }
- const addEntityWithName = (name, callback) =>
- FileSystemImportManager.addEntity(
- user_id,
- project_id,
- parent_folder_id,
- name,
- fsPath,
- false,
+ return RestoreManager._findOrCreateFolder(
+ project_id,
+ dirname,
+ function (error, parent_folder_id) {
+ if (error != null) {
+ return callback(error)
+ }
+ const addEntityWithName = (name, callback) =>
+ FileSystemImportManager.addEntity(
+ user_id,
+ project_id,
+ parent_folder_id,
+ name,
+ fsPath,
+ false,
+ callback
+ )
+ return RestoreManager._addEntityWithUniqueName(
+ addEntityWithName,
+ basename,
callback
)
- return RestoreManager._addEntityWithUniqueName(
- addEntityWithName,
- basename,
- callback
- )
- })
+ }
+ )
}
)
},
_findOrCreateFolder(project_id, dirname, callback) {
if (callback == null) {
- callback = function(error, folder_id) {}
+ callback = function (error, folder_id) {}
}
- return EditorController.mkdirp(project_id, dirname, function(
- error,
- newFolders,
- lastFolder
- ) {
- if (error != null) {
- return callback(error)
+ return EditorController.mkdirp(
+ project_id,
+ dirname,
+ function (error, newFolders, lastFolder) {
+ if (error != null) {
+ return callback(error)
+ }
+ return callback(null, lastFolder != null ? lastFolder._id : undefined)
}
- return callback(null, lastFolder != null ? lastFolder._id : undefined)
- })
+ )
},
_addEntityWithUniqueName(addEntityWithName, basename, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return addEntityWithName(basename, function(error, entity) {
+ return addEntityWithName(basename, function (error, entity) {
if (error != null) {
if (error instanceof Errors.InvalidNameError) {
// likely a duplicate name, so try with a prefix
@@ -146,7 +147,7 @@ module.exports = RestoreManager = {
_writeFileVersionToDisk(project_id, version, pathname, callback) {
if (callback == null) {
- callback = function(error, fsPath) {}
+ callback = function (error, fsPath) {}
}
const url = `${
Settings.apis.project_history.url
diff --git a/services/web/app/src/Features/InactiveData/InactiveProjectController.js b/services/web/app/src/Features/InactiveData/InactiveProjectController.js
index f2b6babc9d..a8aaa9ba41 100644
--- a/services/web/app/src/Features/InactiveData/InactiveProjectController.js
+++ b/services/web/app/src/Features/InactiveData/InactiveProjectController.js
@@ -22,7 +22,7 @@ module.exports = {
return InactiveProjectManager.deactivateOldProjects(
numberOfProjectsToArchive,
ageOfProjects,
- function(err, projectsDeactivated) {
+ function (err, projectsDeactivated) {
if (err != null) {
return res.sendStatus(500)
} else {
@@ -34,7 +34,7 @@ module.exports = {
deactivateProject(req, res) {
const { project_id } = req.params
- return InactiveProjectManager.deactivateProject(project_id, function(err) {
+ return InactiveProjectManager.deactivateProject(project_id, function (err) {
if (err != null) {
return res.sendStatus(500)
} else {
diff --git a/services/web/app/src/Features/InactiveData/InactiveProjectManager.js b/services/web/app/src/Features/InactiveData/InactiveProjectManager.js
index 01fef41aaa..8c24b9274b 100644
--- a/services/web/app/src/Features/InactiveData/InactiveProjectManager.js
+++ b/services/web/app/src/Features/InactiveData/InactiveProjectManager.js
@@ -24,35 +24,36 @@ const { ObjectId } = require('mongodb')
const MILISECONDS_IN_DAY = 86400000
module.exports = InactiveProjectManager = {
reactivateProjectIfRequired(project_id, callback) {
- return ProjectGetter.getProject(project_id, { active: true }, function(
- err,
- project
- ) {
- if (err != null) {
- OError.tag(err, 'error getting project', {
- project_id
- })
- return callback(err)
- }
- logger.log(
- { project_id, active: project.active },
- 'seeing if need to reactivate project'
- )
-
- if (project.active) {
- return callback()
- }
-
- return DocstoreManager.unarchiveProject(project_id, function(err) {
+ return ProjectGetter.getProject(
+ project_id,
+ { active: true },
+ function (err, project) {
if (err != null) {
- OError.tag(err, 'error reactivating project in docstore', {
+ OError.tag(err, 'error getting project', {
project_id
})
return callback(err)
}
- return ProjectUpdateHandler.markAsActive(project_id, callback)
- })
- })
+ logger.log(
+ { project_id, active: project.active },
+ 'seeing if need to reactivate project'
+ )
+
+ if (project.active) {
+ return callback()
+ }
+
+ return DocstoreManager.unarchiveProject(project_id, function (err) {
+ if (err != null) {
+ OError.tag(err, 'error reactivating project in docstore', {
+ project_id
+ })
+ return callback(err)
+ }
+ return ProjectUpdateHandler.markAsActive(project_id, callback)
+ })
+ }
+ )
},
deactivateOldProjects(limit, daysOld, callback) {
@@ -73,12 +74,12 @@ module.exports = InactiveProjectManager = {
.sort({ _id: 1 })
.limit(limit)
.read('secondary')
- .exec(function(err, projects) {
+ .exec(function (err, projects) {
if (err != null) {
logger.err({ err }, 'could not get projects for deactivating')
}
const jobs = _.map(projects, project => cb =>
- InactiveProjectManager.deactivateProject(project._id, function(err) {
+ InactiveProjectManager.deactivateProject(project._id, function (err) {
if (err) {
logger.err(
{ project_id: project._id, err: err },
@@ -92,7 +93,7 @@ module.exports = InactiveProjectManager = {
{ numberOfProjects: projects && projects.length },
'deactivating projects'
)
- async.series(jobs, function(err) {
+ async.series(jobs, function (err) {
if (err != null) {
logger.warn({ err }, 'error deactivating projects')
}
@@ -107,7 +108,7 @@ module.exports = InactiveProjectManager = {
cb => DocstoreManager.archiveProject(project_id, cb),
cb => ProjectUpdateHandler.markAsInactive(project_id, cb)
]
- return async.series(jobs, function(err) {
+ return async.series(jobs, function (err) {
if (err != null) {
logger.warn({ err, project_id }, 'error deactivating project')
}
diff --git a/services/web/app/src/Features/Institutions/InstitutionsAPI.js b/services/web/app/src/Features/Institutions/InstitutionsAPI.js
index 214a87dd0c..24968540eb 100644
--- a/services/web/app/src/Features/Institutions/InstitutionsAPI.js
+++ b/services/web/app/src/Features/Institutions/InstitutionsAPI.js
@@ -99,7 +99,7 @@ const InstitutionsAPI = {
},
defaultErrorMessage: "Couldn't create affiliation"
},
- function(error, body) {
+ function (error, body) {
if (error) {
if (error.info && error.info.statusCode === 422) {
return callback(
@@ -115,7 +115,7 @@ const InstitutionsAPI = {
// have notifications delete any ip matcher notifications for this university
NotificationsBuilder.ipMatcherAffiliation(userId).read(
university.id,
- function(err) {
+ function (err) {
if (err) {
// log and ignore error
logger.err(
@@ -191,7 +191,7 @@ const InstitutionsAPI = {
}
}
-var makeAffiliationRequest = function(requestOptions, callback) {
+var makeAffiliationRequest = function (requestOptions, callback) {
if (!settings.apis.v1.url) {
return callback(null)
} // service is not configured
@@ -207,7 +207,7 @@ var makeAffiliationRequest = function(requestOptions, callback) {
json: true,
timeout: 20 * 1000
},
- function(error, response, body) {
+ function (error, response, body) {
if (error) {
return callback(
new V1ConnectionError('error getting affiliations from v1').withCause(
diff --git a/services/web/app/src/Features/Institutions/InstitutionsController.js b/services/web/app/src/Features/Institutions/InstitutionsController.js
index dfe8e3a4b5..9898a6496c 100644
--- a/services/web/app/src/Features/Institutions/InstitutionsController.js
+++ b/services/web/app/src/Features/Institutions/InstitutionsController.js
@@ -8,7 +8,7 @@ const ASYNC_AFFILIATIONS_LIMIT = 10
module.exports = {
confirmDomain(req, res, next) {
const { hostname } = req.body
- affiliateUsers(hostname, function(error) {
+ affiliateUsers(hostname, function (error) {
if (error) {
return next(error)
}
@@ -17,13 +17,9 @@ module.exports = {
}
}
-var affiliateUsers = function(hostname, callback) {
- const reversedHostname = hostname
- .trim()
- .split('')
- .reverse()
- .join('')
- UserGetter.getUsersByHostname(hostname, { _id: 1 }, function(error, users) {
+var affiliateUsers = function (hostname, callback) {
+ const reversedHostname = hostname.trim().split('').reverse().join('')
+ UserGetter.getUsersByHostname(hostname, { _id: 1 }, function (error, users) {
if (error) {
OError.tag(error, 'problem fetching users by hostname')
return callback(error)
@@ -44,7 +40,7 @@ var affiliateUsers = function(hostname, callback) {
})
}
-var affiliateUserByReversedHostname = function(
+var affiliateUserByReversedHostname = function (
user,
reversedHostname,
callback
diff --git a/services/web/app/src/Features/Institutions/InstitutionsFeatures.js b/services/web/app/src/Features/Institutions/InstitutionsFeatures.js
index ad2b52acab..afb8ea8c31 100644
--- a/services/web/app/src/Features/Institutions/InstitutionsFeatures.js
+++ b/services/web/app/src/Features/Institutions/InstitutionsFeatures.js
@@ -5,18 +5,21 @@ const Settings = require('settings-sharelatex')
module.exports = InstitutionsFeatures = {
getInstitutionsFeatures(userId, callback) {
- InstitutionsFeatures.getInstitutionsPlan(userId, function(error, planCode) {
- if (error) {
- return callback(error)
+ InstitutionsFeatures.getInstitutionsPlan(
+ userId,
+ function (error, planCode) {
+ if (error) {
+ return callback(error)
+ }
+ const plan = planCode && PlansLocator.findLocalPlanInSettings(planCode)
+ const features = plan && plan.features
+ callback(null, features || {})
}
- const plan = planCode && PlansLocator.findLocalPlanInSettings(planCode)
- const features = plan && plan.features
- callback(null, features || {})
- })
+ )
},
getInstitutionsPlan(userId, callback) {
- InstitutionsFeatures.hasLicence(userId, function(error, hasLicence) {
+ InstitutionsFeatures.hasLicence(userId, function (error, hasLicence) {
if (error) {
return callback(error)
}
@@ -28,7 +31,7 @@ module.exports = InstitutionsFeatures = {
},
hasLicence(userId, callback) {
- UserGetter.getUserFullEmails(userId, function(error, emailsData) {
+ UserGetter.getUserFullEmails(userId, function (error, emailsData) {
if (error) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Institutions/InstitutionsGetter.js b/services/web/app/src/Features/Institutions/InstitutionsGetter.js
index 0eff9095ed..a0d8abbadc 100644
--- a/services/web/app/src/Features/Institutions/InstitutionsGetter.js
+++ b/services/web/app/src/Features/Institutions/InstitutionsGetter.js
@@ -5,7 +5,7 @@ const UserMembershipEntityConfigs = require('../UserMembership/UserMembershipEnt
module.exports = InstitutionsGetter = {
getConfirmedAffiliations(userId, callback) {
- UserGetter.getUserFullEmails(userId, function(error, emailsData) {
+ UserGetter.getUserFullEmails(userId, function (error, emailsData) {
if (error) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Institutions/InstitutionsManager.js b/services/web/app/src/Features/Institutions/InstitutionsManager.js
index 66f21bb03b..481eac8631 100644
--- a/services/web/app/src/Features/Institutions/InstitutionsManager.js
+++ b/services/web/app/src/Features/Institutions/InstitutionsManager.js
@@ -18,8 +18,8 @@ module.exports = {
async.waterfall(
[
cb => fetchInstitutionAndAffiliations(institutionId, cb),
- function(institution, affiliations, cb) {
- affiliations = _.map(affiliations, function(affiliation) {
+ function (institution, affiliations, cb) {
+ affiliations = _.map(affiliations, function (affiliation) {
affiliation.institutionName = institution.name
affiliation.institutionId = institutionId
return affiliation
@@ -50,7 +50,7 @@ module.exports = {
},
getInstitutionUsersSubscriptions(institutionId, callback) {
- getInstitutionAffiliations(institutionId, function(error, affiliations) {
+ getInstitutionAffiliations(institutionId, function (error, affiliations) {
if (error) {
return callback(error)
}
@@ -84,12 +84,12 @@ var fetchInstitutionAndAffiliations = (institutionId, callback) =>
callback
)
-var refreshFeatures = function(affiliation, callback) {
+var refreshFeatures = function (affiliation, callback) {
const userId = ObjectId(affiliation.user_id)
FeaturesUpdater.refreshFeatures(userId, callback)
}
-var refreshFeaturesAndNotify = function(affiliation, callback) {
+var refreshFeaturesAndNotify = function (affiliation, callback) {
const userId = ObjectId(affiliation.user_id)
async.waterfall(
[
@@ -124,7 +124,7 @@ var getUserInfo = (userId, callback) =>
var notifyUser = (user, affiliation, subscription, featuresChanged, callback) =>
async.parallel(
[
- function(cb) {
+ function (cb) {
if (featuresChanged) {
NotificationsBuilder.featuresUpgradedByAffiliation(
affiliation,
@@ -134,7 +134,7 @@ var notifyUser = (user, affiliation, subscription, featuresChanged, callback) =>
cb()
}
},
- function(cb) {
+ function (cb) {
if (
subscription &&
!subscription.planCode.match(/(free|trial)/) &&
@@ -152,7 +152,7 @@ var notifyUser = (user, affiliation, subscription, featuresChanged, callback) =>
callback
)
-var checkFeatures = function(institutionId, users) {
+var checkFeatures = function (institutionId, users) {
const usersSummary = {
confirmedEmailUsers: {
total: users.length, // all users are confirmed email users
@@ -167,7 +167,7 @@ var checkFeatures = function(institutionId, users) {
nonProUsers: []
}
}
- users.forEach(function(user) {
+ users.forEach(function (user) {
let isSSOEntitled = SAMLIdentityManager.userHasEntitlement(
user,
institutionId
diff --git a/services/web/app/src/Features/LinkedFiles/LinkedFilesController.js b/services/web/app/src/Features/LinkedFiles/LinkedFilesController.js
index 6bc4dbc180..6a74b1e48b 100644
--- a/services/web/app/src/Features/LinkedFiles/LinkedFilesController.js
+++ b/services/web/app/src/Features/LinkedFiles/LinkedFilesController.js
@@ -75,7 +75,7 @@ module.exports = LinkedFilesController = {
name,
parent_folder_id,
user_id,
- function(err, newFileId) {
+ function (err, newFileId) {
if (err != null) {
return LinkedFilesController.handleError(err, req, res, next)
}
@@ -88,47 +88,46 @@ module.exports = LinkedFilesController = {
const { project_id, file_id } = req.params
const user_id = AuthenticationController.getLoggedInUserId(req)
- return LinkedFilesHandler.getFileById(project_id, file_id, function(
- err,
- file,
- path,
- parentFolder
- ) {
- if (err != null) {
- return next(err)
- }
- if (file == null) {
- return res.sendStatus(404)
- }
- const { name } = file
- const { linkedFileData } = file
- if (
- linkedFileData == null ||
- (linkedFileData != null ? linkedFileData.provider : undefined) == null
- ) {
- return res.sendStatus(409)
- }
- const { provider } = linkedFileData
- const parent_folder_id = parentFolder._id
- const Agent = LinkedFilesController._getAgent(provider)
- if (Agent == null) {
- return res.sendStatus(400)
- }
-
- return Agent.refreshLinkedFile(
- project_id,
- linkedFileData,
- name,
- parent_folder_id,
- user_id,
- function(err, newFileId) {
- if (err != null) {
- return LinkedFilesController.handleError(err, req, res, next)
- }
- return res.json({ new_file_id: newFileId })
+ return LinkedFilesHandler.getFileById(
+ project_id,
+ file_id,
+ function (err, file, path, parentFolder) {
+ if (err != null) {
+ return next(err)
}
- )
- })
+ if (file == null) {
+ return res.sendStatus(404)
+ }
+ const { name } = file
+ const { linkedFileData } = file
+ if (
+ linkedFileData == null ||
+ (linkedFileData != null ? linkedFileData.provider : undefined) == null
+ ) {
+ return res.sendStatus(409)
+ }
+ const { provider } = linkedFileData
+ const parent_folder_id = parentFolder._id
+ const Agent = LinkedFilesController._getAgent(provider)
+ if (Agent == null) {
+ return res.sendStatus(400)
+ }
+
+ return Agent.refreshLinkedFile(
+ project_id,
+ linkedFileData,
+ name,
+ parent_folder_id,
+ user_id,
+ function (err, newFileId) {
+ if (err != null) {
+ return LinkedFilesController.handleError(err, req, res, next)
+ }
+ return res.json({ new_file_id: newFileId })
+ }
+ )
+ }
+ )
},
handleError(error, req, res, next) {
diff --git a/services/web/app/src/Features/LinkedFiles/LinkedFilesHandler.js b/services/web/app/src/Features/LinkedFiles/LinkedFilesHandler.js
index ab8be9c93f..6fcea6fb91 100644
--- a/services/web/app/src/Features/LinkedFiles/LinkedFilesHandler.js
+++ b/services/web/app/src/Features/LinkedFiles/LinkedFilesHandler.js
@@ -28,7 +28,7 @@ const {
module.exports = LinkedFilesHandler = {
getFileById(project_id, file_id, callback) {
if (callback == null) {
- callback = function(err, file) {}
+ callback = function (err, file) {}
}
return ProjectLocator.findElement(
{
@@ -36,7 +36,7 @@ module.exports = LinkedFilesHandler = {
element_id: file_id,
type: 'file'
},
- function(err, file, path, parentFolder) {
+ function (err, file, path, parentFolder) {
if (err != null) {
return callback(err)
}
@@ -47,14 +47,14 @@ module.exports = LinkedFilesHandler = {
getSourceProject(data, callback) {
if (callback == null) {
- callback = function(err, project) {}
+ callback = function (err, project) {}
}
const projection = { _id: 1, name: 1 }
if (data.v1_source_doc_id != null) {
return Project.findOne(
{ 'overleaf.id': data.v1_source_doc_id },
projection,
- function(err, project) {
+ function (err, project) {
if (err != null) {
return callback(err)
}
@@ -68,7 +68,7 @@ module.exports = LinkedFilesHandler = {
return ProjectGetter.getProject(
data.source_project_id,
projection,
- function(err, project) {
+ function (err, project) {
if (err != null) {
return callback(err)
}
@@ -93,32 +93,33 @@ module.exports = LinkedFilesHandler = {
callback
) {
if (callback == null) {
- callback = function(err, file) {}
+ callback = function (err, file) {}
}
callback = _.once(callback)
- return FileWriter.writeStreamToDisk(project_id, readStream, function(
- err,
- fsPath
- ) {
- if (err != null) {
- return callback(err)
- }
- return EditorController.upsertFile(
- project_id,
- parent_folder_id,
- name,
- fsPath,
- linkedFileData,
- 'upload',
- user_id,
- (err, file) => {
- if (err != null) {
- return callback(err)
- }
- return callback(null, file)
+ return FileWriter.writeStreamToDisk(
+ project_id,
+ readStream,
+ function (err, fsPath) {
+ if (err != null) {
+ return callback(err)
}
- )
- })
+ return EditorController.upsertFile(
+ project_id,
+ parent_folder_id,
+ name,
+ fsPath,
+ linkedFileData,
+ 'upload',
+ user_id,
+ (err, file) => {
+ if (err != null) {
+ return callback(err)
+ }
+ return callback(null, file)
+ }
+ )
+ }
+ )
},
importContent(
@@ -131,31 +132,32 @@ module.exports = LinkedFilesHandler = {
callback
) {
if (callback == null) {
- callback = function(err, file) {}
+ callback = function (err, file) {}
}
callback = _.once(callback)
- return FileWriter.writeContentToDisk(project_id, content, function(
- err,
- fsPath
- ) {
- if (err != null) {
- return callback(err)
- }
- return EditorController.upsertFile(
- project_id,
- parent_folder_id,
- name,
- fsPath,
- linkedFileData,
- 'upload',
- user_id,
- (err, file) => {
- if (err != null) {
- return callback(err)
- }
- return callback(null, file)
+ return FileWriter.writeContentToDisk(
+ project_id,
+ content,
+ function (err, fsPath) {
+ if (err != null) {
+ return callback(err)
}
- )
- })
+ return EditorController.upsertFile(
+ project_id,
+ parent_folder_id,
+ name,
+ fsPath,
+ linkedFileData,
+ 'upload',
+ user_id,
+ (err, file) => {
+ if (err != null) {
+ return callback(err)
+ }
+ return callback(null, file)
+ }
+ )
+ }
+ )
}
}
diff --git a/services/web/app/src/Features/LinkedFiles/ProjectFileAgent.js b/services/web/app/src/Features/LinkedFiles/ProjectFileAgent.js
index f913334b4f..7ef4aa8ac1 100644
--- a/services/web/app/src/Features/LinkedFiles/ProjectFileAgent.js
+++ b/services/web/app/src/Features/LinkedFiles/ProjectFileAgent.js
@@ -73,7 +73,7 @@ module.exports = ProjectFileAgent = {
_prepare(project_id, linkedFileData, user_id, callback) {
if (callback == null) {
- callback = function(err, linkedFileData) {}
+ callback = function (err, linkedFileData) {}
}
return this._checkAuth(
project_id,
@@ -118,7 +118,7 @@ module.exports = ProjectFileAgent = {
return DocstoreManager.getDoc(
source_project._id,
entity._id,
- function(err, lines) {
+ function (err, lines) {
if (err != null) {
return callback(err)
}
@@ -129,7 +129,7 @@ module.exports = ProjectFileAgent = {
name,
parent_folder_id,
user_id,
- function(err, file) {
+ function (err, file) {
if (err != null) {
return callback(err)
}
@@ -143,7 +143,7 @@ module.exports = ProjectFileAgent = {
source_project._id,
entity._id,
null,
- function(err, fileStream) {
+ function (err, fileStream) {
if (err != null) {
return callback(err)
}
@@ -154,7 +154,7 @@ module.exports = ProjectFileAgent = {
name,
parent_folder_id,
user_id,
- function(err, file) {
+ function (err, file) {
if (err != null) {
return callback(err)
}
@@ -174,18 +174,18 @@ module.exports = ProjectFileAgent = {
_getEntity(linkedFileData, current_user_id, callback) {
if (callback == null) {
- callback = function(err, entity, type) {}
+ callback = function (err, entity, type) {}
}
callback = _.once(callback)
const { source_entity_path } = linkedFileData
- return this._getSourceProject(linkedFileData, function(err, project) {
+ return this._getSourceProject(linkedFileData, function (err, project) {
if (err != null) {
return callback(err)
}
const source_project_id = project._id
return DocumentUpdaterHandler.flushProjectToMongo(
source_project_id,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -195,7 +195,7 @@ module.exports = ProjectFileAgent = {
path: source_entity_path,
exactCaseMatch: true
},
- function(err, entity, type) {
+ function (err, entity, type) {
if (err != null) {
if (/^not found.*/.test(err.toString())) {
err = new SourceFileNotFoundError()
@@ -236,13 +236,13 @@ module.exports = ProjectFileAgent = {
_checkAuth(project_id, data, current_user_id, callback) {
if (callback == null) {
- callback = function(error, allowed) {}
+ callback = function (error, allowed) {}
}
callback = _.once(callback)
if (!ProjectFileAgent._validate(data)) {
return callback(new BadDataError())
}
- return this._getSourceProject(data, function(err, project) {
+ return this._getSourceProject(data, function (err, project) {
if (err != null) {
return callback(err)
}
@@ -250,7 +250,7 @@ module.exports = ProjectFileAgent = {
current_user_id,
project._id,
null,
- function(err, canRead) {
+ function (err, canRead) {
if (err != null) {
return callback(err)
}
diff --git a/services/web/app/src/Features/LinkedFiles/ProjectOutputFileAgent.js b/services/web/app/src/Features/LinkedFiles/ProjectOutputFileAgent.js
index 6ae8fecb10..6fffb28f3c 100644
--- a/services/web/app/src/Features/LinkedFiles/ProjectOutputFileAgent.js
+++ b/services/web/app/src/Features/LinkedFiles/ProjectOutputFileAgent.js
@@ -32,7 +32,7 @@ const logger = require('logger-sharelatex')
module.exports = ProjectOutputFileAgent = {
_prepare(project_id, linkedFileData, user_id, callback) {
if (callback == null) {
- callback = function(err, linkedFileData) {}
+ callback = function (err, linkedFileData) {}
}
return this._checkAuth(
project_id,
@@ -91,7 +91,7 @@ module.exports = ProjectOutputFileAgent = {
name,
parent_folder_id,
user_id,
- function(err, file) {
+ function (err, file) {
if (err != null) {
return callback(err)
}
@@ -147,7 +147,7 @@ module.exports = ProjectOutputFileAgent = {
name,
parent_folder_id,
user_id,
- function(err, file) {
+ function (err, file) {
if (err != null) {
return callback(err)
}
@@ -197,13 +197,13 @@ module.exports = ProjectOutputFileAgent = {
_checkAuth(project_id, data, current_user_id, callback) {
if (callback == null) {
- callback = function(err, allowed) {}
+ callback = function (err, allowed) {}
}
callback = _.once(callback)
if (!this._validate(data)) {
return callback(new BadDataError())
}
- return this._getSourceProject(data, function(err, project) {
+ return this._getSourceProject(data, function (err, project) {
if (err != null) {
return callback(err)
}
@@ -211,7 +211,7 @@ module.exports = ProjectOutputFileAgent = {
current_user_id,
project._id,
null,
- function(err, canRead) {
+ function (err, canRead) {
if (err != null) {
return callback(err)
}
@@ -223,11 +223,11 @@ module.exports = ProjectOutputFileAgent = {
_getFileStream(linkedFileData, user_id, callback) {
if (callback == null) {
- callback = function(err, fileStream) {}
+ callback = function (err, fileStream) {}
}
callback = _.once(callback)
const { source_output_file_path, build_id } = linkedFileData
- return this._getSourceProject(linkedFileData, function(err, project) {
+ return this._getSourceProject(linkedFileData, function (err, project) {
if (err != null) {
return callback(err)
}
@@ -237,7 +237,7 @@ module.exports = ProjectOutputFileAgent = {
user_id,
build_id,
source_output_file_path,
- function(err, readStream) {
+ function (err, readStream) {
if (err != null) {
return callback(err)
}
@@ -250,48 +250,49 @@ module.exports = ProjectOutputFileAgent = {
_compileAndGetFileStream(linkedFileData, user_id, callback) {
if (callback == null) {
- callback = function(err, stream, build_id) {}
+ callback = function (err, stream, build_id) {}
}
callback = _.once(callback)
const { source_output_file_path } = linkedFileData
- return this._getSourceProject(linkedFileData, function(err, project) {
+ return this._getSourceProject(linkedFileData, function (err, project) {
if (err != null) {
return callback(err)
}
const source_project_id = project._id
- return CompileManager.compile(source_project_id, user_id, {}, function(
- err,
- status,
- outputFiles
- ) {
- if (err != null) {
- return callback(err)
- }
- if (status !== 'success') {
- return callback(new OutputFileFetchFailedError())
- }
- const outputFile = _.find(
- outputFiles,
- o => o.path === source_output_file_path
- )
- if (outputFile == null) {
- return callback(new OutputFileFetchFailedError())
- }
- const build_id = outputFile.build
- return ClsiManager.getOutputFileStream(
- source_project_id,
- user_id,
- build_id,
- source_output_file_path,
- function(err, readStream) {
- if (err != null) {
- return callback(err)
- }
- readStream.pause()
- return callback(null, readStream, build_id)
+ return CompileManager.compile(
+ source_project_id,
+ user_id,
+ {},
+ function (err, status, outputFiles) {
+ if (err != null) {
+ return callback(err)
}
- )
- })
+ if (status !== 'success') {
+ return callback(new OutputFileFetchFailedError())
+ }
+ const outputFile = _.find(
+ outputFiles,
+ o => o.path === source_output_file_path
+ )
+ if (outputFile == null) {
+ return callback(new OutputFileFetchFailedError())
+ }
+ const build_id = outputFile.build
+ return ClsiManager.getOutputFileStream(
+ source_project_id,
+ user_id,
+ build_id,
+ source_output_file_path,
+ function (err, readStream) {
+ if (err != null) {
+ return callback(err)
+ }
+ readStream.pause()
+ return callback(null, readStream, build_id)
+ }
+ )
+ }
+ )
})
}
}
diff --git a/services/web/app/src/Features/LinkedFiles/UrlAgent.js b/services/web/app/src/Features/LinkedFiles/UrlAgent.js
index 04353cc0b6..561f6ded72 100644
--- a/services/web/app/src/Features/LinkedFiles/UrlAgent.js
+++ b/services/web/app/src/Features/LinkedFiles/UrlAgent.js
@@ -30,40 +30,42 @@ module.exports = UrlAgent = {
callback
) {
linkedFileData = this._sanitizeData(linkedFileData)
- return this._getUrlStream(project_id, linkedFileData, user_id, function(
- err,
- readStream
- ) {
- if (err != null) {
- return callback(err)
- }
- readStream.on('error', callback)
- return readStream.on('response', function(response) {
- if (response.statusCode >= 200 && response.statusCode < 300) {
- readStream.resume()
- return LinkedFilesHandler.importFromStream(
- project_id,
- readStream,
- linkedFileData,
- name,
- parent_folder_id,
- user_id,
- function(err, file) {
- if (err != null) {
- return callback(err)
- }
- return callback(null, file._id)
- }
- ) // Created
- } else {
- const error = new UrlFetchFailedError(
- `url fetch failed: ${linkedFileData.url}`
- )
- error.statusCode = response.statusCode
- return callback(error)
+ return this._getUrlStream(
+ project_id,
+ linkedFileData,
+ user_id,
+ function (err, readStream) {
+ if (err != null) {
+ return callback(err)
}
- })
- })
+ readStream.on('error', callback)
+ return readStream.on('response', function (response) {
+ if (response.statusCode >= 200 && response.statusCode < 300) {
+ readStream.resume()
+ return LinkedFilesHandler.importFromStream(
+ project_id,
+ readStream,
+ linkedFileData,
+ name,
+ parent_folder_id,
+ user_id,
+ function (err, file) {
+ if (err != null) {
+ return callback(err)
+ }
+ return callback(null, file._id)
+ }
+ ) // Created
+ } else {
+ const error = new UrlFetchFailedError(
+ `url fetch failed: ${linkedFileData.url}`
+ )
+ error.statusCode = response.statusCode
+ return callback(error)
+ }
+ })
+ }
+ )
},
refreshLinkedFile(
@@ -93,7 +95,7 @@ module.exports = UrlAgent = {
_getUrlStream(project_id, data, current_user_id, callback) {
if (callback == null) {
- callback = function(error, fsPath) {}
+ callback = function (error, fsPath) {}
}
callback = _.once(callback)
let { url } = data
diff --git a/services/web/app/src/Features/Metadata/MetaController.js b/services/web/app/src/Features/Metadata/MetaController.js
index 0a1d1b99dc..7f033d4a91 100644
--- a/services/web/app/src/Features/Metadata/MetaController.js
+++ b/services/web/app/src/Features/Metadata/MetaController.js
@@ -21,22 +21,22 @@ module.exports = MetaController = {
getMetadata(req, res, next) {
const { project_id } = req.params
logger.log({ project_id }, 'getting all labels for project')
- return MetaHandler.getAllMetaForProject(project_id, function(
- err,
- projectMeta
- ) {
- if (err != null) {
- OError.tag(
- err,
- '[MetaController] error getting all labels from project',
- {
- project_id
- }
- )
- return next(err)
+ return MetaHandler.getAllMetaForProject(
+ project_id,
+ function (err, projectMeta) {
+ if (err != null) {
+ OError.tag(
+ err,
+ '[MetaController] error getting all labels from project',
+ {
+ project_id
+ }
+ )
+ return next(err)
+ }
+ return res.json({ projectId: project_id, projectMeta })
}
- return res.json({ projectId: project_id, projectMeta })
- })
+ )
},
broadcastMetadataForDoc(req, res, next) {
@@ -44,27 +44,28 @@ module.exports = MetaController = {
const { doc_id } = req.params
const { broadcast } = req.body
logger.log({ project_id, doc_id, broadcast }, 'getting labels for doc')
- return MetaHandler.getMetaForDoc(project_id, doc_id, function(
- err,
- docMeta
- ) {
- if (err != null) {
- OError.tag(err, '[MetaController] error getting labels from doc', {
- project_id,
- doc_id
- })
- return next(err)
+ return MetaHandler.getMetaForDoc(
+ project_id,
+ doc_id,
+ function (err, docMeta) {
+ if (err != null) {
+ OError.tag(err, '[MetaController] error getting labels from doc', {
+ project_id,
+ doc_id
+ })
+ return next(err)
+ }
+ // default to broadcasting, unless explicitly disabled (for backwards compatibility)
+ if (broadcast !== false) {
+ EditorRealTimeController.emitToRoom(project_id, 'broadcastDocMeta', {
+ docId: doc_id,
+ meta: docMeta
+ })
+ return res.sendStatus(200)
+ } else {
+ return res.json({ docId: doc_id, meta: docMeta })
+ }
}
- // default to broadcasting, unless explicitly disabled (for backwards compatibility)
- if (broadcast !== false) {
- EditorRealTimeController.emitToRoom(project_id, 'broadcastDocMeta', {
- docId: doc_id,
- meta: docMeta
- })
- return res.sendStatus(200)
- } else {
- return res.json({ docId: doc_id, meta: docMeta })
- }
- })
+ )
}
}
diff --git a/services/web/app/src/Features/Metadata/MetaHandler.js b/services/web/app/src/Features/Metadata/MetaHandler.js
index 23bc08f4c2..b036d1748e 100644
--- a/services/web/app/src/Features/Metadata/MetaHandler.js
+++ b/services/web/app/src/Features/Metadata/MetaHandler.js
@@ -33,43 +33,49 @@ module.exports = MetaHandler = {
getAllMetaForProject(projectId, callback) {
if (callback == null) {
- callback = function(err, projectMeta) {}
+ callback = function (err, projectMeta) {}
}
- return DocumentUpdaterHandler.flushProjectToMongo(projectId, function(err) {
- if (err != null) {
- return callback(err)
- }
- return ProjectEntityHandler.getAllDocs(projectId, function(err, docs) {
+ return DocumentUpdaterHandler.flushProjectToMongo(
+ projectId,
+ function (err) {
if (err != null) {
return callback(err)
}
- const projectMeta = MetaHandler.extractMetaFromProjectDocs(docs)
- return callback(null, projectMeta)
- })
- })
+ return ProjectEntityHandler.getAllDocs(projectId, function (err, docs) {
+ if (err != null) {
+ return callback(err)
+ }
+ const projectMeta = MetaHandler.extractMetaFromProjectDocs(docs)
+ return callback(null, projectMeta)
+ })
+ }
+ )
},
getMetaForDoc(projectId, docId, callback) {
if (callback == null) {
- callback = function(err, docMeta) {}
+ callback = function (err, docMeta) {}
}
- return DocumentUpdaterHandler.flushDocToMongo(projectId, docId, function(
- err
- ) {
- if (err != null) {
- return callback(err)
- }
- return ProjectEntityHandler.getDoc(projectId, docId, function(
- err,
- lines
- ) {
+ return DocumentUpdaterHandler.flushDocToMongo(
+ projectId,
+ docId,
+ function (err) {
if (err != null) {
return callback(err)
}
- const docMeta = MetaHandler.extractMetaFromDoc(lines)
- return callback(null, docMeta)
- })
- })
+ return ProjectEntityHandler.getDoc(
+ projectId,
+ docId,
+ function (err, lines) {
+ if (err != null) {
+ return callback(err)
+ }
+ const docMeta = MetaHandler.extractMetaFromDoc(lines)
+ return callback(null, docMeta)
+ }
+ )
+ }
+ )
},
extractMetaFromDoc(lines) {
diff --git a/services/web/app/src/Features/Newsletter/NewsletterManager.js b/services/web/app/src/Features/Newsletter/NewsletterManager.js
index cf5a1fbceb..1bc4d4cd94 100644
--- a/services/web/app/src/Features/Newsletter/NewsletterManager.js
+++ b/services/web/app/src/Features/Newsletter/NewsletterManager.js
@@ -180,10 +180,7 @@ function makeMailchimpProvider() {
}
function hashEmail(email) {
- return crypto
- .createHash('md5')
- .update(email.toLowerCase())
- .digest('hex')
+ return crypto.createHash('md5').update(email.toLowerCase()).digest('hex')
}
function getMergeFields(user) {
diff --git a/services/web/app/src/Features/Notifications/NotificationsBuilder.js b/services/web/app/src/Features/Notifications/NotificationsBuilder.js
index 72602d70c5..b00c3e8bbc 100644
--- a/services/web/app/src/Features/Notifications/NotificationsBuilder.js
+++ b/services/web/app/src/Features/Notifications/NotificationsBuilder.js
@@ -8,7 +8,7 @@ function dropboxDuplicateProjectNames(userId) {
key: `dropboxDuplicateProjectNames-${userId}`,
create(projectName, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
NotificationsHandler.createNotification(
userId,
@@ -22,7 +22,7 @@ function dropboxDuplicateProjectNames(userId) {
},
read(callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
NotificationsHandler.markAsReadWithKey(userId, this.key, callback)
}
@@ -34,7 +34,7 @@ function featuresUpgradedByAffiliation(affiliation, user) {
key: `features-updated-by=${affiliation.institutionId}`,
create(callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
const messageOpts = { institutionName: affiliation.institutionName }
NotificationsHandler.createNotification(
@@ -49,7 +49,7 @@ function featuresUpgradedByAffiliation(affiliation, user) {
},
read(callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
NotificationsHandler.markAsReadByKeyOnly(this.key, callback)
}
@@ -61,7 +61,7 @@ function redundantPersonalSubscription(affiliation, user) {
key: `redundant-personal-subscription-${affiliation.institutionId}`,
create(callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
const messageOpts = { institutionName: affiliation.institutionName }
NotificationsHandler.createNotification(
@@ -76,7 +76,7 @@ function redundantPersonalSubscription(affiliation, user) {
},
read(callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
NotificationsHandler.markAsReadByKeyOnly(this.key, callback)
}
@@ -88,7 +88,7 @@ function projectInvite(invite, project, sendingUser, user) {
key: `project-invite-${invite._id}`,
create(callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
const messageOpts = {
userName: sendingUser.first_name,
@@ -107,7 +107,7 @@ function projectInvite(invite, project, sendingUser, user) {
},
read(callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
NotificationsHandler.markAsReadByKeyOnly(this.key, callback)
}
@@ -118,7 +118,7 @@ function ipMatcherAffiliation(userId) {
return {
create(ip, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
if (!settings.apis.v1.url) {
// service is not configured
@@ -133,7 +133,7 @@ function ipMatcherAffiliation(userId) {
json: true,
timeout: 20 * 1000
},
- function(error, response, body) {
+ function (error, response, body) {
if (error != null) {
return callback(error)
}
@@ -167,7 +167,7 @@ function ipMatcherAffiliation(userId) {
read(universityId, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
const key = `ip-matched-affiliation-${universityId}`
NotificationsHandler.markAsReadWithKey(userId, key, callback)
@@ -180,7 +180,7 @@ function tpdsFileLimit(userId) {
key: `tpdsFileLimit-${userId}`,
create(projectName, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
const messageOpts = {
projectName: projectName
@@ -197,7 +197,7 @@ function tpdsFileLimit(userId) {
},
read(callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
NotificationsHandler.markAsReadByKeyOnly(this.key, callback)
}
@@ -215,7 +215,7 @@ const NotificationsBuilder = {
}
NotificationsBuilder.promises = {
- redundantPersonalSubscription: function(affiliation, user) {
+ redundantPersonalSubscription: function (affiliation, user) {
return promisifyAll(redundantPersonalSubscription(affiliation, user))
}
}
diff --git a/services/web/app/src/Features/Notifications/NotificationsController.js b/services/web/app/src/Features/Notifications/NotificationsController.js
index fa26a57bac..bfaaeaf6c3 100644
--- a/services/web/app/src/Features/Notifications/NotificationsController.js
+++ b/services/web/app/src/Features/Notifications/NotificationsController.js
@@ -17,19 +17,22 @@ const _ = require('underscore')
module.exports = {
getAllUnreadNotifications(req, res) {
const user_id = AuthenticationController.getLoggedInUserId(req)
- return NotificationsHandler.getUserNotifications(user_id, function(
- err,
- unreadNotifications
- ) {
- unreadNotifications = _.map(unreadNotifications, function(notification) {
- notification.html = req.i18n.translate(
- notification.templateKey,
- notification.messageOpts
+ return NotificationsHandler.getUserNotifications(
+ user_id,
+ function (err, unreadNotifications) {
+ unreadNotifications = _.map(
+ unreadNotifications,
+ function (notification) {
+ notification.html = req.i18n.translate(
+ notification.templateKey,
+ notification.messageOpts
+ )
+ return notification
+ }
)
- return notification
- })
- return res.send(unreadNotifications)
- })
+ return res.send(unreadNotifications)
+ }
+ )
},
markNotificationAsRead(req, res) {
diff --git a/services/web/app/src/Features/Notifications/NotificationsHandler.js b/services/web/app/src/Features/Notifications/NotificationsHandler.js
index 9a09539ee5..dc9a2f01c8 100644
--- a/services/web/app/src/Features/Notifications/NotificationsHandler.js
+++ b/services/web/app/src/Features/Notifications/NotificationsHandler.js
@@ -17,7 +17,7 @@ const logger = require('logger-sharelatex')
const oneSecond = 1000
-const makeRequest = function(opts, callback) {
+const makeRequest = function (opts, callback) {
if (
(settings.apis.notifications != null
? settings.apis.notifications.url
@@ -41,7 +41,7 @@ module.exports = {
timeout: oneSecond,
method: 'GET'
}
- return makeRequest(opts, function(err, res, unreadNotifications) {
+ return makeRequest(opts, function (err, res, unreadNotifications) {
const statusCode = res != null ? res.statusCode : 500
if (err != null || statusCode !== 200) {
const e = new Error(
diff --git a/services/web/app/src/Features/Project/ProjectApiController.js b/services/web/app/src/Features/Project/ProjectApiController.js
index 4985f074b2..5cf7f980e4 100644
--- a/services/web/app/src/Features/Project/ProjectApiController.js
+++ b/services/web/app/src/Features/Project/ProjectApiController.js
@@ -17,14 +17,14 @@ const logger = require('logger-sharelatex')
module.exports = {
getProjectDetails(req, res, next) {
const { project_id } = req.params
- return ProjectDetailsHandler.getDetails(project_id, function(
- err,
- projDetails
- ) {
- if (err != null) {
- return next(err)
+ return ProjectDetailsHandler.getDetails(
+ project_id,
+ function (err, projDetails) {
+ if (err != null) {
+ return next(err)
+ }
+ return res.json(projDetails)
}
- return res.json(projDetails)
- })
+ )
}
}
diff --git a/services/web/app/src/Features/Project/ProjectCollabratecDetailsHandler.js b/services/web/app/src/Features/Project/ProjectCollabratecDetailsHandler.js
index bf959580e2..342adb1678 100644
--- a/services/web/app/src/Features/Project/ProjectCollabratecDetailsHandler.js
+++ b/services/web/app/src/Features/Project/ProjectCollabratecDetailsHandler.js
@@ -25,7 +25,7 @@ module.exports = ProjectCollabratecDetailsHandler = {
callback
) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
return ProjectCollabratecDetailsHandler.setCollabratecUsers(
project_id,
@@ -36,7 +36,7 @@ module.exports = ProjectCollabratecDetailsHandler = {
isLinkedCollabratecUserProject(project_id, user_id, callback) {
if (callback == null) {
- callback = function(err, isLinked) {}
+ callback = function (err, isLinked) {}
}
try {
project_id = ObjectId(project_id)
@@ -53,7 +53,7 @@ module.exports = ProjectCollabratecDetailsHandler = {
}
}
}
- return Project.findOne(query, { _id: 1 }, function(err, project) {
+ return Project.findOne(query, { _id: 1 }, function (err, project) {
if (err != null) {
callback(err)
}
@@ -68,7 +68,7 @@ module.exports = ProjectCollabratecDetailsHandler = {
callback
) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
try {
project_id = ObjectId(project_id)
@@ -102,7 +102,7 @@ module.exports = ProjectCollabratecDetailsHandler = {
setCollabratecUsers(project_id, collabratec_users, callback) {
let err
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
try {
project_id = ObjectId(project_id)
@@ -127,7 +127,7 @@ module.exports = ProjectCollabratecDetailsHandler = {
unlinkCollabratecUserProject(project_id, user_id, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
try {
project_id = ObjectId(project_id)
@@ -149,7 +149,7 @@ module.exports = ProjectCollabratecDetailsHandler = {
updateCollabratecUserIds(old_user_id, new_user_id, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
try {
old_user_id = ObjectId(old_user_id)
diff --git a/services/web/app/src/Features/Project/ProjectController.js b/services/web/app/src/Features/Project/ProjectController.js
index 8d1a8c02d3..5e6b3afd29 100644
--- a/services/web/app/src/Features/Project/ProjectController.js
+++ b/services/web/app/src/Features/Project/ProjectController.js
@@ -64,10 +64,7 @@ const ProjectController = {
return true
}
const data = `${rolloutName}:${objectId.toString()}`
- const md5hash = crypto
- .createHash('md5')
- .update(data)
- .digest('hex')
+ const md5hash = crypto.createHash('md5').update(data).digest('hex')
const counter = parseInt(md5hash.slice(26, 32), 16)
return counter % 100 < percentage
},
@@ -162,7 +159,7 @@ const ProjectController = {
const projectId = req.params.Project_id
const userId = AuthenticationController.getLoggedInUserId(req)
- ProjectDeleter.archiveProject(projectId, userId, function(err) {
+ ProjectDeleter.archiveProject(projectId, userId, function (err) {
if (err != null) {
return next(err)
} else {
@@ -175,7 +172,7 @@ const ProjectController = {
const projectId = req.params.Project_id
const userId = AuthenticationController.getLoggedInUserId(req)
- ProjectDeleter.unarchiveProject(projectId, userId, function(err) {
+ ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
if (err != null) {
return next(err)
} else {
@@ -188,7 +185,7 @@ const ProjectController = {
const projectId = req.params.project_id
const userId = AuthenticationController.getLoggedInUserId(req)
- ProjectDeleter.trashProject(projectId, userId, function(err) {
+ ProjectDeleter.trashProject(projectId, userId, function (err) {
if (err != null) {
return next(err)
} else {
@@ -201,7 +198,7 @@ const ProjectController = {
const projectId = req.params.project_id
const userId = AuthenticationController.getLoggedInUserId(req)
- ProjectDeleter.untrashProject(projectId, userId, function(err) {
+ ProjectDeleter.untrashProject(projectId, userId, function (err) {
if (err != null) {
return next(err)
} else {
diff --git a/services/web/app/src/Features/Project/ProjectCreationHandler.js b/services/web/app/src/Features/Project/ProjectCreationHandler.js
index 18a15e0fd0..c12bcbeb36 100644
--- a/services/web/app/src/Features/Project/ProjectCreationHandler.js
+++ b/services/web/app/src/Features/Project/ProjectCreationHandler.js
@@ -33,7 +33,7 @@ const AnalyticsManager = require('../Analytics/AnalyticsManager')
const ProjectCreationHandler = {
createBlankProject(owner_id, projectName, attributes, callback) {
if (callback == null) {
- callback = function(error, project) {}
+ callback = function (error, project) {}
}
metrics.inc('project-creation')
if (arguments.length === 3) {
@@ -41,59 +41,60 @@ const ProjectCreationHandler = {
attributes = {}
}
- return ProjectDetailsHandler.validateProjectName(projectName, function(
- error
- ) {
- if (error != null) {
- return callback(error)
- }
- if (attributes.overleaf !== undefined && attributes.overleaf != null) {
- return ProjectCreationHandler._createBlankProject(
- owner_id,
- projectName,
- attributes,
- function(error, project) {
- if (error != null) {
- return callback(error)
- }
- AnalyticsManager.recordEvent(owner_id, 'project-imported', {
- projectId: project._id,
- attributes
- })
- return callback(error, project)
- }
- )
- } else {
- return HistoryManager.initializeProject(function(error, history) {
- if (error != null) {
- return callback(error)
- }
- attributes.overleaf = {
- history: { id: history != null ? history.overleaf_id : undefined }
- }
+ return ProjectDetailsHandler.validateProjectName(
+ projectName,
+ function (error) {
+ if (error != null) {
+ return callback(error)
+ }
+ if (attributes.overleaf !== undefined && attributes.overleaf != null) {
return ProjectCreationHandler._createBlankProject(
owner_id,
projectName,
attributes,
- function(error, project) {
+ function (error, project) {
if (error != null) {
return callback(error)
}
- AnalyticsManager.recordEvent(owner_id, 'project-created', {
+ AnalyticsManager.recordEvent(owner_id, 'project-imported', {
projectId: project._id,
attributes
})
return callback(error, project)
}
)
- })
+ } else {
+ return HistoryManager.initializeProject(function (error, history) {
+ if (error != null) {
+ return callback(error)
+ }
+ attributes.overleaf = {
+ history: { id: history != null ? history.overleaf_id : undefined }
+ }
+ return ProjectCreationHandler._createBlankProject(
+ owner_id,
+ projectName,
+ attributes,
+ function (error, project) {
+ if (error != null) {
+ return callback(error)
+ }
+ AnalyticsManager.recordEvent(owner_id, 'project-created', {
+ projectId: project._id,
+ attributes
+ })
+ return callback(error, project)
+ }
+ )
+ })
+ }
}
- })
+ )
},
_createBlankProject(owner_id, projectName, attributes, callback) {
if (callback == null) {
- callback = function(error, project) {}
+ callback = function (error, project) {}
}
const rootFolder = new Folder({ name: 'rootFolder' })
@@ -113,28 +114,29 @@ const ProjectCreationHandler = {
}
}
project.rootFolder[0] = rootFolder
- return User.findById(owner_id, 'ace.spellCheckLanguage', function(
- err,
- user
- ) {
- project.spellCheckLanguage = user.ace.spellCheckLanguage
- return project.save(function(err) {
- if (err != null) {
- return callback(err)
- }
- return callback(err, project)
- })
- })
+ return User.findById(
+ owner_id,
+ 'ace.spellCheckLanguage',
+ function (err, user) {
+ project.spellCheckLanguage = user.ace.spellCheckLanguage
+ return project.save(function (err) {
+ if (err != null) {
+ return callback(err)
+ }
+ return callback(err, project)
+ })
+ }
+ )
},
createProjectFromSnippet(owner_id, projectName, docLines, callback) {
if (callback == null) {
- callback = function(error, project) {}
+ callback = function (error, project) {}
}
return ProjectCreationHandler.createBlankProject(
owner_id,
projectName,
- function(error, project) {
+ function (error, project) {
if (error != null) {
return callback(error)
}
@@ -150,12 +152,12 @@ const ProjectCreationHandler = {
createBasicProject(owner_id, projectName, callback) {
if (callback == null) {
- callback = function(error, project) {}
+ callback = function (error, project) {}
}
return ProjectCreationHandler.createBlankProject(
owner_id,
projectName,
- function(error, project) {
+ function (error, project) {
if (error != null) {
return callback(error)
}
@@ -163,7 +165,7 @@ const ProjectCreationHandler = {
'mainbasic.tex',
owner_id,
projectName,
- function(error, docLines) {
+ function (error, docLines) {
if (error != null) {
return callback(error)
}
@@ -181,12 +183,12 @@ const ProjectCreationHandler = {
createExampleProject(owner_id, projectName, callback) {
if (callback == null) {
- callback = function(error, project) {}
+ callback = function (error, project) {}
}
return ProjectCreationHandler.createBlankProject(
owner_id,
projectName,
- function(error, project) {
+ function (error, project) {
if (error != null) {
return callback(error)
}
@@ -197,7 +199,7 @@ const ProjectCreationHandler = {
'main.tex',
owner_id,
projectName,
- function(error, docLines) {
+ function (error, docLines) {
if (error != null) {
return callback(error)
}
@@ -214,7 +216,7 @@ const ProjectCreationHandler = {
'references.bib',
owner_id,
projectName,
- function(error, docLines) {
+ function (error, docLines) {
if (error != null) {
return callback(error)
}
@@ -228,7 +230,7 @@ const ProjectCreationHandler = {
)
}
),
- function(callback) {
+ function (callback) {
const universePath = Path.resolve(
__dirname + '/../../../templates/project_files/universe.jpg'
)
@@ -251,7 +253,7 @@ const ProjectCreationHandler = {
_createRootDoc(project, owner_id, docLines, callback) {
if (callback == null) {
- callback = function(error, project) {}
+ callback = function (error, project) {}
}
return ProjectEntityUpdateHandler.addDoc(
project._id,
@@ -259,7 +261,7 @@ const ProjectCreationHandler = {
'main.tex',
docLines,
owner_id,
- function(error, doc) {
+ function (error, doc) {
if (error != null) {
OError.tag(error, 'error adding root doc when creating project')
return callback(error)
@@ -275,47 +277,48 @@ const ProjectCreationHandler = {
_buildTemplate(template_name, user_id, project_name, callback) {
if (callback == null) {
- callback = function(error, output) {}
+ callback = function (error, output) {}
}
- return User.findById(user_id, 'first_name last_name', function(
- error,
- user
- ) {
- if (error != null) {
- return callback(error)
- }
- const monthNames = [
- 'January',
- 'February',
- 'March',
- 'April',
- 'May',
- 'June',
- 'July',
- 'August',
- 'September',
- 'October',
- 'November',
- 'December'
- ]
-
- const templatePath = Path.resolve(
- __dirname + `/../../../templates/project_files/${template_name}`
- )
- return fs.readFile(templatePath, function(error, template) {
+ return User.findById(
+ user_id,
+ 'first_name last_name',
+ function (error, user) {
if (error != null) {
return callback(error)
}
- const data = {
- project_name,
- user,
- year: new Date().getUTCFullYear(),
- month: monthNames[new Date().getUTCMonth()]
- }
- const output = _.template(template.toString(), data)
- return callback(null, output.split('\n'))
- })
- })
+ const monthNames = [
+ 'January',
+ 'February',
+ 'March',
+ 'April',
+ 'May',
+ 'June',
+ 'July',
+ 'August',
+ 'September',
+ 'October',
+ 'November',
+ 'December'
+ ]
+
+ const templatePath = Path.resolve(
+ __dirname + `/../../../templates/project_files/${template_name}`
+ )
+ return fs.readFile(templatePath, function (error, template) {
+ if (error != null) {
+ return callback(error)
+ }
+ const data = {
+ project_name,
+ user,
+ year: new Date().getUTCFullYear(),
+ month: monthNames[new Date().getUTCMonth()]
+ }
+ const output = _.template(template.toString(), data)
+ return callback(null, output.split('\n'))
+ })
+ }
+ )
}
}
diff --git a/services/web/app/src/Features/Project/ProjectEntityUpdateHandler.js b/services/web/app/src/Features/Project/ProjectEntityUpdateHandler.js
index a67052fabd..77eab54662 100644
--- a/services/web/app/src/Features/Project/ProjectEntityUpdateHandler.js
+++ b/services/web/app/src/Features/Project/ProjectEntityUpdateHandler.js
@@ -308,7 +308,7 @@ const ProjectEntityUpdateHandler = {
addDocWithRanges: wrapWithLock({
beforeLock(next) {
- return function(
+ return function (
projectId,
folderId,
docName,
@@ -457,7 +457,7 @@ const ProjectEntityUpdateHandler = {
addFile: wrapWithLock({
beforeLock(next) {
- return function(
+ return function (
projectId,
folderId,
fileName,
@@ -544,7 +544,7 @@ const ProjectEntityUpdateHandler = {
replaceFile: wrapWithLock({
beforeLock(next) {
- return function(
+ return function (
projectId,
fileId,
fsPath,
@@ -648,7 +648,7 @@ const ProjectEntityUpdateHandler = {
}
}),
- upsertDoc: wrapWithLock(function(
+ upsertDoc: wrapWithLock(function (
projectId,
folderId,
docName,
@@ -796,7 +796,7 @@ const ProjectEntityUpdateHandler = {
upsertFile: wrapWithLock({
beforeLock(next) {
- return function(
+ return function (
projectId,
folderId,
fileName,
@@ -974,7 +974,7 @@ const ProjectEntityUpdateHandler = {
}
}),
- upsertDocWithPath: wrapWithLock(function(
+ upsertDocWithPath: wrapWithLock(function (
projectId,
elementPath,
docLines,
@@ -1014,7 +1014,7 @@ const ProjectEntityUpdateHandler = {
upsertFileWithPath: wrapWithLock({
beforeLock(next) {
- return function(
+ return function (
projectId,
elementPath,
fsPath,
@@ -1102,7 +1102,7 @@ const ProjectEntityUpdateHandler = {
}
}),
- deleteEntity: wrapWithLock(function(
+ deleteEntity: wrapWithLock(function (
projectId,
entityId,
entityType,
@@ -1174,7 +1174,7 @@ const ProjectEntityUpdateHandler = {
)
),
- mkdirp: wrapWithLock(function(projectId, path, callback) {
+ mkdirp: wrapWithLock(function (projectId, path, callback) {
for (let folder of path.split('/')) {
if (folder.length > 0 && !SafePath.isCleanFilename(folder)) {
return callback(new Errors.InvalidNameError('invalid element name'))
@@ -1188,7 +1188,7 @@ const ProjectEntityUpdateHandler = {
)
}),
- mkdirpWithExactCase: wrapWithLock(function(projectId, path, callback) {
+ mkdirpWithExactCase: wrapWithLock(function (projectId, path, callback) {
for (let folder of path.split('/')) {
if (folder.length > 0 && !SafePath.isCleanFilename(folder)) {
return callback(new Errors.InvalidNameError('invalid element name'))
@@ -1202,7 +1202,7 @@ const ProjectEntityUpdateHandler = {
)
}),
- addFolder: wrapWithLock(function(
+ addFolder: wrapWithLock(function (
projectId,
parentFolderId,
folderName,
@@ -1219,7 +1219,7 @@ const ProjectEntityUpdateHandler = {
)
}),
- moveEntity: wrapWithLock(function(
+ moveEntity: wrapWithLock(function (
projectId,
entityId,
destFolderId,
@@ -1272,7 +1272,7 @@ const ProjectEntityUpdateHandler = {
)
}),
- renameEntity: wrapWithLock(function(
+ renameEntity: wrapWithLock(function (
projectId,
entityId,
entityType,
@@ -1572,7 +1572,7 @@ const ProjectEntityUpdateHandler = {
convertDocToFile: wrapWithLock({
beforeLock(next) {
- return function(projectId, docId, userId, callback) {
+ return function (projectId, docId, userId, callback) {
DocumentUpdaterHandler.flushDocToMongo(projectId, docId, err => {
if (err) {
return callback(err)
diff --git a/services/web/app/src/Features/Project/ProjectGetter.js b/services/web/app/src/Features/Project/ProjectGetter.js
index 23e262355b..d4f75b3939 100644
--- a/services/web/app/src/Features/Project/ProjectGetter.js
+++ b/services/web/app/src/Features/Project/ProjectGetter.js
@@ -72,7 +72,7 @@ const ProjectGetter = {
return callback(err)
}
- db.projects.findOne(query, { projection }, function(err, project) {
+ db.projects.findOne(query, { projection }, function (err, project) {
if (err) {
OError.tag(err, 'error getting project', {
query,
@@ -85,43 +85,49 @@ const ProjectGetter = {
},
getProjectIdByReadAndWriteToken(token, callback) {
- Project.findOne({ 'tokens.readAndWrite': token }, { _id: 1 }, function(
- err,
- project
- ) {
- if (err) {
- return callback(err)
+ Project.findOne(
+ { 'tokens.readAndWrite': token },
+ { _id: 1 },
+ function (err, project) {
+ if (err) {
+ return callback(err)
+ }
+ if (project == null) {
+ return callback()
+ }
+ callback(null, project._id)
}
- if (project == null) {
- return callback()
- }
- callback(null, project._id)
- })
+ )
},
findAllUsersProjects(userId, fields, callback) {
const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
- Project.find({ owner_ref: userId }, fields, function(error, ownedProjects) {
- if (error) {
- return callback(error)
- }
- CollaboratorsGetter.getProjectsUserIsMemberOf(userId, fields, function(
- error,
- projects
- ) {
+ Project.find(
+ { owner_ref: userId },
+ fields,
+ function (error, ownedProjects) {
if (error) {
return callback(error)
}
- const result = {
- owned: ownedProjects || [],
- readAndWrite: projects.readAndWrite || [],
- readOnly: projects.readOnly || [],
- tokenReadAndWrite: projects.tokenReadAndWrite || [],
- tokenReadOnly: projects.tokenReadOnly || []
- }
- callback(null, result)
- })
- })
+ CollaboratorsGetter.getProjectsUserIsMemberOf(
+ userId,
+ fields,
+ function (error, projects) {
+ if (error) {
+ return callback(error)
+ }
+ const result = {
+ owned: ownedProjects || [],
+ readAndWrite: projects.readAndWrite || [],
+ readOnly: projects.readOnly || [],
+ tokenReadAndWrite: projects.tokenReadAndWrite || [],
+ tokenReadOnly: projects.tokenReadOnly || []
+ }
+ callback(null, result)
+ }
+ )
+ }
+ )
},
/**
diff --git a/services/web/app/src/Features/Project/ProjectHelper.js b/services/web/app/src/Features/Project/ProjectHelper.js
index 8cf343c5df..46b9737b8b 100644
--- a/services/web/app/src/Features/Project/ProjectHelper.js
+++ b/services/web/app/src/Features/Project/ProjectHelper.js
@@ -126,7 +126,7 @@ function _addSuffixToProjectName(name, suffix, maxLength) {
function _addNumericSuffixToProjectName(name, allProjectNames, maxLength) {
const NUMERIC_SUFFIX_MATCH = / \((\d+)\)$/
- const suffixedName = function(basename, number) {
+ const suffixedName = function (basename, number) {
const suffix = ` (${number})`
return basename.substr(0, maxLength - suffix.length) + suffix
}
diff --git a/services/web/app/src/Features/Project/ProjectHistoryHandler.js b/services/web/app/src/Features/Project/ProjectHistoryHandler.js
index 7e94c4b465..6ae9139630 100644
--- a/services/web/app/src/Features/Project/ProjectHistoryHandler.js
+++ b/services/web/app/src/Features/Project/ProjectHistoryHandler.js
@@ -25,7 +25,7 @@ const ProjectHistoryHandler = {
setHistoryId(project_id, history_id, callback) {
// reject invalid history ids
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
if (!history_id || typeof history_id !== 'number') {
return callback(new Error('invalid history id'))
@@ -34,7 +34,7 @@ const ProjectHistoryHandler = {
return Project.updateOne(
{ _id: project_id, 'overleaf.history.id': { $exists: false } },
{ 'overleaf.history.id': history_id },
- function(err, result) {
+ function (err, result) {
if (err != null) {
return callback(err)
}
@@ -48,29 +48,32 @@ const ProjectHistoryHandler = {
getHistoryId(project_id, callback) {
if (callback == null) {
- callback = function(err, result) {}
+ callback = function (err, result) {}
}
- return ProjectDetailsHandler.getDetails(project_id, function(err, project) {
- if (err != null) {
- return callback(err)
- } // n.b. getDetails returns an error if the project doesn't exist
- return callback(
- null,
- __guard__(
+ return ProjectDetailsHandler.getDetails(
+ project_id,
+ function (err, project) {
+ if (err != null) {
+ return callback(err)
+ } // n.b. getDetails returns an error if the project doesn't exist
+ return callback(
+ null,
__guard__(
- project != null ? project.overleaf : undefined,
- x1 => x1.history
- ),
- x => x.id
+ __guard__(
+ project != null ? project.overleaf : undefined,
+ x1 => x1.history
+ ),
+ x => x.id
+ )
)
- )
- })
+ }
+ )
},
upgradeHistory(project_id, callback) {
// project must have an overleaf.history.id before allowing display of new history
if (callback == null) {
- callback = function(err, result) {}
+ callback = function (err, result) {}
}
return Project.updateOne(
{ _id: project_id, 'overleaf.history.id': { $exists: true } },
@@ -78,7 +81,7 @@ const ProjectHistoryHandler = {
'overleaf.history.display': true,
'overleaf.history.upgradedAt': new Date()
},
- function(err, result) {
+ function (err, result) {
if (err != null) {
return callback(err)
}
@@ -93,7 +96,7 @@ const ProjectHistoryHandler = {
downgradeHistory(project_id, callback) {
if (callback == null) {
- callback = function(err, result) {}
+ callback = function (err, result) {}
}
return Project.updateOne(
{ _id: project_id, 'overleaf.history.upgradedAt': { $exists: true } },
@@ -101,7 +104,7 @@ const ProjectHistoryHandler = {
'overleaf.history.display': false,
$unset: { 'overleaf.history.upgradedAt': 1 }
},
- function(err, result) {
+ function (err, result) {
if (err != null) {
return callback(err)
}
@@ -120,45 +123,45 @@ const ProjectHistoryHandler = {
// state. Setting a history id when one wasn't present before is ok,
// because undefined history ids aren't cached.
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
- return ProjectHistoryHandler.getHistoryId(project_id, function(
- err,
- history_id
- ) {
- if (err != null) {
- return callback(err)
- }
- if (history_id != null) {
- return callback()
- } // history already exists, success
- return HistoryManager.initializeProject(function(err, history) {
+ return ProjectHistoryHandler.getHistoryId(
+ project_id,
+ function (err, history_id) {
if (err != null) {
return callback(err)
}
- if (!(history != null ? history.overleaf_id : undefined)) {
- return callback(new Error('failed to initialize history id'))
- }
- return ProjectHistoryHandler.setHistoryId(
- project_id,
- history.overleaf_id,
- function(err) {
- if (err != null) {
- return callback(err)
- }
- return ProjectEntityUpdateHandler.resyncProjectHistory(
- project_id,
- function(err) {
- if (err != null) {
- return callback(err)
- }
- return HistoryManager.flushProject(project_id, callback)
- }
- )
+ if (history_id != null) {
+ return callback()
+ } // history already exists, success
+ return HistoryManager.initializeProject(function (err, history) {
+ if (err != null) {
+ return callback(err)
}
- )
- })
- })
+ if (!(history != null ? history.overleaf_id : undefined)) {
+ return callback(new Error('failed to initialize history id'))
+ }
+ return ProjectHistoryHandler.setHistoryId(
+ project_id,
+ history.overleaf_id,
+ function (err) {
+ if (err != null) {
+ return callback(err)
+ }
+ return ProjectEntityUpdateHandler.resyncProjectHistory(
+ project_id,
+ function (err) {
+ if (err != null) {
+ return callback(err)
+ }
+ return HistoryManager.flushProject(project_id, callback)
+ }
+ )
+ }
+ )
+ })
+ }
+ )
}
}
diff --git a/services/web/app/src/Features/Project/ProjectLocator.js b/services/web/app/src/Features/Project/ProjectLocator.js
index cbcc27a013..8a823bcf45 100644
--- a/services/web/app/src/Features/Project/ProjectLocator.js
+++ b/services/web/app/src/Features/Project/ProjectLocator.js
@@ -19,11 +19,12 @@ function findElement(options, _callback) {
const elementType = sanitizeTypeOfElement(type)
let count = 0
- const endOfBranch = function() {
+ const endOfBranch = function () {
if (--count === 0) {
logger.warn(
- `element ${elementId} could not be found for project ${projectId ||
- project._id}`
+ `element ${elementId} could not be found for project ${
+ projectId || project._id
+ }`
)
callback(new Errors.NotFoundError('entity not found'))
}
diff --git a/services/web/app/src/Features/Project/ProjectRootDocManager.js b/services/web/app/src/Features/Project/ProjectRootDocManager.js
index 8f6dae91f7..6223e352c1 100644
--- a/services/web/app/src/Features/Project/ProjectRootDocManager.js
+++ b/services/web/app/src/Features/Project/ProjectRootDocManager.js
@@ -28,9 +28,9 @@ const _ = require('underscore')
module.exports = ProjectRootDocManager = {
setRootDocAutomatically(project_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return ProjectEntityHandler.getAllDocs(project_id, function(error, docs) {
+ return ProjectEntityHandler.getAllDocs(project_id, function (error, docs) {
if (error != null) {
return callback(error)
}
@@ -38,23 +38,23 @@ module.exports = ProjectRootDocManager = {
const jobs = _.map(
docs,
(doc, path) =>
- function(cb) {
+ function (cb) {
if (
ProjectEntityUpdateHandler.isPathValidForRootDoc(path) &&
DocumentHelper.contentHasDocumentclass(doc.lines)
) {
- async.setImmediate(function() {
+ async.setImmediate(function () {
cb(doc._id)
})
} else {
- async.setImmediate(function() {
+ async.setImmediate(function () {
cb(null)
})
}
}
)
- return async.series(jobs, function(root_doc_id) {
+ return async.series(jobs, function (root_doc_id) {
if (root_doc_id != null) {
return ProjectEntityUpdateHandler.setRootDoc(
project_id,
@@ -70,7 +70,7 @@ module.exports = ProjectRootDocManager = {
findRootDocFileFromDirectory(directoryPath, callback) {
if (callback == null) {
- callback = function(error, path, content) {}
+ callback = function (error, path, content) {}
}
const filePathsPromise = globby(['**/*.{tex,Rtex}'], {
cwd: directoryPath,
@@ -88,7 +88,7 @@ module.exports = ProjectRootDocManager = {
ProjectRootDocManager._sortFileList(
unsortedFiles,
directoryPath,
- function(err, files) {
+ function (err, files) {
if (err != null) {
return callback(err)
}
@@ -96,12 +96,12 @@ module.exports = ProjectRootDocManager = {
return async.until(
() => doc != null || files.length === 0,
- function(cb) {
+ function (cb) {
const file = files.shift()
return fs.readFile(
Path.join(directoryPath, file),
'utf8',
- function(error, content) {
+ function (error, content) {
if (error != null) {
return cb(error)
}
@@ -131,11 +131,11 @@ module.exports = ProjectRootDocManager = {
setRootDocFromName(project_id, rootDocName, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return ProjectEntityHandler.getAllDocPathsFromProjectById(
project_id,
- function(error, docPaths) {
+ function (error, docPaths) {
let doc_id, path
if (error != null) {
return callback(error)
@@ -180,89 +180,91 @@ module.exports = ProjectRootDocManager = {
ensureRootDocumentIsSet(project_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return ProjectGetter.getProject(project_id, { rootDoc_id: 1 }, function(
- error,
- project
- ) {
- if (error != null) {
- return callback(error)
- }
- if (project == null) {
- return callback(new Error('project not found'))
- }
+ return ProjectGetter.getProject(
+ project_id,
+ { rootDoc_id: 1 },
+ function (error, project) {
+ if (error != null) {
+ return callback(error)
+ }
+ if (project == null) {
+ return callback(new Error('project not found'))
+ }
- if (project.rootDoc_id != null) {
- return callback()
- } else {
- return ProjectRootDocManager.setRootDocAutomatically(
- project_id,
- callback
- )
+ if (project.rootDoc_id != null) {
+ return callback()
+ } else {
+ return ProjectRootDocManager.setRootDocAutomatically(
+ project_id,
+ callback
+ )
+ }
}
- })
+ )
},
ensureRootDocumentIsValid(project_id, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return ProjectGetter.getProject(project_id, { rootDoc_id: 1 }, function(
- error,
- project
- ) {
- if (error != null) {
- return callback(error)
- }
- if (project == null) {
- return callback(new Error('project not found'))
- }
+ return ProjectGetter.getProject(
+ project_id,
+ { rootDoc_id: 1 },
+ function (error, project) {
+ if (error != null) {
+ return callback(error)
+ }
+ if (project == null) {
+ return callback(new Error('project not found'))
+ }
- if (project.rootDoc_id != null) {
- return ProjectEntityHandler.getAllDocPathsFromProjectById(
- project_id,
- function(error, docPaths) {
- if (error != null) {
- return callback(error)
- }
- let rootDocValid = false
- for (let doc_id in docPaths) {
- const _path = docPaths[doc_id]
- if (doc_id === project.rootDoc_id) {
- rootDocValid = true
+ if (project.rootDoc_id != null) {
+ return ProjectEntityHandler.getAllDocPathsFromProjectById(
+ project_id,
+ function (error, docPaths) {
+ if (error != null) {
+ return callback(error)
+ }
+ let rootDocValid = false
+ for (let doc_id in docPaths) {
+ const _path = docPaths[doc_id]
+ if (doc_id === project.rootDoc_id) {
+ rootDocValid = true
+ }
+ }
+ if (rootDocValid) {
+ return callback()
+ } else {
+ return ProjectEntityUpdateHandler.unsetRootDoc(project_id, () =>
+ ProjectRootDocManager.setRootDocAutomatically(
+ project_id,
+ callback
+ )
+ )
}
}
- if (rootDocValid) {
- return callback()
- } else {
- return ProjectEntityUpdateHandler.unsetRootDoc(project_id, () =>
- ProjectRootDocManager.setRootDocAutomatically(
- project_id,
- callback
- )
- )
- }
- }
- )
- } else {
- return ProjectRootDocManager.setRootDocAutomatically(
- project_id,
- callback
- )
+ )
+ } else {
+ return ProjectRootDocManager.setRootDocAutomatically(
+ project_id,
+ callback
+ )
+ }
}
- })
+ )
},
_sortFileList(listToSort, rootDirectory, callback) {
if (callback == null) {
- callback = function(error, result) {}
+ callback = function (error, result) {}
}
return async.mapLimit(
listToSort,
5,
(filePath, cb) =>
- fs.stat(Path.join(rootDirectory, filePath), function(err, stat) {
+ fs.stat(Path.join(rootDirectory, filePath), function (err, stat) {
if (err != null) {
return cb(err)
}
@@ -273,7 +275,7 @@ module.exports = ProjectRootDocManager = {
name: Path.basename(filePath)
})
}),
- function(err, files) {
+ function (err, files) {
if (err != null) {
return callback(err)
}
diff --git a/services/web/app/src/Features/Project/ProjectUpdateHandler.js b/services/web/app/src/Features/Project/ProjectUpdateHandler.js
index 46606502ab..455454b0a0 100644
--- a/services/web/app/src/Features/Project/ProjectUpdateHandler.js
+++ b/services/web/app/src/Features/Project/ProjectUpdateHandler.js
@@ -17,7 +17,7 @@ const logger = require('logger-sharelatex')
module.exports = {
markAsUpdated(projectId, lastUpdatedAt, lastUpdatedBy, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
if (lastUpdatedAt == null) {
lastUpdatedAt = new Date()
@@ -38,7 +38,7 @@ module.exports = {
markAsOpened(project_id, callback) {
const conditions = { _id: project_id }
const update = { lastOpened: Date.now() }
- return Project.updateOne(conditions, update, {}, function(err) {
+ return Project.updateOne(conditions, update, {}, function (err) {
if (callback != null) {
return callback()
}
@@ -48,7 +48,7 @@ module.exports = {
markAsInactive(project_id, callback) {
const conditions = { _id: project_id }
const update = { active: false }
- return Project.updateOne(conditions, update, {}, function(err) {
+ return Project.updateOne(conditions, update, {}, function (err) {
if (callback != null) {
return callback()
}
@@ -58,7 +58,7 @@ module.exports = {
markAsActive(project_id, callback) {
const conditions = { _id: project_id }
const update = { active: true }
- return Project.updateOne(conditions, update, {}, function(err) {
+ return Project.updateOne(conditions, update, {}, function (err) {
if (callback != null) {
return callback()
}
diff --git a/services/web/app/src/Features/Project/SafePath.js b/services/web/app/src/Features/Project/SafePath.js
index d3cc05ff4a..b33ed68af0 100644
--- a/services/web/app/src/Features/Project/SafePath.js
+++ b/services/web/app/src/Features/Project/SafePath.js
@@ -18,7 +18,7 @@
// frontend/js/ide/directives/SafePath.js
// frontend/js/features/file-tree/util/safe-path.js
-const load = function() {
+const load = function () {
let SafePath
const BADCHAR_RX = new RegExp(
`\
diff --git a/services/web/app/src/Features/Publishers/PublishersGetter.js b/services/web/app/src/Features/Publishers/PublishersGetter.js
index 5c4ae5f134..85e5d8de9c 100644
--- a/services/web/app/src/Features/Publishers/PublishersGetter.js
+++ b/services/web/app/src/Features/Publishers/PublishersGetter.js
@@ -21,7 +21,7 @@ const _ = require('underscore')
module.exports = PublishersGetter = {
getManagedPublishers(user_id, callback) {
if (callback == null) {
- callback = function(error, managedPublishers) {}
+ callback = function (error, managedPublishers) {}
}
return UserMembershipsHandler.getEntitiesByUser(
UserMembershipEntityConfigs.publisher,
diff --git a/services/web/app/src/Features/Referal/ReferalAllocator.js b/services/web/app/src/Features/Referal/ReferalAllocator.js
index a6707a29d7..8bebf2558d 100644
--- a/services/web/app/src/Features/Referal/ReferalAllocator.js
+++ b/services/web/app/src/Features/Referal/ReferalAllocator.js
@@ -5,14 +5,14 @@ const FeaturesUpdater = require('../Subscription/FeaturesUpdater')
module.exports = {
allocate(referalId, newUserId, referalSource, referalMedium, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
if (referalId == null) {
return callback(null)
}
const query = { referal_id: referalId }
- return User.findOne(query, { _id: 1 }, function(error, user) {
+ return User.findOne(query, { _id: 1 }, function (error, user) {
if (error != null) {
return callback(error)
}
@@ -32,7 +32,7 @@ module.exports = {
}
},
{},
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'something went wrong allocating referal', {
referalId,
diff --git a/services/web/app/src/Features/Referal/ReferalFeatures.js b/services/web/app/src/Features/Referal/ReferalFeatures.js
index e51cbb4334..6ce0924d8b 100644
--- a/services/web/app/src/Features/Referal/ReferalFeatures.js
+++ b/services/web/app/src/Features/Referal/ReferalFeatures.js
@@ -7,10 +7,10 @@ let ReferalFeatures
module.exports = ReferalFeatures = {
getBonusFeatures(userId, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
const query = { _id: userId }
- User.findOne(query, { refered_user_count: 1 }, function(error, user) {
+ User.findOne(query, { refered_user_count: 1 }, function (error, user) {
if (error) {
return callback(error)
}
@@ -37,7 +37,7 @@ module.exports = ReferalFeatures = {
_getBonusLevel(user) {
let highestBonusLevel = 0
- _.each(_.keys(Settings.bonus_features), function(level) {
+ _.each(_.keys(Settings.bonus_features), function (level) {
const levelIsLessThanUser = level <= user.refered_user_count
const levelIsMoreThanCurrentHighest = level >= highestBonusLevel
if (levelIsLessThanUser && levelIsMoreThanCurrentHighest) {
diff --git a/services/web/app/src/Features/Referal/ReferalHandler.js b/services/web/app/src/Features/Referal/ReferalHandler.js
index 2a8c54852f..7af328e6e2 100644
--- a/services/web/app/src/Features/Referal/ReferalHandler.js
+++ b/services/web/app/src/Features/Referal/ReferalHandler.js
@@ -3,7 +3,7 @@ const { User } = require('../../models/User')
module.exports = {
getReferedUsers(userId, callback) {
const projection = { refered_users: 1, refered_user_count: 1 }
- User.findById(userId, projection, function(err, user) {
+ User.findById(userId, projection, function (err, user) {
if (err) {
return callback(err)
}
diff --git a/services/web/app/src/Features/References/ReferencesController.js b/services/web/app/src/Features/References/ReferencesController.js
index 34303fe8dc..c7a638f5fc 100644
--- a/services/web/app/src/Features/References/ReferencesController.js
+++ b/services/web/app/src/Features/References/ReferencesController.js
@@ -28,7 +28,7 @@ module.exports = ReferencesController = {
)
return res.sendStatus(400)
}
- return ReferencesHandler.index(projectId, docIds, function(err, data) {
+ return ReferencesHandler.index(projectId, docIds, function (err, data) {
if (err != null) {
logger.err({ err, projectId }, 'error indexing all references')
return res.sendStatus(500)
@@ -46,7 +46,7 @@ module.exports = ReferencesController = {
indexAll(req, res) {
const projectId = req.params.Project_id
const { shouldBroadcast } = req.body
- return ReferencesHandler.indexAll(projectId, function(err, data) {
+ return ReferencesHandler.indexAll(projectId, function (err, data) {
if (err != null) {
logger.err({ err, projectId }, 'error indexing all references')
return res.sendStatus(500)
diff --git a/services/web/app/src/Features/References/ReferencesHandler.js b/services/web/app/src/Features/References/ReferencesHandler.js
index c162d043c2..91091d0847 100644
--- a/services/web/app/src/Features/References/ReferencesHandler.js
+++ b/services/web/app/src/Features/References/ReferencesHandler.js
@@ -42,8 +42,8 @@ module.exports = ReferencesHandler = {
_findBibFileIds(project) {
const ids = []
- var _process = function(folder) {
- _.each(folder.fileRefs || [], function(file) {
+ var _process = function (folder) {
+ _.each(folder.fileRefs || [], function (file) {
if (
__guard__(file != null ? file.name : undefined, x1 =>
x1.match(/^.*\.bib$/)
@@ -60,8 +60,8 @@ module.exports = ReferencesHandler = {
_findBibDocIds(project) {
const ids = []
- var _process = function(folder) {
- _.each(folder.docs || [], function(doc) {
+ var _process = function (folder) {
+ _.each(folder.docs || [], function (doc) {
if (
__guard__(doc != null ? doc.name : undefined, x1 =>
x1.match(/^.*\.bib$/)
@@ -78,32 +78,33 @@ module.exports = ReferencesHandler = {
_isFullIndex(project, callback) {
if (callback == null) {
- callback = function(err, result) {}
+ callback = function (err, result) {}
}
- return UserGetter.getUser(project.owner_ref, { features: true }, function(
- err,
- owner
- ) {
- if (err != null) {
- return callback(err)
+ return UserGetter.getUser(
+ project.owner_ref,
+ { features: true },
+ function (err, owner) {
+ if (err != null) {
+ return callback(err)
+ }
+ const features = owner != null ? owner.features : undefined
+ return callback(
+ null,
+ (features != null ? features.references : undefined) === true ||
+ (features != null ? features.referencesSearch : undefined) === true
+ )
}
- const features = owner != null ? owner.features : undefined
- return callback(
- null,
- (features != null ? features.references : undefined) === true ||
- (features != null ? features.referencesSearch : undefined) === true
- )
- })
+ )
},
indexAll(projectId, callback) {
if (callback == null) {
- callback = function(err, data) {}
+ callback = function (err, data) {}
}
return ProjectGetter.getProject(
projectId,
{ rootFolder: true, owner_ref: 1 },
- function(err, project) {
+ function (err, project) {
if (err) {
OError.tag(err, 'error finding project', {
projectId
@@ -126,12 +127,12 @@ module.exports = ReferencesHandler = {
index(projectId, docIds, callback) {
if (callback == null) {
- callback = function(err, data) {}
+ callback = function (err, data) {}
}
return ProjectGetter.getProject(
projectId,
{ rootFolder: true, owner_ref: 1 },
- function(err, project) {
+ function (err, project) {
if (err) {
OError.tag(err, 'error finding project', {
projectId
@@ -153,7 +154,7 @@ module.exports = ReferencesHandler = {
if (!Features.hasFeature('references')) {
return callback()
}
- return ReferencesHandler._isFullIndex(project, function(err, isFullIndex) {
+ return ReferencesHandler._isFullIndex(project, function (err, isFullIndex) {
if (err) {
OError.tag(err, 'error checking whether to do full index', {
projectId
@@ -168,7 +169,7 @@ module.exports = ReferencesHandler = {
docIds.map(docId => cb =>
DocumentUpdaterHandler.flushDocToMongo(projectId, docId, cb)
),
- function(err) {
+ function (err) {
// continue
if (err) {
OError.tag(err, 'error flushing docs to mongo', {
@@ -192,7 +193,7 @@ module.exports = ReferencesHandler = {
fullIndex: isFullIndex
}
},
- function(err, res, data) {
+ function (err, res, data) {
if (err) {
OError.tag(err, 'error communicating with references api', {
projectId
diff --git a/services/web/app/src/Features/Security/LoginRateLimiter.js b/services/web/app/src/Features/Security/LoginRateLimiter.js
index e4db5809fb..2373f45939 100644
--- a/services/web/app/src/Features/Security/LoginRateLimiter.js
+++ b/services/web/app/src/Features/Security/LoginRateLimiter.js
@@ -16,7 +16,7 @@ function processLoginRequest(email, callback) {
function recordSuccessfulLogin(email, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
RateLimiter.clearRateLimit('login', email, callback)
}
diff --git a/services/web/app/src/Features/Security/OneTimeTokenHandler.js b/services/web/app/src/Features/Security/OneTimeTokenHandler.js
index 0fac2c72b0..70957e1922 100644
--- a/services/web/app/src/Features/Security/OneTimeTokenHandler.js
+++ b/services/web/app/src/Features/Security/OneTimeTokenHandler.js
@@ -26,7 +26,7 @@ module.exports = {
options = {}
}
if (callback == null) {
- callback = function(error, data) {}
+ callback = function (error, data) {}
}
if (typeof options === 'function') {
callback = options
@@ -44,7 +44,7 @@ module.exports = {
createdAt,
expiresAt
},
- function(error) {
+ function (error) {
if (error != null) {
return callback(error)
}
@@ -55,7 +55,7 @@ module.exports = {
getValueFromTokenAndExpire(use, token, callback) {
if (callback == null) {
- callback = function(error, data) {}
+ callback = function (error, data) {}
}
const now = new Date()
return db.tokens.findOneAndUpdate(
@@ -70,7 +70,7 @@ module.exports = {
usedAt: now
}
},
- function(error, result) {
+ function (error, result) {
if (error != null) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Security/RateLimiterMiddleware.js b/services/web/app/src/Features/Security/RateLimiterMiddleware.js
index 5fb9a1040e..b4f874f959 100644
--- a/services/web/app/src/Features/Security/RateLimiterMiddleware.js
+++ b/services/web/app/src/Features/Security/RateLimiterMiddleware.js
@@ -16,7 +16,7 @@ const settings = require('settings-sharelatex')
Unique clients are identified by user_id if logged in, and IP address if not.
*/
function rateLimit(opts) {
- return function(req, res, next) {
+ return function (req, res, next) {
const userId = AuthenticationController.getLoggedInUserId(req) || req.ip
if (
settings.smokeTest &&
@@ -41,7 +41,7 @@ function rateLimit(opts) {
subjectName,
throttle: opts.maxRequests || 6
}
- return RateLimiter.addCount(options, function(error, canContinue) {
+ return RateLimiter.addCount(options, function (error, canContinue) {
if (error != null) {
return next(error)
}
@@ -62,7 +62,7 @@ function loginRateLimit(req, res, next) {
if (!email) {
return next()
}
- LoginRateLimiter.processLoginRequest(email, function(err, isAllowed) {
+ LoginRateLimiter.processLoginRequest(email, function (err, isAllowed) {
if (err) {
return next(err)
}
diff --git a/services/web/app/src/Features/ServerAdmin/AdminController.js b/services/web/app/src/Features/ServerAdmin/AdminController.js
index 8404a8628d..e3164024b1 100644
--- a/services/web/app/src/Features/ServerAdmin/AdminController.js
+++ b/services/web/app/src/Features/ServerAdmin/AdminController.js
@@ -27,7 +27,7 @@ const SystemMessageManager = require('../SystemMessages/SystemMessageManager')
const oneMinInMs = 60 * 1000
-var updateOpenConnetionsMetrics = function() {
+var updateOpenConnetionsMetrics = function () {
metrics.gauge(
'open_connections.socketio',
__guard__(
@@ -79,7 +79,7 @@ const AdminController = {
})()
}
- return SystemMessageManager.getMessagesFromDB(function(
+ return SystemMessageManager.getMessagesFromDB(function (
error,
systemMessages
) {
@@ -124,7 +124,7 @@ const AdminController = {
writeAllToMongo(req, res) {
logger.log('writing all docs to mongo')
Settings.mongo.writeAll = true
- return DocumentUpdaterHandler.flushAllDocsToMongo(function() {
+ return DocumentUpdaterHandler.flushAllDocsToMongo(function () {
logger.log('all docs have been saved to mongo')
return res.sendStatus(200)
})
@@ -144,18 +144,19 @@ const AdminController = {
},
createMessage(req, res, next) {
- return SystemMessageManager.createMessage(req.body.content, function(
- error
- ) {
- if (error != null) {
- return next(error)
+ return SystemMessageManager.createMessage(
+ req.body.content,
+ function (error) {
+ if (error != null) {
+ return next(error)
+ }
+ return res.sendStatus(200)
}
- return res.sendStatus(200)
- })
+ )
},
clearMessages(req, res, next) {
- return SystemMessageManager.clearMessages(function(error) {
+ return SystemMessageManager.clearMessages(function (error) {
if (error != null) {
return next(error)
}
diff --git a/services/web/app/src/Features/Spelling/SpellingController.js b/services/web/app/src/Features/Spelling/SpellingController.js
index 7932eae880..25d73d12a7 100644
--- a/services/web/app/src/Features/Spelling/SpellingController.js
+++ b/services/web/app/src/Features/Spelling/SpellingController.js
@@ -38,7 +38,7 @@ module.exports = {
json: req.body,
timeout: TEN_SECONDS
})
- .on('error', function(error) {
+ .on('error', function (error) {
logger.error({ err: error }, 'Spelling API error')
return res.status(500).end()
})
diff --git a/services/web/app/src/Features/StaticPages/HomeController.js b/services/web/app/src/Features/StaticPages/HomeController.js
index 32ca3d0db6..90d5a6ba78 100644
--- a/services/web/app/src/Features/StaticPages/HomeController.js
+++ b/services/web/app/src/Features/StaticPages/HomeController.js
@@ -48,14 +48,14 @@ module.exports = HomeController = {
},
externalPage(page, title) {
- return function(req, res, next) {
+ return function (req, res, next) {
if (next == null) {
- next = function(error) {}
+ next = function (error) {}
}
const path = Path.resolve(
__dirname + `/../../../views/external/${page}.pug`
)
- return fs.exists(path, function(exists) {
+ return fs.exists(path, function (exists) {
// No error in this callback - old method in Node.js!
if (exists) {
return res.render(`external/${page}.pug`, { title })
diff --git a/services/web/app/src/Features/Subscription/FeaturesUpdater.js b/services/web/app/src/Features/Subscription/FeaturesUpdater.js
index 4e02a111a7..2a5246ceaf 100644
--- a/services/web/app/src/Features/Subscription/FeaturesUpdater.js
+++ b/services/web/app/src/Features/Subscription/FeaturesUpdater.js
@@ -67,7 +67,7 @@ const FeaturesUpdater = {
FeaturesUpdater._getFeaturesOverrides(userId, cb)
}
}
- async.series(jobs, function(err, results) {
+ async.series(jobs, function (err, results) {
if (err) {
OError.tag(
err,
@@ -158,26 +158,25 @@ const FeaturesUpdater = {
},
_getV1Features(userId, callback) {
- V1SubscriptionManager.getPlanCodeFromV1(userId, function(
- err,
- planCode,
- v1Id
- ) {
- if (err) {
- if ((err ? err.name : undefined) === 'NotFoundError') {
- return callback(null, [])
+ V1SubscriptionManager.getPlanCodeFromV1(
+ userId,
+ function (err, planCode, v1Id) {
+ if (err) {
+ if ((err ? err.name : undefined) === 'NotFoundError') {
+ return callback(null, [])
+ }
+ return callback(err)
}
- return callback(err)
- }
- callback(
- err,
- FeaturesUpdater._mergeFeatures(
- V1SubscriptionManager.getGrandfatheredFeaturesForV1User(v1Id) || {},
- FeaturesUpdater._planCodeToFeatures(planCode)
+ callback(
+ err,
+ FeaturesUpdater._mergeFeatures(
+ V1SubscriptionManager.getGrandfatheredFeaturesForV1User(v1Id) || {},
+ FeaturesUpdater._planCodeToFeatures(planCode)
+ )
)
- )
- })
+ }
+ )
},
_mergeFeatures(featuresA, featuresB) {
@@ -277,31 +276,32 @@ const FeaturesUpdater = {
doSyncFromV1(v1UserId, callback) {
logger.log({ v1UserId }, '[AccountSync] starting account sync')
- return UserGetter.getUser({ 'overleaf.id': v1UserId }, { _id: 1 }, function(
- err,
- user
- ) {
- if (err != null) {
- OError.tag(err, '[AccountSync] error getting user', {
- v1UserId
- })
- return callback(err)
+ return UserGetter.getUser(
+ { 'overleaf.id': v1UserId },
+ { _id: 1 },
+ function (err, user) {
+ if (err != null) {
+ OError.tag(err, '[AccountSync] error getting user', {
+ v1UserId
+ })
+ return callback(err)
+ }
+ if ((user != null ? user._id : undefined) == null) {
+ logger.warn({ v1UserId }, '[AccountSync] no user found for v1 id')
+ return callback(null)
+ }
+ logger.log(
+ { v1UserId, userId: user._id },
+ '[AccountSync] updating user subscription and features'
+ )
+ return FeaturesUpdater.refreshFeatures(user._id, callback)
}
- if ((user != null ? user._id : undefined) == null) {
- logger.warn({ v1UserId }, '[AccountSync] no user found for v1 id')
- return callback(null)
- }
- logger.log(
- { v1UserId, userId: user._id },
- '[AccountSync] updating user subscription and features'
- )
- return FeaturesUpdater.refreshFeatures(user._id, callback)
- })
+ )
}
}
const refreshFeaturesPromise = userId =>
- new Promise(function(resolve, reject) {
+ new Promise(function (resolve, reject) {
FeaturesUpdater.refreshFeatures(
userId,
(error, features, featuresChanged) => {
diff --git a/services/web/app/src/Features/Subscription/LimitationsManager.js b/services/web/app/src/Features/Subscription/LimitationsManager.js
index 9f0270a94a..cf0085b379 100644
--- a/services/web/app/src/Features/Subscription/LimitationsManager.js
+++ b/services/web/app/src/Features/Subscription/LimitationsManager.js
@@ -41,7 +41,7 @@ module.exports = LimitationsManager = {
},
allowedNumberOfCollaboratorsForUser(user_id, callback) {
- return UserGetter.getUser(user_id, { features: 1 }, function(error, user) {
+ return UserGetter.getUser(user_id, { features: 1 }, function (error, user) {
if (error != null) {
return callback(error)
}
@@ -55,7 +55,7 @@ module.exports = LimitationsManager = {
canAddXCollaborators(project_id, x_collaborators, callback) {
if (callback == null) {
- callback = function(error, allowed) {}
+ callback = function (error, allowed) {}
}
return this.allowedNumberOfCollaboratorsInProject(
project_id,
@@ -94,7 +94,7 @@ module.exports = LimitationsManager = {
hasPaidSubscription(user, callback) {
if (callback == null) {
- callback = function(err, hasSubscriptionOrIsMember) {}
+ callback = function (err, hasSubscriptionOrIsMember) {}
}
return this.userHasV2Subscription(
user,
@@ -132,27 +132,27 @@ module.exports = LimitationsManager = {
userHasV2Subscription(user, callback) {
if (callback == null) {
- callback = function(err, hasSubscription, subscription) {}
+ callback = function (err, hasSubscription, subscription) {}
}
- return SubscriptionLocator.getUsersSubscription(user._id, function(
- err,
- subscription
- ) {
- if (err != null) {
- return callback(err)
+ return SubscriptionLocator.getUsersSubscription(
+ user._id,
+ function (err, subscription) {
+ if (err != null) {
+ return callback(err)
+ }
+ const hasValidSubscription =
+ subscription != null &&
+ (subscription.recurlySubscription_id != null ||
+ (subscription != null ? subscription.customAccount : undefined) ===
+ true)
+ return callback(err, hasValidSubscription, subscription)
}
- const hasValidSubscription =
- subscription != null &&
- (subscription.recurlySubscription_id != null ||
- (subscription != null ? subscription.customAccount : undefined) ===
- true)
- return callback(err, hasValidSubscription, subscription)
- })
+ )
},
userHasV1OrV2Subscription(user, callback) {
if (callback == null) {
- callback = function(err, hasSubscription) {}
+ callback = function (err, hasSubscription) {}
}
return this.userHasV2Subscription(user, (err, hasV2Subscription) => {
if (err != null) {
@@ -175,35 +175,37 @@ module.exports = LimitationsManager = {
userIsMemberOfGroupSubscription(user, callback) {
if (callback == null) {
- callback = function(error, isMember, subscriptions) {}
+ callback = function (error, isMember, subscriptions) {}
}
- return SubscriptionLocator.getMemberSubscriptions(user._id, function(
- err,
- subscriptions
- ) {
- if (subscriptions == null) {
- subscriptions = []
+ return SubscriptionLocator.getMemberSubscriptions(
+ user._id,
+ function (err, subscriptions) {
+ if (subscriptions == null) {
+ subscriptions = []
+ }
+ if (err != null) {
+ return callback(err)
+ }
+ return callback(err, subscriptions.length > 0, subscriptions)
}
- if (err != null) {
- return callback(err)
- }
- return callback(err, subscriptions.length > 0, subscriptions)
- })
+ )
},
userHasV1Subscription(user, callback) {
if (callback == null) {
- callback = function(error, hasV1Subscription) {}
+ callback = function (error, hasV1Subscription) {}
}
- return V1SubscriptionManager.getSubscriptionsFromV1(user._id, function(
- err,
- v1Subscription
- ) {
- return callback(
- err,
- !!(v1Subscription != null ? v1Subscription.has_subscription : undefined)
- )
- })
+ return V1SubscriptionManager.getSubscriptionsFromV1(
+ user._id,
+ function (err, v1Subscription) {
+ return callback(
+ err,
+ !!(v1Subscription != null
+ ? v1Subscription.has_subscription
+ : undefined)
+ )
+ }
+ )
},
teamHasReachedMemberLimit(subscription) {
@@ -217,27 +219,27 @@ module.exports = LimitationsManager = {
hasGroupMembersLimitReached(subscriptionId, callback) {
if (callback == null) {
- callback = function(err, limitReached, subscription) {}
+ callback = function (err, limitReached, subscription) {}
}
- return SubscriptionLocator.getSubscription(subscriptionId, function(
- err,
- subscription
- ) {
- if (err != null) {
- OError.tag(err, 'error getting subscription', {
- subscriptionId
- })
- return callback(err)
- }
- if (subscription == null) {
- logger.warn({ subscriptionId }, 'no subscription found')
- return callback(new Error('no subscription found'))
- }
+ return SubscriptionLocator.getSubscription(
+ subscriptionId,
+ function (err, subscription) {
+ if (err != null) {
+ OError.tag(err, 'error getting subscription', {
+ subscriptionId
+ })
+ return callback(err)
+ }
+ if (subscription == null) {
+ logger.warn({ subscriptionId }, 'no subscription found')
+ return callback(new Error('no subscription found'))
+ }
- const limitReached = LimitationsManager.teamHasReachedMemberLimit(
- subscription
- )
- return callback(err, limitReached, subscription)
- })
+ const limitReached = LimitationsManager.teamHasReachedMemberLimit(
+ subscription
+ )
+ return callback(err, limitReached, subscription)
+ }
+ )
}
}
diff --git a/services/web/app/src/Features/Subscription/RecurlyWrapper.js b/services/web/app/src/Features/Subscription/RecurlyWrapper.js
index bcf0167356..ac1811ff25 100644
--- a/services/web/app/src/Features/Subscription/RecurlyWrapper.js
+++ b/services/web/app/src/Features/Subscription/RecurlyWrapper.js
@@ -65,7 +65,7 @@ const RecurlyWrapper = {
method: 'GET',
expect404: true
},
- function(error, response, responseBody) {
+ function (error, response, responseBody) {
if (error) {
OError.tag(
error,
@@ -86,20 +86,20 @@ const RecurlyWrapper = {
return next(null, cache)
}
logger.log({ user_id: user._id }, 'user appears to exist in recurly')
- return RecurlyWrapper._parseAccountXml(responseBody, function(
- err,
- account
- ) {
- if (err) {
- OError.tag(err, 'error parsing account', {
- user_id: user._id
- })
- return next(err)
+ return RecurlyWrapper._parseAccountXml(
+ responseBody,
+ function (err, account) {
+ if (err) {
+ OError.tag(err, 'error parsing account', {
+ user_id: user._id
+ })
+ return next(err)
+ }
+ cache.userExists = true
+ cache.account = account
+ return next(null, cache)
}
- cache.userExists = true
- cache.account = account
- return next(null, cache)
- })
+ )
}
)
},
@@ -142,19 +142,19 @@ const RecurlyWrapper = {
)
return next(error)
}
- return RecurlyWrapper._parseAccountXml(responseBody, function(
- err,
- account
- ) {
- if (err) {
- OError.tag(err, 'error creating account', {
- user_id: user._id
- })
- return next(err)
+ return RecurlyWrapper._parseAccountXml(
+ responseBody,
+ function (err, account) {
+ if (err) {
+ OError.tag(err, 'error creating account', {
+ user_id: user._id
+ })
+ return next(err)
+ }
+ cache.account = account
+ return next(null, cache)
}
- cache.account = account
- return next(null, cache)
- })
+ )
}
)
},
@@ -189,20 +189,20 @@ const RecurlyWrapper = {
)
return next(error)
}
- return RecurlyWrapper._parseBillingInfoXml(responseBody, function(
- err,
- billingInfo
- ) {
- if (err) {
- OError.tag(err, 'error creating billing info', {
- user_id: user._id,
- accountCode
- })
- return next(err)
+ return RecurlyWrapper._parseBillingInfoXml(
+ responseBody,
+ function (err, billingInfo) {
+ if (err) {
+ OError.tag(err, 'error creating billing info', {
+ user_id: user._id,
+ accountCode
+ })
+ return next(err)
+ }
+ cache.billingInfo = billingInfo
+ return next(null, cache)
}
- cache.billingInfo = billingInfo
- return next(null, cache)
- })
+ )
}
)
},
@@ -255,19 +255,19 @@ const RecurlyWrapper = {
)
return next(error)
}
- return RecurlyWrapper._parseBillingInfoXml(responseBody, function(
- err,
- billingInfo
- ) {
- if (err) {
- OError.tag(err, 'error updating billing info', {
- user_id: user._id
- })
- return next(err)
+ return RecurlyWrapper._parseBillingInfoXml(
+ responseBody,
+ function (err, billingInfo) {
+ if (err) {
+ OError.tag(err, 'error updating billing info', {
+ user_id: user._id
+ })
+ return next(err)
+ }
+ cache.billingInfo = billingInfo
+ return next(null, cache)
}
- cache.billingInfo = billingInfo
- return next(null, cache)
- })
+ )
}
)
},
@@ -308,19 +308,19 @@ const RecurlyWrapper = {
)
return next(error)
}
- return RecurlyWrapper._parseSubscriptionXml(responseBody, function(
- err,
- subscription
- ) {
- if (err) {
- OError.tag(err, 'error creating subscription', {
- user_id: user._id
- })
- return next(err)
+ return RecurlyWrapper._parseSubscriptionXml(
+ responseBody,
+ function (err, subscription) {
+ if (err) {
+ OError.tag(err, 'error creating subscription', {
+ user_id: user._id
+ })
+ return next(err)
+ }
+ cache.subscription = subscription
+ return next(null, cache)
}
- cache.subscription = subscription
- return next(null, cache)
- })
+ )
}
)
}
@@ -348,7 +348,7 @@ const RecurlyWrapper = {
RecurlyWrapper._paypal.setAddressAndCompanyBillingInfo,
RecurlyWrapper._paypal.createSubscription
],
- function(err, result) {
+ function (err, result) {
if (err) {
OError.tag(err, 'error in paypal subscription creation process', {
user_id: user._id
@@ -449,7 +449,7 @@ const RecurlyWrapper = {
const { expect404, expect422 } = options
delete options.expect404
delete options.expect422
- return request(options, function(error, response, body) {
+ return request(options, function (error, response, body) {
if (
error == null &&
response.statusCode !== 200 &&
@@ -532,16 +532,16 @@ const RecurlyWrapper = {
)
}
- return RecurlyWrapper.getAccount(accountId, function(
- error,
- account
- ) {
- if (error != null) {
- return callback(error)
+ return RecurlyWrapper.getAccount(
+ accountId,
+ function (error, account) {
+ if (error != null) {
+ return callback(error)
+ }
+ recurlySubscription.account = account
+ return callback(null, recurlySubscription)
}
- recurlySubscription.account = account
- return callback(null, recurlySubscription)
- })
+ )
} else {
return callback(null, recurlySubscription)
}
@@ -566,7 +566,7 @@ const RecurlyWrapper = {
if (error != null) {
return callback(error)
}
- return RecurlyWrapper._parseXml(body, function(err, data) {
+ return RecurlyWrapper._parseXml(body, function (err, data) {
if (err != null) {
logger.warn({ err }, 'could not get accoutns')
callback(err)
@@ -620,29 +620,30 @@ const RecurlyWrapper = {
if (error != null) {
return callback(error)
}
- return RecurlyWrapper._parseRedemptionsXml(body, function(
- error,
- redemptions
- ) {
- if (error != null) {
- return callback(error)
- }
- const activeRedemptions = redemptions.filter(
- redemption => redemption.state === 'active'
- )
- const couponCodes = activeRedemptions.map(
- redemption => redemption.coupon_code
- )
- return Async.map(couponCodes, RecurlyWrapper.getCoupon, function(
- error,
- coupons
- ) {
+ return RecurlyWrapper._parseRedemptionsXml(
+ body,
+ function (error, redemptions) {
if (error != null) {
return callback(error)
}
- return callback(null, coupons)
- })
- })
+ const activeRedemptions = redemptions.filter(
+ redemption => redemption.state === 'active'
+ )
+ const couponCodes = activeRedemptions.map(
+ redemption => redemption.coupon_code
+ )
+ return Async.map(
+ couponCodes,
+ RecurlyWrapper.getCoupon,
+ function (error, coupons) {
+ if (error != null) {
+ return callback(error)
+ }
+ return callback(null, coupons)
+ }
+ )
+ }
+ )
}
)
},
@@ -776,9 +777,9 @@ const RecurlyWrapper = {
url: `subscriptions/${subscriptionId}/cancel`,
method: 'put'
},
- function(error, response, body) {
+ function (error, response, body) {
if (error != null) {
- return RecurlyWrapper._parseXml(body, function(_err, parsed) {
+ return RecurlyWrapper._parseXml(body, function (_err, parsed) {
if (
__guard__(
parsed != null ? parsed.error : undefined,
@@ -870,7 +871,7 @@ const RecurlyWrapper = {
listAccountActiveSubscriptions(account_id, callback) {
if (callback == null) {
- callback = function(error, subscriptions) {}
+ callback = function (error, subscriptions) {}
}
return RecurlyWrapper.apiRequest(
{
@@ -880,7 +881,7 @@ const RecurlyWrapper = {
},
expect404: true
},
- function(error, response, body) {
+ function (error, response, body) {
if (error != null) {
return callback(error)
}
@@ -975,7 +976,7 @@ const RecurlyWrapper = {
},
_parseXmlAndGetAttribute(xml, attribute, callback) {
- return RecurlyWrapper._parseXml(xml, function(error, data) {
+ return RecurlyWrapper._parseXml(xml, function (error, data) {
if (error != null) {
return callback(error)
}
@@ -990,7 +991,7 @@ const RecurlyWrapper = {
},
_parseXml(xml, callback) {
- var convertDataTypes = function(data) {
+ var convertDataTypes = function (data) {
let key, value
if (data != null && data.$ != null) {
if (data.$.nil === 'nil') {
@@ -1033,7 +1034,7 @@ const RecurlyWrapper = {
explicitArray: false,
emptyTag: ''
})
- return parser.parseString(xml, function(error, data) {
+ return parser.parseString(xml, function (error, data) {
if (error != null) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Subscription/SubscriptionController.js b/services/web/app/src/Features/Subscription/SubscriptionController.js
index dd6552a6d7..b393a5e3b4 100644
--- a/services/web/app/src/Features/Subscription/SubscriptionController.js
+++ b/services/web/app/src/Features/Subscription/SubscriptionController.js
@@ -41,7 +41,7 @@ module.exports = SubscriptionController = {
return GeoIpLookup.getCurrencyCode(
(req.query != null ? req.query.ip : undefined) || req.ip,
- function(err, recomendedCurrency) {
+ function (err, recomendedCurrency) {
if (err != null) {
return next(err)
}
@@ -57,16 +57,17 @@ module.exports = SubscriptionController = {
})
const user_id = AuthenticationController.getLoggedInUserId(req)
if (user_id != null) {
- return UserGetter.getUser(user_id, { signUpDate: 1 }, function(
- err,
- user
- ) {
- if (err != null) {
- return next(err)
+ return UserGetter.getUser(
+ user_id,
+ { signUpDate: 1 },
+ function (err, user) {
+ if (err != null) {
+ return next(err)
+ }
+ currentUser = user
+ return render()
}
- currentUser = user
- return render()
- })
+ )
} else {
return render()
}
@@ -81,68 +82,68 @@ module.exports = SubscriptionController = {
if (!plan) {
return HttpErrorHandler.unprocessableEntity(req, res, 'Plan not found')
}
- return LimitationsManager.userHasV1OrV2Subscription(user, function(
- err,
- hasSubscription
- ) {
- if (err != null) {
- return next(err)
- }
- if (hasSubscription) {
- return res.redirect('/user/subscription?hasSubscription=true')
- } else {
- // LimitationsManager.userHasV2Subscription only checks Mongo. Double check with
- // Recurly as well at this point (we don't do this most places for speed).
- return SubscriptionHandler.validateNoSubscriptionInRecurly(
- user._id,
- function(error, valid) {
- if (error != null) {
- return next(error)
- }
- if (!valid) {
- res.redirect('/user/subscription?hasSubscription=true')
- } else {
- let currency =
- req.query.currency != null
- ? req.query.currency.toUpperCase()
- : undefined
- return GeoIpLookup.getCurrencyCode(
- (req.query != null ? req.query.ip : undefined) || req.ip,
- function(err, recomendedCurrency, countryCode) {
- if (err != null) {
- return next(err)
- }
- if (recomendedCurrency != null && currency == null) {
- currency = recomendedCurrency
- }
- return res.render('subscriptions/new', {
- title: 'subscribe',
- currency,
- countryCode,
- plan,
- showStudentPlan: req.query.ssp === 'true',
- recurlyConfig: JSON.stringify({
+ return LimitationsManager.userHasV1OrV2Subscription(
+ user,
+ function (err, hasSubscription) {
+ if (err != null) {
+ return next(err)
+ }
+ if (hasSubscription) {
+ return res.redirect('/user/subscription?hasSubscription=true')
+ } else {
+ // LimitationsManager.userHasV2Subscription only checks Mongo. Double check with
+ // Recurly as well at this point (we don't do this most places for speed).
+ return SubscriptionHandler.validateNoSubscriptionInRecurly(
+ user._id,
+ function (error, valid) {
+ if (error != null) {
+ return next(error)
+ }
+ if (!valid) {
+ res.redirect('/user/subscription?hasSubscription=true')
+ } else {
+ let currency =
+ req.query.currency != null
+ ? req.query.currency.toUpperCase()
+ : undefined
+ return GeoIpLookup.getCurrencyCode(
+ (req.query != null ? req.query.ip : undefined) || req.ip,
+ function (err, recomendedCurrency, countryCode) {
+ if (err != null) {
+ return next(err)
+ }
+ if (recomendedCurrency != null && currency == null) {
+ currency = recomendedCurrency
+ }
+ return res.render('subscriptions/new', {
+ title: 'subscribe',
currency,
- subdomain: Settings.apis.recurly.subdomain
- }),
- showCouponField: !!req.query.scf,
- showVatField: !!req.query.svf,
- gaOptimize: true
- })
- }
- )
+ countryCode,
+ plan,
+ showStudentPlan: req.query.ssp === 'true',
+ recurlyConfig: JSON.stringify({
+ currency,
+ subdomain: Settings.apis.recurly.subdomain
+ }),
+ showCouponField: !!req.query.scf,
+ showVatField: !!req.query.svf,
+ gaOptimize: true
+ })
+ }
+ )
+ }
}
- }
- )
+ )
+ }
}
- })
+ )
},
userSubscriptionPage(req, res, next) {
const user = AuthenticationController.getSessionUser(req)
return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
user,
- function(error, results) {
+ function (error, results) {
if (error != null) {
return next(error)
}
@@ -155,31 +156,31 @@ module.exports = SubscriptionController = {
managedPublishers,
v1SubscriptionStatus
} = results
- return LimitationsManager.userHasV1OrV2Subscription(user, function(
- err,
- hasSubscription
- ) {
- if (error != null) {
- return next(error)
+ return LimitationsManager.userHasV1OrV2Subscription(
+ user,
+ function (err, hasSubscription) {
+ if (error != null) {
+ return next(error)
+ }
+ const fromPlansPage = req.query.hasSubscription
+ const plans = SubscriptionViewModelBuilder.buildPlansList()
+ const data = {
+ title: 'your_subscription',
+ plans,
+ user,
+ hasSubscription,
+ fromPlansPage,
+ personalSubscription,
+ memberGroupSubscriptions,
+ managedGroupSubscriptions,
+ confirmedMemberAffiliations,
+ managedInstitutions,
+ managedPublishers,
+ v1SubscriptionStatus
+ }
+ return res.render('subscriptions/dashboard', data)
}
- const fromPlansPage = req.query.hasSubscription
- const plans = SubscriptionViewModelBuilder.buildPlansList()
- const data = {
- title: 'your_subscription',
- plans,
- user,
- hasSubscription,
- fromPlansPage,
- personalSubscription,
- memberGroupSubscriptions,
- managedGroupSubscriptions,
- confirmedMemberAffiliations,
- managedInstitutions,
- managedPublishers,
- v1SubscriptionStatus
- }
- return res.render('subscriptions/dashboard', data)
- })
+ )
}
)
},
@@ -193,54 +194,54 @@ module.exports = SubscriptionController = {
}
const { subscriptionDetails } = req.body
- return LimitationsManager.userHasV1OrV2Subscription(user, function(
- err,
- hasSubscription
- ) {
- if (err != null) {
- return next(err)
- }
- if (hasSubscription) {
- logger.warn({ user_id: user._id }, 'user already has subscription')
- return res.sendStatus(409) // conflict
- }
- return SubscriptionHandler.createSubscription(
- user,
- subscriptionDetails,
- recurlyTokenIds,
- function(err) {
- if (!err) {
- return res.sendStatus(201)
- }
-
- if (
- err instanceof SubscriptionErrors.RecurlyTransactionError ||
- err instanceof Errors.InvalidError
- ) {
- logger.error({ err }, 'recurly transaction error, potential 422')
- return HttpErrorHandler.unprocessableEntity(
- req,
- res,
- err.message,
- OError.getFullInfo(err).public
- )
- }
-
- logger.warn(
- { err, user_id: user._id },
- 'something went wrong creating subscription'
- )
- next(err)
+ return LimitationsManager.userHasV1OrV2Subscription(
+ user,
+ function (err, hasSubscription) {
+ if (err != null) {
+ return next(err)
}
- )
- })
+ if (hasSubscription) {
+ logger.warn({ user_id: user._id }, 'user already has subscription')
+ return res.sendStatus(409) // conflict
+ }
+ return SubscriptionHandler.createSubscription(
+ user,
+ subscriptionDetails,
+ recurlyTokenIds,
+ function (err) {
+ if (!err) {
+ return res.sendStatus(201)
+ }
+
+ if (
+ err instanceof SubscriptionErrors.RecurlyTransactionError ||
+ err instanceof Errors.InvalidError
+ ) {
+ logger.error({ err }, 'recurly transaction error, potential 422')
+ return HttpErrorHandler.unprocessableEntity(
+ req,
+ res,
+ err.message,
+ OError.getFullInfo(err).public
+ )
+ }
+
+ logger.warn(
+ { err, user_id: user._id },
+ 'something went wrong creating subscription'
+ )
+ next(err)
+ }
+ )
+ }
+ )
},
successful_subscription(req, res, next) {
const user = AuthenticationController.getSessionUser(req)
return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
user,
- function(error, { personalSubscription }) {
+ function (error, { personalSubscription }) {
if (error != null) {
return next(error)
}
@@ -258,7 +259,7 @@ module.exports = SubscriptionController = {
cancelSubscription(req, res, next) {
const user = AuthenticationController.getSessionUser(req)
logger.log({ user_id: user._id }, 'canceling subscription')
- return SubscriptionHandler.cancelSubscription(user, function(err) {
+ return SubscriptionHandler.cancelSubscription(user, function (err) {
if (err != null) {
OError.tag(err, 'something went wrong canceling subscription', {
user_id: user._id
@@ -281,7 +282,7 @@ module.exports = SubscriptionController = {
cancelV1Subscription(req, res, next) {
const user_id = AuthenticationController.getLoggedInUserId(req)
logger.log({ user_id }, 'canceling v1 subscription')
- return V1SubscriptionManager.cancelV1Subscription(user_id, function(err) {
+ return V1SubscriptionManager.cancelV1Subscription(user_id, function (err) {
if (err != null) {
OError.tag(err, 'something went wrong canceling v1 subscription', {
user_id
@@ -310,7 +311,7 @@ module.exports = SubscriptionController = {
user,
planCode,
null,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'something went wrong updating subscription', {
user_id: user._id
@@ -324,20 +325,22 @@ module.exports = SubscriptionController = {
updateAccountEmailAddress(req, res, next) {
const user = AuthenticationController.getSessionUser(req)
- RecurlyWrapper.updateAccountEmailAddress(user._id, user.email, function(
- error
- ) {
- if (error) {
- return next(error)
+ RecurlyWrapper.updateAccountEmailAddress(
+ user._id,
+ user.email,
+ function (error) {
+ if (error) {
+ return next(error)
+ }
+ res.sendStatus(200)
}
- res.sendStatus(200)
- })
+ )
},
reactivateSubscription(req, res, next) {
const user = AuthenticationController.getSessionUser(req)
logger.log({ user_id: user._id }, 'reactivating subscription')
- return SubscriptionHandler.reactivateSubscription(user, function(err) {
+ return SubscriptionHandler.reactivateSubscription(user, function (err) {
if (err != null) {
OError.tag(err, 'something went wrong reactivating subscription', {
user_id: user._id
@@ -363,7 +366,7 @@ module.exports = SubscriptionController = {
return SubscriptionHandler.syncSubscription(
recurlySubscription,
{ ip: req.ip },
- function(err) {
+ function (err) {
if (err != null) {
return next(err)
}
@@ -374,7 +377,7 @@ module.exports = SubscriptionController = {
const recurlyAccountCode = eventData.account.account_code
return SubscriptionHandler.attemptPaypalInvoiceCollection(
recurlyAccountCode,
- function(err) {
+ function (err) {
if (err) {
return next(err)
}
@@ -388,36 +391,38 @@ module.exports = SubscriptionController = {
renderUpgradeToAnnualPlanPage(req, res, next) {
const user = AuthenticationController.getSessionUser(req)
- return LimitationsManager.userHasV2Subscription(user, function(
- err,
- hasSubscription,
- subscription
- ) {
- let planName
- if (err != null) {
- return next(err)
+ return LimitationsManager.userHasV2Subscription(
+ user,
+ function (err, hasSubscription, subscription) {
+ let planName
+ if (err != null) {
+ return next(err)
+ }
+ const planCode =
+ subscription != null ? subscription.planCode.toLowerCase() : undefined
+ if (
+ (planCode != null ? planCode.indexOf('annual') : undefined) !== -1
+ ) {
+ planName = 'annual'
+ } else if (
+ (planCode != null ? planCode.indexOf('student') : undefined) !== -1
+ ) {
+ planName = 'student'
+ } else if (
+ (planCode != null ? planCode.indexOf('collaborator') : undefined) !==
+ -1
+ ) {
+ planName = 'collaborator'
+ }
+ if (!hasSubscription) {
+ return res.redirect('/user/subscription/plans')
+ }
+ return res.render('subscriptions/upgradeToAnnual', {
+ title: 'Upgrade to annual',
+ planName
+ })
}
- const planCode =
- subscription != null ? subscription.planCode.toLowerCase() : undefined
- if ((planCode != null ? planCode.indexOf('annual') : undefined) !== -1) {
- planName = 'annual'
- } else if (
- (planCode != null ? planCode.indexOf('student') : undefined) !== -1
- ) {
- planName = 'student'
- } else if (
- (planCode != null ? planCode.indexOf('collaborator') : undefined) !== -1
- ) {
- planName = 'collaborator'
- }
- if (!hasSubscription) {
- return res.redirect('/user/subscription/plans')
- }
- return res.render('subscriptions/upgradeToAnnual', {
- title: 'Upgrade to annual',
- planName
- })
- })
+ )
},
processUpgradeToAnnualPlan(req, res, next) {
@@ -433,7 +438,7 @@ module.exports = SubscriptionController = {
user,
annualPlanName,
coupon_code,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'error updating subscription', {
user_id: user._id
@@ -447,29 +452,32 @@ module.exports = SubscriptionController = {
extendTrial(req, res, next) {
const user = AuthenticationController.getSessionUser(req)
- return LimitationsManager.userHasV2Subscription(user, function(
- err,
- hasSubscription,
- subscription
- ) {
- if (err != null) {
- return next(err)
- }
- return SubscriptionHandler.extendTrial(subscription, 14, function(err) {
+ return LimitationsManager.userHasV2Subscription(
+ user,
+ function (err, hasSubscription, subscription) {
if (err != null) {
- return res.sendStatus(500)
- } else {
- return res.sendStatus(200)
+ return next(err)
}
- })
- })
+ return SubscriptionHandler.extendTrial(
+ subscription,
+ 14,
+ function (err) {
+ if (err != null) {
+ return res.sendStatus(500)
+ } else {
+ return res.sendStatus(200)
+ }
+ }
+ )
+ }
+ )
},
recurlyNotificationParser(req, res, next) {
let xml = ''
req.on('data', chunk => (xml += chunk))
return req.on('end', () =>
- RecurlyWrapper._parseXml(xml, function(error, body) {
+ RecurlyWrapper._parseXml(xml, function (error, body) {
if (error != null) {
return next(error)
}
@@ -481,7 +489,7 @@ module.exports = SubscriptionController = {
refreshUserFeatures(req, res, next) {
const { user_id } = req.params
- return FeaturesUpdater.refreshFeatures(user_id, function(error) {
+ return FeaturesUpdater.refreshFeatures(user_id, function (error) {
if (error != null) {
return next(error)
}
diff --git a/services/web/app/src/Features/Subscription/SubscriptionGroupController.js b/services/web/app/src/Features/Subscription/SubscriptionGroupController.js
index ba131dbf70..cca068025e 100644
--- a/services/web/app/src/Features/Subscription/SubscriptionGroupController.js
+++ b/services/web/app/src/Features/Subscription/SubscriptionGroupController.js
@@ -30,7 +30,7 @@ module.exports = {
return SubscriptionGroupHandler.removeUserFromGroup(
subscription._id,
userToRemove_id,
- function(err) {
+ function (err) {
if (err != null) {
OError.tag(err, 'error removing user from group', {
subscriptionId: subscription._id,
@@ -46,28 +46,28 @@ module.exports = {
removeSelfFromGroup(req, res, next) {
const subscriptionId = req.query.subscriptionId
const userToRemove_id = AuthenticationController.getLoggedInUserId(req)
- return SubscriptionLocator.getSubscription(subscriptionId, function(
- error,
- subscription
- ) {
- if (error != null) {
- return next(error)
- }
-
- return SubscriptionGroupHandler.removeUserFromGroup(
- subscription._id,
- userToRemove_id,
- function(err) {
- if (err != null) {
- logger.err(
- { err, userToRemove_id, subscriptionId },
- 'error removing self from group'
- )
- return res.sendStatus(500)
- }
- return res.sendStatus(200)
+ return SubscriptionLocator.getSubscription(
+ subscriptionId,
+ function (error, subscription) {
+ if (error != null) {
+ return next(error)
}
- )
- })
+
+ return SubscriptionGroupHandler.removeUserFromGroup(
+ subscription._id,
+ userToRemove_id,
+ function (err) {
+ if (err != null) {
+ logger.err(
+ { err, userToRemove_id, subscriptionId },
+ 'error removing self from group'
+ )
+ return res.sendStatus(500)
+ }
+ return res.sendStatus(200)
+ }
+ )
+ }
+ )
}
}
diff --git a/services/web/app/src/Features/Subscription/SubscriptionGroupHandler.js b/services/web/app/src/Features/Subscription/SubscriptionGroupHandler.js
index 6fa0299a6f..c34ecfa424 100644
--- a/services/web/app/src/Features/Subscription/SubscriptionGroupHandler.js
+++ b/services/web/app/src/Features/Subscription/SubscriptionGroupHandler.js
@@ -41,7 +41,7 @@ const SubscriptionGroupHandler = {
return Subscription.updateOne(
{ admin_id: oldId },
{ admin_id: newId },
- function(error) {
+ function (error) {
if (error != null) {
return callback(error)
}
@@ -51,7 +51,7 @@ const SubscriptionGroupHandler = {
'manager_ids',
oldId,
newId,
- function(error) {
+ function (error) {
if (error != null) {
return callback(error)
}
@@ -71,12 +71,12 @@ const SubscriptionGroupHandler = {
isUserPartOfGroup(user_id, subscription_id, callback) {
if (callback == null) {
- callback = function(err, partOfGroup) {}
+ callback = function (err, partOfGroup) {}
}
return SubscriptionLocator.getSubscriptionByMemberIdAndId(
user_id,
subscription_id,
- function(err, subscription) {
+ function (err, subscription) {
let partOfGroup
if (subscription != null) {
partOfGroup = true
@@ -90,7 +90,7 @@ const SubscriptionGroupHandler = {
getTotalConfirmedUsersInGroup(subscription_id, callback) {
if (callback == null) {
- callback = function(err, totalUsers) {}
+ callback = function (err, totalUsers) {}
}
return SubscriptionLocator.getSubscription(
subscription_id,
@@ -106,7 +106,7 @@ const SubscriptionGroupHandler = {
}
}
-var replaceInArray = function(model, property, oldValue, newValue, callback) {
+var replaceInArray = function (model, property, oldValue, newValue, callback) {
// Mongo won't let us pull and addToSet in the same query, so do it in
// two. Note we need to add first, since the query is based on the old user.
const query = {}
@@ -118,7 +118,7 @@ var replaceInArray = function(model, property, oldValue, newValue, callback) {
const setOldValue = {}
setOldValue[property] = oldValue
- model.updateMany(query, { $addToSet: setNewValue }, function(error) {
+ model.updateMany(query, { $addToSet: setNewValue }, function (error) {
if (error) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Subscription/SubscriptionHandler.js b/services/web/app/src/Features/Subscription/SubscriptionHandler.js
index 5cf835d77e..bf99a8f666 100644
--- a/services/web/app/src/Features/Subscription/SubscriptionHandler.js
+++ b/services/web/app/src/Features/Subscription/SubscriptionHandler.js
@@ -11,228 +11,227 @@ const Analytics = require('../Analytics/AnalyticsManager')
const SubscriptionHandler = {
validateNoSubscriptionInRecurly(userId, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
- RecurlyWrapper.listAccountActiveSubscriptions(userId, function(
- error,
- subscriptions
- ) {
- if (subscriptions == null) {
- subscriptions = []
- }
- if (error != null) {
- return callback(error)
- }
- if (subscriptions.length > 0) {
- SubscriptionUpdater.syncSubscription(subscriptions[0], userId, function(
- error
- ) {
- if (error != null) {
- return callback(error)
- }
- callback(null, false)
- })
- } else {
- callback(null, true)
- }
- })
- },
-
- createSubscription(user, subscriptionDetails, recurlyTokenIds, callback) {
- SubscriptionHandler.validateNoSubscriptionInRecurly(user._id, function(
- error,
- valid
- ) {
- if (error != null) {
- return callback(error)
- }
- if (!valid) {
- return callback(new Error('user already has subscription in recurly'))
- }
- RecurlyWrapper.createSubscription(
- user,
- subscriptionDetails,
- recurlyTokenIds,
- function(error, recurlySubscription) {
- if (error != null) {
- return callback(error)
- }
- return SubscriptionUpdater.syncSubscription(
- recurlySubscription,
- user._id,
- function(error) {
+ RecurlyWrapper.listAccountActiveSubscriptions(
+ userId,
+ function (error, subscriptions) {
+ if (subscriptions == null) {
+ subscriptions = []
+ }
+ if (error != null) {
+ return callback(error)
+ }
+ if (subscriptions.length > 0) {
+ SubscriptionUpdater.syncSubscription(
+ subscriptions[0],
+ userId,
+ function (error) {
if (error != null) {
return callback(error)
}
- return callback()
+ callback(null, false)
}
)
+ } else {
+ callback(null, true)
}
- )
- })
+ }
+ )
+ },
+
+ createSubscription(user, subscriptionDetails, recurlyTokenIds, callback) {
+ SubscriptionHandler.validateNoSubscriptionInRecurly(
+ user._id,
+ function (error, valid) {
+ if (error != null) {
+ return callback(error)
+ }
+ if (!valid) {
+ return callback(new Error('user already has subscription in recurly'))
+ }
+ RecurlyWrapper.createSubscription(
+ user,
+ subscriptionDetails,
+ recurlyTokenIds,
+ function (error, recurlySubscription) {
+ if (error != null) {
+ return callback(error)
+ }
+ return SubscriptionUpdater.syncSubscription(
+ recurlySubscription,
+ user._id,
+ function (error) {
+ if (error != null) {
+ return callback(error)
+ }
+ return callback()
+ }
+ )
+ }
+ )
+ }
+ )
},
updateSubscription(user, planCode, couponCode, callback) {
- LimitationsManager.userHasV2Subscription(user, function(
- err,
- hasSubscription,
- subscription
- ) {
- if (err) {
- logger.warn(
- { err, user_id: user._id, hasSubscription },
- 'there was an error checking user v2 subscription'
- )
- }
- if (!hasSubscription) {
- return callback()
- } else {
- return async.series(
- [
- function(cb) {
- if (couponCode == null) {
- return cb()
- }
- RecurlyWrapper.getSubscription(
- subscription.recurlySubscription_id,
- { includeAccount: true },
- function(err, usersSubscription) {
- if (err != null) {
- return callback(err)
- }
- RecurlyWrapper.redeemCoupon(
- usersSubscription.account.account_code,
- couponCode,
- cb
- )
+ LimitationsManager.userHasV2Subscription(
+ user,
+ function (err, hasSubscription, subscription) {
+ if (err) {
+ logger.warn(
+ { err, user_id: user._id, hasSubscription },
+ 'there was an error checking user v2 subscription'
+ )
+ }
+ if (!hasSubscription) {
+ return callback()
+ } else {
+ return async.series(
+ [
+ function (cb) {
+ if (couponCode == null) {
+ return cb()
}
- )
- },
- cb =>
- RecurlyWrapper.updateSubscription(
- subscription.recurlySubscription_id,
- { plan_code: planCode, timeframe: 'now' },
- function(error, recurlySubscription) {
- if (error != null) {
- return callback(error)
+ RecurlyWrapper.getSubscription(
+ subscription.recurlySubscription_id,
+ { includeAccount: true },
+ function (err, usersSubscription) {
+ if (err != null) {
+ return callback(err)
+ }
+ RecurlyWrapper.redeemCoupon(
+ usersSubscription.account.account_code,
+ couponCode,
+ cb
+ )
}
- SubscriptionUpdater.syncSubscription(
- recurlySubscription,
- user._id,
- cb
- )
- }
- )
- ],
- callback
- )
+ )
+ },
+ cb =>
+ RecurlyWrapper.updateSubscription(
+ subscription.recurlySubscription_id,
+ { plan_code: planCode, timeframe: 'now' },
+ function (error, recurlySubscription) {
+ if (error != null) {
+ return callback(error)
+ }
+ SubscriptionUpdater.syncSubscription(
+ recurlySubscription,
+ user._id,
+ cb
+ )
+ }
+ )
+ ],
+ callback
+ )
+ }
}
- })
+ )
},
cancelSubscription(user, callback) {
- LimitationsManager.userHasV2Subscription(user, function(
- err,
- hasSubscription,
- subscription
- ) {
- if (err) {
- logger.warn(
- { err, user_id: user._id, hasSubscription },
- 'there was an error checking user v2 subscription'
- )
- }
- if (hasSubscription) {
- RecurlyWrapper.cancelSubscription(
- subscription.recurlySubscription_id,
- function(error) {
- if (error != null) {
- return callback(error)
- }
- const emailOpts = {
- to: user.email,
- first_name: user.first_name
- }
- const ONE_HOUR_IN_MS = 1000 * 60 * 60
- setTimeout(
- () =>
- EmailHandler.sendEmail(
- 'canceledSubscription',
- emailOpts,
- err => {
- if (err != null) {
- logger.warn(
- { err },
- 'failed to send confirmation email for subscription cancellation'
- )
+ LimitationsManager.userHasV2Subscription(
+ user,
+ function (err, hasSubscription, subscription) {
+ if (err) {
+ logger.warn(
+ { err, user_id: user._id, hasSubscription },
+ 'there was an error checking user v2 subscription'
+ )
+ }
+ if (hasSubscription) {
+ RecurlyWrapper.cancelSubscription(
+ subscription.recurlySubscription_id,
+ function (error) {
+ if (error != null) {
+ return callback(error)
+ }
+ const emailOpts = {
+ to: user.email,
+ first_name: user.first_name
+ }
+ const ONE_HOUR_IN_MS = 1000 * 60 * 60
+ setTimeout(
+ () =>
+ EmailHandler.sendEmail(
+ 'canceledSubscription',
+ emailOpts,
+ err => {
+ if (err != null) {
+ logger.warn(
+ { err },
+ 'failed to send confirmation email for subscription cancellation'
+ )
+ }
}
- }
- ),
- ONE_HOUR_IN_MS
- )
- Analytics.recordEvent(user._id, 'subscription-canceled')
- callback()
- }
- )
- } else {
- callback()
+ ),
+ ONE_HOUR_IN_MS
+ )
+ Analytics.recordEvent(user._id, 'subscription-canceled')
+ callback()
+ }
+ )
+ } else {
+ callback()
+ }
}
- })
+ )
},
reactivateSubscription(user, callback) {
- LimitationsManager.userHasV2Subscription(user, function(
- err,
- hasSubscription,
- subscription
- ) {
- if (err) {
- logger.warn(
- { err, user_id: user._id, hasSubscription },
- 'there was an error checking user v2 subscription'
- )
- }
- if (hasSubscription) {
- RecurlyWrapper.reactivateSubscription(
- subscription.recurlySubscription_id,
- function(error) {
- if (error != null) {
- return callback(error)
- }
- EmailHandler.sendEmail(
- 'reactivatedSubscription',
- { to: user.email },
- err => {
- if (err != null) {
- logger.warn(
- { err },
- 'failed to send reactivation confirmation email'
- )
- }
+ LimitationsManager.userHasV2Subscription(
+ user,
+ function (err, hasSubscription, subscription) {
+ if (err) {
+ logger.warn(
+ { err, user_id: user._id, hasSubscription },
+ 'there was an error checking user v2 subscription'
+ )
+ }
+ if (hasSubscription) {
+ RecurlyWrapper.reactivateSubscription(
+ subscription.recurlySubscription_id,
+ function (error) {
+ if (error != null) {
+ return callback(error)
}
- )
- Analytics.recordEvent(user._id, 'subscription-reactivated')
- callback()
- }
- )
- } else {
- callback()
+ EmailHandler.sendEmail(
+ 'reactivatedSubscription',
+ { to: user.email },
+ err => {
+ if (err != null) {
+ logger.warn(
+ { err },
+ 'failed to send reactivation confirmation email'
+ )
+ }
+ }
+ )
+ Analytics.recordEvent(user._id, 'subscription-reactivated')
+ callback()
+ }
+ )
+ } else {
+ callback()
+ }
}
- })
+ )
},
syncSubscription(recurlySubscription, requesterData, callback) {
RecurlyWrapper.getSubscription(
recurlySubscription.uuid,
{ includeAccount: true },
- function(error, recurlySubscription) {
+ function (error, recurlySubscription) {
if (error != null) {
return callback(error)
}
User.findById(
recurlySubscription.account.account_code,
{ _id: 1 },
- function(error, user) {
+ function (error, user) {
if (error != null) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Subscription/SubscriptionLocator.js b/services/web/app/src/Features/Subscription/SubscriptionLocator.js
index c79fa758de..bb89b26654 100644
--- a/services/web/app/src/Features/Subscription/SubscriptionLocator.js
+++ b/services/web/app/src/Features/Subscription/SubscriptionLocator.js
@@ -21,20 +21,20 @@ require('./GroupPlansData') // make sure dynamic group plans are loaded
const SubscriptionLocator = {
getUsersSubscription(user_or_id, callback) {
const user_id = SubscriptionLocator._getUserId(user_or_id)
- return Subscription.findOne({ admin_id: user_id }, function(
- err,
- subscription
- ) {
- logger.log({ user_id }, 'got users subscription')
- return callback(err, subscription)
- })
+ return Subscription.findOne(
+ { admin_id: user_id },
+ function (err, subscription) {
+ logger.log({ user_id }, 'got users subscription')
+ return callback(err, subscription)
+ }
+ )
},
getUserIndividualSubscription(user_or_id, callback) {
const user_id = SubscriptionLocator._getUserId(user_or_id)
return Subscription.findOne(
{ admin_id: user_id, groupPlan: false },
- function(err, subscription) {
+ function (err, subscription) {
logger.log({ user_id }, 'got users individual subscription')
return callback(err, subscription)
}
@@ -43,7 +43,7 @@ const SubscriptionLocator = {
getManagedGroupSubscriptions(user_or_id, callback) {
if (callback == null) {
- callback = function(error, managedSubscriptions) {}
+ callback = function (error, managedSubscriptions) {}
}
const user_id = SubscriptionLocator._getUserId(user_or_id)
return Subscription.find({
diff --git a/services/web/app/src/Features/Subscription/SubscriptionUpdater.js b/services/web/app/src/Features/Subscription/SubscriptionUpdater.js
index e136b50def..8d6ae4dcca 100644
--- a/services/web/app/src/Features/Subscription/SubscriptionUpdater.js
+++ b/services/web/app/src/Features/Subscription/SubscriptionUpdater.js
@@ -45,37 +45,37 @@ const SubscriptionUpdater = {
callback = requesterData
requesterData = {}
}
- SubscriptionLocator.getUsersSubscription(adminUserId, function(
- err,
- subscription
- ) {
- if (err != null) {
- return callback(err)
- }
- if (subscription != null) {
- SubscriptionUpdater._updateSubscriptionFromRecurly(
- recurlySubscription,
- subscription,
- requesterData,
- callback
- )
- } else {
- SubscriptionUpdater._createNewSubscription(adminUserId, function(
- err,
- subscription
- ) {
- if (err != null) {
- return callback(err)
- }
+ SubscriptionLocator.getUsersSubscription(
+ adminUserId,
+ function (err, subscription) {
+ if (err != null) {
+ return callback(err)
+ }
+ if (subscription != null) {
SubscriptionUpdater._updateSubscriptionFromRecurly(
recurlySubscription,
subscription,
requesterData,
callback
)
- })
+ } else {
+ SubscriptionUpdater._createNewSubscription(
+ adminUserId,
+ function (err, subscription) {
+ if (err != null) {
+ return callback(err)
+ }
+ SubscriptionUpdater._updateSubscriptionFromRecurly(
+ recurlySubscription,
+ subscription,
+ requesterData,
+ callback
+ )
+ }
+ )
+ }
}
- })
+ )
},
addUserToGroup(subscriptionId, userId, callback) {
@@ -86,7 +86,7 @@ const SubscriptionUpdater = {
SubscriptionUpdater.addUsersToGroupWithoutFeaturesRefresh(
subscriptionId,
memberIds,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
@@ -104,7 +104,7 @@ const SubscriptionUpdater = {
removeUserFromGroups(filter, userId, callback) {
const removeOperation = { $pull: { member_ids: userId } }
- Subscription.updateMany(filter, removeOperation, function(err) {
+ Subscription.updateMany(filter, removeOperation, function (err) {
if (err != null) {
OError.tag(err, 'error removing user from groups', {
filter,
@@ -112,7 +112,7 @@ const SubscriptionUpdater = {
})
return callback(err)
}
- UserGetter.getUser(userId, function(error, user) {
+ UserGetter.getUser(userId, function (error, user) {
if (error) {
return callback(error)
}
@@ -130,23 +130,23 @@ const SubscriptionUpdater = {
},
removeUserFromAllGroups(userId, callback) {
- SubscriptionLocator.getMemberSubscriptions(userId, function(
- error,
- subscriptions
- ) {
- if (error) {
- return callback(error)
+ SubscriptionLocator.getMemberSubscriptions(
+ userId,
+ function (error, subscriptions) {
+ if (error) {
+ return callback(error)
+ }
+ if (!subscriptions) {
+ return callback()
+ }
+ const subscriptionIds = subscriptions.map(sub => sub._id)
+ SubscriptionUpdater.removeUserFromGroups(
+ { _id: subscriptionIds },
+ userId,
+ callback
+ )
}
- if (!subscriptions) {
- return callback()
- }
- const subscriptionIds = subscriptions.map(sub => sub._id)
- SubscriptionUpdater.removeUserFromGroups(
- { _id: subscriptionIds },
- userId,
- callback
- )
- })
+ )
},
deleteWithV1Id(v1TeamId, callback) {
@@ -155,7 +155,7 @@ const SubscriptionUpdater = {
deleteSubscription(subscription, deleterData, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
async.series(
[
@@ -178,38 +178,38 @@ const SubscriptionUpdater = {
},
restoreSubscription(subscriptionId, callback) {
- SubscriptionLocator.getDeletedSubscription(subscriptionId, function(
- err,
- deletedSubscription
- ) {
- if (err) {
- return callback(err)
+ SubscriptionLocator.getDeletedSubscription(
+ subscriptionId,
+ function (err, deletedSubscription) {
+ if (err) {
+ return callback(err)
+ }
+ let subscription = deletedSubscription.subscription
+ async.series(
+ [
+ cb =>
+ // 1. upsert subscription
+ db.subscriptions.updateOne(
+ { _id: subscription._id },
+ subscription,
+ { upsert: true },
+ cb
+ ),
+ cb =>
+ // 2. refresh users features. Do this before removing the
+ // subscription so the restore can be retried if this fails
+ SubscriptionUpdater._refreshUsersFeatures(subscription, cb),
+ cb =>
+ // 3. remove deleted subscription
+ DeletedSubscription.deleteOne(
+ { 'subscription._id': subscription._id },
+ callback
+ )
+ ],
+ callback
+ )
}
- let subscription = deletedSubscription.subscription
- async.series(
- [
- cb =>
- // 1. upsert subscription
- db.subscriptions.updateOne(
- { _id: subscription._id },
- subscription,
- { upsert: true },
- cb
- ),
- cb =>
- // 2. refresh users features. Do this before removing the
- // subscription so the restore can be retried if this fails
- SubscriptionUpdater._refreshUsersFeatures(subscription, cb),
- cb =>
- // 3. remove deleted subscription
- DeletedSubscription.deleteOne(
- { 'subscription._id': subscription._id },
- callback
- )
- ],
- callback
- )
- })
+ )
},
_refreshUsersFeatures(subscription, callback) {
@@ -284,7 +284,7 @@ const SubscriptionUpdater = {
})
}
}
- subscription.save(function(error) {
+ subscription.save(function (error) {
if (error) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Subscription/TeamInvitesController.js b/services/web/app/src/Features/Subscription/TeamInvitesController.js
index bb616de634..548fe494b9 100644
--- a/services/web/app/src/Features/Subscription/TeamInvitesController.js
+++ b/services/web/app/src/Features/Subscription/TeamInvitesController.js
@@ -37,7 +37,7 @@ module.exports = {
teamManagerId,
subscription,
email,
- function(err, inviteUserData) {
+ function (err, inviteUserData) {
if (err != null) {
if (err.alreadyInTeam) {
return res.status(400).json({
@@ -66,58 +66,58 @@ module.exports = {
const { token } = req.params
const userId = AuthenticationController.getLoggedInUserId(req)
- return TeamInvitesHandler.getInvite(token, function(
- err,
- invite,
- teamSubscription
- ) {
- if (err != null) {
- return next(err)
- }
-
- if (!invite) {
- return ErrorController.notFound(req, res, next)
- }
-
- return SubscriptionLocator.getUsersSubscription(userId, function(
- err,
- personalSubscription
- ) {
+ return TeamInvitesHandler.getInvite(
+ token,
+ function (err, invite, teamSubscription) {
if (err != null) {
return next(err)
}
- const hasIndividualRecurlySubscription =
- personalSubscription != null &&
- personalSubscription.planCode.match(/(free|trial)/) == null &&
- personalSubscription.groupPlan === false &&
- personalSubscription.recurlySubscription_id != null &&
- personalSubscription.recurlySubscription_id !== ''
+ if (!invite) {
+ return ErrorController.notFound(req, res, next)
+ }
- return res.render('subscriptions/team/invite', {
- inviterName: invite.inviterName,
- inviteToken: invite.token,
- hasIndividualRecurlySubscription,
- appName: settings.appName,
- expired: req.query.expired
- })
- })
- })
+ return SubscriptionLocator.getUsersSubscription(
+ userId,
+ function (err, personalSubscription) {
+ if (err != null) {
+ return next(err)
+ }
+
+ const hasIndividualRecurlySubscription =
+ personalSubscription != null &&
+ personalSubscription.planCode.match(/(free|trial)/) == null &&
+ personalSubscription.groupPlan === false &&
+ personalSubscription.recurlySubscription_id != null &&
+ personalSubscription.recurlySubscription_id !== ''
+
+ return res.render('subscriptions/team/invite', {
+ inviterName: invite.inviterName,
+ inviteToken: invite.token,
+ hasIndividualRecurlySubscription,
+ appName: settings.appName,
+ expired: req.query.expired
+ })
+ }
+ )
+ }
+ )
},
acceptInvite(req, res, next) {
const { token } = req.params
const userId = AuthenticationController.getLoggedInUserId(req)
- return TeamInvitesHandler.acceptInvite(token, userId, function(
- err,
- results
- ) {
- if (err != null) {
- return next(err)
+ return TeamInvitesHandler.acceptInvite(
+ token,
+ userId,
+ function (err, results) {
+ if (err != null) {
+ return next(err)
+ }
+ return res.sendStatus(204)
}
- return res.sendStatus(204)
- })
+ )
},
revokeInvite(req, res) {
@@ -132,7 +132,7 @@ module.exports = {
teamManagerId,
subscription,
email,
- function(err, results) {
+ function (err, results) {
if (err != null) {
return next(err)
}
diff --git a/services/web/app/src/Features/Subscription/TeamInvitesHandler.js b/services/web/app/src/Features/Subscription/TeamInvitesHandler.js
index 159e2c3521..851552103f 100644
--- a/services/web/app/src/Features/Subscription/TeamInvitesHandler.js
+++ b/services/web/app/src/Features/Subscription/TeamInvitesHandler.js
@@ -20,20 +20,20 @@ const Errors = require('../Errors/Errors')
module.exports = TeamInvitesHandler = {
getInvite(token, callback) {
- return Subscription.findOne({ 'teamInvites.token': token }, function(
- err,
- subscription
- ) {
- if (err) {
- return callback(err)
- }
- if (!subscription) {
- return callback(new Errors.NotFoundError('team not found'))
- }
+ return Subscription.findOne(
+ { 'teamInvites.token': token },
+ function (err, subscription) {
+ if (err) {
+ return callback(err)
+ }
+ if (!subscription) {
+ return callback(new Errors.NotFoundError('team not found'))
+ }
- const invite = subscription.teamInvites.find(i => i.token === token)
- callback(null, invite, subscription)
- })
+ const invite = subscription.teamInvites.find(i => i.token === token)
+ callback(null, invite, subscription)
+ }
+ )
},
createInvite(teamManagerId, subscription, email, callback) {
@@ -41,12 +41,12 @@ module.exports = TeamInvitesHandler = {
if (!email) {
return callback(new Error('invalid email'))
}
- return UserGetter.getUser(teamManagerId, function(error, teamManager) {
+ return UserGetter.getUser(teamManagerId, function (error, teamManager) {
if (error) {
return callback(error)
}
- removeLegacyInvite(subscription.id, email, function(error) {
+ removeLegacyInvite(subscription.id, email, function (error) {
if (error) {
return callback(error)
}
@@ -56,31 +56,31 @@ module.exports = TeamInvitesHandler = {
},
importInvite(subscription, inviterName, email, token, sentAt, callback) {
- checkIfInviteIsPossible(subscription, email, function(
- error,
- possible,
- reason
- ) {
- if (error) {
- return callback(error)
- }
- if (!possible) {
- return callback(reason)
- }
+ checkIfInviteIsPossible(
+ subscription,
+ email,
+ function (error, possible, reason) {
+ if (error) {
+ return callback(error)
+ }
+ if (!possible) {
+ return callback(reason)
+ }
- subscription.teamInvites.push({
- email,
- inviterName,
- token,
- sentAt
- })
+ subscription.teamInvites.push({
+ email,
+ inviterName,
+ token,
+ sentAt
+ })
- subscription.save(callback)
- })
+ subscription.save(callback)
+ }
+ )
},
acceptInvite(token, userId, callback) {
- TeamInvitesHandler.getInvite(token, function(err, invite, subscription) {
+ TeamInvitesHandler.getInvite(token, function (err, invite, subscription) {
if (err) {
return callback(err)
}
@@ -88,15 +88,17 @@ module.exports = TeamInvitesHandler = {
return callback(new Errors.NotFoundError('invite not found'))
}
- SubscriptionUpdater.addUserToGroup(subscription._id, userId, function(
- err
- ) {
- if (err) {
- return callback(err)
- }
+ SubscriptionUpdater.addUserToGroup(
+ subscription._id,
+ userId,
+ function (err) {
+ if (err) {
+ return callback(err)
+ }
- removeInviteFromTeam(subscription.id, invite.email, callback)
- })
+ removeInviteFromTeam(subscription.id, invite.email, callback)
+ }
+ )
})
},
@@ -112,7 +114,7 @@ module.exports = TeamInvitesHandler = {
// email is in Subscription.invited_emails when they join. We'll remove this
// after a short while.
createTeamInvitesForLegacyInvitedEmail(email, callback) {
- SubscriptionLocator.getGroupsWithEmailInvite(email, function(err, teams) {
+ SubscriptionLocator.getGroupsWithEmailInvite(email, function (err, teams) {
if (err) {
return callback(err)
}
@@ -127,81 +129,83 @@ module.exports = TeamInvitesHandler = {
}
}
-var createInvite = function(subscription, email, inviter, callback) {
- checkIfInviteIsPossible(subscription, email, function(
- error,
- possible,
- reason
- ) {
- if (error) {
- return callback(error)
- }
- if (!possible) {
- return callback(reason)
- }
-
- // don't send invites when inviting self; add user directly to the group
- const isInvitingSelf = inviter.emails.some(
- emailData => emailData.email === email
- )
- if (isInvitingSelf) {
- return SubscriptionUpdater.addUserToGroup(
- subscription._id,
- inviter._id,
- err => {
- if (err) {
- return callback(err)
- }
-
- // legacy: remove any invite that might have been created in the past
- removeInviteFromTeam(subscription._id, email, error => {
- const inviteUserData = {
- email: inviter.email,
- first_name: inviter.first_name,
- last_name: inviter.last_name,
- invite: false
- }
- callback(error, inviteUserData)
- })
- }
- )
- }
-
- const inviterName = getInviterName(inviter)
- let invite = subscription.teamInvites.find(invite => invite.email === email)
-
- if (invite) {
- invite.sentAt = new Date()
- } else {
- invite = {
- email,
- inviterName,
- token: crypto.randomBytes(32).toString('hex'),
- sentAt: new Date()
- }
- subscription.teamInvites.push(invite)
- }
-
- subscription.save(function(error) {
+var createInvite = function (subscription, email, inviter, callback) {
+ checkIfInviteIsPossible(
+ subscription,
+ email,
+ function (error, possible, reason) {
if (error) {
return callback(error)
}
-
- const opts = {
- to: email,
- inviter,
- acceptInviteUrl: `${settings.siteUrl}/subscription/invites/${invite.token}/`,
- appName: settings.appName
+ if (!possible) {
+ return callback(reason)
}
- EmailHandler.sendEmail('verifyEmailToJoinTeam', opts, error => {
- Object.assign(invite, { invite: true })
- callback(error, invite)
+
+ // don't send invites when inviting self; add user directly to the group
+ const isInvitingSelf = inviter.emails.some(
+ emailData => emailData.email === email
+ )
+ if (isInvitingSelf) {
+ return SubscriptionUpdater.addUserToGroup(
+ subscription._id,
+ inviter._id,
+ err => {
+ if (err) {
+ return callback(err)
+ }
+
+ // legacy: remove any invite that might have been created in the past
+ removeInviteFromTeam(subscription._id, email, error => {
+ const inviteUserData = {
+ email: inviter.email,
+ first_name: inviter.first_name,
+ last_name: inviter.last_name,
+ invite: false
+ }
+ callback(error, inviteUserData)
+ })
+ }
+ )
+ }
+
+ const inviterName = getInviterName(inviter)
+ let invite = subscription.teamInvites.find(
+ invite => invite.email === email
+ )
+
+ if (invite) {
+ invite.sentAt = new Date()
+ } else {
+ invite = {
+ email,
+ inviterName,
+ token: crypto.randomBytes(32).toString('hex'),
+ sentAt: new Date()
+ }
+ subscription.teamInvites.push(invite)
+ }
+
+ subscription.save(function (error) {
+ if (error) {
+ return callback(error)
+ }
+
+ const opts = {
+ to: email,
+ inviter,
+ acceptInviteUrl: `${settings.siteUrl}/subscription/invites/${invite.token}/`,
+ appName: settings.appName
+ }
+ EmailHandler.sendEmail('verifyEmailToJoinTeam', opts, error => {
+ Object.assign(invite, { invite: true })
+ callback(error, invite)
+ })
})
- })
- })
+ }
+ )
}
-var removeInviteFromTeam = function(subscriptionId, email, callback) {
+var removeInviteFromTeam = function (subscriptionId, email, callback) {
const searchConditions = { _id: new ObjectId(subscriptionId.toString()) }
const removeInvite = { $pull: { teamInvites: { email } } }
@@ -227,7 +231,7 @@ var removeLegacyInvite = (subscriptionId, email, callback) =>
callback
)
-var checkIfInviteIsPossible = function(subscription, email, callback) {
+var checkIfInviteIsPossible = function (subscription, email, callback) {
if (!subscription.groupPlan) {
logger.log(
{ subscriptionId: subscription.id },
@@ -244,7 +248,7 @@ var checkIfInviteIsPossible = function(subscription, email, callback) {
return callback(null, false, { limitReached: true })
}
- UserGetter.getUserByAnyEmail(email, function(error, existingUser) {
+ UserGetter.getUserByAnyEmail(email, function (error, existingUser) {
if (error) {
return callback(error)
}
@@ -268,7 +272,7 @@ var checkIfInviteIsPossible = function(subscription, email, callback) {
})
}
-var getInviterName = function(inviter) {
+var getInviterName = function (inviter) {
let inviterName
if (inviter.first_name && inviter.last_name) {
inviterName = `${inviter.first_name} ${inviter.last_name} (${inviter.email})`
diff --git a/services/web/app/src/Features/Subscription/V1SubscriptionManager.js b/services/web/app/src/Features/Subscription/V1SubscriptionManager.js
index 033ca24a17..d13ea4c960 100644
--- a/services/web/app/src/Features/Subscription/V1SubscriptionManager.js
+++ b/services/web/app/src/Features/Subscription/V1SubscriptionManager.js
@@ -26,7 +26,7 @@ module.exports = V1SubscriptionManager = {
// - 'v1_free'
getPlanCodeFromV1(userId, callback) {
if (callback == null) {
- callback = function(err, planCode, v1Id) {}
+ callback = function (err, planCode, v1Id) {}
}
return V1SubscriptionManager._v1Request(
userId,
@@ -36,7 +36,7 @@ module.exports = V1SubscriptionManager = {
return `/api/v1/sharelatex/users/${v1Id}/plan_code`
}
},
- function(error, body, v1Id) {
+ function (error, body, v1Id) {
if (error != null) {
return callback(error)
}
@@ -54,7 +54,7 @@ module.exports = V1SubscriptionManager = {
getSubscriptionsFromV1(userId, callback) {
if (callback == null) {
- callback = function(err, subscriptions, v1Id) {}
+ callback = function (err, subscriptions, v1Id) {}
}
return V1SubscriptionManager._v1Request(
userId,
@@ -70,7 +70,7 @@ module.exports = V1SubscriptionManager = {
getSubscriptionStatusFromV1(userId, callback) {
if (callback == null) {
- callback = function(err, status) {}
+ callback = function (err, status) {}
}
return V1SubscriptionManager._v1Request(
userId,
@@ -86,7 +86,7 @@ module.exports = V1SubscriptionManager = {
cancelV1Subscription(userId, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
return V1SubscriptionManager._v1Request(
userId,
@@ -102,22 +102,23 @@ module.exports = V1SubscriptionManager = {
v1IdForUser(userId, callback) {
if (callback == null) {
- callback = function(err, v1Id) {}
+ callback = function (err, v1Id) {}
}
- return UserGetter.getUser(userId, { 'overleaf.id': 1 }, function(
- err,
- user
- ) {
- if (err != null) {
- return callback(err)
- }
- const v1Id = __guard__(
- user != null ? user.overleaf : undefined,
- x => x.id
- )
+ return UserGetter.getUser(
+ userId,
+ { 'overleaf.id': 1 },
+ function (err, user) {
+ if (err != null) {
+ return callback(err)
+ }
+ const v1Id = __guard__(
+ user != null ? user.overleaf : undefined,
+ x => x.id
+ )
- return callback(null, v1Id)
- })
+ return callback(null, v1Id)
+ }
+ )
},
// v1 accounts created before migration to v2 had github and mendeley for free
@@ -140,13 +141,13 @@ module.exports = V1SubscriptionManager = {
_v1Request(userId, options, callback) {
if (callback == null) {
- callback = function(err, body, v1Id) {}
+ callback = function (err, body, v1Id) {}
}
if (!settings.apis.v1.url) {
return callback(null, null)
}
- return V1SubscriptionManager.v1IdForUser(userId, function(err, v1Id) {
+ return V1SubscriptionManager.v1IdForUser(userId, function (err, v1Id) {
if (err != null) {
return callback(err)
}
@@ -167,7 +168,7 @@ module.exports = V1SubscriptionManager = {
json: true,
timeout: 15 * 1000
},
- function(error, response, body) {
+ function (error, response, body) {
if (error != null) {
return callback(
new V1ConnectionError({
diff --git a/services/web/app/src/Features/SystemMessages/SystemMessageManager.js b/services/web/app/src/Features/SystemMessages/SystemMessageManager.js
index 3cd6d9389d..99e8873de6 100644
--- a/services/web/app/src/Features/SystemMessages/SystemMessageManager.js
+++ b/services/web/app/src/Features/SystemMessages/SystemMessageManager.js
@@ -15,28 +15,28 @@ const { SystemMessage } = require('../../models/SystemMessage')
module.exports = SystemMessageManager = {
getMessages(callback) {
if (callback == null) {
- callback = function(error, messages) {}
+ callback = function (error, messages) {}
}
callback(null, this._cachedMessages)
},
getMessagesFromDB(callback) {
if (callback == null) {
- callback = function(error, messages) {}
+ callback = function (error, messages) {}
}
return SystemMessage.find({}, callback)
},
clearMessages(callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return SystemMessage.deleteMany({}, callback)
},
createMessage(content, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
const message = new SystemMessage({ content })
return message.save(callback)
diff --git a/services/web/app/src/Features/Tags/TagsController.js b/services/web/app/src/Features/Tags/TagsController.js
index 19756cc47a..95913d279e 100644
--- a/services/web/app/src/Features/Tags/TagsController.js
+++ b/services/web/app/src/Features/Tags/TagsController.js
@@ -7,7 +7,7 @@ const TagsController = {
if (!userId) {
return next(new Errors.NotFoundError())
}
- TagsHandler.getAllTags(userId, function(error, allTags) {
+ TagsHandler.getAllTags(userId, function (error, allTags) {
if (error != null) {
return next(error)
}
@@ -28,7 +28,7 @@ const TagsController = {
createTag(req, res, next) {
const userId = AuthenticationController.getLoggedInUserId(req)
const { name } = req.body
- TagsHandler.createTag(userId, name, function(error, tag) {
+ TagsHandler.createTag(userId, name, function (error, tag) {
if (error != null) {
return next(error)
}
@@ -39,7 +39,7 @@ const TagsController = {
addProjectToTag(req, res, next) {
const userId = AuthenticationController.getLoggedInUserId(req)
const { tagId, projectId } = req.params
- TagsHandler.addProjectToTag(userId, tagId, projectId, function(error) {
+ TagsHandler.addProjectToTag(userId, tagId, projectId, function (error) {
if (error) {
return next(error)
}
@@ -50,18 +50,23 @@ const TagsController = {
removeProjectFromTag(req, res, next) {
const userId = AuthenticationController.getLoggedInUserId(req)
const { tagId, projectId } = req.params
- TagsHandler.removeProjectFromTag(userId, tagId, projectId, function(error) {
- if (error) {
- return next(error)
+ TagsHandler.removeProjectFromTag(
+ userId,
+ tagId,
+ projectId,
+ function (error) {
+ if (error) {
+ return next(error)
+ }
+ res.status(204).end()
}
- res.status(204).end()
- })
+ )
},
deleteTag(req, res, next) {
const userId = AuthenticationController.getLoggedInUserId(req)
const { tagId } = req.params
- TagsHandler.deleteTag(userId, tagId, function(error) {
+ TagsHandler.deleteTag(userId, tagId, function (error) {
if (error) {
return next(error)
}
@@ -76,7 +81,7 @@ const TagsController = {
if (!name) {
return res.status(400).end()
}
- TagsHandler.renameTag(userId, tagId, name, function(error) {
+ TagsHandler.renameTag(userId, tagId, name, function (error) {
if (error) {
return next(error)
}
diff --git a/services/web/app/src/Features/Tags/TagsHandler.js b/services/web/app/src/Features/Tags/TagsHandler.js
index cee8e9401b..36d2a339c6 100644
--- a/services/web/app/src/Features/Tags/TagsHandler.js
+++ b/services/web/app/src/Features/Tags/TagsHandler.js
@@ -7,9 +7,9 @@ function getAllTags(userId, callback) {
function createTag(userId, name, callback) {
if (!callback) {
- callback = function() {}
+ callback = function () {}
}
- Tag.create({ user_id: userId, name }, function(err, tag) {
+ Tag.create({ user_id: userId, name }, function (err, tag) {
// on duplicate key error return existing tag
if (err && err.code === 11000) {
return Tag.findOne({ user_id: userId, name }, callback)
@@ -20,7 +20,7 @@ function createTag(userId, name, callback) {
function renameTag(userId, tagId, name, callback) {
if (!callback) {
- callback = function() {}
+ callback = function () {}
}
Tag.updateOne(
{
@@ -38,7 +38,7 @@ function renameTag(userId, tagId, name, callback) {
function deleteTag(userId, tagId, callback) {
if (!callback) {
- callback = function() {}
+ callback = function () {}
}
Tag.deleteOne(
{
@@ -52,7 +52,7 @@ function deleteTag(userId, tagId, callback) {
// TODO: unused?
function updateTagUserIds(oldUserId, newUserId, callback) {
if (!callback) {
- callback = function() {}
+ callback = function () {}
}
const searchOps = { user_id: oldUserId }
const updateOperation = { $set: { user_id: newUserId } }
@@ -61,7 +61,7 @@ function updateTagUserIds(oldUserId, newUserId, callback) {
function removeProjectFromTag(userId, tagId, projectId, callback) {
if (!callback) {
- callback = function() {}
+ callback = function () {}
}
const searchOps = {
_id: tagId,
@@ -73,7 +73,7 @@ function removeProjectFromTag(userId, tagId, projectId, callback) {
function addProjectToTag(userId, tagId, projectId, callback) {
if (!callback) {
- callback = function() {}
+ callback = function () {}
}
const searchOps = {
_id: tagId,
@@ -85,7 +85,7 @@ function addProjectToTag(userId, tagId, projectId, callback) {
function addProjectToTagName(userId, name, projectId, callback) {
if (!callback) {
- callback = function() {}
+ callback = function () {}
}
const searchOps = {
name,
diff --git a/services/web/app/src/Features/Templates/TemplatesController.js b/services/web/app/src/Features/Templates/TemplatesController.js
index 853c1f53f2..f060083cb9 100644
--- a/services/web/app/src/Features/Templates/TemplatesController.js
+++ b/services/web/app/src/Features/Templates/TemplatesController.js
@@ -57,7 +57,7 @@ module.exports = TemplatesController = {
req.body.templateVersionId,
user_id,
req.body.imageName,
- function(err, project) {
+ function (err, project) {
if (err != null) {
return next(err)
}
diff --git a/services/web/app/src/Features/Templates/TemplatesManager.js b/services/web/app/src/Features/Templates/TemplatesManager.js
index 07222b4f81..b023aba5bc 100644
--- a/services/web/app/src/Features/Templates/TemplatesManager.js
+++ b/services/web/app/src/Features/Templates/TemplatesManager.js
@@ -49,11 +49,11 @@ const TemplatesManager = {
},
timeout: 60 * 1000
})
- zipReq.on('error', function(err) {
+ zipReq.on('error', function (err) {
logger.warn({ err }, 'error getting zip from template API')
return callback(err)
})
- return FileWriter.ensureDumpFolderExists(function(err) {
+ return FileWriter.ensureDumpFolderExists(function (err) {
if (err != null) {
return callback(err)
}
@@ -65,7 +65,7 @@ const TemplatesManager = {
fromV1TemplateId: templateId,
fromV1TemplateVersionId: templateVersionId
}
- writeStream.on('close', function() {
+ writeStream.on('close', function () {
if (zipReq.response.statusCode !== 200) {
logger.warn(
{ uri: zipUrl, statusCode: zipReq.response.statusCode },
@@ -78,7 +78,7 @@ const TemplatesManager = {
projectName,
dumpPath,
attributes,
- function(err, project) {
+ function (err, project) {
if (err != null) {
OError.tag(err, 'problem building project from zip', {
zipReq
@@ -97,11 +97,11 @@ const TemplatesManager = {
cb
)
],
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
- fs.unlink(dumpPath, function(err) {
+ fs.unlink(dumpPath, function (err) {
if (err != null) {
return logger.err({ err }, 'error unlinking template zip')
}
@@ -114,7 +114,7 @@ const TemplatesManager = {
{ _id: project._id },
update,
{},
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
diff --git a/services/web/app/src/Features/ThirdPartyDataStore/TpdsController.js b/services/web/app/src/Features/ThirdPartyDataStore/TpdsController.js
index 29cffd97fa..bac877a9d2 100644
--- a/services/web/app/src/Features/ThirdPartyDataStore/TpdsController.js
+++ b/services/web/app/src/Features/ThirdPartyDataStore/TpdsController.js
@@ -119,7 +119,7 @@ module.exports = {
}
},
- parseParams: (parseParams = function(req) {
+ parseParams: (parseParams = function (req) {
let filePath, projectName
let path = req.params[0]
const userId = req.params.user_id
diff --git a/services/web/app/src/Features/ThirdPartyDataStore/UpdateMerger.js b/services/web/app/src/Features/ThirdPartyDataStore/UpdateMerger.js
index 6cdd0bca90..4dae2ecefd 100644
--- a/services/web/app/src/Features/ThirdPartyDataStore/UpdateMerger.js
+++ b/services/web/app/src/Features/ThirdPartyDataStore/UpdateMerger.js
@@ -25,166 +25,173 @@ const ProjectEntityHandler = require('../Project/ProjectEntityHandler')
module.exports = UpdateMerger = {
mergeUpdate(user_id, project_id, path, updateRequest, source, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return FileWriter.writeStreamToDisk(project_id, updateRequest, function(
- err,
- fsPath
- ) {
- if (err != null) {
- return callback(err)
+ return FileWriter.writeStreamToDisk(
+ project_id,
+ updateRequest,
+ function (err, fsPath) {
+ if (err != null) {
+ return callback(err)
+ }
+ return UpdateMerger._mergeUpdate(
+ user_id,
+ project_id,
+ path,
+ fsPath,
+ source,
+ mergeErr =>
+ fs.unlink(fsPath, function (deleteErr) {
+ if (deleteErr != null) {
+ logger.err({ project_id, fsPath }, 'error deleting file')
+ }
+ return callback(mergeErr)
+ })
+ )
}
- return UpdateMerger._mergeUpdate(
- user_id,
- project_id,
- path,
- fsPath,
- source,
- mergeErr =>
- fs.unlink(fsPath, function(deleteErr) {
- if (deleteErr != null) {
- logger.err({ project_id, fsPath }, 'error deleting file')
- }
- return callback(mergeErr)
- })
- )
- })
+ )
},
_findExistingFileType(project_id, path, callback) {
- ProjectEntityHandler.getAllEntities(project_id, function(err, docs, files) {
- if (err != null) {
- return callback(err)
+ ProjectEntityHandler.getAllEntities(
+ project_id,
+ function (err, docs, files) {
+ if (err != null) {
+ return callback(err)
+ }
+ var existingFileType = null
+ if (_.some(files, f => f.path === path)) {
+ existingFileType = 'file'
+ }
+ if (_.some(docs, d => d.path === path)) {
+ existingFileType = 'doc'
+ }
+ callback(null, existingFileType)
}
- var existingFileType = null
- if (_.some(files, f => f.path === path)) {
- existingFileType = 'file'
- }
- if (_.some(docs, d => d.path === path)) {
- existingFileType = 'doc'
- }
- callback(null, existingFileType)
- })
+ )
},
_determineFileType(project_id, path, fsPath, callback) {
if (callback == null) {
- callback = function(err, fileType) {}
+ callback = function (err, fileType) {}
}
// check if there is an existing file with the same path (we either need
// to overwrite it or delete it)
- UpdateMerger._findExistingFileType(project_id, path, function(
- err,
- existingFileType
- ) {
- if (err) {
- return callback(err)
- }
- // determine whether the update should create a doc or binary file
- FileTypeManager.getType(path, fsPath, function(
- err,
- { binary, encoding }
- ) {
- if (err != null) {
+ UpdateMerger._findExistingFileType(
+ project_id,
+ path,
+ function (err, existingFileType) {
+ if (err) {
return callback(err)
}
+ // determine whether the update should create a doc or binary file
+ FileTypeManager.getType(
+ path,
+ fsPath,
+ function (err, { binary, encoding }) {
+ if (err != null) {
+ return callback(err)
+ }
- // If we receive a non-utf8 encoding, we won't be able to keep things in
- // sync, so we'll treat non-utf8 files as binary
- const isBinary = binary || encoding !== 'utf-8'
+ // If we receive a non-utf8 encoding, we won't be able to keep things in
+ // sync, so we'll treat non-utf8 files as binary
+ const isBinary = binary || encoding !== 'utf-8'
- // Existing | Update | Action
- // ---------|-----------|-------
- // file | isBinary | existing-file
- // file | !isBinary | existing-file
- // doc | isBinary | new-file, delete-existing-doc
- // doc | !isBinary | existing-doc
- // null | isBinary | new-file
- // null | !isBinary | new-doc
+ // Existing | Update | Action
+ // ---------|-----------|-------
+ // file | isBinary | existing-file
+ // file | !isBinary | existing-file
+ // doc | isBinary | new-file, delete-existing-doc
+ // doc | !isBinary | existing-doc
+ // null | isBinary | new-file
+ // null | !isBinary | new-doc
- // if a binary file already exists, always keep it as a binary file
- // even if the update looks like a text file
- if (existingFileType === 'file') {
- return callback(null, 'existing-file')
- }
+ // if a binary file already exists, always keep it as a binary file
+ // even if the update looks like a text file
+ if (existingFileType === 'file') {
+ return callback(null, 'existing-file')
+ }
- // if there is an existing doc, keep it as a doc except when the
- // incoming update is binary. In that case delete the doc and replace
- // it with a new file.
- if (existingFileType === 'doc') {
- if (isBinary) {
- return callback(null, 'new-file', 'delete-existing-doc')
- } else {
- return callback(null, 'existing-doc')
+ // if there is an existing doc, keep it as a doc except when the
+ // incoming update is binary. In that case delete the doc and replace
+ // it with a new file.
+ if (existingFileType === 'doc') {
+ if (isBinary) {
+ return callback(null, 'new-file', 'delete-existing-doc')
+ } else {
+ return callback(null, 'existing-doc')
+ }
+ }
+ // if there no existing file, create a file or doc as needed
+ return callback(null, isBinary ? 'new-file' : 'new-doc')
}
- }
- // if there no existing file, create a file or doc as needed
- return callback(null, isBinary ? 'new-file' : 'new-doc')
- })
- })
+ )
+ }
+ )
},
_mergeUpdate(user_id, project_id, path, fsPath, source, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return UpdateMerger._determineFileType(project_id, path, fsPath, function(
- err,
- fileType,
- deleteOriginalEntity
- ) {
- if (err != null) {
- return callback(err)
+ return UpdateMerger._determineFileType(
+ project_id,
+ path,
+ fsPath,
+ function (err, fileType, deleteOriginalEntity) {
+ if (err != null) {
+ return callback(err)
+ }
+ async.series(
+ [
+ function (cb) {
+ if (deleteOriginalEntity) {
+ // currently we only delete docs
+ UpdateMerger.deleteUpdate(user_id, project_id, path, source, cb)
+ } else {
+ cb()
+ }
+ },
+ function (cb) {
+ if (['existing-file', 'new-file'].includes(fileType)) {
+ return UpdateMerger.p.processFile(
+ project_id,
+ fsPath,
+ path,
+ source,
+ user_id,
+ cb
+ )
+ } else if (['existing-doc', 'new-doc'].includes(fileType)) {
+ return UpdateMerger.p.processDoc(
+ project_id,
+ user_id,
+ fsPath,
+ path,
+ source,
+ cb
+ )
+ } else {
+ return cb(new Error('unrecognized file'))
+ }
+ }
+ ],
+ callback
+ )
}
- async.series(
- [
- function(cb) {
- if (deleteOriginalEntity) {
- // currently we only delete docs
- UpdateMerger.deleteUpdate(user_id, project_id, path, source, cb)
- } else {
- cb()
- }
- },
- function(cb) {
- if (['existing-file', 'new-file'].includes(fileType)) {
- return UpdateMerger.p.processFile(
- project_id,
- fsPath,
- path,
- source,
- user_id,
- cb
- )
- } else if (['existing-doc', 'new-doc'].includes(fileType)) {
- return UpdateMerger.p.processDoc(
- project_id,
- user_id,
- fsPath,
- path,
- source,
- cb
- )
- } else {
- return cb(new Error('unrecognized file'))
- }
- }
- ],
- callback
- )
- })
+ )
},
deleteUpdate(user_id, project_id, path, source, callback) {
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
return EditorController.deleteEntityWithPath(
project_id,
path,
source,
user_id,
- function() {
+ function () {
return callback()
}
)
@@ -192,32 +199,32 @@ module.exports = UpdateMerger = {
p: {
processDoc(project_id, user_id, fsPath, path, source, callback) {
- return UpdateMerger.p.readFileIntoTextArray(fsPath, function(
- err,
- docLines
- ) {
- if (err != null) {
- OError.tag(
- err,
- 'error reading file into text array for process doc update',
- {
- project_id
- }
- )
- return callback(err)
- }
- logger.log({ docLines }, 'processing doc update from tpds')
- return EditorController.upsertDocWithPath(
- project_id,
- path,
- docLines,
- source,
- user_id,
- function(err) {
+ return UpdateMerger.p.readFileIntoTextArray(
+ fsPath,
+ function (err, docLines) {
+ if (err != null) {
+ OError.tag(
+ err,
+ 'error reading file into text array for process doc update',
+ {
+ project_id
+ }
+ )
return callback(err)
}
- )
- })
+ logger.log({ docLines }, 'processing doc update from tpds')
+ return EditorController.upsertDocWithPath(
+ project_id,
+ path,
+ docLines,
+ source,
+ user_id,
+ function (err) {
+ return callback(err)
+ }
+ )
+ }
+ )
},
processFile(project_id, fsPath, path, source, user_id, callback) {
@@ -228,14 +235,14 @@ module.exports = UpdateMerger = {
null,
source,
user_id,
- function(err) {
+ function (err) {
return callback(err)
}
)
},
readFileIntoTextArray(path, callback) {
- return fs.readFile(path, 'utf8', function(error, content) {
+ return fs.readFile(path, 'utf8', function (error, content) {
if (content == null) {
content = ''
}
diff --git a/services/web/app/src/Features/TokenAccess/TokenAccessHandler.js b/services/web/app/src/Features/TokenAccess/TokenAccessHandler.js
index 7a326fec81..fd70ec224d 100644
--- a/services/web/app/src/Features/TokenAccess/TokenAccessHandler.js
+++ b/services/web/app/src/Features/TokenAccess/TokenAccessHandler.js
@@ -121,7 +121,7 @@ const TokenAccessHandler = {
{
'tokens.readAndWritePrefix': numerics
},
- function(err, project) {
+ function (err, project) {
if (err != null) {
return callback(err)
}
@@ -263,7 +263,7 @@ const TokenAccessHandler = {
}
V1Api.request(
{ url: `/api/v1/sharelatex/docs/${token}/is_published` },
- function(err, response, body) {
+ function (err, response, body) {
if (err != null) {
return callback(err)
}
@@ -279,7 +279,7 @@ const TokenAccessHandler = {
exported: false
})
}
- UserGetter.getUser(v2UserId, { overleaf: 1 }, function(err, user) {
+ UserGetter.getUser(v2UserId, { overleaf: 1 }, function (err, user) {
if (err != null) {
return callback(err)
}
@@ -289,7 +289,7 @@ const TokenAccessHandler = {
}
V1Api.request(
{ url: `/api/v1/sharelatex/users/${v1UserId}/docs/${token}/info` },
- function(err, response, body) {
+ function (err, response, body) {
if (err != null) {
return callback(err)
}
diff --git a/services/web/app/src/Features/TokenGenerator/TokenGenerator.js b/services/web/app/src/Features/TokenGenerator/TokenGenerator.js
index d2ae7ef390..bb2059a576 100644
--- a/services/web/app/src/Features/TokenGenerator/TokenGenerator.js
+++ b/services/web/app/src/Features/TokenGenerator/TokenGenerator.js
@@ -61,11 +61,11 @@ const TokenGenerator = {
generateUniqueReadOnlyToken(callback) {
if (callback == null) {
- callback = function(err, token) {}
+ callback = function (err, token) {}
}
return Async.retry(
10,
- function(cb) {
+ function (cb) {
const token = TokenGenerator.readOnlyToken()
if (!Features.hasFeature('overleaf-integration')) {
@@ -77,7 +77,7 @@ const TokenGenerator = {
url: `/api/v1/sharelatex/docs/read_token/${token}/exists`,
json: true
},
- function(err, response, body) {
+ function (err, response, body) {
if (err != null) {
return cb(err)
}
diff --git a/services/web/app/src/Features/Uploads/ArchiveManager.js b/services/web/app/src/Features/Uploads/ArchiveManager.js
index b64cd08e7e..23d8ee7fd6 100644
--- a/services/web/app/src/Features/Uploads/ArchiveManager.js
+++ b/services/web/app/src/Features/Uploads/ArchiveManager.js
@@ -33,12 +33,12 @@ const ONE_MEG = 1024 * 1024
const ArchiveManager = {
_isZipTooLarge(source, callback) {
if (callback == null) {
- callback = function(err, isTooLarge) {}
+ callback = function (err, isTooLarge) {}
}
callback = _.once(callback)
let totalSizeInBytes = null
- return yauzl.open(source, { lazyEntries: true }, function(err, zipfile) {
+ return yauzl.open(source, { lazyEntries: true }, function (err, zipfile) {
if (err != null) {
return callback(new InvalidZipFileError().withCause(err))
}
@@ -54,13 +54,13 @@ const ArchiveManager = {
// read all the entries
zipfile.readEntry()
- zipfile.on('entry', function(entry) {
+ zipfile.on('entry', function (entry) {
totalSizeInBytes += entry.uncompressedSize
return zipfile.readEntry()
}) // get the next entry
// no more entries to read
- return zipfile.on('end', function() {
+ return zipfile.on('end', function () {
if (totalSizeInBytes == null || isNaN(totalSizeInBytes)) {
logger.warn(
{ source, totalSizeInBytes },
@@ -79,7 +79,7 @@ const ArchiveManager = {
_checkFilePath(entry, destination, callback) {
// transform backslashes to forwardslashes to accommodate badly-behaved zip archives
if (callback == null) {
- callback = function(err, destFile) {}
+ callback = function (err, destFile) {}
}
const transformedFilename = entry.fileName.replace(/\\/g, '/')
// check if the entry is a directory
@@ -104,25 +104,25 @@ const ArchiveManager = {
_writeFileEntry(zipfile, entry, destFile, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
callback = _.once(callback)
- return zipfile.openReadStream(entry, function(err, readStream) {
+ return zipfile.openReadStream(entry, function (err, readStream) {
if (err != null) {
return callback(err)
}
readStream.on('error', callback)
readStream.on('end', callback)
- const errorHandler = function(err) {
+ const errorHandler = function (err) {
// clean up before calling callback
readStream.unpipe()
readStream.destroy()
return callback(err)
}
- return fse.ensureDir(Path.dirname(destFile), function(err) {
+ return fse.ensureDir(Path.dirname(destFile), function (err) {
if (err != null) {
return errorHandler(err)
}
@@ -135,11 +135,11 @@ const ArchiveManager = {
_extractZipFiles(source, destination, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
callback = _.once(callback)
- return yauzl.open(source, { lazyEntries: true }, function(err, zipfile) {
+ return yauzl.open(source, { lazyEntries: true }, function (err, zipfile) {
if (err != null) {
return callback(err)
}
@@ -148,41 +148,45 @@ const ArchiveManager = {
zipfile.readEntry()
let entryFileCount = 0
- zipfile.on('entry', function(entry) {
- return ArchiveManager._checkFilePath(entry, destination, function(
- err,
- destFile
- ) {
- if (err != null) {
- logger.warn({ err, source, destination }, 'skipping bad file path')
- zipfile.readEntry() // bad path, just skip to the next file
- return
- }
- if (destFile != null) {
- // only write files
- return ArchiveManager._writeFileEntry(
- zipfile,
- entry,
- destFile,
- function(err) {
- if (err != null) {
- OError.tag(err, 'error unzipping file entry', {
- source,
- destFile
- })
- zipfile.close() // bail out, stop reading file entries
- return callback(err)
- } else {
- entryFileCount++
- return zipfile.readEntry()
+ zipfile.on('entry', function (entry) {
+ return ArchiveManager._checkFilePath(
+ entry,
+ destination,
+ function (err, destFile) {
+ if (err != null) {
+ logger.warn(
+ { err, source, destination },
+ 'skipping bad file path'
+ )
+ zipfile.readEntry() // bad path, just skip to the next file
+ return
+ }
+ if (destFile != null) {
+ // only write files
+ return ArchiveManager._writeFileEntry(
+ zipfile,
+ entry,
+ destFile,
+ function (err) {
+ if (err != null) {
+ OError.tag(err, 'error unzipping file entry', {
+ source,
+ destFile
+ })
+ zipfile.close() // bail out, stop reading file entries
+ return callback(err)
+ } else {
+ entryFileCount++
+ return zipfile.readEntry()
+ }
}
- }
- ) // continue to the next file
- } else {
- // if it's a directory, continue
- return zipfile.readEntry()
+ ) // continue to the next file
+ } else {
+ // if it's a directory, continue
+ return zipfile.readEntry()
+ }
}
- })
+ )
})
// no more entries to read
return zipfile.on('end', () => {
@@ -197,14 +201,14 @@ const ArchiveManager = {
extractZipArchive(source, destination, _callback) {
if (_callback == null) {
- _callback = function(err) {}
+ _callback = function (err) {}
}
- const callback = function(...args) {
+ const callback = function (...args) {
_callback(...Array.from(args || []))
- return (_callback = function() {})
+ return (_callback = function () {})
}
- return ArchiveManager._isZipTooLarge(source, function(err, isTooLarge) {
+ return ArchiveManager._isZipTooLarge(source, function (err, isTooLarge) {
if (err != null) {
OError.tag(err, 'error checking size of zip file')
return callback(err)
@@ -217,34 +221,36 @@ const ArchiveManager = {
const timer = new metrics.Timer('unzipDirectory')
logger.log({ source, destination }, 'unzipping file')
- return ArchiveManager._extractZipFiles(source, destination, function(
- err
- ) {
- timer.done()
- if (err != null) {
- OError.tag(err, 'unzip failed', {
- source,
- destination
- })
- return callback(err)
- } else {
- return callback()
+ return ArchiveManager._extractZipFiles(
+ source,
+ destination,
+ function (err) {
+ timer.done()
+ if (err != null) {
+ OError.tag(err, 'unzip failed', {
+ source,
+ destination
+ })
+ return callback(err)
+ } else {
+ return callback()
+ }
}
- })
+ )
})
},
findTopLevelDirectory(directory, callback) {
if (callback == null) {
- callback = function(error, topLevelDir) {}
+ callback = function (error, topLevelDir) {}
}
- return fs.readdir(directory, function(error, files) {
+ return fs.readdir(directory, function (error, files) {
if (error != null) {
return callback(error)
}
if (files.length === 1) {
const childPath = Path.join(directory, files[0])
- return fs.stat(childPath, function(error, stat) {
+ return fs.stat(childPath, function (error, stat) {
if (error != null) {
return callback(error)
}
diff --git a/services/web/app/src/Features/Uploads/ProjectUploadController.js b/services/web/app/src/Features/Uploads/ProjectUploadController.js
index 6587351f57..d3d60dc060 100644
--- a/services/web/app/src/Features/Uploads/ProjectUploadController.js
+++ b/services/web/app/src/Features/Uploads/ProjectUploadController.js
@@ -40,8 +40,8 @@ module.exports = ProjectUploadController = {
user_id,
name,
path,
- function(error, project) {
- fs.unlink(path, function() {})
+ function (error, project) {
+ fs.unlink(path, function () {})
timer.done()
if (error != null) {
logger.error(
@@ -88,8 +88,8 @@ module.exports = ProjectUploadController = {
name,
path,
true,
- function(error, entity) {
- fs.unlink(path, function() {})
+ function (error, entity) {
+ fs.unlink(path, function () {})
timer.done()
if (error != null) {
logger.error(
@@ -132,7 +132,7 @@ module.exports = ProjectUploadController = {
.status(500)
.json({ success: false, error: req.i18n.translate('upload_failed') })
}
- return upload.single('qqfile')(req, res, function(err) {
+ return upload.single('qqfile')(req, res, function (err) {
if (err instanceof multer.MulterError && err.code === 'LIMIT_FILE_SIZE') {
return res
.status(422)
diff --git a/services/web/app/src/Features/User/ThirdPartyIdentityManager.js b/services/web/app/src/Features/User/ThirdPartyIdentityManager.js
index ec6341cbed..2d9530d076 100644
--- a/services/web/app/src/Features/User/ThirdPartyIdentityManager.js
+++ b/services/web/app/src/Features/User/ThirdPartyIdentityManager.js
@@ -22,7 +22,7 @@ function getUser(providerId, externalUserId, callback) {
)
}
const query = _getUserQuery(providerId, externalUserId)
- User.findOne(query, function(err, user) {
+ User.findOne(query, function (err, user) {
if (err != null) {
return callback(err)
}
@@ -34,25 +34,26 @@ function getUser(providerId, externalUserId, callback) {
}
function login(providerId, externalUserId, externalData, callback) {
- ThirdPartyIdentityManager.getUser(providerId, externalUserId, function(
- err,
- user
- ) {
- if (err != null) {
- return callback(err)
+ ThirdPartyIdentityManager.getUser(
+ providerId,
+ externalUserId,
+ function (err, user) {
+ if (err != null) {
+ return callback(err)
+ }
+ if (!externalData) {
+ return callback(null, user)
+ }
+ const query = _getUserQuery(providerId, externalUserId)
+ const update = _thirdPartyIdentifierUpdate(
+ user,
+ providerId,
+ externalUserId,
+ externalData
+ )
+ User.findOneAndUpdate(query, update, { new: true }, callback)
}
- if (!externalData) {
- return callback(null, user)
- }
- const query = _getUserQuery(providerId, externalUserId)
- const update = _thirdPartyIdentifierUpdate(
- user,
- providerId,
- externalUserId,
- externalData
- )
- User.findOneAndUpdate(query, update, { new: true }, callback)
- })
+ )
}
function link(
@@ -115,7 +116,7 @@ function link(
userId,
providerId,
auditLog,
- function(err) {
+ function (err) {
if (err != null) {
return callback(err)
}
diff --git a/services/web/app/src/Features/User/UserCreator.js b/services/web/app/src/Features/User/UserCreator.js
index 68791e6cdb..38fa15226f 100644
--- a/services/web/app/src/Features/User/UserCreator.js
+++ b/services/web/app/src/Features/User/UserCreator.js
@@ -45,11 +45,7 @@ async function createNewUser(attributes, options = {}) {
user.featureSwitches.pdfng = true
}
- const reversedHostname = user.email
- .split('@')[1]
- .split('')
- .reverse()
- .join('')
+ const reversedHostname = user.email.split('@')[1].split('').reverse().join('')
const emailData = {
email: user.email,
diff --git a/services/web/app/src/Features/User/UserEmailsConfirmationHandler.js b/services/web/app/src/Features/User/UserEmailsConfirmationHandler.js
index dec6295ebf..ba36fcc0e2 100644
--- a/services/web/app/src/Features/User/UserEmailsConfirmationHandler.js
+++ b/services/web/app/src/Features/User/UserEmailsConfirmationHandler.js
@@ -31,7 +31,7 @@ function sendConfirmationEmail(userId, email, emailTemplate, callback) {
'email_confirmation',
data,
{ expiresIn: TOKEN_EXPIRY_IN_S },
- function(err, token) {
+ function (err, token) {
if (err) {
return callback(err)
}
@@ -52,7 +52,7 @@ const UserEmailsConfirmationHandler = {
OneTimeTokenHandler.getValueFromTokenAndExpire(
'email_confirmation',
token,
- function(error, data) {
+ function (error, data) {
if (error) {
return callback(error)
}
@@ -65,7 +65,7 @@ const UserEmailsConfirmationHandler = {
if (!userId || email !== EmailHelper.parseEmail(email)) {
return callback(new Errors.NotFoundError('invalid data'))
}
- UserGetter.getUser(userId, {}, function(error, user) {
+ UserGetter.getUser(userId, {}, function (error, user) {
if (error) {
return callback(error)
}
diff --git a/services/web/app/src/Features/User/UserEmailsController.js b/services/web/app/src/Features/User/UserEmailsController.js
index 219291161c..dbe81451df 100644
--- a/services/web/app/src/Features/User/UserEmailsController.js
+++ b/services/web/app/src/Features/User/UserEmailsController.js
@@ -67,28 +67,30 @@ function resendConfirmation(req, res, next) {
if (!email) {
return res.sendStatus(422)
}
- UserGetter.getUserByAnyEmail(email, { _id: 1 }, function(error, user) {
+ UserGetter.getUserByAnyEmail(email, { _id: 1 }, function (error, user) {
if (error) {
return next(error)
}
if (!user || user._id.toString() !== userId) {
return res.sendStatus(422)
}
- UserEmailsConfirmationHandler.sendConfirmationEmail(userId, email, function(
- error
- ) {
- if (error) {
- return next(error)
+ UserEmailsConfirmationHandler.sendConfirmationEmail(
+ userId,
+ email,
+ function (error) {
+ if (error) {
+ return next(error)
+ }
+ res.sendStatus(200)
}
- res.sendStatus(200)
- })
+ )
})
}
const UserEmailsController = {
list(req, res, next) {
const userId = AuthenticationController.getLoggedInUserId(req)
- UserGetter.getUserFullEmails(userId, function(error, fullEmails) {
+ UserGetter.getUserFullEmails(userId, function (error, fullEmails) {
if (error) {
return next(error)
}
@@ -105,7 +107,7 @@ const UserEmailsController = {
return res.sendStatus(422)
}
- UserUpdater.removeEmailAddress(userId, email, function(error) {
+ UserUpdater.removeEmailAddress(userId, email, function (error) {
if (error) {
return next(error)
}
@@ -163,7 +165,7 @@ const UserEmailsController = {
email,
req.body.role,
req.body.department,
- function(error) {
+ function (error) {
if (error) {
return next(error)
}
@@ -188,19 +190,22 @@ const UserEmailsController = {
message: req.i18n.translate('confirmation_link_broken')
})
}
- UserEmailsConfirmationHandler.confirmEmailFromToken(token, function(error) {
- if (error) {
- if (error instanceof Errors.NotFoundError) {
- res.status(404).json({
- message: req.i18n.translate('confirmation_token_invalid')
- })
+ UserEmailsConfirmationHandler.confirmEmailFromToken(
+ token,
+ function (error) {
+ if (error) {
+ if (error instanceof Errors.NotFoundError) {
+ res.status(404).json({
+ message: req.i18n.translate('confirmation_token_invalid')
+ })
+ } else {
+ next(error)
+ }
} else {
- next(error)
+ res.sendStatus(200)
}
- } else {
- res.sendStatus(200)
}
- })
+ )
},
_handleEmailError(error, req, res, next) {
diff --git a/services/web/app/src/Features/User/UserGetter.js b/services/web/app/src/Features/User/UserGetter.js
index c2554e659a..20c51dcbe6 100644
--- a/services/web/app/src/Features/User/UserGetter.js
+++ b/services/web/app/src/Features/User/UserGetter.js
@@ -161,11 +161,7 @@ const UserGetter = {
},
getUsersByHostname(hostname, projection, callback) {
- const reversedHostname = hostname
- .trim()
- .split('')
- .reverse()
- .join('')
+ const reversedHostname = hostname.trim().split('').reverse().join('')
const query = {
emails: { $exists: true },
'emails.reversedHostname': reversedHostname
@@ -184,7 +180,7 @@ const UserGetter = {
// check for duplicate email address. This is also enforced at the DB level
ensureUniqueEmailAddress(newEmail, callback) {
- this.getUserByAnyEmail(newEmail, function(error, user) {
+ this.getUserByAnyEmail(newEmail, function (error, user) {
if (user) {
return callback(new Errors.EmailExistsError())
}
@@ -199,7 +195,7 @@ var decorateFullEmails = (
affiliationsData,
samlIdentifiers
) => {
- emailsData.forEach(function(emailData) {
+ emailsData.forEach(function (emailData) {
emailData.default = emailData.email === defaultEmail
const affiliation = affiliationsData.find(
diff --git a/services/web/app/src/Features/User/UserInfoController.js b/services/web/app/src/Features/User/UserInfoController.js
index d903664bc3..0f0b177baf 100644
--- a/services/web/app/src/Features/User/UserInfoController.js
+++ b/services/web/app/src/Features/User/UserInfoController.js
@@ -19,7 +19,7 @@ module.exports = UserController = {
email: true,
signUpDate: true
},
- function(error, user) {
+ function (error, user) {
if (error) {
return next(error)
}
@@ -43,7 +43,7 @@ module.exports = UserController = {
UserGetter.getUser(
query,
{ _id: true, first_name: true, last_name: true, email: true },
- function(error, user) {
+ function (error, user) {
if (error) {
return next(error)
}
diff --git a/services/web/app/src/Features/User/UserSessionsManager.js b/services/web/app/src/Features/User/UserSessionsManager.js
index bee472d70b..ba066ecb9c 100644
--- a/services/web/app/src/Features/User/UserSessionsManager.js
+++ b/services/web/app/src/Features/User/UserSessionsManager.js
@@ -27,7 +27,7 @@ UserSessionsManager = {
.multi()
.sadd(sessionSetKey, value)
.pexpire(sessionSetKey, `${Settings.cookieSessionLength}`) // in milliseconds
- .exec(function(err, response) {
+ .exec(function (err, response) {
if (err) {
OError.tag(
err,
@@ -39,14 +39,14 @@ UserSessionsManager = {
)
return callback(err)
}
- UserSessionsManager._checkSessions(user, function() {})
+ UserSessionsManager._checkSessions(user, function () {})
callback()
})
},
untrackSession(user, sessionId, callback) {
if (!callback) {
- callback = function() {}
+ callback = function () {}
}
if (!user) {
return callback(null)
@@ -60,7 +60,7 @@ UserSessionsManager = {
.multi()
.srem(sessionSetKey, value)
.pexpire(sessionSetKey, `${Settings.cookieSessionLength}`) // in milliseconds
- .exec(function(err, response) {
+ .exec(function (err, response) {
if (err) {
OError.tag(
err,
@@ -72,7 +72,7 @@ UserSessionsManager = {
)
return callback(err)
}
- UserSessionsManager._checkSessions(user, function() {})
+ UserSessionsManager._checkSessions(user, function () {})
callback()
})
},
@@ -80,7 +80,7 @@ UserSessionsManager = {
getAllUserSessions(user, exclude, callback) {
exclude = _.map(exclude, UserSessionsManager._sessionKey)
const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
- rclient.smembers(sessionSetKey, function(err, sessionKeys) {
+ rclient.smembers(sessionSetKey, function (err, sessionKeys) {
if (err) {
OError.tag(err, 'error getting all session keys for user from redis', {
user_id: user._id
@@ -96,7 +96,7 @@ UserSessionsManager = {
Async.mapSeries(
sessionKeys,
(k, cb) => rclient.get(k, cb),
- function(err, sessions) {
+ function (err, sessions) {
if (err) {
OError.tag(err, 'error getting all sessions for user from redis', {
user_id: user._id
@@ -136,7 +136,7 @@ UserSessionsManager = {
return callback(null)
}
const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
- rclient.smembers(sessionSetKey, function(err, sessionKeys) {
+ rclient.smembers(sessionSetKey, function (err, sessionKeys) {
if (err) {
OError.tag(err, 'error getting contents of UserSessions set', {
user_id: user._id,
@@ -162,7 +162,7 @@ UserSessionsManager = {
const deletions = keysToDelete.map(k => cb => rclient.del(k, cb))
- Async.series(deletions, function(err, _result) {
+ Async.series(deletions, function (err, _result) {
if (err) {
OError.tag(err, 'error revoking all sessions for user', {
user_id: user._id,
@@ -170,7 +170,7 @@ UserSessionsManager = {
})
return callback(err)
}
- rclient.srem(sessionSetKey, keysToDelete, function(err) {
+ rclient.srem(sessionSetKey, keysToDelete, function (err) {
if (err) {
OError.tag(err, 'error removing session set for user', {
user_id: user._id,
@@ -192,7 +192,7 @@ UserSessionsManager = {
rclient.pexpire(
sessionSetKey,
`${Settings.cookieSessionLength}`, // in milliseconds
- function(err, response) {
+ function (err, response) {
if (err) {
OError.tag(err, 'error while updating ttl on UserSessions set', {
user_id: user._id
@@ -209,7 +209,7 @@ UserSessionsManager = {
return callback(null)
}
const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
- rclient.smembers(sessionSetKey, function(err, sessionKeys) {
+ rclient.smembers(sessionSetKey, function (err, sessionKeys) {
if (err) {
OError.tag(err, 'error getting contents of UserSessions set', {
user_id: user._id,
@@ -219,12 +219,12 @@ UserSessionsManager = {
}
Async.series(
sessionKeys.map(key => next =>
- rclient.get(key, function(err, val) {
+ rclient.get(key, function (err, val) {
if (err) {
return next(err)
}
if (!val) {
- rclient.srem(sessionSetKey, key, function(err, result) {
+ rclient.srem(sessionSetKey, key, function (err, result) {
return next(err)
})
} else {
@@ -232,7 +232,7 @@ UserSessionsManager = {
}
})
),
- function(err, results) {
+ function (err, results) {
callback(err)
}
)
diff --git a/services/web/app/src/Features/User/UserUpdater.js b/services/web/app/src/Features/User/UserUpdater.js
index 322f4948cc..f022d45f91 100644
--- a/services/web/app/src/Features/User/UserUpdater.js
+++ b/services/web/app/src/Features/User/UserUpdater.js
@@ -69,11 +69,7 @@ async function addEmailAddress(userId, newEmail, affiliationOptions, auditLog) {
}
try {
- const reversedHostname = newEmail
- .split('@')[1]
- .split('')
- .reverse()
- .join('')
+ const reversedHostname = newEmail.split('@')[1].split('').reverse().join('')
const update = {
$push: {
emails: { email: newEmail, createdAt: new Date(), reversedHostname }
diff --git a/services/web/app/src/Features/UserMembership/UserMembershipController.js b/services/web/app/src/Features/UserMembership/UserMembershipController.js
index 8acf4e24ea..67fbf621f0 100644
--- a/services/web/app/src/Features/UserMembership/UserMembershipController.js
+++ b/services/web/app/src/Features/UserMembership/UserMembershipController.js
@@ -19,34 +19,35 @@ const CSVParser = require('json2csv').Parser
module.exports = {
index(req, res, next) {
const { entity, entityConfig } = req
- return entity.fetchV1Data(function(error, entity) {
+ return entity.fetchV1Data(function (error, entity) {
if (error != null) {
return next(error)
}
- return UserMembershipHandler.getUsers(entity, entityConfig, function(
- error,
- users
- ) {
- let entityName
- if (error != null) {
- return next(error)
+ return UserMembershipHandler.getUsers(
+ entity,
+ entityConfig,
+ function (error, users) {
+ let entityName
+ if (error != null) {
+ return next(error)
+ }
+ const entityPrimaryKey = entity[
+ entityConfig.fields.primaryKey
+ ].toString()
+ if (entityConfig.fields.name) {
+ entityName = entity[entityConfig.fields.name]
+ }
+ return res.render('user_membership/index', {
+ name: entityName,
+ users,
+ groupSize: entityConfig.hasMembersLimit
+ ? entity.membersLimit
+ : undefined,
+ translations: entityConfig.translations,
+ paths: entityConfig.pathsFor(entityPrimaryKey)
+ })
}
- const entityPrimaryKey = entity[
- entityConfig.fields.primaryKey
- ].toString()
- if (entityConfig.fields.name) {
- entityName = entity[entityConfig.fields.name]
- }
- return res.render('user_membership/index', {
- name: entityName,
- users,
- groupSize: entityConfig.hasMembersLimit
- ? entity.membersLimit
- : undefined,
- translations: entityConfig.translations,
- paths: entityConfig.pathsFor(entityPrimaryKey)
- })
- })
+ )
})
},
@@ -66,31 +67,33 @@ module.exports = {
return next(new Errors.NotFoundError('Cannot add users to entity'))
}
- return UserMembershipHandler.addUser(entity, entityConfig, email, function(
- error,
- user
- ) {
- if (error != null ? error.alreadyAdded : undefined) {
- return res.status(400).json({
- error: {
- code: 'user_already_added',
- message: req.i18n.translate('user_already_added')
- }
- })
+ return UserMembershipHandler.addUser(
+ entity,
+ entityConfig,
+ email,
+ function (error, user) {
+ if (error != null ? error.alreadyAdded : undefined) {
+ return res.status(400).json({
+ error: {
+ code: 'user_already_added',
+ message: req.i18n.translate('user_already_added')
+ }
+ })
+ }
+ if (error != null ? error.userNotFound : undefined) {
+ return res.status(404).json({
+ error: {
+ code: 'user_not_found',
+ message: req.i18n.translate('user_not_found')
+ }
+ })
+ }
+ if (error != null) {
+ return next(error)
+ }
+ return res.json({ user })
}
- if (error != null ? error.userNotFound : undefined) {
- return res.status(404).json({
- error: {
- code: 'user_not_found',
- message: req.i18n.translate('user_not_found')
- }
- })
- }
- if (error != null) {
- return next(error)
- }
- return res.json({ user })
- })
+ )
},
remove(req, res, next) {
@@ -115,7 +118,7 @@ module.exports = {
entity,
entityConfig,
userId,
- function(error, user) {
+ function (error, user) {
if (error != null ? error.isAdmin : undefined) {
return res.status(400).json({
error: {
@@ -136,18 +139,19 @@ module.exports = {
const { entity, entityConfig } = req
const fields = ['email', 'last_logged_in_at']
- return UserMembershipHandler.getUsers(entity, entityConfig, function(
- error,
- users
- ) {
- if (error != null) {
- return next(error)
+ return UserMembershipHandler.getUsers(
+ entity,
+ entityConfig,
+ function (error, users) {
+ if (error != null) {
+ return next(error)
+ }
+ const csvParser = new CSVParser({ fields })
+ res.header('Content-Disposition', 'attachment; filename=Group.csv')
+ res.contentType('text/csv')
+ return res.send(csvParser.parse(users))
}
- const csvParser = new CSVParser({ fields })
- res.header('Content-Disposition', 'attachment; filename=Group.csv')
- res.contentType('text/csv')
- return res.send(csvParser.parse(users))
- })
+ )
},
new(req, res, next) {
@@ -161,14 +165,15 @@ module.exports = {
const entityId = req.params.id
const entityConfig = req.entityConfig
- return UserMembershipHandler.createEntity(entityId, entityConfig, function(
- error,
- entity
- ) {
- if (error != null) {
- return next(error)
+ return UserMembershipHandler.createEntity(
+ entityId,
+ entityConfig,
+ function (error, entity) {
+ if (error != null) {
+ return next(error)
+ }
+ return res.redirect(entityConfig.pathsFor(entityId).index)
}
- return res.redirect(entityConfig.pathsFor(entityId).index)
- })
+ )
}
}
diff --git a/services/web/app/src/Features/UserMembership/UserMembershipHandler.js b/services/web/app/src/Features/UserMembership/UserMembershipHandler.js
index aa8d364ee2..7e8af761ff 100644
--- a/services/web/app/src/Features/UserMembership/UserMembershipHandler.js
+++ b/services/web/app/src/Features/UserMembership/UserMembershipHandler.js
@@ -29,7 +29,7 @@ const UserMembershipEntityConfigs = require('./UserMembershipEntityConfigs')
const UserMembershipHandler = {
getEntityWithoutAuthorizationCheck(entityId, entityConfig, callback) {
if (callback == null) {
- callback = function(error, entity) {}
+ callback = function (error, entity) {}
}
const query = buildEntityQuery(entityId, entityConfig)
return EntityModels[entityConfig.modelName].findOne(query, callback)
@@ -37,7 +37,7 @@ const UserMembershipHandler = {
createEntity(entityId, entityConfig, callback) {
if (callback == null) {
- callback = function(error, entity) {}
+ callback = function (error, entity) {}
}
const data = buildEntityQuery(entityId, entityConfig)
return EntityModels[entityConfig.modelName].create(data, callback)
@@ -45,7 +45,7 @@ const UserMembershipHandler = {
getUsers(entity, entityConfig, callback) {
if (callback == null) {
- callback = function(error, users) {}
+ callback = function (error, users) {}
}
const attributes = entityConfig.fields.read
return getPopulatedListOfMembers(entity, attributes, callback)
@@ -53,10 +53,10 @@ const UserMembershipHandler = {
addUser(entity, entityConfig, email, callback) {
if (callback == null) {
- callback = function(error, user) {}
+ callback = function (error, user) {}
}
const attribute = entityConfig.fields.write
- return UserGetter.getUserByAnyEmail(email, function(error, user) {
+ return UserGetter.getUserByAnyEmail(email, function (error, user) {
if (error != null) {
return callback(error)
}
@@ -75,7 +75,7 @@ const UserMembershipHandler = {
removeUser(entity, entityConfig, userId, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
const attribute = entityConfig.fields.write
if (entity.admin_id != null ? entity.admin_id.equals(userId) : undefined) {
@@ -88,9 +88,9 @@ const UserMembershipHandler = {
UserMembershipHandler.promises = promisifyAll(UserMembershipHandler)
module.exports = UserMembershipHandler
-var getPopulatedListOfMembers = function(entity, attributes, callback) {
+var getPopulatedListOfMembers = function (entity, attributes, callback) {
if (callback == null) {
- callback = function(error, users) {}
+ callback = function (error, users) {}
}
const userObjects = []
@@ -107,25 +107,25 @@ var getPopulatedListOfMembers = function(entity, attributes, callback) {
return async.map(userObjects, UserMembershipViewModel.buildAsync, callback)
}
-var addUserToEntity = function(entity, attribute, user, callback) {
+var addUserToEntity = function (entity, attribute, user, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
const fieldUpdate = {}
fieldUpdate[attribute] = user._id
return entity.updateOne({ $addToSet: fieldUpdate }, callback)
}
-var removeUserFromEntity = function(entity, attribute, userId, callback) {
+var removeUserFromEntity = function (entity, attribute, userId, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
const fieldUpdate = {}
fieldUpdate[attribute] = userId
return entity.updateOne({ $pull: fieldUpdate }, callback)
}
-var buildEntityQuery = function(entityId, entityConfig, loggedInUser) {
+var buildEntityQuery = function (entityId, entityConfig, loggedInUser) {
if (ObjectId.isValid(entityId.toString())) {
entityId = ObjectId(entityId)
}
diff --git a/services/web/app/src/Features/UserMembership/UserMembershipViewModel.js b/services/web/app/src/Features/UserMembership/UserMembershipViewModel.js
index 8098a79381..ac4279370c 100644
--- a/services/web/app/src/Features/UserMembership/UserMembershipViewModel.js
+++ b/services/web/app/src/Features/UserMembership/UserMembershipViewModel.js
@@ -25,7 +25,7 @@ module.exports = UserMembershipViewModel = {
buildAsync(userOrIdOrEmail, callback) {
if (callback == null) {
- callback = function(error, viewModel) {}
+ callback = function (error, viewModel) {}
}
if (!isObjectIdInstance(userOrIdOrEmail)) {
// userOrIdOrEmail is a user or an email and can be parsed by #build
@@ -39,7 +39,7 @@ module.exports = UserMembershipViewModel = {
last_name: 1,
lastLoggedIn: 1
}
- return UserGetter.getUser(userId, projection, function(error, user) {
+ return UserGetter.getUser(userId, projection, function (error, user) {
if (error != null || user == null) {
return callback(null, buildUserViewModelWithId(userId.toString()))
}
@@ -48,7 +48,7 @@ module.exports = UserMembershipViewModel = {
}
}
-var buildUserViewModel = function(user, isInvite) {
+var buildUserViewModel = function (user, isInvite) {
if (isInvite == null) {
isInvite = false
}
diff --git a/services/web/app/src/Features/UserMembership/UserMembershipsHandler.js b/services/web/app/src/Features/UserMembership/UserMembershipsHandler.js
index 73ccc4e653..c178f92d61 100644
--- a/services/web/app/src/Features/UserMembership/UserMembershipsHandler.js
+++ b/services/web/app/src/Features/UserMembership/UserMembershipsHandler.js
@@ -23,7 +23,7 @@ const UserMembershipsHandler = {
removeUserFromAllEntities(userId, callback) {
// get all writable entity types
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
const entityConfigs = []
for (let key in UserMembershipEntityConfigs) {
@@ -48,7 +48,7 @@ const UserMembershipsHandler = {
removeUserFromEntities(entityConfig, userId, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
const removeOperation = { $pull: {} }
removeOperation.$pull[entityConfig.fields.write] = userId
@@ -61,26 +61,26 @@ const UserMembershipsHandler = {
getEntitiesByUser(entityConfig, userId, callback) {
if (callback == null) {
- callback = function(error, entities) {}
+ callback = function (error, entities) {}
}
const query = Object.assign({}, entityConfig.baseQuery)
query[entityConfig.fields.access] = userId
- return EntityModels[entityConfig.modelName].find(query, function(
- error,
- entities
- ) {
- if (entities == null) {
- entities = []
+ return EntityModels[entityConfig.modelName].find(
+ query,
+ function (error, entities) {
+ if (entities == null) {
+ entities = []
+ }
+ if (error != null) {
+ return callback(error)
+ }
+ return async.mapSeries(
+ entities,
+ (entity, cb) => entity.fetchV1Data(cb),
+ callback
+ )
}
- if (error != null) {
- return callback(error)
- }
- return async.mapSeries(
- entities,
- (entity, cb) => entity.fetchV1Data(cb),
- callback
- )
- })
+ )
}
}
diff --git a/services/web/app/src/Features/V1/V1Handler.js b/services/web/app/src/Features/V1/V1Handler.js
index 1ec932bcff..5bc9f68385 100644
--- a/services/web/app/src/Features/V1/V1Handler.js
+++ b/services/web/app/src/Features/V1/V1Handler.js
@@ -22,7 +22,7 @@ const logger = require('logger-sharelatex')
module.exports = V1Handler = {
authWithV1(email, password, callback) {
if (callback == null) {
- callback = function(err, isValid, v1Profile) {}
+ callback = function (err, isValid, v1Profile) {}
}
return V1Api.request(
{
@@ -31,7 +31,7 @@ module.exports = V1Handler = {
json: { email, password },
expectedStatusCodes: [403]
},
- function(err, response, body) {
+ function (err, response, body) {
if (err != null) {
OError.tag(err, '[V1Handler] error while talking to v1 login api', {
email
@@ -65,7 +65,7 @@ module.exports = V1Handler = {
doPasswordReset(v1_user_id, password, callback) {
if (callback == null) {
- callback = function(err, created) {}
+ callback = function (err, created) {}
}
return V1Api.request(
@@ -78,7 +78,7 @@ module.exports = V1Handler = {
},
expectedStatusCodes: [200]
},
- function(err, response, body) {
+ function (err, response, body) {
if (err != null) {
OError.tag(err, 'error while talking to v1 password reset api', {
v1_user_id
diff --git a/services/web/app/src/infrastructure/CSP.js b/services/web/app/src/infrastructure/CSP.js
index eac931700e..8697e991f2 100644
--- a/services/web/app/src/infrastructure/CSP.js
+++ b/services/web/app/src/infrastructure/CSP.js
@@ -1,12 +1,12 @@
const crypto = require('crypto')
-module.exports = function({
+module.exports = function ({
reportUri,
reportOnly = false,
exclude = [],
percentage
}) {
- return function(req, res, next) {
+ return function (req, res, next) {
const originalRender = res.render
res.render = (...args) => {
diff --git a/services/web/app/src/infrastructure/Csrf.js b/services/web/app/src/infrastructure/Csrf.js
index 5abecc5ec7..3372bba4e0 100644
--- a/services/web/app/src/infrastructure/Csrf.js
+++ b/services/web/app/src/infrastructure/Csrf.js
@@ -69,7 +69,7 @@ class Csrf {
static validateRequest(req, cb) {
// run a dummy csrf check to see if it returns an error
if (cb == null) {
- cb = function(valid) {}
+ cb = function (valid) {}
}
return csrf(req, null, err => cb(err))
}
diff --git a/services/web/app/src/infrastructure/ExpressLocals.js b/services/web/app/src/infrastructure/ExpressLocals.js
index ae035ccd98..a60280fcdd 100644
--- a/services/web/app/src/infrastructure/ExpressLocals.js
+++ b/services/web/app/src/infrastructure/ExpressLocals.js
@@ -26,19 +26,19 @@ if (!IS_DEV_ENV) {
const I18N_HTML_INJECTIONS = new Set()
-module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
- webRouter.use(function(req, res, next) {
+module.exports = function (webRouter, privateApiRouter, publicApiRouter) {
+ webRouter.use(function (req, res, next) {
res.locals.session = req.session
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
res.locals.isIE = /\b(msie|trident)\b/i.test(req.headers['user-agent'])
next()
})
function addSetContentDisposition(req, res, next) {
- res.setContentDisposition = function(type, opts) {
+ res.setContentDisposition = function (type, opts) {
const directives = _.map(
opts,
(v, k) => `${k}="${encodeURIComponent(v)}"`
@@ -52,7 +52,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
privateApiRouter.use(addSetContentDisposition)
publicApiRouter.use(addSetContentDisposition)
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
req.externalAuthenticationSystemUsed =
Features.externalAuthenticationSystemUsed
res.locals.externalAuthenticationSystemUsed =
@@ -61,7 +61,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
let staticFilesBase
const cdnAvailable =
@@ -83,13 +83,13 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
staticFilesBase = ''
}
- res.locals.buildBaseAssetPath = function() {
+ res.locals.buildBaseAssetPath = function () {
// Return the base asset path (including the CDN url) so that webpack can
// use this to dynamically fetch scripts (e.g. PDFjs worker)
return Url.resolve(staticFilesBase, '/')
}
- res.locals.buildJsPath = function(jsFile) {
+ res.locals.buildJsPath = function (jsFile) {
let path
if (IS_DEV_ENV) {
// In dev: resolve path within JS asset directory
@@ -108,7 +108,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
// Temporary hack while jQuery/Angular dependencies are *not* bundled,
// instead copied into output directory
- res.locals.buildCopiedJsAssetPath = function(jsFile) {
+ res.locals.buildCopiedJsAssetPath = function (jsFile) {
let path
if (IS_DEV_ENV) {
// In dev: resolve path to root directory
@@ -141,7 +141,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
(brandVariation != null ? brandVariation.brand_id : undefined) ===
IEEE_BRAND_ID
- res.locals.getCssThemeModifier = function(userSettings, brandVariation) {
+ res.locals.getCssThemeModifier = function (userSettings, brandVariation) {
// Themes only exist in OL v2
if (Settings.overleaf != null) {
// The IEEE theme takes precedence over the user personal setting, i.e. a user with
@@ -154,7 +154,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
}
}
- res.locals.buildStylesheetPath = function(cssFileName) {
+ res.locals.buildStylesheetPath = function (cssFileName) {
let path
if (IS_DEV_ENV) {
// In dev: resolve path within CSS asset directory
@@ -171,11 +171,11 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
return Url.resolve(staticFilesBase, path)
}
- res.locals.buildCssPath = function(themeModifier = '') {
+ res.locals.buildCssPath = function (themeModifier = '') {
return res.locals.buildStylesheetPath(`${themeModifier}style.css`)
}
- res.locals.buildImgPath = function(imgFile) {
+ res.locals.buildImgPath = function (imgFile) {
const path = Path.join('/img/', imgFile)
return Url.resolve(staticFilesBase, path)
}
@@ -183,8 +183,8 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
next()
})
- webRouter.use(function(req, res, next) {
- res.locals.translate = function(key, vars, components) {
+ webRouter.use(function (req, res, next) {
+ res.locals.translate = function (key, vars, components) {
vars = vars || {}
if (Settings.i18n.checkForHTMLInVars) {
@@ -216,7 +216,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
const parsedOriginalUrl = Url.parse(req.originalUrl)
res.locals.currentUrl = parsedOriginalUrl.pathname
res.locals.currentUrlWithQueryParams = parsedOriginalUrl.path
- res.locals.capitalize = function(string) {
+ res.locals.capitalize = function (string) {
if (string.length === 0) {
return ''
}
@@ -225,8 +225,8 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
next()
})
- webRouter.use(function(req, res, next) {
- res.locals.getUserEmail = function() {
+ webRouter.use(function (req, res, next) {
+ res.locals.getUserEmail = function () {
const user = AuthenticationController.getSessionUser(req)
const email = (user != null ? user.email : undefined) || ''
return email
@@ -234,13 +234,13 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
res.locals.StringHelper = require('../Features/Helpers/StringHelper')
next()
})
- webRouter.use(function(req, res, next) {
- res.locals.buildReferalUrl = function(referalMedium) {
+ webRouter.use(function (req, res, next) {
+ res.locals.buildReferalUrl = function (referalMedium) {
let url = Settings.siteUrl
const currentUser = AuthenticationController.getSessionUser(req)
if (
@@ -251,7 +251,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
}
return url
}
- res.locals.getReferalId = function() {
+ res.locals.getReferalId = function () {
const currentUser = AuthenticationController.getSessionUser(req)
if (
currentUser != null &&
@@ -263,25 +263,25 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
res.locals.csrfToken = req != null ? req.csrfToken() : undefined
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
res.locals.gaToken =
Settings.analytics && Settings.analytics.ga && Settings.analytics.ga.token
res.locals.gaOptimizeId = _.get(Settings, ['analytics', 'gaOptimize', 'id'])
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
res.locals.getReqQueryParam = field =>
req.query != null ? req.query[field] : undefined
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
const currentUser = AuthenticationController.getSessionUser(req)
if (currentUser != null) {
res.locals.user = {
@@ -293,7 +293,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
res.locals.getLoggedInUserId = () =>
AuthenticationController.getLoggedInUserId(req)
res.locals.getSessionUser = () =>
@@ -301,7 +301,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
// Clone the nav settings so they can be modified for each request
res.locals.nav = {}
for (let key in Settings.nav) {
@@ -311,7 +311,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
if (Settings.reloadModuleViewsOnEachRequest) {
Modules.loadViewIncludes()
}
@@ -320,7 +320,7 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
// TODO
if (Settings.overleaf != null) {
res.locals.overallThemes = [
@@ -339,12 +339,12 @@ module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
res.locals.settings = Settings
next()
})
- webRouter.use(function(req, res, next) {
+ webRouter.use(function (req, res, next) {
res.locals.ExposedSettings = {
isOverleaf: Settings.overleaf != null,
appName: Settings.appName,
diff --git a/services/web/app/src/infrastructure/FileWriter.js b/services/web/app/src/infrastructure/FileWriter.js
index 9faf3984ad..bef1075222 100644
--- a/services/web/app/src/infrastructure/FileWriter.js
+++ b/services/web/app/src/infrastructure/FileWriter.js
@@ -59,9 +59,9 @@ class SizeLimitedStream extends Transform {
const FileWriter = {
ensureDumpFolderExists(callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
- return fs.mkdir(Settings.path.dumpFolder, function(error) {
+ return fs.mkdir(Settings.path.dumpFolder, function (error) {
if (error != null && error.code !== 'EEXIST') {
// Ignore error about already existing
return callback(error)
@@ -72,22 +72,22 @@ const FileWriter = {
writeLinesToDisk(identifier, lines, callback) {
if (callback == null) {
- callback = function(error, fsPath) {}
+ callback = function (error, fsPath) {}
}
return FileWriter.writeContentToDisk(identifier, lines.join('\n'), callback)
},
writeContentToDisk(identifier, content, callback) {
if (callback == null) {
- callback = function(error, fsPath) {}
+ callback = function (error, fsPath) {}
}
callback = _.once(callback)
const fsPath = `${Settings.path.dumpFolder}/${identifier}_${uuid.v4()}`
- return FileWriter.ensureDumpFolderExists(function(error) {
+ return FileWriter.ensureDumpFolderExists(function (error) {
if (error != null) {
return callback(error)
}
- return fs.writeFile(fsPath, content, function(error) {
+ return fs.writeFile(fsPath, content, function (error) {
if (error != null) {
return callback(error)
}
@@ -102,7 +102,7 @@ const FileWriter = {
options = {}
}
if (callback == null) {
- callback = function(error, fsPath) {}
+ callback = function (error, fsPath) {}
}
options = options || {}
@@ -110,7 +110,7 @@ const FileWriter = {
stream.pause()
- FileWriter.ensureDumpFolderExists(function(error) {
+ FileWriter.ensureDumpFolderExists(function (error) {
const writeStream = fs.createWriteStream(fsPath)
if (error != null) {
@@ -124,13 +124,13 @@ const FileWriter = {
// if writing fails, we want to consume the bytes from the source, to avoid leaks
for (const evt of ['error', 'close']) {
- writeStream.on(evt, function() {
+ writeStream.on(evt, function () {
passThrough.unpipe(writeStream)
passThrough.resume()
})
}
- pipeline(stream, passThrough, writeStream, function(err) {
+ pipeline(stream, passThrough, writeStream, function (err) {
if (
options.maxSizeBytes &&
passThrough.bytes >= options.maxSizeBytes &&
@@ -168,20 +168,20 @@ const FileWriter = {
options = {}
}
if (callback == null) {
- callback = function(error, fsPath) {}
+ callback = function (error, fsPath) {}
}
options = options || {}
callback = _.once(callback)
const stream = request.get(url)
- stream.on('error', function(err) {
+ stream.on('error', function (err) {
logger.warn(
{ err, identifier, url },
'[writeUrlToDisk] something went wrong with writing to disk'
)
callback(err)
})
- stream.on('response', function(response) {
+ stream.on('response', function (response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
FileWriter.writeStreamToDisk(identifier, stream, options, callback)
} else {
diff --git a/services/web/app/src/infrastructure/GeoIpLookup.js b/services/web/app/src/infrastructure/GeoIpLookup.js
index 06db3ecea3..f72dc44d9d 100644
--- a/services/web/app/src/infrastructure/GeoIpLookup.js
+++ b/services/web/app/src/infrastructure/GeoIpLookup.js
@@ -74,7 +74,7 @@ module.exports = GeoIpLookup = {
json: true
}
logger.log({ ip, opts }, 'getting geo ip details')
- return request.get(opts, function(err, res, ipDetails) {
+ return request.get(opts, function (err, res, ipDetails) {
if (err != null) {
logger.warn({ err, ip }, 'error getting ip details')
}
@@ -83,7 +83,7 @@ module.exports = GeoIpLookup = {
},
getCurrencyCode(ip, callback) {
- return GeoIpLookup.getDetails(ip, function(err, ipDetails) {
+ return GeoIpLookup.getDetails(ip, function (err, ipDetails) {
if (err != null || ipDetails == null) {
logger.err(
{ err, ip },
diff --git a/services/web/app/src/infrastructure/Modules.js b/services/web/app/src/infrastructure/Modules.js
index 9e84a0e655..32d677306e 100644
--- a/services/web/app/src/infrastructure/Modules.js
+++ b/services/web/app/src/infrastructure/Modules.js
@@ -122,7 +122,7 @@ function fireHook(name, ...rest) {
const callback = rest[adjustedLength - 1]
const methods = _hooks[name] || []
const callMethods = methods.map(method => cb => method(...args, cb))
- async.series(callMethods, function(error, results) {
+ async.series(callMethods, function (error, results) {
if (error) {
return callback(error)
}
diff --git a/services/web/app/src/infrastructure/ProxyManager.js b/services/web/app/src/infrastructure/ProxyManager.js
index c6a190a40e..34ab84f2dc 100644
--- a/services/web/app/src/infrastructure/ProxyManager.js
+++ b/services/web/app/src/infrastructure/ProxyManager.js
@@ -23,7 +23,7 @@ module.exports = ProxyManager = {
for (var proxyUrl in settings.proxyUrls) {
const target = settings.proxyUrls[proxyUrl]
result.push(
- (function(target) {
+ (function (target) {
const method =
(target.options != null ? target.options.method : undefined) ||
'get'
@@ -39,7 +39,7 @@ module.exports = ProxyManager = {
},
createProxy(target) {
- return function(req, res, next) {
+ return function (req, res, next) {
const targetUrl = makeTargetUrl(target, req)
logger.log({ targetUrl, reqUrl: req.url }, 'proxying url')
@@ -67,7 +67,7 @@ module.exports = ProxyManager = {
// make a URL from a proxy target.
// if the query is specified, set/replace the target's query with the given query
-var makeTargetUrl = function(target, req) {
+var makeTargetUrl = function (target, req) {
const targetUrl = URL.parse(parseSettingUrl(target, req))
if (req.query != null && Object.keys(req.query).length > 0) {
targetUrl.query = req.query
@@ -76,7 +76,7 @@ var makeTargetUrl = function(target, req) {
return targetUrl.format()
}
-var parseSettingUrl = function(target, { params }) {
+var parseSettingUrl = function (target, { params }) {
let path
if (typeof target === 'string') {
return target
diff --git a/services/web/app/src/infrastructure/RandomLogging.js b/services/web/app/src/infrastructure/RandomLogging.js
index 8a58f951b2..a7967ccd04 100644
--- a/services/web/app/src/infrastructure/RandomLogging.js
+++ b/services/web/app/src/infrastructure/RandomLogging.js
@@ -11,7 +11,7 @@
let trackOpenSockets
const _ = require('underscore')
const metrics = require('@overleaf/metrics')
-;(trackOpenSockets = function() {
+;(trackOpenSockets = function () {
metrics.gauge(
'http.open-sockets',
_.size(require('http').globalAgent.sockets.length),
diff --git a/services/web/app/src/infrastructure/RateLimiter.js b/services/web/app/src/infrastructure/RateLimiter.js
index a199ec8759..0da816a7a2 100644
--- a/services/web/app/src/infrastructure/RateLimiter.js
+++ b/services/web/app/src/infrastructure/RateLimiter.js
@@ -11,7 +11,7 @@ const RateLimiter = {
return callback(null, true)
}
if (callback == null) {
- callback = function() {}
+ callback = function () {}
}
const namespace = `RateLimit:${opts.endpointName}:`
const k = `{${opts.subjectName}}`
@@ -21,7 +21,7 @@ const RateLimiter = {
interval: opts.timeInterval * 1000,
maxInInterval: opts.throttle
})
- limiter(k, function(err, timeLeft, actionsLeft) {
+ limiter(k, function (err, timeLeft, actionsLeft) {
if (err) {
return callback(err)
}
diff --git a/services/web/app/src/infrastructure/RedirectManager.js b/services/web/app/src/infrastructure/RedirectManager.js
index 4f046974bc..943d2b8625 100644
--- a/services/web/app/src/infrastructure/RedirectManager.js
+++ b/services/web/app/src/infrastructure/RedirectManager.js
@@ -38,7 +38,7 @@ module.exports = RedirectManager = {
},
createRedirect(target) {
- return function(req, res, next) {
+ return function (req, res, next) {
let url
if (
(req.headers != null ? req.headers['x-skip-redirects'] : undefined) !=
@@ -75,7 +75,7 @@ module.exports = RedirectManager = {
// Naively get the query params string. Stringifying the req.query object may
// have differences between Express and Rails, so safer to just pass the raw
// string
-var getQueryString = function(req) {
+var getQueryString = function (req) {
const { search } = URL.parse(req.url)
if (search) {
return search
diff --git a/services/web/app/src/infrastructure/Server.js b/services/web/app/src/infrastructure/Server.js
index 77cbf634e6..4b6a6833d0 100644
--- a/services/web/app/src/infrastructure/Server.js
+++ b/services/web/app/src/infrastructure/Server.js
@@ -141,7 +141,7 @@ passport.use(
passport.serializeUser(AuthenticationController.serializeUser)
passport.deserializeUser(AuthenticationController.deserializeUser)
-Modules.hooks.fire('passportSetup', passport, function(err) {
+Modules.hooks.fire('passportSetup', passport, function (err) {
if (err != null) {
logger.err({ err }, 'error setting up passport in modules')
}
@@ -155,7 +155,7 @@ webRouter.use(translations.i18nMiddleware)
webRouter.use(translations.setLangBasedOnDomainMiddleware)
// Measure expiry from last request, not last login
-webRouter.use(function(req, res, next) {
+webRouter.use(function (req, res, next) {
if (!req.session.noSessionCallback) {
req.session.touch()
if (AuthenticationController.isUserLoggedIn(req)) {
@@ -177,7 +177,7 @@ expressLocals(webRouter, privateApiRouter, publicApiRouter)
webRouter.use(SessionAutostartMiddleware.invokeCallbackMiddleware)
-webRouter.use(function(req, res, next) {
+webRouter.use(function (req, res, next) {
if (Settings.siteIsOpen) {
next()
} else if (
@@ -190,7 +190,7 @@ webRouter.use(function(req, res, next) {
}
})
-webRouter.use(function(req, res, next) {
+webRouter.use(function (req, res, next) {
if (Settings.editorIsOpen) {
next()
} else if (req.url.indexOf('/admin') === 0) {
@@ -204,7 +204,7 @@ webRouter.use(AuthenticationController.validateAdmin)
// add security headers using Helmet
const noCacheMiddleware = require('nocache')()
-webRouter.use(function(req, res, next) {
+webRouter.use(function (req, res, next) {
const isLoggedIn = AuthenticationController.isUserLoggedIn(req)
const isProjectPage = !!req.path.match('^/project/[a-f0-9]{24}$')
if (isLoggedIn || isProjectPage) {
diff --git a/services/web/app/src/infrastructure/SessionStoreManager.js b/services/web/app/src/infrastructure/SessionStoreManager.js
index c4f4db1f71..0f490584d0 100644
--- a/services/web/app/src/infrastructure/SessionStoreManager.js
+++ b/services/web/app/src/infrastructure/SessionStoreManager.js
@@ -40,7 +40,7 @@ module.exports = {
enableValidationToken(sessionStore) {
// generate an identifier from the sessionID for every new session
const originalGenerate = sessionStore.generate
- sessionStore.generate = function(req) {
+ sessionStore.generate = function (req) {
originalGenerate(req)
// add the validation token as a property that cannot be overwritten
Object.defineProperty(req.session, 'validationToken', {
diff --git a/services/web/app/src/infrastructure/Translations.js b/services/web/app/src/infrastructure/Translations.js
index 9f77c00af5..a36aa431db 100644
--- a/services/web/app/src/infrastructure/Translations.js
+++ b/services/web/app/src/infrastructure/Translations.js
@@ -9,7 +9,7 @@ const fallbackLanguageCode = Settings.i18n.defaultLng || 'en'
const availableLanguageCodes = []
const availableHosts = new Map()
const subdomainConfigs = new Map()
-Object.values(Settings.i18n.subdomainLang || {}).forEach(function(spec) {
+Object.values(Settings.i18n.subdomainLang || {}).forEach(function (spec) {
availableLanguageCodes.push(spec.lngCode)
// prebuild a host->lngCode mapping for the usage at runtime in the
// middleware
diff --git a/services/web/app/src/models/Institution.js b/services/web/app/src/models/Institution.js
index 0f17873470..68fab64cc4 100644
--- a/services/web/app/src/models/Institution.js
+++ b/services/web/app/src/models/Institution.js
@@ -15,7 +15,7 @@ const InstitutionSchema = new Schema({
})
// fetch institution's data from v1 API. Errors are ignored
-InstitutionSchema.method('fetchV1Data', function(callback) {
+InstitutionSchema.method('fetchV1Data', function (callback) {
const url = `${settings.apis.v1.url}/universities/list/${this.v1Id}`
request.get(url, (error, response, body) => {
let parsedBody
diff --git a/services/web/app/src/models/Project.js b/services/web/app/src/models/Project.js
index 2d290567ba..71e8fe03b5 100644
--- a/services/web/app/src/models/Project.js
+++ b/services/web/app/src/models/Project.js
@@ -118,7 +118,7 @@ const ProjectSchema = new Schema({
deferredTpdsFlushCounter: { type: Number }
})
-ProjectSchema.statics.getProject = function(projectOrId, fields, callback) {
+ProjectSchema.statics.getProject = function (projectOrId, fields, callback) {
if (projectOrId._id != null) {
callback(null, projectOrId)
} else {
diff --git a/services/web/app/src/models/ProjectInvite.js b/services/web/app/src/models/ProjectInvite.js
index d41aad4b41..be5811b066 100644
--- a/services/web/app/src/models/ProjectInvite.js
+++ b/services/web/app/src/models/ProjectInvite.js
@@ -5,7 +5,7 @@ const { ObjectId } = Schema
const EXPIRY_IN_SECONDS = 60 * 60 * 24 * 30
-const ExpiryDate = function() {
+const ExpiryDate = function () {
const timestamp = new Date()
timestamp.setSeconds(timestamp.getSeconds() + EXPIRY_IN_SECONDS)
return timestamp
diff --git a/services/web/app/src/models/Publisher.js b/services/web/app/src/models/Publisher.js
index 95a9181e21..d940d7fd73 100644
--- a/services/web/app/src/models/Publisher.js
+++ b/services/web/app/src/models/Publisher.js
@@ -11,7 +11,7 @@ const PublisherSchema = new Schema({
})
// fetch publisher's (brand on v1) data from v1 API. Errors are ignored
-PublisherSchema.method('fetchV1Data', function(callback) {
+PublisherSchema.method('fetchV1Data', function (callback) {
request(
{
baseUrl: settings.apis.v1.url,
diff --git a/services/web/app/src/models/Subscription.js b/services/web/app/src/models/Subscription.js
index ac5604fb92..cdfcc09854 100644
--- a/services/web/app/src/models/Subscription.js
+++ b/services/web/app/src/models/Subscription.js
@@ -14,7 +14,7 @@ const SubscriptionSchema = new Schema({
type: [ObjectId],
ref: 'User',
required: true,
- validate: function(managers) {
+ validate: function (managers) {
// require at least one manager
return !!managers.length
}
@@ -41,7 +41,7 @@ const SubscriptionSchema = new Schema({
})
// Subscriptions have no v1 data to fetch
-SubscriptionSchema.method('fetchV1Data', function(callback) {
+SubscriptionSchema.method('fetchV1Data', function (callback) {
callback(null, this)
})
diff --git a/services/web/app/src/router.js b/services/web/app/src/router.js
index 2e8b70b650..4a844309cc 100644
--- a/services/web/app/src/router.js
+++ b/services/web/app/src/router.js
@@ -338,7 +338,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
// PDF Download button
webRouter.get(
/^\/download\/project\/([^/]*)\/output\/output\.pdf$/,
- function(req, res, next) {
+ function (req, res, next) {
const params = { Project_id: req.params[0] }
req.params = params
next()
@@ -350,7 +350,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
// PDF Download button for specific build
webRouter.get(
/^\/download\/project\/([^/]*)\/build\/([0-9a-f-]+)\/output\/output\.pdf$/,
- function(req, res, next) {
+ function (req, res, next) {
const params = {
Project_id: req.params[0],
build_id: req.params[1]
@@ -373,7 +373,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
// Used by the pdf viewers
webRouter.get(
/^\/project\/([^/]*)\/output\/(.*)$/,
- function(req, res, next) {
+ function (req, res, next) {
const params = {
Project_id: req.params[0],
file: req.params[1]
@@ -388,7 +388,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
// direct url access to output files for a specific build (query string not required)
webRouter.get(
/^\/project\/([^/]*)\/build\/([0-9a-f-]+)\/output\/(.*)$/,
- function(req, res, next) {
+ function (req, res, next) {
const params = {
Project_id: req.params[0],
build_id: req.params[1],
@@ -405,7 +405,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
// direct url access to output files for user but no build, to retrieve files when build fails
webRouter.get(
/^\/project\/([^/]*)\/user\/([0-9a-f-]+)\/output\/(.*)$/,
- function(req, res, next) {
+ function (req, res, next) {
const params = {
Project_id: req.params[0],
user_id: req.params[1],
@@ -422,7 +422,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
// direct url access to output files for a specific user and build (query string not required)
webRouter.get(
/^\/project\/([^/]*)\/user\/([0-9a-f]+)\/build\/([0-9a-f-]+)\/output\/(.*)$/,
- function(req, res, next) {
+ function (req, res, next) {
const params = {
Project_id: req.params[0],
user_id: req.params[1],
@@ -761,7 +761,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
privateApiRouter.get(
/^\/internal\/project\/([^/]*)\/output\/(.*)$/,
- function(req, res, next) {
+ function (req, res, next) {
const params = {
Project_id: req.params[0],
file: req.params[1]
@@ -883,7 +883,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
)
publicApiRouter.get(
/^\/api\/clsi\/compile\/([^/]*)\/build\/([0-9a-f-]+)\/output\/(.*)$/,
- function(req, res, next) {
+ function (req, res, next) {
const params = {
submission_id: req.params[0],
build_id: req.params[1],
@@ -906,7 +906,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
InstitutionsController.confirmDomain
)
- webRouter.get('/chrome', function(req, res, next) {
+ webRouter.get('/chrome', function (req, res, next) {
// Match v1 behaviour - this is used for a Chrome web app
if (AuthenticationController.isUserLoggedIn(req)) {
res.redirect('/project')
@@ -1032,40 +1032,42 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
timeInterval: 60
}),
AuthorizationMiddleware.ensureUserCanReadProject,
- function(req, res) {
+ function (req, res) {
const projectId = req.params.Project_id
- const sendRes = _.once(function(statusCode, message) {
+ const sendRes = _.once(function (statusCode, message) {
res.status(statusCode)
res.send(message)
ClsiCookieManager.clearServerId(projectId)
}) // force every compile to a new server
// set a timeout
- var handler = setTimeout(function() {
+ var handler = setTimeout(function () {
sendRes(500, 'Compiler timed out')
handler = null
}, 10000)
// use a valid user id for testing
const testUserId = '123456789012345678901234'
// run the compile
- CompileManager.compile(projectId, testUserId, {}, function(
- error,
- status
- ) {
- if (handler) {
- clearTimeout(handler)
+ CompileManager.compile(
+ projectId,
+ testUserId,
+ {},
+ function (error, status) {
+ if (handler) {
+ clearTimeout(handler)
+ }
+ if (error) {
+ sendRes(500, `Compiler returned error ${error.message}`)
+ } else if (status === 'success') {
+ sendRes(200, 'Compiler returned in less than 10 seconds')
+ } else {
+ sendRes(500, `Compiler returned failure ${status}`)
+ }
}
- if (error) {
- sendRes(500, `Compiler returned error ${error.message}`)
- } else if (status === 'success') {
- sendRes(200, 'Compiler returned in less than 10 seconds')
- } else {
- sendRes(500, `Compiler returned failure ${status}`)
- }
- })
+ )
}
)
- webRouter.get('/no-cache', function(req, res, next) {
+ webRouter.get('/no-cache', function (req, res, next) {
res.header('Cache-Control', 'max-age=0')
res.sendStatus(404)
})
@@ -1073,21 +1075,21 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
webRouter.get('/oops-express', (req, res, next) =>
next(new Error('Test error'))
)
- webRouter.get('/oops-internal', function(req, res, next) {
+ webRouter.get('/oops-internal', function (req, res, next) {
throw new Error('Test error')
})
webRouter.get('/oops-mongo', (req, res, next) =>
- require('./models/Project').Project.findOne({}, function() {
+ require('./models/Project').Project.findOne({}, function () {
throw new Error('Test error')
})
)
- privateApiRouter.get('/opps-small', function(req, res, next) {
+ privateApiRouter.get('/opps-small', function (req, res, next) {
logger.err('test error occured')
res.sendStatus(200)
})
- webRouter.post('/error/client', function(req, res, next) {
+ webRouter.post('/error/client', function (req, res, next) {
logger.warn(
{ err: req.body.error, meta: req.body.meta },
'client side error'
diff --git a/services/web/frontend/js/base.js b/services/web/frontend/js/base.js
index 746e1317f8..62d5788a4c 100644
--- a/services/web/frontend/js/base.js
+++ b/services/web/frontend/js/base.js
@@ -38,7 +38,7 @@ const App = angular
'ngTagsInput',
'ui.select'
])
- .config(function($qProvider, $httpProvider, uiSelectConfig) {
+ .config(function ($qProvider, $httpProvider, uiSelectConfig) {
$qProvider.errorOnUnhandledRejections(false)
uiSelectConfig.spinnerClass = 'fa fa-refresh ui-select-spin'
diff --git a/services/web/frontend/js/directives/asyncForm.js b/services/web/frontend/js/directives/asyncForm.js
index d3a49a83ac..100f0fa493 100644
--- a/services/web/frontend/js/directives/asyncForm.js
+++ b/services/web/frontend/js/directives/asyncForm.js
@@ -4,7 +4,7 @@ App.directive('asyncForm', ($http, validateCaptcha, validateCaptchaV3) => ({
controller: [
'$scope',
'$location',
- function($scope, $location) {
+ function ($scope, $location) {
this.getEmail = () => $scope.email
this.getEmailFromQuery = () =>
$location.search().email || $location.search().new_email
@@ -23,7 +23,7 @@ App.directive('asyncForm', ($http, validateCaptcha, validateCaptchaV3) => ({
ctrl.getEmailFromQuery() ||
attrs.newEmail
- const validateCaptchaIfEnabled = function(callback) {
+ const validateCaptchaIfEnabled = function (callback) {
if (attrs.captchaActionName) {
validateCaptchaV3(attrs.captchaActionName)
}
@@ -34,7 +34,7 @@ App.directive('asyncForm', ($http, validateCaptcha, validateCaptchaV3) => ({
}
}
- const submitRequest = function(grecaptchaResponse) {
+ const submitRequest = function (grecaptchaResponse) {
const formData = {}
for (let data of Array.from(element.serializeArray())) {
formData[data.name] = data.value
@@ -54,7 +54,7 @@ App.directive('asyncForm', ($http, validateCaptcha, validateCaptchaV3) => ({
return httpRequestFn(element.attr('action'), formData, {
disableAutoLoginRedirect: true
})
- .then(function(httpResponse) {
+ .then(function (httpResponse) {
const { data, headers } = httpResponse
scope[attrs.name].inflight = false
response.success = true
@@ -86,7 +86,7 @@ App.directive('asyncForm', ($http, validateCaptcha, validateCaptchaV3) => ({
location.href = URL.createObjectURL(blob) // Trigger file save
}
})
- .catch(function(httpResponse) {
+ .catch(function (httpResponse) {
const { data, status } = httpResponse
scope[attrs.name].inflight = false
response.success = false
@@ -153,7 +153,7 @@ App.directive('asyncForm', ($http, validateCaptcha, validateCaptchaV3) => ({
return $HTTP_FNS[method.toLowerCase()]
}
- element.on('submit', function(e) {
+ element.on('submit', function (e) {
e.preventDefault()
submit()
})
diff --git a/services/web/frontend/js/directives/autoSubmitForm.js b/services/web/frontend/js/directives/autoSubmitForm.js
index 68b338f8ca..35f471ead8 100644
--- a/services/web/frontend/js/directives/autoSubmitForm.js
+++ b/services/web/frontend/js/directives/autoSubmitForm.js
@@ -1,5 +1,5 @@
import App from '../base'
-App.directive('autoSubmitForm', function() {
+App.directive('autoSubmitForm', function () {
return {
link(scope, element) {
element.submit() // Runs on load
diff --git a/services/web/frontend/js/directives/bookmarkableTabset.js b/services/web/frontend/js/directives/bookmarkableTabset.js
index 29da4ed80b..78019f75a2 100644
--- a/services/web/frontend/js/directives/bookmarkableTabset.js
+++ b/services/web/frontend/js/directives/bookmarkableTabset.js
@@ -4,7 +4,7 @@ App.directive('bookmarkableTabset', $location => ({
restrict: 'A',
require: 'tabset',
link(scope, el, attrs, tabset) {
- const _makeActive = function(hash) {
+ const _makeActive = function (hash) {
if (hash && hash !== '') {
const matchingTab = _.find(
tabset.tabs,
@@ -17,7 +17,7 @@ App.directive('bookmarkableTabset', $location => ({
}
}
- scope.$applyAsync(function() {
+ scope.$applyAsync(function () {
// for page load
const hash = $location.hash()
_makeActive(hash)
@@ -27,10 +27,7 @@ App.directive('bookmarkableTabset', $location => ({
// within a tab to another tab
const linksToTabs = document.querySelectorAll('.link-to-tab')
const _clickLinkToTab = event => {
- const hash = event.currentTarget
- .getAttribute('href')
- .split('#')
- .pop()
+ const hash = event.currentTarget.getAttribute('href').split('#').pop()
_makeActive(hash)
}
@@ -51,7 +48,7 @@ App.directive('bookmarkableTab', $location => ({
const tabId = attrs.bookmarkableTab
if (tabScope && tabId && tabId !== '') {
tabScope.bookmarkableTabId = tabId
- tabScope.$watch('active', function(isActive, wasActive) {
+ tabScope.$watch('active', function (isActive, wasActive) {
if (isActive && !wasActive && $location.hash() !== tabId) {
return $location.hash(tabId)
}
diff --git a/services/web/frontend/js/directives/complexPassword.js b/services/web/frontend/js/directives/complexPassword.js
index e778571408..598f8c61ed 100644
--- a/services/web/frontend/js/directives/complexPassword.js
+++ b/services/web/frontend/js/directives/complexPassword.js
@@ -56,7 +56,7 @@ App.directive('complexPassword', () => ({
const passField = new PassField.Field('passwordField', opts)
const [asyncFormCtrl, ngModelCtrl] = Array.from(ctrl)
- ngModelCtrl.$parsers.unshift(function(modelValue) {
+ ngModelCtrl.$parsers.unshift(function (modelValue) {
let isValid = passField.validatePass()
const email = asyncFormCtrl.getEmail() || window.usersEmail
@@ -75,8 +75,9 @@ App.directive('complexPassword', () => ({
}
if (opts.length.max != null && modelValue.length >= opts.length.max) {
isValid = false
- scope.complexPasswordErrorMessage = `Maximum password length ${opts
- .length.max - 1} exceeded`
+ scope.complexPasswordErrorMessage = `Maximum password length ${
+ opts.length.max - 1
+ } exceeded`
}
if (opts.length.min != null && modelValue.length < opts.length.min) {
isValid = false
diff --git a/services/web/frontend/js/directives/equals.js b/services/web/frontend/js/directives/equals.js
index a2f7ccb253..f34f175c82 100644
--- a/services/web/frontend/js/directives/equals.js
+++ b/services/web/frontend/js/directives/equals.js
@@ -12,7 +12,7 @@ export default App.directive('equals', () => ({
link(scope, elem, attrs, ctrl) {
const firstField = `#${attrs.equals}`
return elem.add(firstField).on('keyup', () =>
- scope.$apply(function() {
+ scope.$apply(function () {
const equal = elem.val() === $(firstField).val()
return ctrl.$setValidity('areEqual', equal)
})
diff --git a/services/web/frontend/js/directives/eventTracking.js b/services/web/frontend/js/directives/eventTracking.js
index b916f8fe6f..b0d4616f54 100644
--- a/services/web/frontend/js/directives/eventTracking.js
+++ b/services/web/frontend/js/directives/eventTracking.js
@@ -51,7 +51,7 @@ import _ from 'lodash'
import App from '../base'
-const isInViewport = function(element) {
+const isInViewport = function (element) {
const elTop = element.offset().top
const elBtm = elTop + element.outerHeight()
@@ -74,7 +74,7 @@ export default App.directive('eventTracking', eventTracking => ({
const segmentation = scope.eventSegmentation || {}
segmentation.page = window.location.pathname
- const sendEvent = function(scrollEvent) {
+ const sendEvent = function (scrollEvent) {
/*
@param {boolean} scrollEvent Use to unbind scroll event
*/
@@ -104,7 +104,7 @@ export default App.directive('eventTracking', eventTracking => ({
timeoutAmt = parseInt(attrs.eventHoverAmt, 10)
}
return element
- .on('mouseenter', function() {
+ .on('mouseenter', function () {
timer = setTimeout(() => sendEvent(), timeoutAmt)
})
.on('mouseleave', () => clearTimeout(timer))
diff --git a/services/web/frontend/js/directives/expandableTextArea.js b/services/web/frontend/js/directives/expandableTextArea.js
index 59a6dcece1..4b4682b5a7 100644
--- a/services/web/frontend/js/directives/expandableTextArea.js
+++ b/services/web/frontend/js/directives/expandableTextArea.js
@@ -10,7 +10,7 @@ import App from '../base'
export default App.directive('expandableTextArea', () => ({
restrict: 'A',
link(scope, el) {
- const resetHeight = function() {
+ const resetHeight = function () {
const curHeight = el.outerHeight()
const fitHeight = el.prop('scrollHeight')
// clear height if text area is empty
diff --git a/services/web/frontend/js/directives/fineUpload.js b/services/web/frontend/js/directives/fineUpload.js
index d708751223..46752155cd 100644
--- a/services/web/frontend/js/directives/fineUpload.js
+++ b/services/web/frontend/js/directives/fineUpload.js
@@ -40,12 +40,12 @@ export default App.directive('fineUpload', $timeout => ({
validation.sizeLimit = scope.sizeLimit
}
const maxConnections = scope.maxConnections || 1
- const onComplete = scope.onCompleteCallback || function() {}
- const onUpload = scope.onUploadCallback || function() {}
- const onError = scope.onErrorCallback || function() {}
- const onValidateBatch = scope.onValidateBatch || function() {}
- const onSubmit = scope.onSubmitCallback || function() {}
- const onCancel = scope.onCancelCallback || function() {}
+ const onComplete = scope.onCompleteCallback || function () {}
+ const onUpload = scope.onUploadCallback || function () {}
+ const onError = scope.onErrorCallback || function () {}
+ const onValidateBatch = scope.onValidateBatch || function () {}
+ const onSubmit = scope.onSubmitCallback || function () {}
+ const onCancel = scope.onCancelCallback || function () {}
if (scope.autoUpload == null) {
autoUpload = true
} else {
diff --git a/services/web/frontend/js/directives/focus.js b/services/web/frontend/js/directives/focus.js
index 1d35bcaf5d..1756275027 100644
--- a/services/web/frontend/js/directives/focus.js
+++ b/services/web/frontend/js/directives/focus.js
@@ -14,7 +14,7 @@ let selectName
App.directive('focusWhen', $timeout => ({
restrict: 'A',
link(scope, element, attr) {
- return scope.$watch(attr.focusWhen, function(value) {
+ return scope.$watch(attr.focusWhen, function (value) {
if (value) {
return $timeout(() => element.focus())
}
@@ -32,7 +32,7 @@ App.directive('focusOn', $timeout => ({
App.directive('selectWhen', $timeout => ({
restrict: 'A',
link(scope, element, attr) {
- return scope.$watch(attr.selectWhen, function(value) {
+ return scope.$watch(attr.selectWhen, function (value) {
if (value) {
return $timeout(() => element.select())
}
@@ -50,7 +50,7 @@ App.directive('selectOn', $timeout => ({
App.directive('selectNameWhen', $timeout => ({
restrict: 'A',
link(scope, element, attrs) {
- return scope.$watch(attrs.selectNameWhen, function(value) {
+ return scope.$watch(attrs.selectNameWhen, function (value) {
if (value) {
return $timeout(() => selectName(element))
}
@@ -71,7 +71,7 @@ App.directive('focus', $timeout => ({
},
link(scope, element) {
- return scope.$watch('trigger', function(value) {
+ return scope.$watch('trigger', function (value) {
if (value === 'true') {
return $timeout(() => element[0].focus())
}
@@ -79,7 +79,7 @@ App.directive('focus', $timeout => ({
}
}))
-selectName = function(element) {
+selectName = function (element) {
// Select up to last '.'. I.e. everything except the file extension
element.focus()
const name = element.val()
diff --git a/services/web/frontend/js/directives/mathjax.js b/services/web/frontend/js/directives/mathjax.js
index b7c947071e..ec39d16b19 100644
--- a/services/web/frontend/js/directives/mathjax.js
+++ b/services/web/frontend/js/directives/mathjax.js
@@ -3,7 +3,7 @@ import _ from 'lodash'
import App from '../base'
-export default App.directive('mathjax', function($compile, $parse) {
+export default App.directive('mathjax', function ($compile, $parse) {
return {
link(scope, element, attrs) {
if (!(MathJax && MathJax.Hub)) return
diff --git a/services/web/frontend/js/directives/maxHeight.js b/services/web/frontend/js/directives/maxHeight.js
index 5bb5fe3c4f..aca26d0b2f 100644
--- a/services/web/frontend/js/directives/maxHeight.js
+++ b/services/web/frontend/js/directives/maxHeight.js
@@ -11,7 +11,7 @@ import App from '../base'
export default App.directive('maxHeight', () => ({
restrict: 'A',
link(scope, element, attrs) {
- return scope.$watch(attrs.maxHeight, function(value) {
+ return scope.$watch(attrs.maxHeight, function (value) {
if (value != null) {
return element.css({ 'max-height': value })
}
diff --git a/services/web/frontend/js/directives/onEnter.js b/services/web/frontend/js/directives/onEnter.js
index 93b4e24392..7c99867ffc 100644
--- a/services/web/frontend/js/directives/onEnter.js
+++ b/services/web/frontend/js/directives/onEnter.js
@@ -8,7 +8,7 @@
import App from '../base'
export default App.directive('onEnter', () => (scope, element, attrs) =>
- element.bind('keydown keypress', function(event) {
+ element.bind('keydown keypress', function (event) {
if (event.which === 13) {
scope.$apply(() => scope.$eval(attrs.onEnter, { event }))
return event.preventDefault()
diff --git a/services/web/frontend/js/directives/rightClick.js b/services/web/frontend/js/directives/rightClick.js
index 0a2292faed..fd316c8d9e 100644
--- a/services/web/frontend/js/directives/rightClick.js
+++ b/services/web/frontend/js/directives/rightClick.js
@@ -10,7 +10,7 @@ import App from '../base'
export default App.directive('rightClick', () => ({
restrict: 'A',
link(scope, element, attrs) {
- return element.bind('contextmenu', function(e) {
+ return element.bind('contextmenu', function (e) {
e.preventDefault()
e.stopPropagation()
return scope.$eval(attrs.rightClick)
diff --git a/services/web/frontend/js/directives/selectAll.js b/services/web/frontend/js/directives/selectAll.js
index 8ff336f36c..e163ff01a1 100644
--- a/services/web/frontend/js/directives/selectAll.js
+++ b/services/web/frontend/js/directives/selectAll.js
@@ -14,7 +14,7 @@ import App from '../base'
App.directive('selectAllList', () => ({
controller: [
'$scope',
- function($scope) {
+ function ($scope) {
// Selecting or deselecting all should apply to all projects
this.selectAll = () => $scope.$broadcast('select-all:select')
@@ -31,7 +31,7 @@ App.directive('selectAll', () => ({
link(scope, element, attrs, selectAllListController) {
scope.$on('select-all:clear', () => element.prop('checked', false))
- return element.change(function() {
+ return element.change(function () {
if (element.is(':checked')) {
selectAllListController.selectAll()
} else {
@@ -50,13 +50,13 @@ App.directive('selectIndividual', () => ({
link(scope, element, attrs, selectAllListController) {
let ignoreChanges = false
- scope.$watch('ngModel', function(value) {
+ scope.$watch('ngModel', function (value) {
if (value != null && !ignoreChanges) {
return selectAllListController.clearSelectAllState()
}
})
- scope.$on('select-all:select', function() {
+ scope.$on('select-all:select', function () {
if (element.prop('disabled')) {
return
}
@@ -65,7 +65,7 @@ App.directive('selectIndividual', () => ({
return (ignoreChanges = false)
})
- scope.$on('select-all:deselect', function() {
+ scope.$on('select-all:deselect', function () {
if (element.prop('disabled')) {
return
}
@@ -74,12 +74,12 @@ App.directive('selectIndividual', () => ({
return (ignoreChanges = false)
})
- return scope.$on('select-all:row-clicked', function() {
+ return scope.$on('select-all:row-clicked', function () {
if (element.prop('disabled')) {
return
}
ignoreChanges = true
- scope.$apply(function() {
+ scope.$apply(function () {
scope.ngModel = !scope.ngModel
if (!scope.ngModel) {
return selectAllListController.clearSelectAllState()
diff --git a/services/web/frontend/js/directives/videoPlayState.js b/services/web/frontend/js/directives/videoPlayState.js
index 49ac974b23..0f84153e61 100644
--- a/services/web/frontend/js/directives/videoPlayState.js
+++ b/services/web/frontend/js/directives/videoPlayState.js
@@ -16,7 +16,7 @@ export default App.directive('videoPlayState', $parse => ({
const videoDOMEl = element[0]
return scope.$watch(
() => $parse(attrs.videoPlayState)(scope),
- function(shouldPlay) {
+ function (shouldPlay) {
if (shouldPlay) {
videoDOMEl.currentTime = 0
return videoDOMEl.play()
diff --git a/services/web/frontend/js/features/chat/controllers/chat-controller.js b/services/web/frontend/js/features/chat/controllers/chat-controller.js
index 54439a927c..fb85de03bf 100644
--- a/services/web/frontend/js/features/chat/controllers/chat-controller.js
+++ b/services/web/frontend/js/features/chat/controllers/chat-controller.js
@@ -4,7 +4,7 @@ import { rootContext } from '../../../shared/context/root-context'
import ChatPane from '../components/chat-pane'
-App.controller('ReactChatController', function($scope, ide) {
+App.controller('ReactChatController', function ($scope, ide) {
$scope.chatIsOpen = ide.$scope.ui.chatOpen
ide.$scope.$watch('ui.chatOpen', newValue => {
diff --git a/services/web/frontend/js/features/clone-project-modal/controllers/left-menu-clone-project-modal-controller.js b/services/web/frontend/js/features/clone-project-modal/controllers/left-menu-clone-project-modal-controller.js
index 0957cab2b5..c776bdfcb2 100644
--- a/services/web/frontend/js/features/clone-project-modal/controllers/left-menu-clone-project-modal-controller.js
+++ b/services/web/frontend/js/features/clone-project-modal/controllers/left-menu-clone-project-modal-controller.js
@@ -5,38 +5,38 @@ import CloneProjectModal from '../components/clone-project-modal'
App.component('cloneProjectModal', react2angular(CloneProjectModal))
-export default App.controller('LeftMenuCloneProjectModalController', function(
- $scope,
- ide
-) {
- $scope.show = false
- $scope.projectId = ide.$scope.project_id
+export default App.controller(
+ 'LeftMenuCloneProjectModalController',
+ function ($scope, ide) {
+ $scope.show = false
+ $scope.projectId = ide.$scope.project_id
- $scope.handleHide = () => {
- $scope.$applyAsync(() => {
- $scope.show = false
- })
+ $scope.handleHide = () => {
+ $scope.$applyAsync(() => {
+ $scope.show = false
+ })
+ }
+
+ $scope.openProject = projectId => {
+ window.location.assign(`/project/${projectId}`)
+ }
+
+ $scope.openCloneProjectModal = () => {
+ $scope.$applyAsync(() => {
+ const { project } = ide.$scope
+
+ if (project) {
+ $scope.projectId = project._id
+ $scope.projectName = project.name
+
+ $scope.show = true
+
+ // TODO: is this needed
+ window.setTimeout(() => {
+ $scope.$broadcast('open')
+ }, 200)
+ }
+ })
+ }
}
-
- $scope.openProject = projectId => {
- window.location.assign(`/project/${projectId}`)
- }
-
- $scope.openCloneProjectModal = () => {
- $scope.$applyAsync(() => {
- const { project } = ide.$scope
-
- if (project) {
- $scope.projectId = project._id
- $scope.projectName = project.name
-
- $scope.show = true
-
- // TODO: is this needed
- window.setTimeout(() => {
- $scope.$broadcast('open')
- }, 200)
- }
- })
- }
-})
+)
diff --git a/services/web/frontend/js/features/editor-navigation-toolbar/controllers/editor-navigation-toolbar-controller.js b/services/web/frontend/js/features/editor-navigation-toolbar/controllers/editor-navigation-toolbar-controller.js
index 6d7312b558..1b42337789 100644
--- a/services/web/frontend/js/features/editor-navigation-toolbar/controllers/editor-navigation-toolbar-controller.js
+++ b/services/web/frontend/js/features/editor-navigation-toolbar/controllers/editor-navigation-toolbar-controller.js
@@ -3,7 +3,7 @@ import { react2angular } from 'react2angular'
import EditorNavigationToolbarRoot from '../components/editor-navigation-toolbar-root'
import { rootContext } from '../../../shared/context/root-context'
-App.controller('EditorNavigationToolbarController', function($scope, ide) {
+App.controller('EditorNavigationToolbarController', function ($scope, ide) {
// wrapper is required to avoid scope problems with `this` inside `EditorManager`
$scope.openDoc = (doc, args) => ide.editorManager.openDoc(doc, args)
})
diff --git a/services/web/frontend/js/features/file-tree/contexts/file-tree-main.js b/services/web/frontend/js/features/file-tree/contexts/file-tree-main.js
index 51bbdb2d18..96437ae9d6 100644
--- a/services/web/frontend/js/features/file-tree/contexts/file-tree-main.js
+++ b/services/web/frontend/js/features/file-tree/contexts/file-tree-main.js
@@ -15,7 +15,7 @@ export function useFileTreeMainContext() {
return context
}
-export const FileTreeMainProvider = function({
+export const FileTreeMainProvider = function ({
projectId,
hasWritePermissions,
userHasFeature,
diff --git a/services/web/frontend/js/features/file-tree/contexts/file-tree-mutable.js b/services/web/frontend/js/features/file-tree/contexts/file-tree-mutable.js
index dd653a981e..0a2766365a 100644
--- a/services/web/frontend/js/features/file-tree/contexts/file-tree-mutable.js
+++ b/services/web/frontend/js/features/file-tree/contexts/file-tree-mutable.js
@@ -76,7 +76,7 @@ function fileTreeMutableReducer({ fileTreeData }, action) {
}
}
-export const FileTreeMutableProvider = function({ rootFolder, children }) {
+export const FileTreeMutableProvider = function ({ rootFolder, children }) {
const [{ fileTreeData, fileCount }, dispatch] = useReducer(
fileTreeMutableReducer,
{
diff --git a/services/web/frontend/js/features/file-tree/controllers/file-tree-controller.js b/services/web/frontend/js/features/file-tree/controllers/file-tree-controller.js
index b14f92434e..fbe68c704e 100644
--- a/services/web/frontend/js/features/file-tree/controllers/file-tree-controller.js
+++ b/services/web/frontend/js/features/file-tree/controllers/file-tree-controller.js
@@ -4,7 +4,7 @@ import { cloneDeep } from 'lodash'
import FileTreeRoot from '../components/file-tree-root'
-App.controller('ReactFileTreeController', function(
+App.controller('ReactFileTreeController', function (
$scope,
$timeout,
ide
diff --git a/services/web/frontend/js/features/hotkeys-modal/controllers/hotkeys-modal-controller.js b/services/web/frontend/js/features/hotkeys-modal/controllers/hotkeys-modal-controller.js
index 8dbea70cee..43fa47feb6 100644
--- a/services/web/frontend/js/features/hotkeys-modal/controllers/hotkeys-modal-controller.js
+++ b/services/web/frontend/js/features/hotkeys-modal/controllers/hotkeys-modal-controller.js
@@ -5,7 +5,7 @@ import HotkeysModal from '../components/hotkeys-modal'
App.component('hotkeysModal', react2angular(HotkeysModal, undefined))
-export default App.controller('HotkeysModalController', function($scope) {
+export default App.controller('HotkeysModalController', function ($scope) {
$scope.show = false
$scope.isMac = /Mac/i.test(navigator.platform)
diff --git a/services/web/frontend/js/features/outline/controllers/outline-controller.js b/services/web/frontend/js/features/outline/controllers/outline-controller.js
index da5a2125ea..6fcd720a19 100644
--- a/services/web/frontend/js/features/outline/controllers/outline-controller.js
+++ b/services/web/frontend/js/features/outline/controllers/outline-controller.js
@@ -3,7 +3,7 @@ import OutlinePane from '../components/outline-pane'
import { react2angular } from 'react2angular'
import { rootContext } from '../../../shared/context/root-context'
-App.controller('OutlineController', function($scope, ide, eventTracking) {
+App.controller('OutlineController', function ($scope, ide, eventTracking) {
$scope.isTexFile = false
$scope.outline = []
$scope.eventTracking = eventTracking
diff --git a/services/web/frontend/js/features/share-project-modal/controllers/react-share-project-modal-controller.js b/services/web/frontend/js/features/share-project-modal/controllers/react-share-project-modal-controller.js
index 94bb0cad42..8f34610c77 100644
--- a/services/web/frontend/js/features/share-project-modal/controllers/react-share-project-modal-controller.js
+++ b/services/web/frontend/js/features/share-project-modal/controllers/react-share-project-modal-controller.js
@@ -9,65 +9,64 @@ App.component(
react2angular(ShareProjectModal, undefined, ['ide'])
)
-export default App.controller('ReactShareProjectModalController', function(
- $scope,
- eventTracking,
- ide
-) {
- $scope.isAdmin = false
- $scope.show = false
+export default App.controller(
+ 'ReactShareProjectModalController',
+ function ($scope, eventTracking, ide) {
+ $scope.isAdmin = false
+ $scope.show = false
- $scope.handleHide = () => {
- $scope.$applyAsync(() => {
- $scope.show = false
- })
- }
-
- $scope.openShareProjectModal = isAdmin => {
- eventTracking.sendMBOnce('ide-open-share-modal-once')
- $scope.$applyAsync(() => {
- $scope.isAdmin = isAdmin
- $scope.show = true
- })
- }
-
- /* tokens */
-
- ide.socket.on('project:tokens:changed', data => {
- if (data.tokens != null) {
+ $scope.handleHide = () => {
$scope.$applyAsync(() => {
- $scope.project.tokens = data.tokens
+ $scope.show = false
})
}
- })
- ide.socket.on('project:membership:changed', data => {
- if (data.members) {
- listProjectMembers($scope.project)
- .then(({ members }) => {
- if (members) {
- $scope.$applyAsync(() => {
- $scope.project.members = members
- })
- }
- })
- .catch(() => {
- console.error('Error fetching members for project')
- })
+ $scope.openShareProjectModal = isAdmin => {
+ eventTracking.sendMBOnce('ide-open-share-modal-once')
+ $scope.$applyAsync(() => {
+ $scope.isAdmin = isAdmin
+ $scope.show = true
+ })
}
- if (data.invites) {
- listProjectInvites($scope.project)
- .then(({ invites }) => {
- if (invites) {
- $scope.$applyAsync(() => {
- $scope.project.invites = invites
- })
- }
+ /* tokens */
+
+ ide.socket.on('project:tokens:changed', data => {
+ if (data.tokens != null) {
+ $scope.$applyAsync(() => {
+ $scope.project.tokens = data.tokens
})
- .catch(() => {
- console.error('Error fetching invites for project')
- })
- }
- })
-})
+ }
+ })
+
+ ide.socket.on('project:membership:changed', data => {
+ if (data.members) {
+ listProjectMembers($scope.project)
+ .then(({ members }) => {
+ if (members) {
+ $scope.$applyAsync(() => {
+ $scope.project.members = members
+ })
+ }
+ })
+ .catch(() => {
+ console.error('Error fetching members for project')
+ })
+ }
+
+ if (data.invites) {
+ listProjectInvites($scope.project)
+ .then(({ invites }) => {
+ if (invites) {
+ $scope.$applyAsync(() => {
+ $scope.project.invites = invites
+ })
+ }
+ })
+ .catch(() => {
+ console.error('Error fetching invites for project')
+ })
+ }
+ })
+ }
+)
diff --git a/services/web/frontend/js/features/word-count-modal/controllers/word-count-modal-controller.js b/services/web/frontend/js/features/word-count-modal/controllers/word-count-modal-controller.js
index c4d1ae1fd8..c1820ec5ce 100644
--- a/services/web/frontend/js/features/word-count-modal/controllers/word-count-modal-controller.js
+++ b/services/web/frontend/js/features/word-count-modal/controllers/word-count-modal-controller.js
@@ -5,24 +5,24 @@ import WordCountModal from '../components/word-count-modal'
App.component('wordCountModal', react2angular(WordCountModal))
-export default App.controller('WordCountModalController', function(
- $scope,
- ide
-) {
- $scope.show = false
- $scope.projectId = ide.project_id
+export default App.controller(
+ 'WordCountModalController',
+ function ($scope, ide) {
+ $scope.show = false
+ $scope.projectId = ide.project_id
- $scope.handleHide = () => {
- $scope.$applyAsync(() => {
- $scope.show = false
- })
- }
+ $scope.handleHide = () => {
+ $scope.$applyAsync(() => {
+ $scope.show = false
+ })
+ }
- $scope.openWordCountModal = () => {
- $scope.$applyAsync(() => {
- $scope.clsiServerId = ide.clsiServerId
- $scope.projectId = ide.project_id
- $scope.show = true
- })
+ $scope.openWordCountModal = () => {
+ $scope.$applyAsync(() => {
+ $scope.clsiServerId = ide.clsiServerId
+ $scope.projectId = ide.project_id
+ $scope.show = true
+ })
+ }
}
-})
+)
diff --git a/services/web/frontend/js/filters/formatDate.js b/services/web/frontend/js/filters/formatDate.js
index e330230b9e..702e53fd75 100644
--- a/services/web/frontend/js/filters/formatDate.js
+++ b/services/web/frontend/js/filters/formatDate.js
@@ -22,7 +22,7 @@ moment.updateLocale('en', {
App.filter(
'formatDate',
() =>
- function(date, format) {
+ function (date, format) {
if (!date) return 'N/A'
if (format == null) {
format = 'Do MMM YYYY, h:mm a'
@@ -34,16 +34,12 @@ App.filter(
App.filter(
'utcDate',
() =>
- function(date, format) {
+ function (date, format) {
if (!date) return 'N/A'
if (format == null) {
format = 'D MMM YYYY, HH:mm:ss'
}
- return (
- moment(date)
- .utc()
- .format(format) + ' UTC'
- )
+ return moment(date).utc().format(format) + ' UTC'
}
)
diff --git a/services/web/frontend/js/ide.js b/services/web/frontend/js/ide.js
index 88eb792897..b0dbd18d49 100644
--- a/services/web/frontend/js/ide.js
+++ b/services/web/frontend/js/ide.js
@@ -64,293 +64,296 @@ import '../../modules/modules-ide.js'
import './shared/context/controllers/root-context-controller'
import './features/editor-navigation-toolbar/controllers/editor-navigation-toolbar-controller'
-App.controller('IdeController', function(
- $scope,
- $timeout,
- ide,
- localStorage,
- eventTracking,
- metadata,
- $q,
- CobrandingDataService
-) {
- // Don't freak out if we're already in an apply callback
- let err, pdfLayout, userAgent
- $scope.$originalApply = $scope.$apply
- $scope.$apply = function(fn) {
- if (fn == null) {
- fn = function() {}
+App.controller(
+ 'IdeController',
+ function (
+ $scope,
+ $timeout,
+ ide,
+ localStorage,
+ eventTracking,
+ metadata,
+ $q,
+ CobrandingDataService
+ ) {
+ // Don't freak out if we're already in an apply callback
+ let err, pdfLayout, userAgent
+ $scope.$originalApply = $scope.$apply
+ $scope.$apply = function (fn) {
+ if (fn == null) {
+ fn = function () {}
+ }
+ const phase = this.$root.$$phase
+ if (phase === '$apply' || phase === '$digest') {
+ return fn()
+ } else {
+ return this.$originalApply(fn)
+ }
}
- const phase = this.$root.$$phase
- if (phase === '$apply' || phase === '$digest') {
- return fn()
- } else {
- return this.$originalApply(fn)
+
+ $scope.state = {
+ loading: true,
+ load_progress: 40,
+ error: null
}
- }
-
- $scope.state = {
- loading: true,
- load_progress: 40,
- error: null
- }
- $scope.ui = {
- leftMenuShown: false,
- view: 'editor',
- chatOpen: false,
- pdfLayout: 'sideBySide',
- pdfHidden: false,
- pdfWidth: 0,
- reviewPanelOpen: localStorage(`ui.reviewPanelOpen.${window.project_id}`),
- miniReviewPanelVisible: false,
- chatResizerSizeOpen: 7,
- chatResizerSizeClosed: 0
- }
- $scope.user = window.user
-
- $scope.settings = window.userSettings
- $scope.anonymous = window.anonymous
- $scope.isTokenMember = window.isTokenMember
- $scope.isRestrictedTokenMember = window.isRestrictedTokenMember
-
- $scope.cobranding = {
- isProjectCobranded: CobrandingDataService.isProjectCobranded(),
- logoImgUrl: CobrandingDataService.getLogoImgUrl(),
- submitBtnHtml: CobrandingDataService.getSubmitBtnHtml(),
- brandVariationName: CobrandingDataService.getBrandVariationName(),
- brandVariationHomeUrl: CobrandingDataService.getBrandVariationHomeUrl()
- }
-
- $scope.chat = {}
-
- ide.toggleReviewPanel = $scope.toggleReviewPanel = function() {
- if (!$scope.project.features.trackChangesVisible) {
- return
+ $scope.ui = {
+ leftMenuShown: false,
+ view: 'editor',
+ chatOpen: false,
+ pdfLayout: 'sideBySide',
+ pdfHidden: false,
+ pdfWidth: 0,
+ reviewPanelOpen: localStorage(`ui.reviewPanelOpen.${window.project_id}`),
+ miniReviewPanelVisible: false,
+ chatResizerSizeOpen: 7,
+ chatResizerSizeClosed: 0
}
- $scope.ui.reviewPanelOpen = !$scope.ui.reviewPanelOpen
- return eventTracking.sendMB('rp-toggle-panel', {
- value: $scope.ui.reviewPanelOpen
+ $scope.user = window.user
+
+ $scope.settings = window.userSettings
+ $scope.anonymous = window.anonymous
+ $scope.isTokenMember = window.isTokenMember
+ $scope.isRestrictedTokenMember = window.isRestrictedTokenMember
+
+ $scope.cobranding = {
+ isProjectCobranded: CobrandingDataService.isProjectCobranded(),
+ logoImgUrl: CobrandingDataService.getLogoImgUrl(),
+ submitBtnHtml: CobrandingDataService.getSubmitBtnHtml(),
+ brandVariationName: CobrandingDataService.getBrandVariationName(),
+ brandVariationHomeUrl: CobrandingDataService.getBrandVariationHomeUrl()
+ }
+
+ $scope.chat = {}
+
+ ide.toggleReviewPanel = $scope.toggleReviewPanel = function () {
+ if (!$scope.project.features.trackChangesVisible) {
+ return
+ }
+ $scope.ui.reviewPanelOpen = !$scope.ui.reviewPanelOpen
+ return eventTracking.sendMB('rp-toggle-panel', {
+ value: $scope.ui.reviewPanelOpen
+ })
+ }
+
+ $scope.$watch('ui.reviewPanelOpen', function (value) {
+ if (value != null) {
+ return localStorage(`ui.reviewPanelOpen.${window.project_id}`, value)
+ }
})
- }
- $scope.$watch('ui.reviewPanelOpen', function(value) {
- if (value != null) {
- return localStorage(`ui.reviewPanelOpen.${window.project_id}`, value)
+ $scope.$on('layout:pdf:resize', function (_, layoutState) {
+ $scope.ui.pdfHidden = layoutState.east.initClosed
+ return ($scope.ui.pdfWidth = layoutState.east.size)
+ })
+
+ $scope.$watch('ui.view', function (newView, oldView) {
+ if (newView !== oldView) {
+ $scope.$broadcast('layout:flat-screen:toggle')
+ }
+ if (newView != null && newView !== 'editor' && newView !== 'pdf') {
+ return eventTracking.sendMBOnce(`ide-open-view-${newView}-once`)
+ }
+ })
+
+ $scope.$watch('ui.chatOpen', function (isOpen) {
+ if (isOpen) {
+ return eventTracking.sendMBOnce('ide-open-chat-once')
+ }
+ })
+
+ $scope.$watch('ui.leftMenuShown', function (isOpen) {
+ if (isOpen) {
+ return eventTracking.sendMBOnce('ide-open-left-menu-once')
+ }
+ })
+
+ $scope.trackHover = feature =>
+ eventTracking.sendMBOnce(`ide-hover-${feature}-once`)
+ // End of tracking code.
+
+ window._ide = ide
+
+ ide.validFileRegex = '^[^*/]*$' // Don't allow * and /
+
+ let useFallbackWebsocket =
+ window.location &&
+ window.location.search &&
+ window.location.search.match(/ws=fallback/)
+ // if we previously failed to load the websocket fall back to null (the siteUrl)
+ ide.wsUrl = useFallbackWebsocket ? null : window.sharelatex.wsUrl || null // websocket url (if defined)
+
+ ide.project_id = $scope.project_id = window.project_id
+ ide.$scope = $scope
+
+ ide.referencesSearchManager = new ReferencesManager(ide, $scope)
+ ide.loadingManager = new LoadingManager($scope)
+ ide.connectionManager = new ConnectionManager(ide, $scope)
+ ide.fileTreeManager = new FileTreeManager(ide, $scope)
+ ide.editorManager = new EditorManager(ide, $scope, localStorage)
+ ide.onlineUsersManager = new OnlineUsersManager(ide, $scope)
+ if (window.data.useV2History) {
+ ide.historyManager = new HistoryV2Manager(ide, $scope, localStorage)
+ } else {
+ ide.historyManager = new HistoryManager(ide, $scope)
}
- })
+ ide.pdfManager = new PdfManager(ide, $scope)
+ ide.permissionsManager = new PermissionsManager(ide, $scope)
+ ide.binaryFilesManager = new BinaryFilesManager(ide, $scope)
+ ide.metadataManager = new MetadataManager(ide, $scope, metadata)
+ ide.outlineManager = new OutlineManager(ide, $scope)
- $scope.$on('layout:pdf:resize', function(_, layoutState) {
- $scope.ui.pdfHidden = layoutState.east.initClosed
- return ($scope.ui.pdfWidth = layoutState.east.size)
- })
-
- $scope.$watch('ui.view', function(newView, oldView) {
- if (newView !== oldView) {
- $scope.$broadcast('layout:flat-screen:toggle')
- }
- if (newView != null && newView !== 'editor' && newView !== 'pdf') {
- return eventTracking.sendMBOnce(`ide-open-view-${newView}-once`)
- }
- })
-
- $scope.$watch('ui.chatOpen', function(isOpen) {
- if (isOpen) {
- return eventTracking.sendMBOnce('ide-open-chat-once')
- }
- })
-
- $scope.$watch('ui.leftMenuShown', function(isOpen) {
- if (isOpen) {
- return eventTracking.sendMBOnce('ide-open-left-menu-once')
- }
- })
-
- $scope.trackHover = feature =>
- eventTracking.sendMBOnce(`ide-hover-${feature}-once`)
- // End of tracking code.
-
- window._ide = ide
-
- ide.validFileRegex = '^[^*/]*$' // Don't allow * and /
-
- let useFallbackWebsocket =
- window.location &&
- window.location.search &&
- window.location.search.match(/ws=fallback/)
- // if we previously failed to load the websocket fall back to null (the siteUrl)
- ide.wsUrl = useFallbackWebsocket ? null : window.sharelatex.wsUrl || null // websocket url (if defined)
-
- ide.project_id = $scope.project_id = window.project_id
- ide.$scope = $scope
-
- ide.referencesSearchManager = new ReferencesManager(ide, $scope)
- ide.loadingManager = new LoadingManager($scope)
- ide.connectionManager = new ConnectionManager(ide, $scope)
- ide.fileTreeManager = new FileTreeManager(ide, $scope)
- ide.editorManager = new EditorManager(ide, $scope, localStorage)
- ide.onlineUsersManager = new OnlineUsersManager(ide, $scope)
- if (window.data.useV2History) {
- ide.historyManager = new HistoryV2Manager(ide, $scope, localStorage)
- } else {
- ide.historyManager = new HistoryManager(ide, $scope)
- }
- ide.pdfManager = new PdfManager(ide, $scope)
- ide.permissionsManager = new PermissionsManager(ide, $scope)
- ide.binaryFilesManager = new BinaryFilesManager(ide, $scope)
- ide.metadataManager = new MetadataManager(ide, $scope, metadata)
- ide.outlineManager = new OutlineManager(ide, $scope)
-
- let inited = false
- $scope.$on('project:joined', function() {
- if (inited) {
- return
- }
- inited = true
- if (
- __guard__(
- $scope != null ? $scope.project : undefined,
- x => x.deletedByExternalDataSource
- )
- ) {
- ide.showGenericMessageModal(
- 'Project Renamed or Deleted',
- `\
+ let inited = false
+ $scope.$on('project:joined', function () {
+ if (inited) {
+ return
+ }
+ inited = true
+ if (
+ __guard__(
+ $scope != null ? $scope.project : undefined,
+ x => x.deletedByExternalDataSource
+ )
+ ) {
+ ide.showGenericMessageModal(
+ 'Project Renamed or Deleted',
+ `\
This project has either been renamed or deleted by an external data source such as Dropbox.
We don't want to delete your data on Overleaf, so this project still contains your history and collaborators.
If the project has been renamed please look in your project list for a new project under the new name.\
`
- )
- }
- return $timeout(function() {
- if ($scope.permissions.write) {
- let _labelsInitialLoadDone
- ide.metadataManager.loadProjectMetaFromServer()
- return (_labelsInitialLoadDone = true)
+ )
}
- }, 200)
- })
+ return $timeout(function () {
+ if ($scope.permissions.write) {
+ let _labelsInitialLoadDone
+ ide.metadataManager.loadProjectMetaFromServer()
+ return (_labelsInitialLoadDone = true)
+ }
+ }, 200)
+ })
- // Count the first 'doc:opened' as a sign that the ide is loaded
- // and broadcast a message. This is a good event to listen for
- // if you want to wait until the ide is fully loaded and initialized
- let _loaded = false
- $scope.$on('doc:opened', function() {
- if (_loaded) {
- return
+ // Count the first 'doc:opened' as a sign that the ide is loaded
+ // and broadcast a message. This is a good event to listen for
+ // if you want to wait until the ide is fully loaded and initialized
+ let _loaded = false
+ $scope.$on('doc:opened', function () {
+ if (_loaded) {
+ return
+ }
+ $scope.$broadcast('ide:loaded')
+ return (_loaded = true)
+ })
+
+ $scope.$on('cursor:editor:update', eventTracking.editingSessionHeartbeat)
+
+ const DARK_THEMES = [
+ 'ambiance',
+ 'chaos',
+ 'clouds_midnight',
+ 'cobalt',
+ 'idle_fingers',
+ 'merbivore',
+ 'merbivore_soft',
+ 'mono_industrial',
+ 'monokai',
+ 'pastel_on_dark',
+ 'solarized_dark',
+ 'terminal',
+ 'tomorrow_night',
+ 'tomorrow_night_blue',
+ 'tomorrow_night_bright',
+ 'tomorrow_night_eighties',
+ 'twilight',
+ 'vibrant_ink'
+ ]
+ $scope.darkTheme = false
+ $scope.$watch('settings.editorTheme', function (theme) {
+ if (Array.from(DARK_THEMES).includes(theme)) {
+ return ($scope.darkTheme = true)
+ } else {
+ return ($scope.darkTheme = false)
+ }
+ })
+
+ ide.localStorage = localStorage
+
+ ide.browserIsSafari = false
+
+ $scope.switchToFlatLayout = function (view) {
+ $scope.ui.pdfLayout = 'flat'
+ $scope.ui.view = view
+ return ide.localStorage('pdf.layout', 'flat')
}
- $scope.$broadcast('ide:loaded')
- return (_loaded = true)
- })
- $scope.$on('cursor:editor:update', eventTracking.editingSessionHeartbeat)
+ $scope.switchToSideBySideLayout = function (view) {
+ $scope.ui.pdfLayout = 'sideBySide'
+ $scope.ui.view = view
+ return localStorage('pdf.layout', 'split')
+ }
- const DARK_THEMES = [
- 'ambiance',
- 'chaos',
- 'clouds_midnight',
- 'cobalt',
- 'idle_fingers',
- 'merbivore',
- 'merbivore_soft',
- 'mono_industrial',
- 'monokai',
- 'pastel_on_dark',
- 'solarized_dark',
- 'terminal',
- 'tomorrow_night',
- 'tomorrow_night_blue',
- 'tomorrow_night_bright',
- 'tomorrow_night_eighties',
- 'twilight',
- 'vibrant_ink'
- ]
- $scope.darkTheme = false
- $scope.$watch('settings.editorTheme', function(theme) {
- if (Array.from(DARK_THEMES).includes(theme)) {
- return ($scope.darkTheme = true)
+ if ((pdfLayout = localStorage('pdf.layout'))) {
+ if (pdfLayout === 'split') {
+ $scope.switchToSideBySideLayout()
+ }
+ if (pdfLayout === 'flat') {
+ $scope.switchToFlatLayout()
+ }
} else {
- return ($scope.darkTheme = false)
- }
- })
-
- ide.localStorage = localStorage
-
- ide.browserIsSafari = false
-
- $scope.switchToFlatLayout = function(view) {
- $scope.ui.pdfLayout = 'flat'
- $scope.ui.view = view
- return ide.localStorage('pdf.layout', 'flat')
- }
-
- $scope.switchToSideBySideLayout = function(view) {
- $scope.ui.pdfLayout = 'sideBySide'
- $scope.ui.view = view
- return localStorage('pdf.layout', 'split')
- }
-
- if ((pdfLayout = localStorage('pdf.layout'))) {
- if (pdfLayout === 'split') {
$scope.switchToSideBySideLayout()
}
- if (pdfLayout === 'flat') {
- $scope.switchToFlatLayout()
+
+ try {
+ ;({ userAgent } = navigator)
+ ide.browserIsSafari =
+ userAgent &&
+ /.*Safari\/.*/.test(userAgent) &&
+ !/.*Chrome\/.*/.test(userAgent) &&
+ !/.*Chromium\/.*/.test(userAgent)
+ } catch (error) {
+ err = error
+ console.error(err)
}
- } else {
- $scope.switchToSideBySideLayout()
- }
- try {
- ;({ userAgent } = navigator)
- ide.browserIsSafari =
- userAgent &&
- /.*Safari\/.*/.test(userAgent) &&
- !/.*Chrome\/.*/.test(userAgent) &&
- !/.*Chromium\/.*/.test(userAgent)
- } catch (error) {
- err = error
- console.error(err)
- }
-
- if (ide.browserIsSafari) {
- ide.safariScrollPatcher = new SafariScrollPatcher($scope)
- }
-
- // Fix Chrome 61 and 62 text-shadow rendering
- let browserIsChrome61or62 = false
- try {
- const chromeVersion =
- parseFloat(navigator.userAgent.split(' Chrome/')[1]) || null
- browserIsChrome61or62 = chromeVersion != null
- if (browserIsChrome61or62) {
- document.styleSheets[0].insertRule(
- '.ace_editor.ace_autocomplete .ace_completion-highlight { text-shadow: none !important; font-weight: bold; }',
- 1
- )
+ if (ide.browserIsSafari) {
+ ide.safariScrollPatcher = new SafariScrollPatcher($scope)
}
- } catch (error1) {
- err = error1
- console.error(err)
- }
- // User can append ?ft=somefeature to url to activate a feature toggle
- ide.featureToggle = __guard__(
- __guard__(
- typeof location !== 'undefined' && location !== null
- ? location.search
- : undefined,
- x1 => x1.match(/^\?ft=(\w+)$/)
- ),
- x => x[1]
- )
-
- return ide.socket.on('project:publicAccessLevel:changed', data => {
- if (data.newAccessLevel != null) {
- ide.$scope.project.publicAccesLevel = data.newAccessLevel
- return $scope.$digest()
+ // Fix Chrome 61 and 62 text-shadow rendering
+ let browserIsChrome61or62 = false
+ try {
+ const chromeVersion =
+ parseFloat(navigator.userAgent.split(' Chrome/')[1]) || null
+ browserIsChrome61or62 = chromeVersion != null
+ if (browserIsChrome61or62) {
+ document.styleSheets[0].insertRule(
+ '.ace_editor.ace_autocomplete .ace_completion-highlight { text-shadow: none !important; font-weight: bold; }',
+ 1
+ )
+ }
+ } catch (error1) {
+ err = error1
+ console.error(err)
}
- })
-})
+
+ // User can append ?ft=somefeature to url to activate a feature toggle
+ ide.featureToggle = __guard__(
+ __guard__(
+ typeof location !== 'undefined' && location !== null
+ ? location.search
+ : undefined,
+ x1 => x1.match(/^\?ft=(\w+)$/)
+ ),
+ x => x[1]
+ )
+
+ return ide.socket.on('project:publicAccessLevel:changed', data => {
+ if (data.newAccessLevel != null) {
+ ide.$scope.project.publicAccesLevel = data.newAccessLevel
+ return $scope.$digest()
+ }
+ })
+ }
+)
export default angular.bootstrap(document.body, ['SharelatexApp'])
diff --git a/services/web/frontend/js/ide/binary-files/controllers/BinaryFileController.js b/services/web/frontend/js/ide/binary-files/controllers/BinaryFileController.js
index 3d77857809..3c8d722827 100644
--- a/services/web/frontend/js/ide/binary-files/controllers/BinaryFileController.js
+++ b/services/web/frontend/js/ide/binary-files/controllers/BinaryFileController.js
@@ -1,196 +1,189 @@
import App from '../../../base'
-export default App.controller('BinaryFileController', function(
- $scope,
- $rootScope,
- $http,
- $timeout,
- $element,
- ide,
- waitFor
-) {
- const MAX_FILE_SIZE = 2 * 1024 * 1024
- const MAX_URL_LENGTH = 60
- const FRONT_OF_URL_LENGTH = 35
- const FILLER = '...'
- const TAIL_OF_URL_LENGTH =
- MAX_URL_LENGTH - FRONT_OF_URL_LENGTH - FILLER.length
+export default App.controller(
+ 'BinaryFileController',
+ function ($scope, $rootScope, $http, $timeout, $element, ide, waitFor) {
+ const MAX_FILE_SIZE = 2 * 1024 * 1024
+ const MAX_URL_LENGTH = 60
+ const FRONT_OF_URL_LENGTH = 35
+ const FILLER = '...'
+ const TAIL_OF_URL_LENGTH =
+ MAX_URL_LENGTH - FRONT_OF_URL_LENGTH - FILLER.length
- const textExtensions = window.ExposedSettings.textExtensions
- const imageExtensions = ['png', 'jpg', 'jpeg', 'gif']
- const previewableExtensions = []
+ const textExtensions = window.ExposedSettings.textExtensions
+ const imageExtensions = ['png', 'jpg', 'jpeg', 'gif']
+ const previewableExtensions = []
- const extension = file =>
- file.name
- .split('.')
- .pop()
- .toLowerCase()
+ const extension = file => file.name.split('.').pop().toLowerCase()
- $scope.isTextFile = () =>
- textExtensions.indexOf(extension($scope.openFile)) > -1
- $scope.isImageFile = () =>
- imageExtensions.indexOf(extension($scope.openFile)) > -1
- $scope.isPreviewableFile = () =>
- previewableExtensions.indexOf(extension($scope.openFile)) > -1
- $scope.isUnpreviewableFile = () =>
- !$scope.isTextFile() && !$scope.isImageFile() && !$scope.isPreviewableFile()
+ $scope.isTextFile = () =>
+ textExtensions.indexOf(extension($scope.openFile)) > -1
+ $scope.isImageFile = () =>
+ imageExtensions.indexOf(extension($scope.openFile)) > -1
+ $scope.isPreviewableFile = () =>
+ previewableExtensions.indexOf(extension($scope.openFile)) > -1
+ $scope.isUnpreviewableFile = () =>
+ !$scope.isTextFile() &&
+ !$scope.isImageFile() &&
+ !$scope.isPreviewableFile()
- $scope.textPreview = {
- loading: false,
- shouldShowDots: false,
- error: false,
- data: null
- }
-
- $scope.refreshing = false
- $scope.refreshError = null
-
- $scope.displayUrl = function(url) {
- if (url == null) {
- return
+ $scope.textPreview = {
+ loading: false,
+ shouldShowDots: false,
+ error: false,
+ data: null
}
- if (url.length > MAX_URL_LENGTH) {
- const front = url.slice(0, FRONT_OF_URL_LENGTH)
- const tail = url.slice(url.length - TAIL_OF_URL_LENGTH)
- return front + FILLER + tail
- }
- return url
- }
- $scope.refreshFile = function(file) {
- $scope.refreshing = true
+ $scope.refreshing = false
$scope.refreshError = null
- window.expectingLinkedFileRefreshedSocketFor = file.name
- ide.fileTreeManager
- .refreshLinkedFile(file)
- .then(function(response) {
- const { data } = response
- const newFileId = data.new_file_id
- $timeout(
- () =>
- waitFor(() => ide.fileTreeManager.findEntityById(newFileId), 5000)
- .then(newFile => {
- ide.binaryFilesManager.openFile(newFile)
- window.expectingLinkedFileRefreshedSocketFor = null
- })
- .catch(err => console.warn(err)),
- 0
- )
- $scope.refreshError = null
- })
- .catch(response => ($scope.refreshError = response.data))
- .finally(() => {
- $scope.refreshing = false
- const provider = file.linkedFileData.provider
- if (
- provider === 'mendeley' ||
- provider === 'zotero' ||
- file.name.match(/^.*\.bib$/)
- ) {
- ide.$scope.$emit('references:should-reindex', {})
- }
- })
- }
-
- // Callback fired when the `img` tag fails to load,
- // `failedLoad` used to show the "No Preview" message
- $scope.failedLoad = false
- window.sl_binaryFilePreviewError = () => {
- $scope.failedLoad = true
- $scope.$apply()
- }
-
- // Callback fired when the `img` tag is done loading,
- // `imgLoaded` is used to show the spinner gif while loading
- $scope.imgLoaded = false
- window.sl_binaryFilePreviewLoaded = () => {
- $scope.imgLoaded = true
- $scope.$apply()
- }
-
- if ($scope.isTextFile()) {
- loadTextFilePreview()
- }
-
- function loadTextFilePreview() {
- const url = `/project/${window.project_id}/file/${$scope.openFile.id}`
- let truncated = false
- displayPreviewLoading()
- getFileSize(url)
- .then(fileSize => {
- const opts = {}
- if (fileSize > MAX_FILE_SIZE) {
- truncated = true
- opts.maxSize = MAX_FILE_SIZE
- }
- return getFileContents(url, opts)
- })
- .then(contents => {
- const displayedContents = truncated
- ? truncateFileContents(contents)
- : contents
- displayPreview(displayedContents, truncated)
- })
- .catch(err => {
- console.error(err)
- displayPreviewError()
- })
- }
-
- function getFileSize(url) {
- return $http.head(url).then(response => {
- const size = parseInt(response.headers('Content-Length'), 10)
- if (isNaN(size)) {
- throw new Error('Could not parse Content-Length header')
+ $scope.displayUrl = function (url) {
+ if (url == null) {
+ return
}
- return size
- })
- }
-
- function getFileContents(url, opts = {}) {
- const { maxSize } = opts
- if (maxSize != null) {
- url += `?range=0-${maxSize}`
+ if (url.length > MAX_URL_LENGTH) {
+ const front = url.slice(0, FRONT_OF_URL_LENGTH)
+ const tail = url.slice(url.length - TAIL_OF_URL_LENGTH)
+ return front + FILLER + tail
+ }
+ return url
}
- return $http
- .get(url, {
- transformResponse: null // Don't parse JSON
+
+ $scope.refreshFile = function (file) {
+ $scope.refreshing = true
+ $scope.refreshError = null
+ window.expectingLinkedFileRefreshedSocketFor = file.name
+ ide.fileTreeManager
+ .refreshLinkedFile(file)
+ .then(function (response) {
+ const { data } = response
+ const newFileId = data.new_file_id
+ $timeout(
+ () =>
+ waitFor(() => ide.fileTreeManager.findEntityById(newFileId), 5000)
+ .then(newFile => {
+ ide.binaryFilesManager.openFile(newFile)
+ window.expectingLinkedFileRefreshedSocketFor = null
+ })
+ .catch(err => console.warn(err)),
+
+ 0
+ )
+ $scope.refreshError = null
+ })
+ .catch(response => ($scope.refreshError = response.data))
+ .finally(() => {
+ $scope.refreshing = false
+ const provider = file.linkedFileData.provider
+ if (
+ provider === 'mendeley' ||
+ provider === 'zotero' ||
+ file.name.match(/^.*\.bib$/)
+ ) {
+ ide.$scope.$emit('references:should-reindex', {})
+ }
+ })
+ }
+
+ // Callback fired when the `img` tag fails to load,
+ // `failedLoad` used to show the "No Preview" message
+ $scope.failedLoad = false
+ window.sl_binaryFilePreviewError = () => {
+ $scope.failedLoad = true
+ $scope.$apply()
+ }
+
+ // Callback fired when the `img` tag is done loading,
+ // `imgLoaded` is used to show the spinner gif while loading
+ $scope.imgLoaded = false
+ window.sl_binaryFilePreviewLoaded = () => {
+ $scope.imgLoaded = true
+ $scope.$apply()
+ }
+
+ if ($scope.isTextFile()) {
+ loadTextFilePreview()
+ }
+
+ function loadTextFilePreview() {
+ const url = `/project/${window.project_id}/file/${$scope.openFile.id}`
+ let truncated = false
+ displayPreviewLoading()
+ getFileSize(url)
+ .then(fileSize => {
+ const opts = {}
+ if (fileSize > MAX_FILE_SIZE) {
+ truncated = true
+ opts.maxSize = MAX_FILE_SIZE
+ }
+ return getFileContents(url, opts)
+ })
+ .then(contents => {
+ const displayedContents = truncated
+ ? truncateFileContents(contents)
+ : contents
+ displayPreview(displayedContents, truncated)
+ })
+ .catch(err => {
+ console.error(err)
+ displayPreviewError()
+ })
+ }
+
+ function getFileSize(url) {
+ return $http.head(url).then(response => {
+ const size = parseInt(response.headers('Content-Length'), 10)
+ if (isNaN(size)) {
+ throw new Error('Could not parse Content-Length header')
+ }
+ return size
})
- .then(response => {
- return response.data
- })
- }
+ }
- function truncateFileContents(contents) {
- return contents.replace(/\n.*$/, '')
- }
+ function getFileContents(url, opts = {}) {
+ const { maxSize } = opts
+ if (maxSize != null) {
+ url += `?range=0-${maxSize}`
+ }
+ return $http
+ .get(url, {
+ transformResponse: null // Don't parse JSON
+ })
+ .then(response => {
+ return response.data
+ })
+ }
- function displayPreviewLoading() {
- $scope.textPreview.data = null
- $scope.textPreview.loading = true
- $scope.textPreview.shouldShowDots = false
- $scope.$apply()
- }
+ function truncateFileContents(contents) {
+ return contents.replace(/\n.*$/, '')
+ }
- function displayPreview(contents, truncated) {
- $scope.textPreview.error = false
- $scope.textPreview.data = contents
- $scope.textPreview.shouldShowDots = truncated
- $timeout(setPreviewHeight, 0)
- }
+ function displayPreviewLoading() {
+ $scope.textPreview.data = null
+ $scope.textPreview.loading = true
+ $scope.textPreview.shouldShowDots = false
+ $scope.$apply()
+ }
- function displayPreviewError() {
- $scope.textPreview.error = true
- $scope.textPreview.loading = false
- }
+ function displayPreview(contents, truncated) {
+ $scope.textPreview.error = false
+ $scope.textPreview.data = contents
+ $scope.textPreview.shouldShowDots = truncated
+ $timeout(setPreviewHeight, 0)
+ }
- function setPreviewHeight() {
- const $preview = $element.find('.text-preview .scroll-container')
- const $header = $element.find('.binary-file-header')
- const maxHeight = $element.height() - $header.height() - 14 // borders + margin
- $preview.css({ 'max-height': maxHeight })
- // Don't show the preview until we've set the height, otherwise we jump around
- $scope.textPreview.loading = false
+ function displayPreviewError() {
+ $scope.textPreview.error = true
+ $scope.textPreview.loading = false
+ }
+
+ function setPreviewHeight() {
+ const $preview = $element.find('.text-preview .scroll-container')
+ const $header = $element.find('.binary-file-header')
+ const maxHeight = $element.height() - $header.height() - 14 // borders + margin
+ $preview.css({ 'max-height': maxHeight })
+ // Don't show the preview until we've set the height, otherwise we jump around
+ $scope.textPreview.loading = false
+ }
}
-})
+)
diff --git a/services/web/frontend/js/ide/chat/controllers/ChatButtonController.js b/services/web/frontend/js/ide/chat/controllers/ChatButtonController.js
index 6071427801..10047cfbba 100644
--- a/services/web/frontend/js/ide/chat/controllers/ChatButtonController.js
+++ b/services/web/frontend/js/ide/chat/controllers/ChatButtonController.js
@@ -13,9 +13,9 @@
*/
import App from '../../../base'
-export default App.controller('ChatButtonController', function($scope, ide) {
+export default App.controller('ChatButtonController', function ($scope, ide) {
let clearNewMessageNotification
- $scope.toggleChat = function() {
+ $scope.toggleChat = function () {
$scope.ui.chatOpen = !$scope.ui.chatOpen
return $scope.resetUnreadMessages()
}
@@ -49,13 +49,13 @@ export default App.controller('ChatButtonController', function($scope, ide) {
let focussed = true
let newMessageNotificationTimeout = null
let originalTitle = null
- $(window).on('focus', function() {
+ $(window).on('focus', function () {
clearNewMessageNotification()
return (focussed = true)
})
$(window).on('blur', () => (focussed = false))
- var flashTitle = function() {
+ var flashTitle = function () {
if (!focussed && newMessageNotificationTimeout == null) {
let changeTitle
if (!originalTitle) {
@@ -72,7 +72,7 @@ export default App.controller('ChatButtonController', function($scope, ide) {
}
}
- return (clearNewMessageNotification = function() {
+ return (clearNewMessageNotification = function () {
clearTimeout(newMessageNotificationTimeout)
newMessageNotificationTimeout = null
if (originalTitle != null) {
diff --git a/services/web/frontend/js/ide/clone/controllers/CloneProjectModalController.js b/services/web/frontend/js/ide/clone/controllers/CloneProjectModalController.js
index e5484fb4f1..0a06bec495 100644
--- a/services/web/frontend/js/ide/clone/controllers/CloneProjectModalController.js
+++ b/services/web/frontend/js/ide/clone/controllers/CloneProjectModalController.js
@@ -11,47 +11,44 @@
*/
import App from '../../../base'
-export default App.controller('CloneProjectModalController', function(
- $scope,
- $modalInstance,
- $timeout,
- $http,
- ide
-) {
- $scope.inputs = { projectName: ide.$scope.project.name + ' (Copy)' }
- $scope.state = {
- inflight: false,
- error: false
- }
+export default App.controller(
+ 'CloneProjectModalController',
+ function ($scope, $modalInstance, $timeout, $http, ide) {
+ $scope.inputs = { projectName: ide.$scope.project.name + ' (Copy)' }
+ $scope.state = {
+ inflight: false,
+ error: false
+ }
- $modalInstance.opened.then(() =>
- $timeout(() => $scope.$broadcast('open'), 200)
- )
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
- const cloneProject = cloneName =>
- $http.post(`/project/${ide.$scope.project._id}/clone`, {
- _csrf: window.csrfToken,
- projectName: cloneName
- })
-
- $scope.clone = function() {
- $scope.state.inflight = true
- $scope.state.error = false
- return cloneProject($scope.inputs.projectName)
- .then(function(response) {
- const { data } = response
- return (window.location = `/project/${data.project_id}`)
+ const cloneProject = cloneName =>
+ $http.post(`/project/${ide.$scope.project._id}/clone`, {
+ _csrf: window.csrfToken,
+ projectName: cloneName
})
- .catch(function(response) {
- const { data, status } = response
- $scope.state.inflight = false
- if (status === 400) {
- return ($scope.state.error = { message: data })
- } else {
- return ($scope.state.error = true)
- }
- })
- }
- return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
-})
+ $scope.clone = function () {
+ $scope.state.inflight = true
+ $scope.state.error = false
+ return cloneProject($scope.inputs.projectName)
+ .then(function (response) {
+ const { data } = response
+ return (window.location = `/project/${data.project_id}`)
+ })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.state.inflight = false
+ if (status === 400) {
+ return ($scope.state.error = { message: data })
+ } else {
+ return ($scope.state.error = true)
+ }
+ })
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
diff --git a/services/web/frontend/js/ide/cobranding/CobrandingDataService.js b/services/web/frontend/js/ide/cobranding/CobrandingDataService.js
index a66da4420b..8f35953330 100644
--- a/services/web/frontend/js/ide/cobranding/CobrandingDataService.js
+++ b/services/web/frontend/js/ide/cobranding/CobrandingDataService.js
@@ -14,7 +14,7 @@
import App from '../../base'
const _cobrandingData = window.brandVariation
-export default App.factory('CobrandingDataService', function() {
+export default App.factory('CobrandingDataService', function () {
const isProjectCobranded = () => _cobrandingData != null
const getLogoImgUrl = () =>
diff --git a/services/web/frontend/js/ide/connection/ConnectionManager.js b/services/web/frontend/js/ide/connection/ConnectionManager.js
index c2fa64adc9..ed80a2a05f 100644
--- a/services/web/frontend/js/ide/connection/ConnectionManager.js
+++ b/services/web/frontend/js/ide/connection/ConnectionManager.js
@@ -15,7 +15,7 @@ import SocketIoShim from './SocketIoShim'
let ConnectionManager
const ONEHOUR = 1000 * 60 * 60
-export default ConnectionManager = (function() {
+export default ConnectionManager = (function () {
ConnectionManager = class ConnectionManager {
static initClass() {
this.prototype.disconnectAfterMs = ONEHOUR * 24
diff --git a/services/web/frontend/js/ide/connection/SocketIoShim.js b/services/web/frontend/js/ide/connection/SocketIoShim.js
index 35e12db59f..771d051554 100644
--- a/services/web/frontend/js/ide/connection/SocketIoShim.js
+++ b/services/web/frontend/js/ide/connection/SocketIoShim.js
@@ -17,7 +17,7 @@ const transparentMethods = [
'removeListener'
]
for (let method of transparentMethods) {
- SocketShimBase.prototype[method] = function() {
+ SocketShimBase.prototype[method] = function () {
this._socket[method].apply(this._socket, arguments)
}
}
diff --git a/services/web/frontend/js/ide/directives/layout.js b/services/web/frontend/js/ide/directives/layout.js
index 5a54d765bb..ac8762fd53 100644
--- a/services/web/frontend/js/ide/directives/layout.js
+++ b/services/web/frontend/js/ide/directives/layout.js
@@ -96,7 +96,7 @@ export default App.directive('layout', ($parse, $compile, ide) => ({
options.east.resizerCursor = 'ew-resize'
options.west.resizerCursor = 'ew-resize'
- const repositionControls = function() {
+ const repositionControls = function () {
state = element.layout().readState()
if (state.east != null) {
const controls = element.find('> .ui-layout-resizer-controls')
@@ -111,7 +111,7 @@ export default App.directive('layout', ($parse, $compile, ide) => ({
}
}
- const repositionCustomToggler = function() {
+ const repositionCustomToggler = function () {
if (customTogglerEl == null) {
return
}
@@ -126,7 +126,7 @@ export default App.directive('layout', ($parse, $compile, ide) => ({
}
}
- const resetOpenStates = function() {
+ const resetOpenStates = function () {
state = element.layout().readState()
if (attrs.openEast != null && state.east != null) {
const openEast = $parse(attrs.openEast)
@@ -135,7 +135,7 @@ export default App.directive('layout', ($parse, $compile, ide) => ({
}
// Someone moved the resizer
- var onInternalResize = function() {
+ var onInternalResize = function () {
state = element.layout().readState()
scope.$broadcast(`layout:${name}:resize`, state)
repositionControls()
@@ -147,7 +147,7 @@ export default App.directive('layout', ($parse, $compile, ide) => ({
let oldWidth = element.width()
// Something resized our parent element
- const onExternalResize = function() {
+ const onExternalResize = function () {
if (
attrs.resizeProportionally != null &&
scope.$eval(attrs.resizeProportionally)
@@ -194,7 +194,7 @@ export default App.directive('layout', ($parse, $compile, ide) => ({
customTogglerScope.tooltipPlacement =
customTogglerPane === 'east' ? 'left' : 'right'
- customTogglerScope.handleClick = function() {
+ customTogglerScope.handleClick = function () {
element.layout().toggle(customTogglerPane)
return repositionCustomToggler()
}
@@ -210,7 +210,7 @@ ng-click=\"handleClick()\">\
element.append(customTogglerEl)
}
- var onPaneOpen = function(pane) {
+ var onPaneOpen = function (pane) {
if (!hasCustomToggler && pane !== customTogglerPane) {
return
}
@@ -219,7 +219,7 @@ ng-click=\"handleClick()\">\
.$applyAsync(() => (customTogglerEl.scope().isOpen = true))
}
- var onPaneClose = function(pane) {
+ var onPaneClose = function (pane) {
if (!hasCustomToggler && pane !== customTogglerPane) {
return
}
@@ -241,7 +241,7 @@ ng-click=\"handleClick()\">\
})
if (attrs.openEast != null) {
- scope.$watch(attrs.openEast, function(value, oldValue) {
+ scope.$watch(attrs.openEast, function (value, oldValue) {
if (value != null && value !== oldValue) {
if (value) {
element.layout().open('east')
@@ -268,14 +268,14 @@ ng-click=\"handleClick()\">\
onInternalResize()
if (attrs.layoutDisabled != null) {
- return scope.$watch(attrs.layoutDisabled, function(value) {
+ return scope.$watch(attrs.layoutDisabled, function (value) {
if (value) {
element.layout().hide('east')
} else {
element.layout().show('east')
}
if (hasCustomToggler) {
- return customTogglerEl.scope().$applyAsync(function() {
+ return customTogglerEl.scope().$applyAsync(function () {
customTogglerEl.scope().isOpen = !value
return (customTogglerEl.scope().isVisible = !value)
})
diff --git a/services/web/frontend/js/ide/editor/Document.js b/services/web/frontend/js/ide/editor/Document.js
index 16e0d4a1a5..605b49db25 100644
--- a/services/web/frontend/js/ide/editor/Document.js
+++ b/services/web/frontend/js/ide/editor/Document.js
@@ -21,7 +21,7 @@ import ShareJsDoc from './ShareJsDoc'
import RangesTracker from '../review-panel/RangesTracker'
let Document
-export default Document = (function() {
+export default Document = (function () {
Document = class Document extends EventEmitter {
static initClass() {
this.prototype.MAX_PENDING_OP_SIZE = 64
@@ -250,7 +250,7 @@ export default Document = (function() {
join(callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
this.wantToBeJoined = true
this._cancelLeave()
@@ -266,7 +266,7 @@ export default Document = (function() {
leave(callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
this.flush() // force an immediate flush when leaving document
this.wantToBeJoined = false
@@ -362,8 +362,9 @@ export default Document = (function() {
// In any other situation, assume the document is unsaved.
saved = false
sl_console.log(
- `[pollSavedStatus] assuming not saved (inflightOp?: ${inflightOp !=
- null}, pendingOp?: ${pendingOp != null})`
+ `[pollSavedStatus] assuming not saved (inflightOp?: ${
+ inflightOp != null
+ }, pendingOp?: ${pendingOp != null})`
)
}
@@ -471,7 +472,7 @@ export default Document = (function() {
_joinDoc(callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
if (this.doc != null) {
this.ide.pushEvent('joinDoc:existing', {
@@ -562,7 +563,7 @@ export default Document = (function() {
_leaveDoc(callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
this.ide.pushEvent('leaveDoc', {
doc_id: this.doc_id
diff --git a/services/web/frontend/js/ide/editor/EditorManager.js b/services/web/frontend/js/ide/editor/EditorManager.js
index 62494715bb..d9a049f2ca 100644
--- a/services/web/frontend/js/ide/editor/EditorManager.js
+++ b/services/web/frontend/js/ide/editor/EditorManager.js
@@ -21,7 +21,7 @@ import './directives/toggleSwitch'
import './controllers/SavingNotificationController'
let EditorManager
-export default EditorManager = (function() {
+export default EditorManager = (function () {
EditorManager = class EditorManager {
static initClass() {
this.prototype._syncTimeout = null
@@ -259,7 +259,7 @@ export default EditorManager = (function() {
_doOpenNewDocument(doc, callback) {
if (callback == null) {
- callback = function(error, sharejs_doc) {}
+ callback = function (error, sharejs_doc) {}
}
sl_console.log('[_doOpenNewDocument] Opening...')
const new_sharejs_doc = Document.getDocument(this.ide, doc.id)
diff --git a/services/web/frontend/js/ide/editor/ShareJsDoc.js b/services/web/frontend/js/ide/editor/ShareJsDoc.js
index 63bbb3ac7f..7219c67e69 100644
--- a/services/web/frontend/js/ide/editor/ShareJsDoc.js
+++ b/services/web/frontend/js/ide/editor/ShareJsDoc.js
@@ -24,7 +24,7 @@ let ShareJsDoc
const SINGLE_USER_FLUSH_DELAY = 2000 // ms
const MULTI_USER_FLUSH_DELAY = 500 // ms
-export default ShareJsDoc = (function() {
+export default ShareJsDoc = (function () {
ShareJsDoc = class ShareJsDoc extends EventEmitter {
static initClass() {
this.prototype.INFLIGHT_OP_TIMEOUT = 5000 // Retry sending ops after 5 seconds without an ack
@@ -171,7 +171,7 @@ export default ShareJsDoc = (function() {
}
this.queuedMessages.push(message)
// keep the queue in order, lowest version first
- this.queuedMessages.sort(function(a, b) {
+ this.queuedMessages.sort(function (a, b) {
return a.v - b.v
})
}
diff --git a/services/web/frontend/js/ide/editor/controllers/SavingNotificationController.js b/services/web/frontend/js/ide/editor/controllers/SavingNotificationController.js
index bb1e002328..63e967b577 100644
--- a/services/web/frontend/js/ide/editor/controllers/SavingNotificationController.js
+++ b/services/web/frontend/js/ide/editor/controllers/SavingNotificationController.js
@@ -14,90 +14,89 @@
import App from '../../../base'
import Document from '../Document'
-export default App.controller('SavingNotificationController', function(
- $scope,
- $interval,
- ide
-) {
- let warnAboutUnsavedChanges
- setInterval(() => pollSavedStatus(), 1000)
+export default App.controller(
+ 'SavingNotificationController',
+ function ($scope, $interval, ide) {
+ let warnAboutUnsavedChanges
+ setInterval(() => pollSavedStatus(), 1000)
- $(window).bind('beforeunload', () => {
- return warnAboutUnsavedChanges()
- })
+ $(window).bind('beforeunload', () => {
+ return warnAboutUnsavedChanges()
+ })
- let lockEditorModal = null // modal showing "connection lost"
- let originalPermissionsLevel
- const MAX_UNSAVED_SECONDS = 15 // lock the editor after this time if unsaved
+ let lockEditorModal = null // modal showing "connection lost"
+ let originalPermissionsLevel
+ const MAX_UNSAVED_SECONDS = 15 // lock the editor after this time if unsaved
- $scope.docSavingStatus = {}
- var pollSavedStatus = function() {
- let t
- const oldStatus = $scope.docSavingStatus
- const oldUnsavedCount = $scope.docSavingStatusCount
- const newStatus = {}
- let newUnsavedCount = 0
- let maxUnsavedSeconds = 0
+ $scope.docSavingStatus = {}
+ var pollSavedStatus = function () {
+ let t
+ const oldStatus = $scope.docSavingStatus
+ const oldUnsavedCount = $scope.docSavingStatusCount
+ const newStatus = {}
+ let newUnsavedCount = 0
+ let maxUnsavedSeconds = 0
- for (let doc_id in Document.openDocs) {
- const doc = Document.openDocs[doc_id]
- const saving = doc.pollSavedStatus()
- if (!saving) {
- newUnsavedCount++
- if (oldStatus[doc_id] != null) {
- newStatus[doc_id] = oldStatus[doc_id]
- t = newStatus[doc_id].unsavedSeconds += 1
- if (t > maxUnsavedSeconds) {
- maxUnsavedSeconds = t
- }
- } else {
- newStatus[doc_id] = {
- unsavedSeconds: 0,
- doc: ide.fileTreeManager.findEntityById(doc_id)
+ for (let doc_id in Document.openDocs) {
+ const doc = Document.openDocs[doc_id]
+ const saving = doc.pollSavedStatus()
+ if (!saving) {
+ newUnsavedCount++
+ if (oldStatus[doc_id] != null) {
+ newStatus[doc_id] = oldStatus[doc_id]
+ t = newStatus[doc_id].unsavedSeconds += 1
+ if (t > maxUnsavedSeconds) {
+ maxUnsavedSeconds = t
+ }
+ } else {
+ newStatus[doc_id] = {
+ unsavedSeconds: 0,
+ doc: ide.fileTreeManager.findEntityById(doc_id)
+ }
}
}
}
- }
- if (newUnsavedCount > 0 && t > MAX_UNSAVED_SECONDS && !lockEditorModal) {
- lockEditorModal = ide.showLockEditorMessageModal(
- 'Connection lost',
- 'Sorry, the connection to the server is down.'
- )
+ if (newUnsavedCount > 0 && t > MAX_UNSAVED_SECONDS && !lockEditorModal) {
+ lockEditorModal = ide.showLockEditorMessageModal(
+ 'Connection lost',
+ 'Sorry, the connection to the server is down.'
+ )
- // put editor in readOnly mode
- originalPermissionsLevel = ide.$scope.permissionsLevel
- ide.$scope.permissionsLevel = 'readOnly'
+ // put editor in readOnly mode
+ originalPermissionsLevel = ide.$scope.permissionsLevel
+ ide.$scope.permissionsLevel = 'readOnly'
- lockEditorModal.result.finally(() => {
- lockEditorModal = null // unset the modal if connection comes back
- // restore original permissions
- ide.$scope.permissionsLevel = originalPermissionsLevel
- })
- }
+ lockEditorModal.result.finally(() => {
+ lockEditorModal = null // unset the modal if connection comes back
+ // restore original permissions
+ ide.$scope.permissionsLevel = originalPermissionsLevel
+ })
+ }
- if (lockEditorModal && newUnsavedCount === 0) {
- lockEditorModal.dismiss('connection back up')
- // restore original permissions if they were changed
- if (originalPermissionsLevel) {
- ide.$scope.permissionsLevel = originalPermissionsLevel
+ if (lockEditorModal && newUnsavedCount === 0) {
+ lockEditorModal.dismiss('connection back up')
+ // restore original permissions if they were changed
+ if (originalPermissionsLevel) {
+ ide.$scope.permissionsLevel = originalPermissionsLevel
+ }
+ }
+
+ // for performance, only update the display if the old or new
+ // counts of unsaved files are nonzeror. If both old and new
+ // unsaved counts are zero then we know we are in a good state
+ // and don't need to do anything to the UI.
+ if (newUnsavedCount || oldUnsavedCount) {
+ $scope.docSavingStatus = newStatus
+ $scope.docSavingStatusCount = newUnsavedCount
+ return $scope.$apply()
}
}
- // for performance, only update the display if the old or new
- // counts of unsaved files are nonzeror. If both old and new
- // unsaved counts are zero then we know we are in a good state
- // and don't need to do anything to the UI.
- if (newUnsavedCount || oldUnsavedCount) {
- $scope.docSavingStatus = newStatus
- $scope.docSavingStatusCount = newUnsavedCount
- return $scope.$apply()
- }
+ return (warnAboutUnsavedChanges = function () {
+ if (Document.hasUnsavedChanges()) {
+ return 'You have unsaved changes. If you leave now they will not be saved.'
+ }
+ })
}
-
- return (warnAboutUnsavedChanges = function() {
- if (Document.hasUnsavedChanges()) {
- return 'You have unsaved changes. If you leave now they will not be saved.'
- }
- })
-})
+)
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor.js b/services/web/frontend/js/ide/editor/directives/aceEditor.js
index 3bc583ab94..87d093da68 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor.js
@@ -43,850 +43,857 @@ ace.config.setDefaultValue('session', 'useWorker', false)
// the cache.
if (ace.config._moduleUrl == null) {
ace.config._moduleUrl = ace.config.moduleUrl
- ace.config.moduleUrl = function(...args) {
+ ace.config.moduleUrl = function (...args) {
const url = ace.config._moduleUrl(...Array.from(args || []))
return url
}
}
-App.directive('aceEditor', function(
- ide,
- $timeout,
- $compile,
- $rootScope,
- eventTracking,
- localStorage,
- $cacheFactory,
- metadata,
- graphics,
- preamble,
- files,
- $http,
- $q,
- $window
-) {
- monkeyPatchSearch($rootScope, $compile)
+App.directive(
+ 'aceEditor',
+ function (
+ ide,
+ $timeout,
+ $compile,
+ $rootScope,
+ eventTracking,
+ localStorage,
+ $cacheFactory,
+ metadata,
+ graphics,
+ preamble,
+ files,
+ $http,
+ $q,
+ $window
+ ) {
+ monkeyPatchSearch($rootScope, $compile)
- return {
- scope: {
- theme: '=',
- showPrintMargin: '=',
- keybindings: '=',
- fontSize: '=',
- autoComplete: '=',
- autoPairDelimiters: '=',
- sharejsDoc: '=',
- spellCheck: '=',
- spellCheckLanguage: '=',
- highlights: '=',
- text: '=',
- readOnly: '=',
- annotations: '=',
- navigateHighlights: '=',
- fileName: '=',
- onCtrlEnter: '=', // Compile
- onCtrlJ: '=', // Toggle the review panel
- onCtrlShiftC: '=', // Add a new comment
- onCtrlShiftA: '=', // Toggle track-changes on/off
- onSave: '=', // Cmd/Ctrl-S or :w in Vim
- syntaxValidation: '=',
- reviewPanel: '=',
- eventsBridge: '=',
- trackChanges: '=',
- docId: '=',
- rendererData: '=',
- lineHeight: '=',
- fontFamily: '='
- },
- link(scope, element, attrs) {
- // Don't freak out if we're already in an apply callback
- let spellCheckManager
- scope.$originalApply = scope.$apply
- scope.$apply = function(fn) {
- if (fn == null) {
- fn = function() {}
+ return {
+ scope: {
+ theme: '=',
+ showPrintMargin: '=',
+ keybindings: '=',
+ fontSize: '=',
+ autoComplete: '=',
+ autoPairDelimiters: '=',
+ sharejsDoc: '=',
+ spellCheck: '=',
+ spellCheckLanguage: '=',
+ highlights: '=',
+ text: '=',
+ readOnly: '=',
+ annotations: '=',
+ navigateHighlights: '=',
+ fileName: '=',
+ onCtrlEnter: '=', // Compile
+ onCtrlJ: '=', // Toggle the review panel
+ onCtrlShiftC: '=', // Add a new comment
+ onCtrlShiftA: '=', // Toggle track-changes on/off
+ onSave: '=', // Cmd/Ctrl-S or :w in Vim
+ syntaxValidation: '=',
+ reviewPanel: '=',
+ eventsBridge: '=',
+ trackChanges: '=',
+ docId: '=',
+ rendererData: '=',
+ lineHeight: '=',
+ fontFamily: '='
+ },
+ link(scope, element, attrs) {
+ // Don't freak out if we're already in an apply callback
+ let spellCheckManager
+ scope.$originalApply = scope.$apply
+ scope.$apply = function (fn) {
+ if (fn == null) {
+ fn = function () {}
+ }
+ const phase = this.$root.$$phase
+ if (phase === '$apply' || phase === '$digest') {
+ return fn()
+ } else {
+ return this.$originalApply(fn)
+ }
}
- const phase = this.$root.$$phase
- if (phase === '$apply' || phase === '$digest') {
- return fn()
- } else {
- return this.$originalApply(fn)
+
+ const editor = ace.edit(element.find('.ace-editor-body')[0])
+ editor.$blockScrolling = Infinity
+
+ // Besides the main editor, other elements will re-use this directive
+ // for displaying read-only content -- e.g. the history panes.
+ const editorAcceptsChanges = attrs.aceEditor === 'editor'
+ if (editorAcceptsChanges) {
+ // end-to-end check for edits -> acks, globally on any doc
+ // This may catch a missing attached ShareJsDoc that in turn bails out
+ // on missing acks.
+ ide.globalEditorWatchdogManager.attachToEditor('Ace', editor)
}
- }
- const editor = ace.edit(element.find('.ace-editor-body')[0])
- editor.$blockScrolling = Infinity
+ // auto-insertion of braces, brackets, dollars
+ editor.setOption('behavioursEnabled', scope.autoPairDelimiters || false)
+ editor.setOption('wrapBehavioursEnabled', false)
- // Besides the main editor, other elements will re-use this directive
- // for displaying read-only content -- e.g. the history panes.
- const editorAcceptsChanges = attrs.aceEditor === 'editor'
- if (editorAcceptsChanges) {
- // end-to-end check for edits -> acks, globally on any doc
- // This may catch a missing attached ShareJsDoc that in turn bails out
- // on missing acks.
- ide.globalEditorWatchdogManager.attachToEditor('Ace', editor)
- }
+ scope.$watch('autoPairDelimiters', autoPairDelimiters => {
+ if (autoPairDelimiters) {
+ return editor.setOption('behavioursEnabled', true)
+ } else {
+ return editor.setOption('behavioursEnabled', false)
+ }
+ })
- // auto-insertion of braces, brackets, dollars
- editor.setOption('behavioursEnabled', scope.autoPairDelimiters || false)
- editor.setOption('wrapBehavioursEnabled', false)
-
- scope.$watch('autoPairDelimiters', autoPairDelimiters => {
- if (autoPairDelimiters) {
- return editor.setOption('behavioursEnabled', true)
- } else {
- return editor.setOption('behavioursEnabled', false)
+ if (!window._debug_editors) {
+ window._debug_editors = []
}
- })
+ window._debug_editors.push(editor)
- if (!window._debug_editors) {
- window._debug_editors = []
- }
- window._debug_editors.push(editor)
+ scope.name = attrs.aceEditor
- scope.name = attrs.aceEditor
+ if (scope.spellCheck) {
+ // only enable spellcheck when explicitly required
+ spellCheckManager = new SpellCheckManager(
+ scope,
+ $cacheFactory,
+ $http,
+ $q,
+ new SpellCheckAdapter(editor)
+ )
+ }
- if (scope.spellCheck) {
- // only enable spellcheck when explicitly required
- spellCheckManager = new SpellCheckManager(
+ /* eslint-disable no-unused-vars */
+ const undoManager = new UndoManager(editor)
+ const highlightsManager = new HighlightsManager(scope, editor, element)
+ const cursorPositionManager = new CursorPositionManager(
scope,
- $cacheFactory,
- $http,
- $q,
- new SpellCheckAdapter(editor)
+ new CursorPositionAdapter(editor),
+ localStorage
)
- }
-
- /* eslint-disable no-unused-vars */
- const undoManager = new UndoManager(editor)
- const highlightsManager = new HighlightsManager(scope, editor, element)
- const cursorPositionManager = new CursorPositionManager(
- scope,
- new CursorPositionAdapter(editor),
- localStorage
- )
- const trackChangesManager = new TrackChangesManager(
- scope,
- editor,
- element,
- new TrackChangesAdapter(editor)
- )
-
- const metadataManager = new MetadataManager(
- scope,
- editor,
- element,
- metadata
- )
- const autoCompleteManager = new AutoCompleteManager(
- scope,
- editor,
- element,
- metadataManager,
- graphics,
- preamble,
- files
- )
-
- // prevent user entering null and non-BMP unicode characters in Ace
- const BAD_CHARS_REGEXP = /[\0\uD800-\uDFFF]/g
- const BAD_CHARS_REPLACEMENT_CHAR = '\uFFFD'
- // the 'exec' event fires for ace functions before they are executed.
- // you can modify the input or reject the event with e.preventDefault()
- editor.commands.on('exec', function(e) {
- // replace bad characters in paste content
- if (e.command && e.command.name === 'paste') {
- BAD_CHARS_REGEXP.lastIndex = 0 // reset stateful regexp for this usage
- if (e.args && BAD_CHARS_REGEXP.test(e.args.text)) {
- e.args.text = e.args.text.replace(
- BAD_CHARS_REGEXP,
- BAD_CHARS_REPLACEMENT_CHAR
- )
- }
- }
- // replace bad characters in keyboard input
- if (e.command && e.command.name === 'insertstring') {
- BAD_CHARS_REGEXP.lastIndex = 0 // reset stateful regexp for this usage
- if (e.args && BAD_CHARS_REGEXP.test(e.args)) {
- e.args = e.args.replace(
- BAD_CHARS_REGEXP,
- BAD_CHARS_REPLACEMENT_CHAR
- )
- }
- }
- })
-
- /* eslint-enable no-unused-vars */
-
- scope.$watch('onSave', function(callback) {
- if (callback != null) {
- Vim.defineEx('write', 'w', callback)
- editor.commands.addCommand({
- name: 'save',
- bindKey: {
- win: 'Ctrl-S',
- mac: 'Command-S'
- },
- exec: callback,
- readOnly: true
- })
- // Not technically 'save', but Ctrl-. recompiles in OL v1
- // so maintain compatibility
- return editor.commands.addCommand({
- name: 'recompile_v1',
- bindKey: {
- win: 'Ctrl-.',
- mac: 'Ctrl-.'
- },
- exec: callback,
- readOnly: true
- })
- }
- })
- editor.commands.removeCommand('transposeletters')
- editor.commands.removeCommand('showSettingsMenu')
- editor.commands.removeCommand('foldall')
-
- // For European keyboards, the / is above 7 so needs Shift pressing.
- // This comes through as Command-Shift-/ on OS X, which is mapped to
- // toggleBlockComment.
- // This doesn't do anything for LaTeX, so remap this to togglecomment to
- // work for European keyboards as normal.
- // On Windows, the key combo comes as Ctrl-Shift-7.
- editor.commands.removeCommand('toggleBlockComment')
- editor.commands.removeCommand('togglecomment')
-
- editor.commands.addCommand({
- name: 'togglecomment',
- bindKey: {
- win: 'Ctrl-/|Ctrl-Shift-7',
- mac: 'Command-/|Command-Shift-/'
- },
- exec(editor) {
- return editor.toggleCommentLines()
- },
- multiSelectAction: 'forEachLine',
- scrollIntoView: 'selectionPart'
- })
-
- // Trigger search AND replace on CMD+F
- editor.commands.addCommand({
- name: 'find',
- bindKey: {
- win: 'Ctrl-F',
- mac: 'Command-F'
- },
- exec(editor) {
- return SearchBox.Search(editor, true)
- },
- readOnly: true
- })
-
- // Bold text on CMD+B
- editor.commands.addCommand({
- name: 'bold',
- bindKey: {
- win: 'Ctrl-B',
- mac: 'Command-B'
- },
- exec(editor) {
- const selection = editor.getSelection()
- if (selection.isEmpty()) {
- editor.insert('\\textbf{}')
- return editor.navigateLeft(1)
- } else {
- const text = editor.getCopyText()
- return editor.insert(`\\textbf{${text}}`)
- }
- },
- readOnly: false
- })
-
- // Italicise text on CMD+I
- editor.commands.addCommand({
- name: 'italics',
- bindKey: {
- win: 'Ctrl-I',
- mac: 'Command-I'
- },
- exec(editor) {
- const selection = editor.getSelection()
- if (selection.isEmpty()) {
- editor.insert('\\textit{}')
- return editor.navigateLeft(1)
- } else {
- const text = editor.getCopyText()
- return editor.insert(`\\textit{${text}}`)
- }
- },
- readOnly: false
- })
-
- scope.$watch('onCtrlEnter', function(callback) {
- if (callback != null) {
- return editor.commands.addCommand({
- name: 'compile',
- bindKey: {
- win: 'Ctrl-Enter',
- mac: 'Command-Enter'
- },
- exec: editor => {
- return callback()
- },
- readOnly: true
- })
- }
- })
-
- scope.$watch('onCtrlJ', function(callback) {
- if (callback != null) {
- return editor.commands.addCommand({
- name: 'toggle-review-panel',
- bindKey: {
- win: 'Ctrl-J',
- mac: 'Command-J'
- },
- exec: editor => {
- return callback()
- },
- readOnly: true
- })
- }
- })
-
- scope.$watch('onCtrlShiftC', function(callback) {
- if (callback != null) {
- return editor.commands.addCommand({
- name: 'add-new-comment',
- bindKey: {
- win: 'Ctrl-Shift-C',
- mac: 'Command-Shift-C'
- },
- exec: editor => {
- return callback()
- },
- readOnly: true
- })
- }
- })
-
- scope.$watch('onCtrlShiftA', function(callback) {
- if (callback != null) {
- return editor.commands.addCommand({
- name: 'toggle-track-changes',
- bindKey: {
- win: 'Ctrl-Shift-A',
- mac: 'Command-Shift-A'
- },
- exec: editor => {
- return callback()
- },
- readOnly: true
- })
- }
- })
-
- // Make '/' work for search in vim mode.
- editor.showCommandLine = arg => {
- if (arg === '/') {
- return SearchBox.Search(editor, true)
- }
- }
-
- const getCursorScreenPosition = function() {
- const session = editor.getSession()
- const cursorPosition = session.selection.getCursor()
- const sessionPos = session.documentToScreenPosition(
- cursorPosition.row,
- cursorPosition.column
+ const trackChangesManager = new TrackChangesManager(
+ scope,
+ editor,
+ element,
+ new TrackChangesAdapter(editor)
)
- return (
- sessionPos.row * editor.renderer.lineHeight - session.getScrollTop()
- )
- }
- if (attrs.resizeOn != null) {
- for (let event of Array.from(attrs.resizeOn.split(','))) {
- scope.$on(event, function() {
- scope.$applyAsync(() => {
- const previousScreenPosition = getCursorScreenPosition()
- editor.resize()
- // Put cursor back to same vertical position on screen
- const newScreenPosition = getCursorScreenPosition()
- const session = editor.getSession()
- return session.setScrollTop(
- session.getScrollTop() +
- newScreenPosition -
- previousScreenPosition
+ const metadataManager = new MetadataManager(
+ scope,
+ editor,
+ element,
+ metadata
+ )
+ const autoCompleteManager = new AutoCompleteManager(
+ scope,
+ editor,
+ element,
+ metadataManager,
+ graphics,
+ preamble,
+ files
+ )
+
+ // prevent user entering null and non-BMP unicode characters in Ace
+ const BAD_CHARS_REGEXP = /[\0\uD800-\uDFFF]/g
+ const BAD_CHARS_REPLACEMENT_CHAR = '\uFFFD'
+ // the 'exec' event fires for ace functions before they are executed.
+ // you can modify the input or reject the event with e.preventDefault()
+ editor.commands.on('exec', function (e) {
+ // replace bad characters in paste content
+ if (e.command && e.command.name === 'paste') {
+ BAD_CHARS_REGEXP.lastIndex = 0 // reset stateful regexp for this usage
+ if (e.args && BAD_CHARS_REGEXP.test(e.args.text)) {
+ e.args.text = e.args.text.replace(
+ BAD_CHARS_REGEXP,
+ BAD_CHARS_REPLACEMENT_CHAR
)
+ }
+ }
+ // replace bad characters in keyboard input
+ if (e.command && e.command.name === 'insertstring') {
+ BAD_CHARS_REGEXP.lastIndex = 0 // reset stateful regexp for this usage
+ if (e.args && BAD_CHARS_REGEXP.test(e.args)) {
+ e.args = e.args.replace(
+ BAD_CHARS_REGEXP,
+ BAD_CHARS_REPLACEMENT_CHAR
+ )
+ }
+ }
+ })
+
+ /* eslint-enable no-unused-vars */
+
+ scope.$watch('onSave', function (callback) {
+ if (callback != null) {
+ Vim.defineEx('write', 'w', callback)
+ editor.commands.addCommand({
+ name: 'save',
+ bindKey: {
+ win: 'Ctrl-S',
+ mac: 'Command-S'
+ },
+ exec: callback,
+ readOnly: true
})
+ // Not technically 'save', but Ctrl-. recompiles in OL v1
+ // so maintain compatibility
+ return editor.commands.addCommand({
+ name: 'recompile_v1',
+ bindKey: {
+ win: 'Ctrl-.',
+ mac: 'Ctrl-.'
+ },
+ exec: callback,
+ readOnly: true
+ })
+ }
+ })
+ editor.commands.removeCommand('transposeletters')
+ editor.commands.removeCommand('showSettingsMenu')
+ editor.commands.removeCommand('foldall')
+
+ // For European keyboards, the / is above 7 so needs Shift pressing.
+ // This comes through as Command-Shift-/ on OS X, which is mapped to
+ // toggleBlockComment.
+ // This doesn't do anything for LaTeX, so remap this to togglecomment to
+ // work for European keyboards as normal.
+ // On Windows, the key combo comes as Ctrl-Shift-7.
+ editor.commands.removeCommand('toggleBlockComment')
+ editor.commands.removeCommand('togglecomment')
+
+ editor.commands.addCommand({
+ name: 'togglecomment',
+ bindKey: {
+ win: 'Ctrl-/|Ctrl-Shift-7',
+ mac: 'Command-/|Command-Shift-/'
+ },
+ exec(editor) {
+ return editor.toggleCommentLines()
+ },
+ multiSelectAction: 'forEachLine',
+ scrollIntoView: 'selectionPart'
+ })
+
+ // Trigger search AND replace on CMD+F
+ editor.commands.addCommand({
+ name: 'find',
+ bindKey: {
+ win: 'Ctrl-F',
+ mac: 'Command-F'
+ },
+ exec(editor) {
+ return SearchBox.Search(editor, true)
+ },
+ readOnly: true
+ })
+
+ // Bold text on CMD+B
+ editor.commands.addCommand({
+ name: 'bold',
+ bindKey: {
+ win: 'Ctrl-B',
+ mac: 'Command-B'
+ },
+ exec(editor) {
+ const selection = editor.getSelection()
+ if (selection.isEmpty()) {
+ editor.insert('\\textbf{}')
+ return editor.navigateLeft(1)
+ } else {
+ const text = editor.getCopyText()
+ return editor.insert(`\\textbf{${text}}`)
+ }
+ },
+ readOnly: false
+ })
+
+ // Italicise text on CMD+I
+ editor.commands.addCommand({
+ name: 'italics',
+ bindKey: {
+ win: 'Ctrl-I',
+ mac: 'Command-I'
+ },
+ exec(editor) {
+ const selection = editor.getSelection()
+ if (selection.isEmpty()) {
+ editor.insert('\\textit{}')
+ return editor.navigateLeft(1)
+ } else {
+ const text = editor.getCopyText()
+ return editor.insert(`\\textit{${text}}`)
+ }
+ },
+ readOnly: false
+ })
+
+ scope.$watch('onCtrlEnter', function (callback) {
+ if (callback != null) {
+ return editor.commands.addCommand({
+ name: 'compile',
+ bindKey: {
+ win: 'Ctrl-Enter',
+ mac: 'Command-Enter'
+ },
+ exec: editor => {
+ return callback()
+ },
+ readOnly: true
+ })
+ }
+ })
+
+ scope.$watch('onCtrlJ', function (callback) {
+ if (callback != null) {
+ return editor.commands.addCommand({
+ name: 'toggle-review-panel',
+ bindKey: {
+ win: 'Ctrl-J',
+ mac: 'Command-J'
+ },
+ exec: editor => {
+ return callback()
+ },
+ readOnly: true
+ })
+ }
+ })
+
+ scope.$watch('onCtrlShiftC', function (callback) {
+ if (callback != null) {
+ return editor.commands.addCommand({
+ name: 'add-new-comment',
+ bindKey: {
+ win: 'Ctrl-Shift-C',
+ mac: 'Command-Shift-C'
+ },
+ exec: editor => {
+ return callback()
+ },
+ readOnly: true
+ })
+ }
+ })
+
+ scope.$watch('onCtrlShiftA', function (callback) {
+ if (callback != null) {
+ return editor.commands.addCommand({
+ name: 'toggle-track-changes',
+ bindKey: {
+ win: 'Ctrl-Shift-A',
+ mac: 'Command-Shift-A'
+ },
+ exec: editor => {
+ return callback()
+ },
+ readOnly: true
+ })
+ }
+ })
+
+ // Make '/' work for search in vim mode.
+ editor.showCommandLine = arg => {
+ if (arg === '/') {
+ return SearchBox.Search(editor, true)
+ }
+ }
+
+ const getCursorScreenPosition = function () {
+ const session = editor.getSession()
+ const cursorPosition = session.selection.getCursor()
+ const sessionPos = session.documentToScreenPosition(
+ cursorPosition.row,
+ cursorPosition.column
+ )
+ return (
+ sessionPos.row * editor.renderer.lineHeight - session.getScrollTop()
+ )
+ }
+
+ if (attrs.resizeOn != null) {
+ for (let event of Array.from(attrs.resizeOn.split(','))) {
+ scope.$on(event, function () {
+ scope.$applyAsync(() => {
+ const previousScreenPosition = getCursorScreenPosition()
+ editor.resize()
+ // Put cursor back to same vertical position on screen
+ const newScreenPosition = getCursorScreenPosition()
+ const session = editor.getSession()
+ return session.setScrollTop(
+ session.getScrollTop() +
+ newScreenPosition -
+ previousScreenPosition
+ )
+ })
+ })
+ }
+ }
+
+ scope.$on(`${scope.name}:set-scroll-size`, function (e, size) {
+ // Make sure that the editor has enough scroll margin above and below
+ // to scroll the review panel with the given size
+ const marginTop = size.overflowTop
+ const { maxHeight } = editor.renderer.layerConfig
+ const marginBottom = Math.max(size.height - maxHeight, 0)
+ return setScrollMargins(marginTop, marginBottom)
+ })
+
+ var setScrollMargins = function (marginTop, marginBottom) {
+ let marginChanged = false
+ if (editor.renderer.scrollMargin.top !== marginTop) {
+ editor.renderer.scrollMargin.top = marginTop
+ marginChanged = true
+ }
+ if (editor.renderer.scrollMargin.bottom !== marginBottom) {
+ editor.renderer.scrollMargin.bottom = marginBottom
+ marginChanged = true
+ }
+ if (marginChanged) {
+ return editor.renderer.updateFull()
+ }
+ }
+
+ const resetScrollMargins = () => setScrollMargins(0, 0)
+
+ scope.$watch('theme', value => editor.setTheme(`ace/theme/${value}`))
+
+ scope.$watch('showPrintMargin', value =>
+ editor.setShowPrintMargin(value)
+ )
+
+ scope.$watch('keybindings', function (value) {
+ if (['vim', 'emacs'].includes(value)) {
+ return editor.setKeyboardHandler(`ace/keyboard/${value}`)
+ } else {
+ return editor.setKeyboardHandler(null)
+ }
+ })
+
+ scope.$watch('fontSize', value =>
+ element.find('.ace_editor, .ace_content').css({
+ 'font-size': value + 'px'
+ })
+ )
+
+ scope.$watch('fontFamily', function (value) {
+ const monospaceFamilies = [
+ 'Monaco',
+ 'Menlo',
+ 'Ubuntu Mono',
+ 'Consolas',
+ 'monospace'
+ ]
+
+ if (value != null) {
+ switch (value) {
+ case 'monaco':
+ return editor.setOption(
+ 'fontFamily',
+ monospaceFamilies.join(', ')
+ )
+ case 'lucida':
+ return editor.setOption(
+ 'fontFamily',
+ '"Lucida Console", "Source Code Pro", monospace'
+ )
+ default:
+ return editor.setOption('fontFamily', null)
+ }
+ }
+ })
+
+ scope.$watch('lineHeight', function (value) {
+ if (value != null) {
+ switch (value) {
+ case 'compact':
+ editor.container.style.lineHeight = 1.33
+ break
+ case 'normal':
+ editor.container.style.lineHeight = 1.6
+ break
+ case 'wide':
+ editor.container.style.lineHeight = 2
+ break
+ default:
+ editor.container.style.lineHeight = 1.6
+ }
+ return editor.renderer.updateFontSize()
+ }
+ })
+
+ scope.$watch('sharejsDoc', function (sharejs_doc, old_sharejs_doc) {
+ if (old_sharejs_doc != null) {
+ scope.$broadcast('beforeChangeDocument')
+ detachFromAce(old_sharejs_doc)
+ }
+ if (sharejs_doc != null) {
+ attachToAce(sharejs_doc)
+ }
+ if (sharejs_doc != null && old_sharejs_doc != null) {
+ return scope.$broadcast('afterChangeDocument')
+ }
+ })
+
+ scope.$watch('text', function (text) {
+ if (text != null) {
+ editor.setValue(text, -1)
+ const session = editor.getSession()
+ return session.setUseWrapMode(true)
+ }
+ })
+
+ scope.$watch('annotations', function (annotations) {
+ const session = editor.getSession()
+ return session.setAnnotations(annotations)
+ })
+
+ scope.$watch('readOnly', value => editor.setReadOnly(!!value))
+
+ scope.$watch('syntaxValidation', function (value) {
+ // ignore undefined settings here
+ // only instances of ace with an explicit value should set useWorker
+ // the history instance will have syntaxValidation undefined
+ if (value != null && syntaxValidationEnabled) {
+ const session = editor.getSession()
+ return session.setOption('useWorker', value)
+ }
+ })
+
+ editor.setOption('scrollPastEnd', true)
+
+ let updateCount = 0
+ const onChange = function () {
+ updateCount++
+
+ if (updateCount === 100) {
+ eventTracking.send('editor-interaction', 'multi-doc-update')
+ }
+ return scope.$emit(`${scope.name}:change`)
+ }
+
+ let currentFirstVisibleRow = null
+ const emitMiddleVisibleRowChanged = () => {
+ const firstVisibleRow = editor.getFirstVisibleRow()
+ if (firstVisibleRow === currentFirstVisibleRow) return
+
+ currentFirstVisibleRow = firstVisibleRow
+ const lastVisibleRow = editor.getLastVisibleRow()
+ scope.$emit(
+ `scroll:editor:update`,
+ Math.floor((firstVisibleRow + lastVisibleRow) / 2)
+ )
+ }
+
+ const onScroll = function (scrollTop) {
+ if (scope.eventsBridge == null) {
+ return
+ }
+ const height = editor.renderer.layerConfig.maxHeight
+ emitMiddleVisibleRowChanged()
+ return scope.eventsBridge.emit('aceScroll', scrollTop, height)
+ }
+
+ const onScrollbarVisibilityChanged = function (event, vRenderer) {
+ if (scope.eventsBridge == null) {
+ return
+ }
+ return scope.eventsBridge.emit(
+ 'aceScrollbarVisibilityChanged',
+ vRenderer.scrollBarV.isVisible,
+ vRenderer.scrollBarV.width
+ )
+ }
+
+ if (scope.eventsBridge != null) {
+ editor.renderer.on(
+ 'scrollbarVisibilityChanged',
+ onScrollbarVisibilityChanged
+ )
+
+ scope.eventsBridge.on('externalScroll', position =>
+ editor.getSession().setScrollTop(position)
+ )
+ scope.eventsBridge.on('refreshScrollPosition', function () {
+ const session = editor.getSession()
+ session.setScrollTop(session.getScrollTop() + 1)
+ return session.setScrollTop(session.getScrollTop() - 1)
})
}
- }
- scope.$on(`${scope.name}:set-scroll-size`, function(e, size) {
- // Make sure that the editor has enough scroll margin above and below
- // to scroll the review panel with the given size
- const marginTop = size.overflowTop
- const { maxHeight } = editor.renderer.layerConfig
- const marginBottom = Math.max(size.height - maxHeight, 0)
- return setScrollMargins(marginTop, marginBottom)
- })
-
- var setScrollMargins = function(marginTop, marginBottom) {
- let marginChanged = false
- if (editor.renderer.scrollMargin.top !== marginTop) {
- editor.renderer.scrollMargin.top = marginTop
- marginChanged = true
- }
- if (editor.renderer.scrollMargin.bottom !== marginBottom) {
- editor.renderer.scrollMargin.bottom = marginBottom
- marginChanged = true
- }
- if (marginChanged) {
- return editor.renderer.updateFull()
- }
- }
-
- const resetScrollMargins = () => setScrollMargins(0, 0)
-
- scope.$watch('theme', value => editor.setTheme(`ace/theme/${value}`))
-
- scope.$watch('showPrintMargin', value => editor.setShowPrintMargin(value))
-
- scope.$watch('keybindings', function(value) {
- if (['vim', 'emacs'].includes(value)) {
- return editor.setKeyboardHandler(`ace/keyboard/${value}`)
- } else {
- return editor.setKeyboardHandler(null)
- }
- })
-
- scope.$watch('fontSize', value =>
- element.find('.ace_editor, .ace_content').css({
- 'font-size': value + 'px'
- })
- )
-
- scope.$watch('fontFamily', function(value) {
- const monospaceFamilies = [
- 'Monaco',
- 'Menlo',
- 'Ubuntu Mono',
- 'Consolas',
- 'monospace'
- ]
-
- if (value != null) {
- switch (value) {
- case 'monaco':
- return editor.setOption(
- 'fontFamily',
- monospaceFamilies.join(', ')
- )
- case 'lucida':
- return editor.setOption(
- 'fontFamily',
- '"Lucida Console", "Source Code Pro", monospace'
- )
- default:
- return editor.setOption('fontFamily', null)
+ const onSessionChangeForSpellCheck = function (e) {
+ spellCheckManager.onSessionChange()
+ if (e.oldSession != null) {
+ e.oldSession.getDocument().off('change', spellCheckManager.onChange)
}
- }
- })
-
- scope.$watch('lineHeight', function(value) {
- if (value != null) {
- switch (value) {
- case 'compact':
- editor.container.style.lineHeight = 1.33
- break
- case 'normal':
- editor.container.style.lineHeight = 1.6
- break
- case 'wide':
- editor.container.style.lineHeight = 2
- break
- default:
- editor.container.style.lineHeight = 1.6
+ e.session.getDocument().on('change', spellCheckManager.onChange)
+ if (e.oldSession != null) {
+ e.oldSession.off('changeScrollTop', spellCheckManager.onScroll)
}
- return editor.renderer.updateFontSize()
+ return e.session.on('changeScrollTop', spellCheckManager.onScroll)
}
- })
- scope.$watch('sharejsDoc', function(sharejs_doc, old_sharejs_doc) {
- if (old_sharejs_doc != null) {
- scope.$broadcast('beforeChangeDocument')
- detachFromAce(old_sharejs_doc)
+ const initSpellCheck = function () {
+ if (!spellCheckManager) return
+ spellCheckManager.init()
+ editor.on('changeSession', onSessionChangeForSpellCheck)
+ onSessionChangeForSpellCheck({
+ session: editor.getSession()
+ }) // Force initial setup
+ return editor.on('nativecontextmenu', spellCheckManager.onContextMenu)
}
- if (sharejs_doc != null) {
- attachToAce(sharejs_doc)
+
+ const tearDownSpellCheck = function () {
+ if (!spellCheckManager) return
+ editor.off('changeSession', onSessionChangeForSpellCheck)
+ return editor.off(
+ 'nativecontextmenu',
+ spellCheckManager.onContextMenu
+ )
}
- if (sharejs_doc != null && old_sharejs_doc != null) {
- return scope.$broadcast('afterChangeDocument')
+
+ const initTrackChanges = function () {
+ trackChangesManager.rangesTracker = scope.sharejsDoc.ranges
+
+ // Force onChangeSession in order to set up highlights etc.
+ trackChangesManager.onChangeSession()
+
+ if (!trackChangesManager) return
+ editor.on('changeSelection', trackChangesManager.onChangeSelection)
+
+ // Selection also moves with updates elsewhere in the document
+ editor.on('change', trackChangesManager.onChangeSelection)
+
+ editor.on('changeSession', trackChangesManager.onChangeSession)
+ editor.on('cut', trackChangesManager.onCut)
+ editor.on('paste', trackChangesManager.onPaste)
+ editor.renderer.on('resize', trackChangesManager.onResize)
}
- })
- scope.$watch('text', function(text) {
- if (text != null) {
- editor.setValue(text, -1)
- const session = editor.getSession()
- return session.setUseWrapMode(true)
+ const tearDownTrackChanges = function () {
+ if (!trackChangesManager) return
+ trackChangesManager.tearDown()
+ editor.off('changeSelection', trackChangesManager.onChangeSelection)
+
+ editor.off('change', trackChangesManager.onChangeSelection)
+ editor.off('changeSession', trackChangesManager.onChangeSession)
+ editor.off('cut', trackChangesManager.onCut)
+ editor.off('paste', trackChangesManager.onPaste)
+ editor.renderer.off('resize', trackChangesManager.onResize)
}
- })
- scope.$watch('annotations', function(annotations) {
- const session = editor.getSession()
- return session.setAnnotations(annotations)
- })
-
- scope.$watch('readOnly', value => editor.setReadOnly(!!value))
-
- scope.$watch('syntaxValidation', function(value) {
- // ignore undefined settings here
- // only instances of ace with an explicit value should set useWorker
- // the history instance will have syntaxValidation undefined
- if (value != null && syntaxValidationEnabled) {
- const session = editor.getSession()
- return session.setOption('useWorker', value)
+ const initUndo = function () {
+ // Emulate onChangeSession event. Note: listening to changeSession
+ // event is unnecessary since this method is called when we switch
+ // sessions (via ShareJS changing) anyway
+ undoManager.onChangeSession(editor.getSession())
+ editor.on('change', undoManager.onChange)
}
- })
- editor.setOption('scrollPastEnd', true)
-
- let updateCount = 0
- const onChange = function() {
- updateCount++
-
- if (updateCount === 100) {
- eventTracking.send('editor-interaction', 'multi-doc-update')
+ const tearDownUndo = function () {
+ editor.off('change', undoManager.onChange)
}
- return scope.$emit(`${scope.name}:change`)
- }
- let currentFirstVisibleRow = null
- const emitMiddleVisibleRowChanged = () => {
- const firstVisibleRow = editor.getFirstVisibleRow()
- if (firstVisibleRow === currentFirstVisibleRow) return
-
- currentFirstVisibleRow = firstVisibleRow
- const lastVisibleRow = editor.getLastVisibleRow()
- scope.$emit(
- `scroll:editor:update`,
- Math.floor((firstVisibleRow + lastVisibleRow) / 2)
- )
- }
-
- const onScroll = function(scrollTop) {
- if (scope.eventsBridge == null) {
- return
- }
- const height = editor.renderer.layerConfig.maxHeight
- emitMiddleVisibleRowChanged()
- return scope.eventsBridge.emit('aceScroll', scrollTop, height)
- }
-
- const onScrollbarVisibilityChanged = function(event, vRenderer) {
- if (scope.eventsBridge == null) {
- return
- }
- return scope.eventsBridge.emit(
- 'aceScrollbarVisibilityChanged',
- vRenderer.scrollBarV.isVisible,
- vRenderer.scrollBarV.width
- )
- }
-
- if (scope.eventsBridge != null) {
- editor.renderer.on(
- 'scrollbarVisibilityChanged',
- onScrollbarVisibilityChanged
- )
-
- scope.eventsBridge.on('externalScroll', position =>
- editor.getSession().setScrollTop(position)
- )
- scope.eventsBridge.on('refreshScrollPosition', function() {
- const session = editor.getSession()
- session.setScrollTop(session.getScrollTop() + 1)
- return session.setScrollTop(session.getScrollTop() - 1)
- })
- }
-
- const onSessionChangeForSpellCheck = function(e) {
- spellCheckManager.onSessionChange()
- if (e.oldSession != null) {
- e.oldSession.getDocument().off('change', spellCheckManager.onChange)
- }
- e.session.getDocument().on('change', spellCheckManager.onChange)
- if (e.oldSession != null) {
- e.oldSession.off('changeScrollTop', spellCheckManager.onScroll)
- }
- return e.session.on('changeScrollTop', spellCheckManager.onScroll)
- }
-
- const initSpellCheck = function() {
- if (!spellCheckManager) return
- spellCheckManager.init()
- editor.on('changeSession', onSessionChangeForSpellCheck)
- onSessionChangeForSpellCheck({
- session: editor.getSession()
- }) // Force initial setup
- return editor.on('nativecontextmenu', spellCheckManager.onContextMenu)
- }
-
- const tearDownSpellCheck = function() {
- if (!spellCheckManager) return
- editor.off('changeSession', onSessionChangeForSpellCheck)
- return editor.off('nativecontextmenu', spellCheckManager.onContextMenu)
- }
-
- const initTrackChanges = function() {
- trackChangesManager.rangesTracker = scope.sharejsDoc.ranges
-
- // Force onChangeSession in order to set up highlights etc.
- trackChangesManager.onChangeSession()
-
- if (!trackChangesManager) return
- editor.on('changeSelection', trackChangesManager.onChangeSelection)
-
- // Selection also moves with updates elsewhere in the document
- editor.on('change', trackChangesManager.onChangeSelection)
-
- editor.on('changeSession', trackChangesManager.onChangeSession)
- editor.on('cut', trackChangesManager.onCut)
- editor.on('paste', trackChangesManager.onPaste)
- editor.renderer.on('resize', trackChangesManager.onResize)
- }
-
- const tearDownTrackChanges = function() {
- if (!trackChangesManager) return
- trackChangesManager.tearDown()
- editor.off('changeSelection', trackChangesManager.onChangeSelection)
-
- editor.off('change', trackChangesManager.onChangeSelection)
- editor.off('changeSession', trackChangesManager.onChangeSession)
- editor.off('cut', trackChangesManager.onCut)
- editor.off('paste', trackChangesManager.onPaste)
- editor.renderer.off('resize', trackChangesManager.onResize)
- }
-
- const initUndo = function() {
- // Emulate onChangeSession event. Note: listening to changeSession
- // event is unnecessary since this method is called when we switch
- // sessions (via ShareJS changing) anyway
- undoManager.onChangeSession(editor.getSession())
- editor.on('change', undoManager.onChange)
- }
-
- const tearDownUndo = function() {
- editor.off('change', undoManager.onChange)
- }
-
- const onSessionChangeForCursorPosition = function(e) {
- if (e.oldSession != null) {
- e.oldSession.selection.off(
+ const onSessionChangeForCursorPosition = function (e) {
+ if (e.oldSession != null) {
+ e.oldSession.selection.off(
+ 'changeCursor',
+ cursorPositionManager.onCursorChange
+ )
+ }
+ return e.session.selection.on(
'changeCursor',
cursorPositionManager.onCursorChange
)
}
- return e.session.selection.on(
- 'changeCursor',
- cursorPositionManager.onCursorChange
- )
- }
- const onUnloadForCursorPosition = () =>
- cursorPositionManager.onUnload(editor.getSession())
+ const onUnloadForCursorPosition = () =>
+ cursorPositionManager.onUnload(editor.getSession())
- const initCursorPosition = function() {
- editor.on('changeSession', onSessionChangeForCursorPosition)
+ const initCursorPosition = function () {
+ editor.on('changeSession', onSessionChangeForCursorPosition)
- // Force initial setup
- onSessionChangeForCursorPosition({ session: editor.getSession() })
+ // Force initial setup
+ onSessionChangeForCursorPosition({ session: editor.getSession() })
- return $(window).on('unload', onUnloadForCursorPosition)
- }
-
- const tearDownCursorPosition = function() {
- editor.off('changeSession', onSessionChangeForCursorPosition)
- return $(window).off('unload', onUnloadForCursorPosition)
- }
-
- initCursorPosition()
-
- // Trigger the event once *only* - this is called after Ace is connected
- // to the ShareJs instance but this event should only be triggered the
- // first time the editor is opened. Not every time the docs opened
- const triggerEditorInitEvent = _.once(() =>
- scope.$broadcast('editorInit')
- )
-
- var attachToAce = function(sharejs_doc) {
- let mode
- const lines = sharejs_doc.getSnapshot().split('\n')
- let session = editor.getSession()
- if (session != null) {
- session.destroy()
+ return $(window).on('unload', onUnloadForCursorPosition)
}
- // see if we can lookup a suitable mode from ace
- // but fall back to text by default
- try {
- if (/\.(Rtex|bbl|tikz)$/i.test(scope.fileName)) {
- // recognise Rtex and bbl as latex
- mode = 'ace/mode/latex'
- } else if (/\.(sty|cls|clo)$/.test(scope.fileName)) {
- // recognise some common files as tex
- mode = 'ace/mode/tex'
- } else {
- ;({ mode } = ModeList.getModeForPath(scope.fileName))
- // we prefer plain_text mode over text mode because ace's
- // text mode is actually for code and has unwanted
- // indenting (see wrapMethod in ace edit_session.js)
- if (mode === 'ace/mode/text') {
- mode = 'ace/mode/plain_text'
- }
- }
- } catch (error) {
- mode = 'ace/mode/plain_text'
+ const tearDownCursorPosition = function () {
+ editor.off('changeSession', onSessionChangeForCursorPosition)
+ return $(window).off('unload', onUnloadForCursorPosition)
}
- // create our new session
- session = new EditSession(lines, mode)
+ initCursorPosition()
- session.setUseWrapMode(true)
- // use syntax validation only when explicitly set
- if (
- scope.syntaxValidation != null &&
- syntaxValidationEnabled &&
- !/\.bib$/.test(scope.fileName)
- ) {
- session.setOption('useWorker', scope.syntaxValidation)
- }
-
- // set to readonly until document change handlers are attached
- editor.setReadOnly(true)
-
- // now attach session to editor
- editor.setSession(session)
-
- const doc = session.getDocument()
- doc.on('change', onChange)
-
- editor.initing = true
- sharejs_doc.attachToAce(editor)
- editor.initing = false
-
- // now ready to edit document
- // respect the readOnly setting, normally false
- editor.setReadOnly(scope.readOnly)
- triggerEditorInitEvent()
-
- if (!scope.readOnly) {
- initSpellCheck()
- }
-
- initTrackChanges()
- initUndo()
-
- resetScrollMargins()
-
- // need to set annotations after attaching because attaching
- // deletes and then inserts document content
- session.setAnnotations(scope.annotations)
-
- session.on('changeScrollTop', eventTracking.editingSessionHeartbeat)
-
- angular
- .element($window)
- .on('click', eventTracking.editingSessionHeartbeat)
-
- scope.$on('$destroy', () =>
- angular
- .element($window)
- .off('click', eventTracking.editingSessionHeartbeat)
+ // Trigger the event once *only* - this is called after Ace is connected
+ // to the ShareJs instance but this event should only be triggered the
+ // first time the editor is opened. Not every time the docs opened
+ const triggerEditorInitEvent = _.once(() =>
+ scope.$broadcast('editorInit')
)
- if (scope.eventsBridge != null) {
- session.on('changeScrollTop', onScroll)
- }
-
- $rootScope.hasLintingError = false
- session.on('changeAnnotation', function() {
- // Both linter errors and compile logs are set as error annotations,
- // however when the user types something, the compile logs are
- // replaced with linter errors. When we check for lint errors before
- // autocompile we are guaranteed to get linter errors
- const hasErrors =
- session
- .getAnnotations()
- .filter(annotation => annotation.type !== 'info').length > 0
-
- if ($rootScope.hasLintingError !== hasErrors) {
- return ($rootScope.hasLintingError = hasErrors)
- }
- })
-
- setTimeout(() =>
- // Let any listeners init themselves
- onScroll(editor.renderer.getScrollTop())
- )
-
- return editor.focus()
- }
-
- var detachFromAce = function(sharejs_doc) {
- tearDownSpellCheck()
- tearDownTrackChanges()
- tearDownUndo()
- sharejs_doc.detachFromAce()
- sharejs_doc.off('remoteop.recordRemote')
-
- const session = editor.getSession()
- session.off('changeScrollTop')
-
- const doc = session.getDocument()
- return doc.off('change', onChange)
- }
-
- if (scope.rendererData != null) {
- editor.renderer.on('changeCharacterSize', () => {
- scope.$apply(
- () => (scope.rendererData.lineHeight = editor.renderer.lineHeight)
- )
- })
- }
-
- scope.$watch('rendererData', function(rendererData) {
- if (rendererData != null) {
- return (rendererData.lineHeight = editor.renderer.lineHeight)
- }
- })
-
- scope.$on('$destroy', function() {
- if (scope.sharejsDoc != null) {
- scope.$broadcast('changeEditor')
- tearDownSpellCheck()
- tearDownCursorPosition()
- tearDownUndo()
- detachFromAce(scope.sharejsDoc)
- const session = editor.getSession()
+ var attachToAce = function (sharejs_doc) {
+ let mode
+ const lines = sharejs_doc.getSnapshot().split('\n')
+ let session = editor.getSession()
if (session != null) {
session.destroy()
}
- return scope.eventsBridge.emit(
- 'aceScrollbarVisibilityChanged',
- false,
- 0
+
+ // see if we can lookup a suitable mode from ace
+ // but fall back to text by default
+ try {
+ if (/\.(Rtex|bbl|tikz)$/i.test(scope.fileName)) {
+ // recognise Rtex and bbl as latex
+ mode = 'ace/mode/latex'
+ } else if (/\.(sty|cls|clo)$/.test(scope.fileName)) {
+ // recognise some common files as tex
+ mode = 'ace/mode/tex'
+ } else {
+ ;({ mode } = ModeList.getModeForPath(scope.fileName))
+ // we prefer plain_text mode over text mode because ace's
+ // text mode is actually for code and has unwanted
+ // indenting (see wrapMethod in ace edit_session.js)
+ if (mode === 'ace/mode/text') {
+ mode = 'ace/mode/plain_text'
+ }
+ }
+ } catch (error) {
+ mode = 'ace/mode/plain_text'
+ }
+
+ // create our new session
+ session = new EditSession(lines, mode)
+
+ session.setUseWrapMode(true)
+ // use syntax validation only when explicitly set
+ if (
+ scope.syntaxValidation != null &&
+ syntaxValidationEnabled &&
+ !/\.bib$/.test(scope.fileName)
+ ) {
+ session.setOption('useWorker', scope.syntaxValidation)
+ }
+
+ // set to readonly until document change handlers are attached
+ editor.setReadOnly(true)
+
+ // now attach session to editor
+ editor.setSession(session)
+
+ const doc = session.getDocument()
+ doc.on('change', onChange)
+
+ editor.initing = true
+ sharejs_doc.attachToAce(editor)
+ editor.initing = false
+
+ // now ready to edit document
+ // respect the readOnly setting, normally false
+ editor.setReadOnly(scope.readOnly)
+ triggerEditorInitEvent()
+
+ if (!scope.readOnly) {
+ initSpellCheck()
+ }
+
+ initTrackChanges()
+ initUndo()
+
+ resetScrollMargins()
+
+ // need to set annotations after attaching because attaching
+ // deletes and then inserts document content
+ session.setAnnotations(scope.annotations)
+
+ session.on('changeScrollTop', eventTracking.editingSessionHeartbeat)
+
+ angular
+ .element($window)
+ .on('click', eventTracking.editingSessionHeartbeat)
+
+ scope.$on('$destroy', () =>
+ angular
+ .element($window)
+ .off('click', eventTracking.editingSessionHeartbeat)
)
+
+ if (scope.eventsBridge != null) {
+ session.on('changeScrollTop', onScroll)
+ }
+
+ $rootScope.hasLintingError = false
+ session.on('changeAnnotation', function () {
+ // Both linter errors and compile logs are set as error annotations,
+ // however when the user types something, the compile logs are
+ // replaced with linter errors. When we check for lint errors before
+ // autocompile we are guaranteed to get linter errors
+ const hasErrors =
+ session
+ .getAnnotations()
+ .filter(annotation => annotation.type !== 'info').length > 0
+
+ if ($rootScope.hasLintingError !== hasErrors) {
+ return ($rootScope.hasLintingError = hasErrors)
+ }
+ })
+
+ setTimeout(() =>
+ // Let any listeners init themselves
+ onScroll(editor.renderer.getScrollTop())
+ )
+
+ return editor.focus()
}
- })
- return scope.$emit(`${scope.name}:inited`, editor)
- },
+ var detachFromAce = function (sharejs_doc) {
+ tearDownSpellCheck()
+ tearDownTrackChanges()
+ tearDownUndo()
+ sharejs_doc.detachFromAce()
+ sharejs_doc.off('remoteop.recordRemote')
- template: `\
+ const session = editor.getSession()
+ session.off('changeScrollTop')
+
+ const doc = session.getDocument()
+ return doc.off('change', onChange)
+ }
+
+ if (scope.rendererData != null) {
+ editor.renderer.on('changeCharacterSize', () => {
+ scope.$apply(
+ () => (scope.rendererData.lineHeight = editor.renderer.lineHeight)
+ )
+ })
+ }
+
+ scope.$watch('rendererData', function (rendererData) {
+ if (rendererData != null) {
+ return (rendererData.lineHeight = editor.renderer.lineHeight)
+ }
+ })
+
+ scope.$on('$destroy', function () {
+ if (scope.sharejsDoc != null) {
+ scope.$broadcast('changeEditor')
+ tearDownSpellCheck()
+ tearDownCursorPosition()
+ tearDownUndo()
+ detachFromAce(scope.sharejsDoc)
+ const session = editor.getSession()
+ if (session != null) {
+ session.destroy()
+ }
+ return scope.eventsBridge.emit(
+ 'aceScrollbarVisibilityChanged',
+ false,
+ 0
+ )
+ }
+ })
+
+ return scope.$emit(`${scope.name}:inited`, editor)
+ },
+
+ template: `\
\
`
+ }
}
-})
+)
function monkeyPatchSearch($rootScope, $compile) {
const searchHtml = `\
@@ -992,7 +1000,7 @@ function monkeyPatchSearch($rootScope, $compile) {
const SB = SearchBox.SearchBox
const { $init } = SB.prototype
- SB.prototype.$init = function() {
+ SB.prototype.$init = function () {
this.element = $compile(searchHtml)($rootScope.$new())[0]
return $init.apply(this)
}
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/AutoCompleteManager.js b/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/AutoCompleteManager.js
index 85606152b8..56f75213b2 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/AutoCompleteManager.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/AutoCompleteManager.js
@@ -179,7 +179,7 @@ class AutoCompleteManager {
score: 60
})
if (references.keys && references.keys.length > 0) {
- references.keys.forEach(function(key) {
+ references.keys.forEach(function (key) {
if (key != null) {
result.push({
caption: `\\${commandName}{${previousArgsCaption}${key}}`,
@@ -282,7 +282,7 @@ class AutoCompleteManager {
// Only override this once since it's global but we may create multiple
// autocomplete handlers
Autocomplete.prototype._insertMatch = Autocomplete.prototype.insertMatch
- Autocomplete.prototype.insertMatch = function(data) {
+ Autocomplete.prototype.insertMatch = function (data) {
const { editor } = this
const pos = editor.getCursorPosition()
@@ -458,7 +458,7 @@ class AutoCompleteManager {
}
}
- Util.retrievePrecedingIdentifier = function(text, pos, regex) {
+ Util.retrievePrecedingIdentifier = function (text, pos, regex) {
let currentLineOffset = 0
for (let i = pos - 1; i <= 0; i++) {
if (text[i] === '\n') {
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/CommandManager.js b/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/CommandManager.js
index c41f87eba7..da53d1438a 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/CommandManager.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/CommandManager.js
@@ -170,12 +170,12 @@ export default CommandManager = class CommandManager {
const score = caption === prefix ? 99 : 50
snippet = caption
var i = 1
- _.times(command[1], function() {
+ _.times(command[1], function () {
snippet += `[\${${i}}]`
caption += '[]'
return i++
})
- _.times(command[2], function() {
+ _.times(command[2], function () {
snippet += `{\${${i}}}`
caption += '{}'
return i++
@@ -204,7 +204,7 @@ export default CommandManager = class CommandManager {
command => command[0].slice(0, commandFragment.length) === commandFragment
)
- return _.map(matchingCommands, function(command) {
+ return _.map(matchingCommands, function (command) {
let completionAfterCursor, completionBeforeCursor
const base = `\\${commandFragment}`
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/EnvironmentManager.js b/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/EnvironmentManager.js
index 03b3efa797..9001696b3f 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/EnvironmentManager.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/EnvironmentManager.js
@@ -129,7 +129,7 @@ $3
}
staticSnippets.push(documentSnippet)
-const parseCustomEnvironments = function(text) {
+const parseCustomEnvironments = function (text) {
let match
const re = /^\\newenvironment{(\w+)}.*$/gm
const result = []
@@ -144,7 +144,7 @@ const parseCustomEnvironments = function(text) {
return result
}
-const parseBeginCommands = function(text) {
+const parseBeginCommands = function (text) {
let match
const re = /^([\t ]*)\\begin{(\w+)}.*\n([\t ]*)/gm
const result = []
@@ -166,12 +166,12 @@ const parseBeginCommands = function(text) {
return result
}
-const hasDocumentEnvironment = function(text) {
+const hasDocumentEnvironment = function (text) {
const re = /^\\begin{document}/m
return re.exec(text) !== null
}
-const hasBibliographyEnvironment = function(text) {
+const hasBibliographyEnvironment = function (text) {
const re = /^\\begin{thebibliography}/m
return re.exec(text) !== null
}
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor/cursor-position/CursorPositionAdapter.js b/services/web/frontend/js/ide/editor/directives/aceEditor/cursor-position/CursorPositionAdapter.js
index 7a477ddd2c..f136002562 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor/cursor-position/CursorPositionAdapter.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor/cursor-position/CursorPositionAdapter.js
@@ -46,10 +46,7 @@ export default CursorPositionAdapter = class CursorPositionAdapter {
}
gotoOffset(offset) {
- const lines = this.editor
- .getSession()
- .getDocument()
- .getAllLines()
+ const lines = this.editor.getSession().getDocument().getAllLines()
const position = EditorShareJsCodec.shareJsOffsetToRowColumn(offset, lines)
return this.gotoLine(position.row + 1, position.column)
}
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor/highlights/HighlightsManager.js b/services/web/frontend/js/ide/editor/directives/aceEditor/highlights/HighlightsManager.js
index 33bcf02c99..f57e8a41a2 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor/highlights/HighlightsManager.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor/highlights/HighlightsManager.js
@@ -369,7 +369,7 @@ export default HighlightsManager = class HighlightsManager {
this.editor.getSession().addMarker(
range,
klass,
- function(html, range, left, top, config) {
+ function (html, range, left, top, config) {
if (range.isMultiLine()) {
return markerLayer.drawTextMarker(html, range, klass, config, style)
} else {
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor/metadata/MetadataManager.js b/services/web/frontend/js/ide/editor/directives/aceEditor/metadata/MetadataManager.js
index 84815a7550..eea37c8a06 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor/metadata/MetadataManager.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor/metadata/MetadataManager.js
@@ -16,7 +16,7 @@ import 'ace/ace'
let MetadataManager
const { Range } = ace.require('ace/range')
-const getLastCommandFragment = function(lineUpToCursor) {
+const getLastCommandFragment = function (lineUpToCursor) {
let m
if ((m = lineUpToCursor.match(/(\\[^\\]+)$/))) {
return m[1]
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor/spell-check/SpellCheckManager.js b/services/web/frontend/js/ide/editor/directives/aceEditor/spell-check/SpellCheckManager.js
index 1c3bd2d8eb..eb52f7ad0d 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor/spell-check/SpellCheckManager.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor/spell-check/SpellCheckManager.js
@@ -331,7 +331,7 @@ class SpellCheckManager {
apiRequest(endpoint, data, callback) {
if (callback == null) {
- callback = function(error, result) {
+ callback = function (error, result) {
console.error(error)
}
}
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesAdapter.js b/services/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesAdapter.js
index 4ae692e994..2120ea5d8d 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesAdapter.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesAdapter.js
@@ -200,10 +200,7 @@ class TrackChangesAdapter {
}
shareJsOffsetToRowColumn(offset) {
- const lines = this.editor
- .getSession()
- .getDocument()
- .getAllLines()
+ const lines = this.editor.getSession().getDocument().getAllLines()
return EditorShareJsCodec.shareJsOffsetToRowColumn(offset, lines)
}
@@ -239,8 +236,8 @@ class TrackChangesAdapter {
// though. This is the code we need to trick:
// var range = marker.range.clipRows(config.firstRow, config.lastRow);
// if (range.isEmpty()) continue;
- ace_range.clipRows = function(first_row, last_row) {
- this.isEmpty = function() {
+ ace_range.clipRows = function (first_row, last_row) {
+ this.isEmpty = function () {
return first_row > this.end.row || last_row < this.start.row
}
return this
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesManager.js b/services/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesManager.js
index afa4d6d50a..e2561ef682 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesManager.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesManager.js
@@ -650,10 +650,7 @@ class TrackChangesManager {
}
_rangeToShareJs(range) {
- const lines = this.editor
- .getSession()
- .getDocument()
- .getLines(0, range.row)
+ const lines = this.editor.getSession().getDocument().getLines(0, range.row)
return EditorShareJsCodec.rangeToShareJs(range, lines)
}
diff --git a/services/web/frontend/js/ide/editor/directives/aceEditor/undo/UndoManager.js b/services/web/frontend/js/ide/editor/directives/aceEditor/undo/UndoManager.js
index 64a00a4ac7..0c2b32ef32 100644
--- a/services/web/frontend/js/ide/editor/directives/aceEditor/undo/UndoManager.js
+++ b/services/web/frontend/js/ide/editor/directives/aceEditor/undo/UndoManager.js
@@ -22,10 +22,7 @@ class UndoManager {
// To hack around this we queue the undo stack clear so that it applies
// after the change is applied
setTimeout(() => {
- this.editor
- .getSession()
- .getUndoManager()
- .reset()
+ this.editor.getSession().getUndoManager().reset()
})
}
}
diff --git a/services/web/frontend/js/ide/file-tree/FileTreeManager.js b/services/web/frontend/js/ide/file-tree/FileTreeManager.js
index 99fe3830cf..ac2ca23ce0 100644
--- a/services/web/frontend/js/ide/file-tree/FileTreeManager.js
+++ b/services/web/frontend/js/ide/file-tree/FileTreeManager.js
@@ -152,7 +152,7 @@ export default FileTreeManager = class FileTreeManager {
multiSelectedCount() {
let count = 0
- this.forEachEntity(function(entity) {
+ this.forEachEntity(function (entity) {
if (entity.multiSelected) {
return count++
}
@@ -162,7 +162,7 @@ export default FileTreeManager = class FileTreeManager {
getMultiSelectedEntities() {
const entities = []
- this.forEachEntity(function(e) {
+ this.forEachEntity(function (e) {
if (e.multiSelected) {
return entities.push(e)
}
@@ -172,7 +172,7 @@ export default FileTreeManager = class FileTreeManager {
getFullCount() {
const entities = []
- this.forEachEntity(function(e) {
+ this.forEachEntity(function (e) {
if (!e.deleted) entities.push(e)
})
return entities.length
@@ -242,7 +242,7 @@ export default FileTreeManager = class FileTreeManager {
findSelectedEntity() {
let selected = null
- this.forEachEntity(function(entity) {
+ this.forEachEntity(function (entity) {
if (entity.selected) {
return (selected = entity)
}
@@ -323,7 +323,7 @@ export default FileTreeManager = class FileTreeManager {
forEachEntity(callback) {
if (callback == null) {
- callback = function(entity, parent_folder, path) {}
+ callback = function (entity, parent_folder, path) {}
}
this._forEachEntityInFolder(this.$scope.rootFolder, null, callback)
@@ -388,10 +388,7 @@ export default FileTreeManager = class FileTreeManager {
if (path == null) {
return
}
- return path
- .split('/')
- .slice(0, -1)
- .join('/')
+ return path.split('/').slice(0, -1).join('/')
}
_findParentFolder(entity) {
@@ -470,7 +467,7 @@ export default FileTreeManager = class FileTreeManager {
}
})
// Keep list ordered by folders, then name
- return this.$scope.docs.sort(function(a, b) {
+ return this.$scope.docs.sort(function (a, b) {
const aDepth = (a.path.match(/\//g) || []).length
const bDepth = (b.path.match(/\//g) || []).length
if (aDepth - bDepth !== 0) {
@@ -679,7 +676,7 @@ export default FileTreeManager = class FileTreeManager {
renameEntity(entity, name, callback) {
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
if (entity.name === name) {
return
@@ -709,7 +706,7 @@ export default FileTreeManager = class FileTreeManager {
// We'll wait for the socket.io notification to
// delete from scope.
if (callback == null) {
- callback = function(error) {}
+ callback = function (error) {}
}
return this.ide.queuedHttp({
method: 'DELETE',
@@ -759,7 +756,7 @@ export default FileTreeManager = class FileTreeManager {
return
}
let parent_folder = null
- this.forEachEntity(function(possible_entity, folder) {
+ this.forEachEntity(function (possible_entity, folder) {
if (possible_entity === entity) {
return (parent_folder = folder)
}
diff --git a/services/web/frontend/js/ide/file-tree/controllers/FileTreeController.js b/services/web/frontend/js/ide/file-tree/controllers/FileTreeController.js
index 8e64371eb2..5ba473b7f1 100644
--- a/services/web/frontend/js/ide/file-tree/controllers/FileTreeController.js
+++ b/services/web/frontend/js/ide/file-tree/controllers/FileTreeController.js
@@ -16,222 +16,224 @@ import _ from 'lodash'
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
-App.controller('FileTreeController', function($scope, $modal, ide, $rootScope) {
- $scope.openNewDocModal = reactBridgeParentFolderId =>
- $modal.open({
- templateUrl: 'newFileModalTemplate',
- controller: 'NewFileModalController',
- size: 'lg',
- resolve: {
- parent_folder() {
- if (reactBridgeParentFolderId) {
- return { id: reactBridgeParentFolderId }
+App.controller(
+ 'FileTreeController',
+ function ($scope, $modal, ide, $rootScope) {
+ $scope.openNewDocModal = reactBridgeParentFolderId =>
+ $modal.open({
+ templateUrl: 'newFileModalTemplate',
+ controller: 'NewFileModalController',
+ size: 'lg',
+ resolve: {
+ parent_folder() {
+ if (reactBridgeParentFolderId) {
+ return { id: reactBridgeParentFolderId }
+ }
+ return ide.fileTreeManager.getCurrentFolder()
+ },
+ projectFeatures() {
+ return ide.$scope.project.features
+ },
+ type() {
+ return 'doc'
+ },
+ userFeatures() {
+ return ide.$scope.user.features
}
- return ide.fileTreeManager.getCurrentFolder()
- },
- projectFeatures() {
- return ide.$scope.project.features
- },
- type() {
- return 'doc'
- },
- userFeatures() {
- return ide.$scope.user.features
}
- }
- })
+ })
- $scope.openNewFolderModal = () =>
- $modal.open({
- templateUrl: 'newFolderModalTemplate',
- controller: 'NewFolderModalController',
- resolve: {
- parent_folder() {
- return ide.fileTreeManager.getCurrentFolder()
- }
- }
- })
-
- $scope.openUploadFileModal = reactBridgeParentFolderId =>
- $modal.open({
- templateUrl: 'newFileModalTemplate',
- controller: 'NewFileModalController',
- size: 'lg',
- resolve: {
- projectFeatures() {
- return ide.$scope.project.features
- },
- parent_folder() {
- if (reactBridgeParentFolderId) {
- return { id: reactBridgeParentFolderId }
+ $scope.openNewFolderModal = () =>
+ $modal.open({
+ templateUrl: 'newFolderModalTemplate',
+ controller: 'NewFolderModalController',
+ resolve: {
+ parent_folder() {
+ return ide.fileTreeManager.getCurrentFolder()
}
- return ide.fileTreeManager.getCurrentFolder()
- },
- type() {
- return 'upload'
- },
- userFeatures() {
- return ide.$scope.user.features
}
- }
- })
+ })
- if (
- window.showReactFileTree &&
- !window.FileTreeReactBridgeOpenNewDocModalListened
- ) {
- window.FileTreeReactBridgeOpenNewDocModalListened = true
- window.addEventListener(
- 'FileTreeReactBridge.openNewDocModal',
- ({ detail }) => {
- if (detail.mode === 'upload') {
- $scope.openUploadFileModal(detail.parentFolderId)
- } else {
- $scope.openNewDocModal(detail.parentFolderId)
+ $scope.openUploadFileModal = reactBridgeParentFolderId =>
+ $modal.open({
+ templateUrl: 'newFileModalTemplate',
+ controller: 'NewFileModalController',
+ size: 'lg',
+ resolve: {
+ projectFeatures() {
+ return ide.$scope.project.features
+ },
+ parent_folder() {
+ if (reactBridgeParentFolderId) {
+ return { id: reactBridgeParentFolderId }
+ }
+ return ide.fileTreeManager.getCurrentFolder()
+ },
+ type() {
+ return 'upload'
+ },
+ userFeatures() {
+ return ide.$scope.user.features
+ }
}
- }
- )
- }
-
- $scope.orderByFoldersFirst = function(entity) {
- if ((entity != null ? entity.type : undefined) === 'folder') {
- return '0'
- }
- return '1'
- }
-
- $scope.startRenamingSelected = () => $scope.$broadcast('rename:selected')
-
- return ($scope.openDeleteModalForSelected = () =>
- $scope.$broadcast('delete:selected'))
-})
-
-App.controller('NewFolderModalController', function(
- $scope,
- ide,
- $modalInstance,
- $timeout,
- parent_folder
-) {
- $scope.inputs = { name: 'name' }
- $scope.state = { inflight: false }
-
- $modalInstance.opened.then(() =>
- $timeout(() => $scope.$broadcast('open'), 200)
- )
-
- $scope.create = function() {
- const { name } = $scope.inputs
- if (name == null || name.length === 0) {
- return
- }
- $scope.state.inflight = true
- return ide.fileTreeManager
- .createFolder(name, $scope.parent_folder)
- .then(function() {
- $scope.state.inflight = false
- return $modalInstance.dismiss('done')
})
- .catch(function(response) {
- const { data } = response
- $scope.error = data
- return ($scope.state.inflight = false)
- })
- }
- return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
-})
-
-App.controller('DuplicateFileModalController', function(
- $scope,
- $modalInstance,
- fileName
-) {
- $scope.fileName = fileName
- $scope.cancel = () => $modalInstance.dismiss('cancel')
-})
-
-App.controller('NewFileModalController', function(
- $scope,
- ide,
- type,
- parent_folder,
- $modalInstance,
- eventTracking,
- projectFeatures,
- userFeatures
-) {
- $scope.file_count = ide.fileTreeManager.getFullCount()
- $scope.type = type
- $scope.parent_folder = parent_folder
- $scope.state = {
- inflight: false,
- valid: true
- }
- $scope.cancel = () => $modalInstance.dismiss('cancel')
- $scope.create = () => $scope.$broadcast('create')
-
- const hasMendeleyFeature =
- (projectFeatures && projectFeatures.references) ||
- (projectFeatures && projectFeatures.mendeley) ||
- (userFeatures && userFeatures.references) ||
- (userFeatures && userFeatures.mendeley)
-
- const hasZoteroFeature =
- (projectFeatures && projectFeatures.references) ||
- (projectFeatures && projectFeatures.zotero) ||
- (userFeatures && userFeatures.references) ||
- (userFeatures && userFeatures.zotero)
-
- $scope.$watch('type', function() {
- if ($scope.type === 'mendeley' && !hasMendeleyFeature) {
- eventTracking.send(
- 'subscription-funnel',
- 'editor-click-feature',
- $scope.type
+ if (
+ window.showReactFileTree &&
+ !window.FileTreeReactBridgeOpenNewDocModalListened
+ ) {
+ window.FileTreeReactBridgeOpenNewDocModalListened = true
+ window.addEventListener(
+ 'FileTreeReactBridge.openNewDocModal',
+ ({ detail }) => {
+ if (detail.mode === 'upload') {
+ $scope.openUploadFileModal(detail.parentFolderId)
+ } else {
+ $scope.openNewDocModal(detail.parentFolderId)
+ }
+ }
)
}
- if ($scope.type === 'zotero' && !hasZoteroFeature) {
- eventTracking.send(
- 'subscription-funnel',
- 'editor-click-feature',
- $scope.type
+
+ $scope.orderByFoldersFirst = function (entity) {
+ if ((entity != null ? entity.type : undefined) === 'folder') {
+ return '0'
+ }
+ return '1'
+ }
+
+ $scope.startRenamingSelected = () => $scope.$broadcast('rename:selected')
+
+ return ($scope.openDeleteModalForSelected = () =>
+ $scope.$broadcast('delete:selected'))
+ }
+)
+
+App.controller(
+ 'NewFolderModalController',
+ function ($scope, ide, $modalInstance, $timeout, parent_folder) {
+ $scope.inputs = { name: 'name' }
+ $scope.state = { inflight: false }
+
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
+
+ $scope.create = function () {
+ const { name } = $scope.inputs
+ if (name == null || name.length === 0) {
+ return
+ }
+ $scope.state.inflight = true
+ return ide.fileTreeManager
+ .createFolder(name, $scope.parent_folder)
+ .then(function () {
+ $scope.state.inflight = false
+ return $modalInstance.dismiss('done')
+ })
+ .catch(function (response) {
+ const { data } = response
+ $scope.error = data
+ return ($scope.state.inflight = false)
+ })
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller(
+ 'DuplicateFileModalController',
+ function ($scope, $modalInstance, fileName) {
+ $scope.fileName = fileName
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
+ }
+)
+
+App.controller(
+ 'NewFileModalController',
+ function (
+ $scope,
+ ide,
+ type,
+ parent_folder,
+ $modalInstance,
+ eventTracking,
+ projectFeatures,
+ userFeatures
+ ) {
+ $scope.file_count = ide.fileTreeManager.getFullCount()
+ $scope.type = type
+ $scope.parent_folder = parent_folder
+ $scope.state = {
+ inflight: false,
+ valid: true
+ }
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
+ $scope.create = () => $scope.$broadcast('create')
+
+ const hasMendeleyFeature =
+ (projectFeatures && projectFeatures.references) ||
+ (projectFeatures && projectFeatures.mendeley) ||
+ (userFeatures && userFeatures.references) ||
+ (userFeatures && userFeatures.mendeley)
+
+ const hasZoteroFeature =
+ (projectFeatures && projectFeatures.references) ||
+ (projectFeatures && projectFeatures.zotero) ||
+ (userFeatures && userFeatures.references) ||
+ (userFeatures && userFeatures.zotero)
+
+ $scope.$watch('type', function () {
+ if ($scope.type === 'mendeley' && !hasMendeleyFeature) {
+ eventTracking.send(
+ 'subscription-funnel',
+ 'editor-click-feature',
+ $scope.type
+ )
+ }
+ if ($scope.type === 'zotero' && !hasZoteroFeature) {
+ eventTracking.send(
+ 'subscription-funnel',
+ 'editor-click-feature',
+ $scope.type
+ )
+ }
+ })
+ $scope.$on('done', (e, opts = {}) => {
+ const isBibFile = opts.name && /^.*\.bib$/.test(opts.name)
+ if (opts.shouldReindexReferences || isBibFile) {
+ ide.$scope.$emit('references:should-reindex', {})
+ }
+ $modalInstance.dismiss('done')
+ })
+
+ if (
+ window.showReactFileTree &&
+ !window.FileTreeReactBridgeOpenNewFileModalListened
+ ) {
+ window.FileTreeReactBridgeOpenNewFileModalListened = true
+ window.addEventListener(
+ 'FileTreeReactBridge.openNewFileModal',
+ ({ detail }) => {
+ if (detail.done) {
+ ide.$scope.FileTreeReactBridgePromise.resolve()
+ }
+ if (detail.error) {
+ ide.$scope.FileTreeReactBridgePromise.reject(detail)
+ }
+ }
)
}
- })
- $scope.$on('done', (e, opts = {}) => {
- const isBibFile = opts.name && /^.*\.bib$/.test(opts.name)
- if (opts.shouldReindexReferences || isBibFile) {
- ide.$scope.$emit('references:should-reindex', {})
- }
- $modalInstance.dismiss('done')
- })
-
- if (
- window.showReactFileTree &&
- !window.FileTreeReactBridgeOpenNewFileModalListened
- ) {
- window.FileTreeReactBridgeOpenNewFileModalListened = true
- window.addEventListener(
- 'FileTreeReactBridge.openNewFileModal',
- ({ detail }) => {
- if (detail.done) {
- ide.$scope.FileTreeReactBridgePromise.resolve()
- }
- if (detail.error) {
- ide.$scope.FileTreeReactBridgePromise.reject(detail)
- }
- }
- )
}
-})
+)
-App.controller('NewDocModalController', function($scope, ide, $timeout) {
+App.controller('NewDocModalController', function ($scope, ide, $timeout) {
$scope.inputs = { name: 'name.tex' }
$timeout(() => $scope.$broadcast('open'), 200)
- return $scope.$on('create', function() {
+ return $scope.$on('create', function () {
const { name } = $scope.inputs
if (name == null || name.length === 0) {
return
@@ -239,16 +241,16 @@ App.controller('NewDocModalController', function($scope, ide, $timeout) {
$scope.state.inflight = true
return ide.fileTreeManager
.createDoc(name, $scope.parent_folder)
- .then(function() {
+ .then(function () {
$scope.state.inflight = false
return $scope.$emit('done')
})
- .catch(function(response) {
+ .catch(function (response) {
const { data } = response
$scope.error = data
$scope.state.inflight = false
})
- .finally(function() {
+ .finally(function () {
if (!$scope.$$phase) {
$scope.$apply()
}
@@ -256,428 +258,423 @@ App.controller('NewDocModalController', function($scope, ide, $timeout) {
})
})
-App.controller('UploadFileModalController', function(
- $scope,
- $rootScope,
- ide,
- $timeout,
- $window
-) {
- $scope.parent_folder_id =
- $scope.parent_folder != null ? $scope.parent_folder.id : undefined
- $scope.project_id = ide.project_id
- $scope.tooManyFiles = false
- $scope.rateLimitHit = false
- $scope.secondsToRedirect = 10
- $scope.notLoggedIn = false
- $scope.conflicts = []
- $scope.control = {}
+App.controller(
+ 'UploadFileModalController',
+ function ($scope, $rootScope, ide, $timeout, $window) {
+ $scope.parent_folder_id =
+ $scope.parent_folder != null ? $scope.parent_folder.id : undefined
+ $scope.project_id = ide.project_id
+ $scope.tooManyFiles = false
+ $scope.rateLimitHit = false
+ $scope.secondsToRedirect = 10
+ $scope.notLoggedIn = false
+ $scope.conflicts = []
+ $scope.control = {}
- const needToLogBackIn = function() {
- $scope.notLoggedIn = true
- var decreseTimeout = () =>
- $timeout(function() {
- if ($scope.secondsToRedirect === 0) {
- return ($window.location.href = `/login?redir=/project/${ide.project_id}`)
- } else {
- decreseTimeout()
- return ($scope.secondsToRedirect = $scope.secondsToRedirect - 1)
+ const needToLogBackIn = function () {
+ $scope.notLoggedIn = true
+ var decreseTimeout = () =>
+ $timeout(function () {
+ if ($scope.secondsToRedirect === 0) {
+ return ($window.location.href = `/login?redir=/project/${ide.project_id}`)
+ } else {
+ decreseTimeout()
+ return ($scope.secondsToRedirect = $scope.secondsToRedirect - 1)
+ }
+ }, 1000)
+
+ return decreseTimeout()
+ }
+
+ $scope.max_files = 40
+ $scope.onComplete = (error, name, response) =>
+ $timeout(function () {
+ uploadCount--
+ if (response.success) {
+ $rootScope.$broadcast('file:upload:complete', response)
}
- }, 1000)
+ if (uploadCount === 0 && response != null && response.success) {
+ return $scope.$emit('done', { name: name })
+ }
+ }, 250)
- return decreseTimeout()
- }
-
- $scope.max_files = 40
- $scope.onComplete = (error, name, response) =>
- $timeout(function() {
- uploadCount--
- if (response.success) {
- $rootScope.$broadcast('file:upload:complete', response)
+ $scope.onValidateBatch = function (files) {
+ if (files.length > $scope.max_files) {
+ $timeout(() => ($scope.tooManyFiles = true), 1)
+ return false
+ } else {
+ return true
}
- if (uploadCount === 0 && response != null && response.success) {
- return $scope.$emit('done', { name: name })
- }
- }, 250)
+ }
- $scope.onValidateBatch = function(files) {
- if (files.length > $scope.max_files) {
- $timeout(() => ($scope.tooManyFiles = true), 1)
- return false
- } else {
+ $scope.onError = function (id, name, reason) {
+ console.log(id, name, reason)
+ if (reason.indexOf('429') !== -1) {
+ return ($scope.rateLimitHit = true)
+ } else if (reason.indexOf('403') !== -1) {
+ return needToLogBackIn()
+ }
+ }
+
+ let _uploadTimer = null
+ const uploadIfNoConflicts = function () {
+ if ($scope.conflicts.length === 0) {
+ return $scope.doUpload()
+ }
+ }
+
+ var uploadCount = 0
+ $scope.onSubmit = function (id, name) {
+ uploadCount++
+ if (ide.fileTreeManager.existsInFolder($scope.parent_folder_id, name)) {
+ $scope.conflicts.push(name)
+ $scope.$apply()
+ }
+ if (_uploadTimer == null) {
+ _uploadTimer = setTimeout(function () {
+ _uploadTimer = null
+ return uploadIfNoConflicts()
+ }, 0)
+ }
return true
}
- }
- $scope.onError = function(id, name, reason) {
- console.log(id, name, reason)
- if (reason.indexOf('429') !== -1) {
- return ($scope.rateLimitHit = true)
- } else if (reason.indexOf('403') !== -1) {
- return needToLogBackIn()
- }
- }
-
- let _uploadTimer = null
- const uploadIfNoConflicts = function() {
- if ($scope.conflicts.length === 0) {
- return $scope.doUpload()
- }
- }
-
- var uploadCount = 0
- $scope.onSubmit = function(id, name) {
- uploadCount++
- if (ide.fileTreeManager.existsInFolder($scope.parent_folder_id, name)) {
- $scope.conflicts.push(name)
+ $scope.onCancel = function (id, name) {
+ uploadCount--
+ const index = $scope.conflicts.indexOf(name)
+ if (index > -1) {
+ $scope.conflicts.splice(index, 1)
+ }
$scope.$apply()
+ return uploadIfNoConflicts()
}
- if (_uploadTimer == null) {
- _uploadTimer = setTimeout(function() {
- _uploadTimer = null
- return uploadIfNoConflicts()
- }, 0)
- }
- return true
+
+ return ($scope.doUpload = () =>
+ __guard__($scope.control != null ? $scope.control.q : undefined, x =>
+ x.uploadStoredFiles()
+ ))
}
+)
- $scope.onCancel = function(id, name) {
- uploadCount--
- const index = $scope.conflicts.indexOf(name)
- if (index > -1) {
- $scope.conflicts.splice(index, 1)
+App.controller(
+ 'ProjectLinkedFileModalController',
+ function ($scope, ide, $timeout) {
+ $scope.data = {
+ projects: null, // or []
+ selectedProjectId: null,
+ projectEntities: null, // or []
+ projectOutputFiles: null, // or []
+ selectedProjectEntity: null,
+ selectedProjectOutputFile: null,
+ buildId: null,
+ name: null
}
- $scope.$apply()
- return uploadIfNoConflicts()
- }
+ $scope.state.inFlight = {
+ projects: false,
+ entities: false,
+ compile: false
+ }
+ $scope.state.isOutputFilesMode = false
+ $scope.state.error = false
- return ($scope.doUpload = () =>
- __guard__($scope.control != null ? $scope.control.q : undefined, x =>
- x.uploadStoredFiles()
- ))
-})
+ $scope.$watch('data.selectedProjectId', function (newVal, oldVal) {
+ if (!newVal) {
+ return
+ }
+ $scope.data.selectedProjectEntity = null
+ $scope.data.selectedProjectOutputFile = null
+ if ($scope.state.isOutputFilesMode) {
+ return $scope.compileProjectAndGetOutputFiles(
+ $scope.data.selectedProjectId
+ )
+ } else {
+ return $scope.getProjectEntities($scope.data.selectedProjectId)
+ }
+ })
-App.controller('ProjectLinkedFileModalController', function(
- $scope,
- ide,
- $timeout
-) {
- $scope.data = {
- projects: null, // or []
- selectedProjectId: null,
- projectEntities: null, // or []
- projectOutputFiles: null, // or []
- selectedProjectEntity: null,
- selectedProjectOutputFile: null,
- buildId: null,
- name: null
- }
- $scope.state.inFlight = {
- projects: false,
- entities: false,
- compile: false
- }
- $scope.state.isOutputFilesMode = false
- $scope.state.error = false
+ $scope.$watch('state.isOutputFilesMode', function (newVal, oldVal) {
+ if (!newVal && !oldVal) {
+ return
+ }
+ $scope.data.selectedProjectOutputFile = null
+ if (newVal === true) {
+ return $scope.compileProjectAndGetOutputFiles(
+ $scope.data.selectedProjectId
+ )
+ } else {
+ return $scope.getProjectEntities($scope.data.selectedProjectId)
+ }
+ })
- $scope.$watch('data.selectedProjectId', function(newVal, oldVal) {
- if (!newVal) {
- return
- }
- $scope.data.selectedProjectEntity = null
- $scope.data.selectedProjectOutputFile = null
- if ($scope.state.isOutputFilesMode) {
- return $scope.compileProjectAndGetOutputFiles(
- $scope.data.selectedProjectId
- )
- } else {
- return $scope.getProjectEntities($scope.data.selectedProjectId)
- }
- })
-
- $scope.$watch('state.isOutputFilesMode', function(newVal, oldVal) {
- if (!newVal && !oldVal) {
- return
- }
- $scope.data.selectedProjectOutputFile = null
- if (newVal === true) {
- return $scope.compileProjectAndGetOutputFiles(
- $scope.data.selectedProjectId
- )
- } else {
- return $scope.getProjectEntities($scope.data.selectedProjectId)
- }
- })
-
- // auto-set filename based on selected file
- $scope.$watch('data.selectedProjectEntity', function(newVal, oldVal) {
- if (!newVal) {
- return
- }
- const fileName = newVal.split('/').reverse()[0]
- if (fileName) {
- $scope.data.name = fileName
- }
- })
-
- // auto-set filename based on selected file
- $scope.$watch('data.selectedProjectOutputFile', function(newVal, oldVal) {
- if (!newVal) {
- return
- }
- if (newVal === 'output.pdf') {
- const project = _.find(
- $scope.data.projects,
- p => p._id === $scope.data.selectedProjectId
- )
- $scope.data.name =
- (project != null ? project.name : undefined) != null
- ? `${project.name}.pdf`
- : 'output.pdf'
- } else {
+ // auto-set filename based on selected file
+ $scope.$watch('data.selectedProjectEntity', function (newVal, oldVal) {
+ if (!newVal) {
+ return
+ }
const fileName = newVal.split('/').reverse()[0]
if (fileName) {
$scope.data.name = fileName
}
- }
- })
+ })
- const _setInFlight = type => ($scope.state.inFlight[type] = true)
-
- const _reset = function(opts) {
- const isError = opts.err === true
- const { inFlight } = $scope.state
- inFlight.projects = inFlight.entities = inFlight.compile = false
- $scope.state.inflight = false
- return ($scope.state.error = isError)
- }
-
- $scope.toggleOutputFilesMode = function() {
- if (!$scope.data.selectedProjectId) {
- return
- }
- return ($scope.state.isOutputFilesMode = !$scope.state.isOutputFilesMode)
- }
-
- $scope.shouldEnableProjectSelect = function() {
- const { state, data } = $scope
- return !state.inFlight.projects && data.projects
- }
-
- $scope.hasNoProjects = function() {
- const { state, data } = $scope
- return (
- !state.inFlight.projects &&
- (data.projects == null || data.projects.length === 0)
- )
- }
-
- $scope.shouldEnableProjectEntitySelect = function() {
- const { state, data } = $scope
- return (
- !state.inFlight.projects &&
- !state.inFlight.entities &&
- data.projects &&
- data.selectedProjectId
- )
- }
-
- $scope.shouldEnableProjectOutputFileSelect = function() {
- const { state, data } = $scope
- return (
- !state.inFlight.projects &&
- !state.inFlight.compile &&
- data.projects &&
- data.selectedProjectId
- )
- }
-
- const validate = function() {
- const { state } = $scope
- const { data } = $scope
- $scope.state.valid =
- !state.inFlight.projects &&
- !state.inFlight.entities &&
- data.projects &&
- data.selectedProjectId &&
- ((!$scope.state.isOutputFilesMode &&
- data.projectEntities &&
- data.selectedProjectEntity) ||
- ($scope.state.isOutputFilesMode &&
- data.projectOutputFiles &&
- data.selectedProjectOutputFile)) &&
- data.name
- }
- $scope.$watch('state', validate, true)
- $scope.$watch('data', validate, true)
-
- $scope.getUserProjects = function() {
- _setInFlight('projects')
- return ide.$http
- .get('/user/projects', {
- _csrf: window.csrfToken
- })
- .then(function(resp) {
- $scope.data.projectEntities = null
- $scope.data.projects = resp.data.projects.filter(
- p => p._id !== ide.project_id
+ // auto-set filename based on selected file
+ $scope.$watch('data.selectedProjectOutputFile', function (newVal, oldVal) {
+ if (!newVal) {
+ return
+ }
+ if (newVal === 'output.pdf') {
+ const project = _.find(
+ $scope.data.projects,
+ p => p._id === $scope.data.selectedProjectId
)
- return _reset({ err: false })
- })
- .catch(err => _reset({ err: true }))
- }
-
- $scope.getProjectEntities = project_id => {
- _setInFlight('entities')
- return ide.$http
- .get(`/project/${project_id}/entities`, {
- _csrf: window.csrfToken
- })
- .then(function(resp) {
- if ($scope.data.selectedProjectId === resp.data.project_id) {
- $scope.data.projectEntities = resp.data.entities
- return _reset({ err: false })
+ $scope.data.name =
+ (project != null ? project.name : undefined) != null
+ ? `${project.name}.pdf`
+ : 'output.pdf'
+ } else {
+ const fileName = newVal.split('/').reverse()[0]
+ if (fileName) {
+ $scope.data.name = fileName
}
- })
- .catch(err => _reset({ err: true }))
- }
+ }
+ })
- $scope.compileProjectAndGetOutputFiles = project_id => {
- _setInFlight('compile')
- return ide.$http
- .post(`/project/${project_id}/compile`, {
- check: 'silent',
- draft: false,
- incrementalCompilesEnabled: false,
- _csrf: window.csrfToken
- })
- .then(function(resp) {
- if (resp.data.status === 'success') {
- const filteredFiles = resp.data.outputFiles.filter(f =>
- f.path.match(/.*\.(pdf|png|jpeg|jpg|gif)/)
+ const _setInFlight = type => ($scope.state.inFlight[type] = true)
+
+ const _reset = function (opts) {
+ const isError = opts.err === true
+ const { inFlight } = $scope.state
+ inFlight.projects = inFlight.entities = inFlight.compile = false
+ $scope.state.inflight = false
+ return ($scope.state.error = isError)
+ }
+
+ $scope.toggleOutputFilesMode = function () {
+ if (!$scope.data.selectedProjectId) {
+ return
+ }
+ return ($scope.state.isOutputFilesMode = !$scope.state.isOutputFilesMode)
+ }
+
+ $scope.shouldEnableProjectSelect = function () {
+ const { state, data } = $scope
+ return !state.inFlight.projects && data.projects
+ }
+
+ $scope.hasNoProjects = function () {
+ const { state, data } = $scope
+ return (
+ !state.inFlight.projects &&
+ (data.projects == null || data.projects.length === 0)
+ )
+ }
+
+ $scope.shouldEnableProjectEntitySelect = function () {
+ const { state, data } = $scope
+ return (
+ !state.inFlight.projects &&
+ !state.inFlight.entities &&
+ data.projects &&
+ data.selectedProjectId
+ )
+ }
+
+ $scope.shouldEnableProjectOutputFileSelect = function () {
+ const { state, data } = $scope
+ return (
+ !state.inFlight.projects &&
+ !state.inFlight.compile &&
+ data.projects &&
+ data.selectedProjectId
+ )
+ }
+
+ const validate = function () {
+ const { state } = $scope
+ const { data } = $scope
+ $scope.state.valid =
+ !state.inFlight.projects &&
+ !state.inFlight.entities &&
+ data.projects &&
+ data.selectedProjectId &&
+ ((!$scope.state.isOutputFilesMode &&
+ data.projectEntities &&
+ data.selectedProjectEntity) ||
+ ($scope.state.isOutputFilesMode &&
+ data.projectOutputFiles &&
+ data.selectedProjectOutputFile)) &&
+ data.name
+ }
+ $scope.$watch('state', validate, true)
+ $scope.$watch('data', validate, true)
+
+ $scope.getUserProjects = function () {
+ _setInFlight('projects')
+ return ide.$http
+ .get('/user/projects', {
+ _csrf: window.csrfToken
+ })
+ .then(function (resp) {
+ $scope.data.projectEntities = null
+ $scope.data.projects = resp.data.projects.filter(
+ p => p._id !== ide.project_id
)
- $scope.data.projectOutputFiles = filteredFiles
- $scope.data.buildId = __guard__(
- filteredFiles != null ? filteredFiles[0] : undefined,
- x => x.build
- )
- console.log('>> build_id', $scope.data.buildId)
return _reset({ err: false })
- } else {
- $scope.data.projectOutputFiles = null
+ })
+ .catch(err => _reset({ err: true }))
+ }
+
+ $scope.getProjectEntities = project_id => {
+ _setInFlight('entities')
+ return ide.$http
+ .get(`/project/${project_id}/entities`, {
+ _csrf: window.csrfToken
+ })
+ .then(function (resp) {
+ if ($scope.data.selectedProjectId === resp.data.project_id) {
+ $scope.data.projectEntities = resp.data.entities
+ return _reset({ err: false })
+ }
+ })
+ .catch(err => _reset({ err: true }))
+ }
+
+ $scope.compileProjectAndGetOutputFiles = project_id => {
+ _setInFlight('compile')
+ return ide.$http
+ .post(`/project/${project_id}/compile`, {
+ check: 'silent',
+ draft: false,
+ incrementalCompilesEnabled: false,
+ _csrf: window.csrfToken
+ })
+ .then(function (resp) {
+ if (resp.data.status === 'success') {
+ const filteredFiles = resp.data.outputFiles.filter(f =>
+ f.path.match(/.*\.(pdf|png|jpeg|jpg|gif)/)
+ )
+ $scope.data.projectOutputFiles = filteredFiles
+ $scope.data.buildId = __guard__(
+ filteredFiles != null ? filteredFiles[0] : undefined,
+ x => x.build
+ )
+ console.log('>> build_id', $scope.data.buildId)
+ return _reset({ err: false })
+ } else {
+ $scope.data.projectOutputFiles = null
+ return _reset({ err: true })
+ }
+ })
+ .catch(function (err) {
+ console.error(err)
return _reset({ err: true })
+ })
+ }
+
+ $scope.init = () => $scope.getUserProjects()
+ $timeout($scope.init, 0)
+
+ return $scope.$on('create', function () {
+ let payload, provider
+ const projectId = $scope.data.selectedProjectId
+ const { name } = $scope.data
+ if ($scope.state.isOutputFilesMode) {
+ provider = 'project_output_file'
+ payload = {
+ source_project_id: projectId,
+ source_output_file_path: $scope.data.selectedProjectOutputFile,
+ build_id: $scope.data.buildId
+ }
+ } else {
+ provider = 'project_file'
+ payload = {
+ source_project_id: projectId,
+ source_entity_path: $scope.data.selectedProjectEntity
}
- })
- .catch(function(err) {
- console.error(err)
- return _reset({ err: true })
- })
- }
-
- $scope.init = () => $scope.getUserProjects()
- $timeout($scope.init, 0)
-
- return $scope.$on('create', function() {
- let payload, provider
- const projectId = $scope.data.selectedProjectId
- const { name } = $scope.data
- if ($scope.state.isOutputFilesMode) {
- provider = 'project_output_file'
- payload = {
- source_project_id: projectId,
- source_output_file_path: $scope.data.selectedProjectOutputFile,
- build_id: $scope.data.buildId
}
- } else {
- provider = 'project_file'
- payload = {
- source_project_id: projectId,
- source_entity_path: $scope.data.selectedProjectEntity
+ _setInFlight('create')
+ ide.fileTreeManager
+ .createLinkedFile(name, $scope.parent_folder, provider, payload)
+ .then(function () {
+ _reset({ err: false })
+ return $scope.$emit('done', { name: name })
+ })
+ .catch(function (response) {
+ const { data } = response
+ $scope.error = data
+ })
+ .finally(function () {
+ if (!$scope.$$phase) {
+ $scope.$apply()
+ }
+ })
+ })
+ }
+)
+
+export default App.controller(
+ 'UrlLinkedFileModalController',
+ function ($scope, ide, $timeout) {
+ $scope.inputs = {
+ name: '',
+ url: ''
+ }
+ $scope.nameChangedByUser = false
+
+ $timeout(() => $scope.$broadcast('open'), 200)
+
+ const validate = function () {
+ const { name, url } = $scope.inputs
+ if (name == null || name.length === 0) {
+ return ($scope.state.valid = false)
+ } else if (url == null || url.length === 0) {
+ return ($scope.state.valid = false)
+ } else {
+ return ($scope.state.valid = true)
}
}
- _setInFlight('create')
- ide.fileTreeManager
- .createLinkedFile(name, $scope.parent_folder, provider, payload)
- .then(function() {
- _reset({ err: false })
- return $scope.$emit('done', { name: name })
- })
- .catch(function(response) {
- const { data } = response
- $scope.error = data
- })
- .finally(function() {
- if (!$scope.$$phase) {
- $scope.$apply()
+ $scope.$watch('inputs.name', validate)
+ $scope.$watch('inputs.url', validate)
+
+ $scope.$watch('inputs.url', function (url) {
+ if (url != null && url !== '' && !$scope.nameChangedByUser) {
+ url = url.replace('://', '') // Ignore http:// etc
+ const parts = url.split('/').reverse()
+ if (parts.length > 1) {
+ // Wait for at one /
+ return ($scope.inputs.name = parts[0])
}
- })
- })
-})
-
-export default App.controller('UrlLinkedFileModalController', function(
- $scope,
- ide,
- $timeout
-) {
- $scope.inputs = {
- name: '',
- url: ''
- }
- $scope.nameChangedByUser = false
-
- $timeout(() => $scope.$broadcast('open'), 200)
-
- const validate = function() {
- const { name, url } = $scope.inputs
- if (name == null || name.length === 0) {
- return ($scope.state.valid = false)
- } else if (url == null || url.length === 0) {
- return ($scope.state.valid = false)
- } else {
- return ($scope.state.valid = true)
- }
- }
- $scope.$watch('inputs.name', validate)
- $scope.$watch('inputs.url', validate)
-
- $scope.$watch('inputs.url', function(url) {
- if (url != null && url !== '' && !$scope.nameChangedByUser) {
- url = url.replace('://', '') // Ignore http:// etc
- const parts = url.split('/').reverse()
- if (parts.length > 1) {
- // Wait for at one /
- return ($scope.inputs.name = parts[0])
}
- }
- })
+ })
- return $scope.$on('create', function() {
- const { name, url } = $scope.inputs
- if (name == null || name.length === 0) {
- return
- }
- if (url == null || url.length === 0) {
- return
- }
- $scope.state.inflight = true
- return ide.fileTreeManager
- .createLinkedFile(name, $scope.parent_folder, 'url', { url })
- .then(function() {
- $scope.state.inflight = false
- return $scope.$emit('done', { name: name })
- })
- .catch(function(response) {
- const { data } = response
- $scope.error = data
- return ($scope.state.inflight = false)
- })
- .finally(function() {
- if (!$scope.$$phase) {
- $scope.$apply()
- }
- })
- })
-})
+ return $scope.$on('create', function () {
+ const { name, url } = $scope.inputs
+ if (name == null || name.length === 0) {
+ return
+ }
+ if (url == null || url.length === 0) {
+ return
+ }
+ $scope.state.inflight = true
+ return ide.fileTreeManager
+ .createLinkedFile(name, $scope.parent_folder, 'url', { url })
+ .then(function () {
+ $scope.state.inflight = false
+ return $scope.$emit('done', { name: name })
+ })
+ .catch(function (response) {
+ const { data } = response
+ $scope.error = data
+ return ($scope.state.inflight = false)
+ })
+ .finally(function () {
+ if (!$scope.$$phase) {
+ $scope.$apply()
+ }
+ })
+ })
+ }
+)
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
diff --git a/services/web/frontend/js/ide/file-tree/controllers/FileTreeEntityController.js b/services/web/frontend/js/ide/file-tree/controllers/FileTreeEntityController.js
index 8403326eaf..f5d8eaee60 100644
--- a/services/web/frontend/js/ide/file-tree/controllers/FileTreeEntityController.js
+++ b/services/web/frontend/js/ide/file-tree/controllers/FileTreeEntityController.js
@@ -14,152 +14,148 @@
*/
import App from '../../../base'
import iconTypeFromName from '../util/iconTypeFromName'
-App.controller('FileTreeEntityController', function(
- $scope,
- ide,
- $modal,
- $element
-) {
- $scope.MAX_DEPTH = 8
+App.controller(
+ 'FileTreeEntityController',
+ function ($scope, ide, $modal, $element) {
+ $scope.MAX_DEPTH = 8
- $scope.select = function(e) {
- if (e.ctrlKey || e.metaKey) {
- e.stopPropagation()
- const initialMultiSelectCount = ide.fileTreeManager.multiSelectedCount()
- ide.fileTreeManager.toggleMultiSelectEntity($scope.entity) === 0
- if (initialMultiSelectCount === 0) {
- // On first multi selection, also include the current active/open file.
- return ide.fileTreeManager.multiSelectSelectedEntity()
- }
- } else {
- ide.fileTreeManager.selectEntity($scope.entity)
- return $scope.$emit('entity:selected', $scope.entity)
- }
- }
-
- if ($scope.entity.type === 'doc') {
- $scope.$watch('entity.selected', function(isSelected) {
- if (isSelected) {
- $scope.$emit('entity-file:selected', $scope.entity)
- if (!_isEntryElVisible($element)) {
- $scope.$applyAsync(function() {
- $element[0].scrollIntoView()
- })
+ $scope.select = function (e) {
+ if (e.ctrlKey || e.metaKey) {
+ e.stopPropagation()
+ const initialMultiSelectCount = ide.fileTreeManager.multiSelectedCount()
+ ide.fileTreeManager.toggleMultiSelectEntity($scope.entity) === 0
+ if (initialMultiSelectCount === 0) {
+ // On first multi selection, also include the current active/open file.
+ return ide.fileTreeManager.multiSelectSelectedEntity()
}
+ } else {
+ ide.fileTreeManager.selectEntity($scope.entity)
+ return $scope.$emit('entity:selected', $scope.entity)
}
- })
- }
+ }
- function _isEntryElVisible($entryEl) {
- const viewportEl = $('.file-tree-list')
- const entryElTop = $entryEl.offset().top
- const entryElBottom = entryElTop + $entryEl.outerHeight()
- const entryListViewportElTop = viewportEl.offset().top
- const entryListViewportElBottom =
- entryListViewportElTop + viewportEl.height()
+ if ($scope.entity.type === 'doc') {
+ $scope.$watch('entity.selected', function (isSelected) {
+ if (isSelected) {
+ $scope.$emit('entity-file:selected', $scope.entity)
+ if (!_isEntryElVisible($element)) {
+ $scope.$applyAsync(function () {
+ $element[0].scrollIntoView()
+ })
+ }
+ }
+ })
+ }
- return (
- entryElTop >= entryListViewportElTop &&
- entryElBottom <= entryListViewportElBottom
- )
- }
+ function _isEntryElVisible($entryEl) {
+ const viewportEl = $('.file-tree-list')
+ const entryElTop = $entryEl.offset().top
+ const entryElBottom = entryElTop + $entryEl.outerHeight()
+ const entryListViewportElTop = viewportEl.offset().top
+ const entryListViewportElBottom =
+ entryListViewportElTop + viewportEl.height()
- $scope.draggableHelper = function() {
- if (ide.fileTreeManager.multiSelectedCount() > 0) {
- return $(
- `
${ide.fileTreeManager.multiSelectedCount()} Files`
+ return (
+ entryElTop >= entryListViewportElTop &&
+ entryElBottom <= entryListViewportElBottom
)
- } else {
- return $(`
${$scope.entity.name}`)
- }
- }
-
- $scope.inputs = { name: $scope.entity.name }
-
- $scope.startRenaming = () => ($scope.entity.renaming = true)
-
- let invalidModalShowing = false
- $scope.finishRenaming = function() {
- // avoid double events when blur and on-enter fire together
- if (!$scope.entity.renaming) {
- return
}
- const { name } = $scope.inputs
+ $scope.draggableHelper = function () {
+ if (ide.fileTreeManager.multiSelectedCount() > 0) {
+ return $(
+ `
${ide.fileTreeManager.multiSelectedCount()} Files`
+ )
+ } else {
+ return $(`
${$scope.entity.name}`)
+ }
+ }
- // validator will set name to undefined for invalid filenames
- if (name == null) {
- // Showing the modal blurs the rename box which calls us again
- // so track this with the invalidModalShowing flag
- if (invalidModalShowing) {
+ $scope.inputs = { name: $scope.entity.name }
+
+ $scope.startRenaming = () => ($scope.entity.renaming = true)
+
+ let invalidModalShowing = false
+ $scope.finishRenaming = function () {
+ // avoid double events when blur and on-enter fire together
+ if (!$scope.entity.renaming) {
return
}
- invalidModalShowing = true
- const modal = $modal.open({
- templateUrl: 'invalidFileNameModalTemplate'
- })
- modal.result.then(() => (invalidModalShowing = false))
- return
- }
- delete $scope.entity.renaming
- if (name == null || name.length === 0) {
- $scope.inputs.name = $scope.entity.name
- return
- }
- return ide.fileTreeManager.renameEntity($scope.entity, name)
- }
+ const { name } = $scope.inputs
- $scope.$on('rename:selected', function() {
- if ($scope.entity.selected) {
- return $scope.startRenaming()
- }
- })
-
- $scope.openDeleteModal = function() {
- let entities
- if (ide.fileTreeManager.multiSelectedCount() > 0) {
- entities = ide.fileTreeManager.getMultiSelectedEntityChildNodes()
- } else {
- entities = [$scope.entity]
- }
- return $modal.open({
- templateUrl: 'deleteEntityModalTemplate',
- controller: 'DeleteEntityModalController',
- resolve: {
- entities() {
- return entities
+ // validator will set name to undefined for invalid filenames
+ if (name == null) {
+ // Showing the modal blurs the rename box which calls us again
+ // so track this with the invalidModalShowing flag
+ if (invalidModalShowing) {
+ return
}
+ invalidModalShowing = true
+ const modal = $modal.open({
+ templateUrl: 'invalidFileNameModalTemplate'
+ })
+ modal.result.then(() => (invalidModalShowing = false))
+ return
+ }
+
+ delete $scope.entity.renaming
+ if (name == null || name.length === 0) {
+ $scope.inputs.name = $scope.entity.name
+ return
+ }
+ return ide.fileTreeManager.renameEntity($scope.entity, name)
+ }
+
+ $scope.$on('rename:selected', function () {
+ if ($scope.entity.selected) {
+ return $scope.startRenaming()
}
})
- }
- $scope.$on('delete:selected', function() {
- if ($scope.entity.selected) {
- return $scope.openDeleteModal()
+ $scope.openDeleteModal = function () {
+ let entities
+ if (ide.fileTreeManager.multiSelectedCount() > 0) {
+ entities = ide.fileTreeManager.getMultiSelectedEntityChildNodes()
+ } else {
+ entities = [$scope.entity]
+ }
+ return $modal.open({
+ templateUrl: 'deleteEntityModalTemplate',
+ controller: 'DeleteEntityModalController',
+ resolve: {
+ entities() {
+ return entities
+ }
+ }
+ })
}
- })
- return ($scope.iconTypeFromName = iconTypeFromName)
-})
+ $scope.$on('delete:selected', function () {
+ if ($scope.entity.selected) {
+ return $scope.openDeleteModal()
+ }
+ })
-export default App.controller('DeleteEntityModalController', function(
- $scope,
- ide,
- $modalInstance,
- entities
-) {
- $scope.state = { inflight: false }
-
- $scope.entities = entities
-
- $scope.delete = function() {
- $scope.state.inflight = true
- for (let entity of Array.from($scope.entities)) {
- ide.fileTreeManager.deleteEntity(entity)
- }
- return $modalInstance.close()
+ return ($scope.iconTypeFromName = iconTypeFromName)
}
+)
- return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
-})
+export default App.controller(
+ 'DeleteEntityModalController',
+ function ($scope, ide, $modalInstance, entities) {
+ $scope.state = { inflight: false }
+
+ $scope.entities = entities
+
+ $scope.delete = function () {
+ $scope.state.inflight = true
+ for (let entity of Array.from($scope.entities)) {
+ ide.fileTreeManager.deleteEntity(entity)
+ }
+ return $modalInstance.close()
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
diff --git a/services/web/frontend/js/ide/file-tree/controllers/FileTreeFolderController.js b/services/web/frontend/js/ide/file-tree/controllers/FileTreeFolderController.js
index 338cf5cc48..564cf45f3a 100644
--- a/services/web/frontend/js/ide/file-tree/controllers/FileTreeFolderController.js
+++ b/services/web/frontend/js/ide/file-tree/controllers/FileTreeFolderController.js
@@ -14,120 +14,121 @@
*/
import App from '../../../base'
-export default App.controller('FileTreeFolderController', function(
- $scope,
- ide,
- $modal,
- localStorage
-) {
- $scope.expanded = localStorage(`folder.${$scope.entity.id}.expanded`) || false
+export default App.controller(
+ 'FileTreeFolderController',
+ function ($scope, ide, $modal, localStorage) {
+ $scope.expanded =
+ localStorage(`folder.${$scope.entity.id}.expanded`) || false
- $scope.toggleExpanded = function() {
- $scope.expanded = !$scope.expanded
- $scope._storeCurrentStateInLocalStorage()
- }
-
- $scope.$on('entity-file:selected', function() {
- $scope.expanded = true
- $scope._storeCurrentStateInLocalStorage()
- })
-
- $scope._storeCurrentStateInLocalStorage = function() {
- localStorage(`folder.${$scope.entity.id}.expanded`, $scope.expanded)
- }
-
- $scope.onDrop = function(events, ui) {
- let entities
- if (ide.fileTreeManager.multiSelectedCount()) {
- entities = ide.fileTreeManager.getMultiSelectedEntityChildNodes()
- } else {
- entities = [$(ui.draggable).scope().entity]
+ $scope.toggleExpanded = function () {
+ $scope.expanded = !$scope.expanded
+ $scope._storeCurrentStateInLocalStorage()
}
- const ids = $scope.entity.children.map(entity => entity.id)
+ $scope.$on('entity-file:selected', function () {
+ $scope.expanded = true
+ $scope._storeCurrentStateInLocalStorage()
+ })
- for (let dropped_entity of Array.from(entities)) {
- if (!ids.includes(dropped_entity.id)) {
- try {
- ide.fileTreeManager.moveEntity(dropped_entity, $scope.entity)
- } catch (err) {
- $modal.open({
- templateUrl: 'duplicateFileModalTemplate',
- controller: 'DuplicateFileModalController',
- resolve: {
- fileName() {
- return dropped_entity.name
+ $scope._storeCurrentStateInLocalStorage = function () {
+ localStorage(`folder.${$scope.entity.id}.expanded`, $scope.expanded)
+ }
+
+ $scope.onDrop = function (events, ui) {
+ let entities
+ if (ide.fileTreeManager.multiSelectedCount()) {
+ entities = ide.fileTreeManager.getMultiSelectedEntityChildNodes()
+ } else {
+ entities = [$(ui.draggable).scope().entity]
+ }
+
+ const ids = $scope.entity.children.map(entity => entity.id)
+
+ for (let dropped_entity of Array.from(entities)) {
+ if (!ids.includes(dropped_entity.id)) {
+ try {
+ ide.fileTreeManager.moveEntity(dropped_entity, $scope.entity)
+ } catch (err) {
+ $modal.open({
+ templateUrl: 'duplicateFileModalTemplate',
+ controller: 'DuplicateFileModalController',
+ resolve: {
+ fileName() {
+ return dropped_entity.name
+ }
}
- }
- })
+ })
+ }
}
}
+ $scope.$digest()
+ // clear highlight explicitly
+ return $('.file-tree-inner .droppable-hover').removeClass(
+ 'droppable-hover'
+ )
}
- $scope.$digest()
- // clear highlight explicitly
- return $('.file-tree-inner .droppable-hover').removeClass('droppable-hover')
- }
- $scope.orderByFoldersFirst = function(entity) {
- // We need this here as well as in FileTreeController
- // since the file-entity diretive creates a new scope
- // that doesn't inherit from previous scopes.
- if ((entity != null ? entity.type : undefined) === 'folder') {
- return '0'
+ $scope.orderByFoldersFirst = function (entity) {
+ // We need this here as well as in FileTreeController
+ // since the file-entity diretive creates a new scope
+ // that doesn't inherit from previous scopes.
+ if ((entity != null ? entity.type : undefined) === 'folder') {
+ return '0'
+ }
+ return '1'
}
- return '1'
+
+ $scope.openNewDocModal = () =>
+ $modal.open({
+ templateUrl: 'newFileModalTemplate',
+ controller: 'NewFileModalController',
+ size: 'lg',
+ resolve: {
+ parent_folder() {
+ return $scope.entity
+ },
+ projectFeatures() {
+ return ide.$scope.project.features
+ },
+ type() {
+ return 'doc'
+ },
+ userFeatures() {
+ return ide.$scope.user.features
+ }
+ }
+ })
+
+ $scope.openNewFolderModal = () =>
+ $modal.open({
+ templateUrl: 'newFolderModalTemplate',
+ controller: 'NewFolderModalController',
+ resolve: {
+ parent_folder() {
+ return $scope.entity
+ }
+ }
+ })
+
+ return ($scope.openUploadFileModal = () =>
+ $modal.open({
+ templateUrl: 'newFileModalTemplate',
+ controller: 'NewFileModalController',
+ size: 'lg',
+ resolve: {
+ parent_folder() {
+ return $scope.entity
+ },
+ projectFeatures() {
+ return ide.$scope.project.features
+ },
+ type() {
+ return 'upload'
+ },
+ userFeatures() {
+ return ide.$scope.user.features
+ }
+ }
+ }))
}
-
- $scope.openNewDocModal = () =>
- $modal.open({
- templateUrl: 'newFileModalTemplate',
- controller: 'NewFileModalController',
- size: 'lg',
- resolve: {
- parent_folder() {
- return $scope.entity
- },
- projectFeatures() {
- return ide.$scope.project.features
- },
- type() {
- return 'doc'
- },
- userFeatures() {
- return ide.$scope.user.features
- }
- }
- })
-
- $scope.openNewFolderModal = () =>
- $modal.open({
- templateUrl: 'newFolderModalTemplate',
- controller: 'NewFolderModalController',
- resolve: {
- parent_folder() {
- return $scope.entity
- }
- }
- })
-
- return ($scope.openUploadFileModal = () =>
- $modal.open({
- templateUrl: 'newFileModalTemplate',
- controller: 'NewFileModalController',
- size: 'lg',
- resolve: {
- parent_folder() {
- return $scope.entity
- },
- projectFeatures() {
- return ide.$scope.project.features
- },
- type() {
- return 'upload'
- },
- userFeatures() {
- return ide.$scope.user.features
- }
- }
- }))
-})
+)
diff --git a/services/web/frontend/js/ide/file-tree/controllers/FileTreeRootFolderController.js b/services/web/frontend/js/ide/file-tree/controllers/FileTreeRootFolderController.js
index 416c10c57b..9469e19e8e 100644
--- a/services/web/frontend/js/ide/file-tree/controllers/FileTreeRootFolderController.js
+++ b/services/web/frontend/js/ide/file-tree/controllers/FileTreeRootFolderController.js
@@ -13,41 +13,42 @@
*/
import App from '../../../base'
-export default App.controller('FileTreeRootFolderController', function(
- $scope,
- $modal,
- ide
-) {
- const { rootFolder } = $scope
- return ($scope.onDrop = function(events, ui) {
- let entities
- if (ide.fileTreeManager.multiSelectedCount()) {
- entities = ide.fileTreeManager.getMultiSelectedEntityChildNodes()
- } else {
- entities = [$(ui.draggable).scope().entity]
- }
+export default App.controller(
+ 'FileTreeRootFolderController',
+ function ($scope, $modal, ide) {
+ const { rootFolder } = $scope
+ return ($scope.onDrop = function (events, ui) {
+ let entities
+ if (ide.fileTreeManager.multiSelectedCount()) {
+ entities = ide.fileTreeManager.getMultiSelectedEntityChildNodes()
+ } else {
+ entities = [$(ui.draggable).scope().entity]
+ }
- const ids = rootFolder.children.map(entity => entity.id)
+ const ids = rootFolder.children.map(entity => entity.id)
- for (let dropped_entity of Array.from(entities)) {
- if (!ids.includes(dropped_entity.id)) {
- try {
- ide.fileTreeManager.moveEntity(dropped_entity, rootFolder)
- } catch (err) {
- $modal.open({
- templateUrl: 'duplicateFileModalTemplate',
- controller: 'DuplicateFileModalController',
- resolve: {
- fileName() {
- return dropped_entity.name
+ for (let dropped_entity of Array.from(entities)) {
+ if (!ids.includes(dropped_entity.id)) {
+ try {
+ ide.fileTreeManager.moveEntity(dropped_entity, rootFolder)
+ } catch (err) {
+ $modal.open({
+ templateUrl: 'duplicateFileModalTemplate',
+ controller: 'DuplicateFileModalController',
+ resolve: {
+ fileName() {
+ return dropped_entity.name
+ }
}
- }
- })
+ })
+ }
}
}
- }
- $scope.$digest()
- // clear highlight explicitly
- return $('.file-tree-inner .droppable-hover').removeClass('droppable-hover')
- })
-})
+ $scope.$digest()
+ // clear highlight explicitly
+ return $('.file-tree-inner .droppable-hover').removeClass(
+ 'droppable-hover'
+ )
+ })
+ }
+)
diff --git a/services/web/frontend/js/ide/file-tree/directives/draggable.js b/services/web/frontend/js/ide/file-tree/directives/draggable.js
index cd55f74788..5c222c689f 100644
--- a/services/web/frontend/js/ide/file-tree/directives/draggable.js
+++ b/services/web/frontend/js/ide/file-tree/directives/draggable.js
@@ -9,7 +9,7 @@ import App from '../../../base'
export default App.directive('draggable', () => ({
link(scope, element, attrs) {
- return scope.$watch(attrs.draggable, function(draggable) {
+ return scope.$watch(attrs.draggable, function (draggable) {
if (draggable) {
return element.draggable({
delay: 250,
diff --git a/services/web/frontend/js/ide/file-tree/directives/droppable.js b/services/web/frontend/js/ide/file-tree/directives/droppable.js
index 0483100484..b01a75b8e5 100644
--- a/services/web/frontend/js/ide/file-tree/directives/droppable.js
+++ b/services/web/frontend/js/ide/file-tree/directives/droppable.js
@@ -9,7 +9,7 @@ import App from '../../../base'
export default App.directive('droppable', () => ({
link(scope, element, attrs) {
- return scope.$watch(attrs.droppable, function(droppable) {
+ return scope.$watch(attrs.droppable, function (droppable) {
if (droppable) {
return element.droppable({
greedy: true,
diff --git a/services/web/frontend/js/ide/file-tree/directives/fileEntity.js b/services/web/frontend/js/ide/file-tree/directives/fileEntity.js
index f6d88195c8..c8d159b162 100644
--- a/services/web/frontend/js/ide/file-tree/directives/fileEntity.js
+++ b/services/web/frontend/js/ide/file-tree/directives/fileEntity.js
@@ -21,25 +21,23 @@ export default App.directive('fileEntity', RecursionHelper => ({
},
templateUrl: 'entityListItemTemplate',
compile(element) {
- return RecursionHelper.compile(element, function(
- scope,
+ return RecursionHelper.compile(
element,
- attrs,
- ctrl
- ) {
- // Don't freak out if we're already in an apply callback
- scope.$originalApply = scope.$apply
- return (scope.$apply = function(fn) {
- if (fn == null) {
- fn = function() {}
- }
- const phase = this.$root.$$phase
- if (phase === '$apply' || phase === '$digest') {
- return fn()
- } else {
- return this.$originalApply(fn)
- }
- })
- })
+ function (scope, element, attrs, ctrl) {
+ // Don't freak out if we're already in an apply callback
+ scope.$originalApply = scope.$apply
+ return (scope.$apply = function (fn) {
+ if (fn == null) {
+ fn = function () {}
+ }
+ const phase = this.$root.$$phase
+ if (phase === '$apply' || phase === '$digest') {
+ return fn()
+ } else {
+ return this.$originalApply(fn)
+ }
+ })
+ }
+ )
}
}))
diff --git a/services/web/frontend/js/ide/file-tree/util/iconTypeFromName.js b/services/web/frontend/js/ide/file-tree/util/iconTypeFromName.js
index d30e9c40b5..6ad913c8d4 100644
--- a/services/web/frontend/js/ide/file-tree/util/iconTypeFromName.js
+++ b/services/web/frontend/js/ide/file-tree/util/iconTypeFromName.js
@@ -12,7 +12,7 @@
*/
let iconTypeFromName
-export default iconTypeFromName = function(name) {
+export default iconTypeFromName = function (name) {
const ext = __guard__(name.split('.').pop(), x => x.toLowerCase())
if (['png', 'pdf', 'jpg', 'jpeg', 'gif'].includes(ext)) {
return 'image'
diff --git a/services/web/frontend/js/ide/files/services/files.js b/services/web/frontend/js/ide/files/services/files.js
index 975e632154..57a3db5dc7 100644
--- a/services/web/frontend/js/ide/files/services/files.js
+++ b/services/web/frontend/js/ide/files/services/files.js
@@ -1,11 +1,11 @@
import _ from 'lodash'
import App from '../../../base'
-export default App.factory('files', function(ide) {
+export default App.factory('files', function (ide) {
const Files = {
getTeXFiles() {
let texFiles = []
- ide.fileTreeManager.forEachEntity(function(entity, _folder, path) {
+ ide.fileTreeManager.forEachEntity(function (entity, _folder, path) {
if (
entity.type === 'doc' &&
/.*\.(tex|md|txt|tikz)/.test(entity.name)
diff --git a/services/web/frontend/js/ide/graphics/services/graphics.js b/services/web/frontend/js/ide/graphics/services/graphics.js
index cc45afe511..3dd7a84e60 100644
--- a/services/web/frontend/js/ide/graphics/services/graphics.js
+++ b/services/web/frontend/js/ide/graphics/services/graphics.js
@@ -13,11 +13,11 @@ import _ from 'lodash'
*/
import App from '../../../base'
-export default App.factory('graphics', function(ide) {
+export default App.factory('graphics', function (ide) {
const Graphics = {
getGraphicsFiles() {
const graphicsFiles = []
- ide.fileTreeManager.forEachEntity(function(entity, folder, path) {
+ ide.fileTreeManager.forEachEntity(function (entity, folder, path) {
if (
entity.type === 'file' &&
__guardMethod__(
diff --git a/services/web/frontend/js/ide/history/HistoryManager.js b/services/web/frontend/js/ide/history/HistoryManager.js
index 1e0a687a5b..1459429237 100644
--- a/services/web/frontend/js/ide/history/HistoryManager.js
+++ b/services/web/frontend/js/ide/history/HistoryManager.js
@@ -22,7 +22,7 @@ import './controllers/HistoryDiffController'
import './directives/infiniteScroll'
let HistoryManager
-export default HistoryManager = (function() {
+export default HistoryManager = (function () {
HistoryManager = class HistoryManager {
static initClass() {
this.prototype.BATCH_SIZE = 10
@@ -176,7 +176,7 @@ export default HistoryManager = (function() {
diff.text = text
return (diff.highlights = highlights)
})
- .catch(function() {
+ .catch(function () {
diff.loading = false
return (diff.error = true)
})
diff --git a/services/web/frontend/js/ide/history/HistoryV2Manager.js b/services/web/frontend/js/ide/history/HistoryV2Manager.js
index 60adb77e46..fbd7582dc4 100644
--- a/services/web/frontend/js/ide/history/HistoryV2Manager.js
+++ b/services/web/frontend/js/ide/history/HistoryV2Manager.js
@@ -37,7 +37,7 @@ import './components/historyFileTree'
import './components/historyFileEntity'
let HistoryManager
-export default HistoryManager = (function() {
+export default HistoryManager = (function () {
HistoryManager = class HistoryManager {
static initClass() {
this.prototype.MAX_RECENT_UPDATES_TO_SELECT = 5
@@ -368,13 +368,13 @@ export default HistoryManager = (function() {
if (previouslySelectedFile != null) {
fileToSelect = previouslySelectedFile
} else {
- let mainFile = _.find(files, function(file) {
+ let mainFile = _.find(files, function (file) {
return /main\.tex$/.test(file.pathname)
})
if (mainFile != null) {
fileToSelect = mainFile
} else {
- let anyTeXFile = _.find(files, function(file) {
+ let anyTeXFile = _.find(files, function (file) {
return /\.tex$/.test(file.pathname)
})
if (anyTeXFile != null) {
@@ -721,7 +721,7 @@ export default HistoryManager = (function() {
this.$scope.history.selection.file.text = text
this.$scope.history.selection.file.loading = false
})
- .catch(function() {})
+ .catch(function () {})
}
reloadDiff() {
@@ -767,7 +767,7 @@ export default HistoryManager = (function() {
diff.text = text
diff.highlights = highlights
})
- .catch(function() {
+ .catch(function () {
diff.loading = false
diff.error = true
})
diff --git a/services/web/frontend/js/ide/history/components/historyEntriesList.js b/services/web/frontend/js/ide/history/components/historyEntriesList.js
index 5e401ca528..c2880b6b0e 100644
--- a/services/web/frontend/js/ide/history/components/historyEntriesList.js
+++ b/services/web/frontend/js/ide/history/components/historyEntriesList.js
@@ -10,12 +10,12 @@
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
-const historyEntriesListController = function($scope, $element, $attrs) {
+const historyEntriesListController = function ($scope, $element, $attrs) {
const ctrl = this
ctrl.$entryListViewportEl = null
ctrl.isDragging = false
- const _isEntryElVisible = function($entryEl) {
+ const _isEntryElVisible = function ($entryEl) {
const entryElTop = $entryEl.offset().top
const entryElBottom = entryElTop + $entryEl.outerHeight()
const entryListViewportElTop = ctrl.$entryListViewportEl.offset().top
@@ -27,11 +27,11 @@ const historyEntriesListController = function($scope, $element, $attrs) {
entryElBottom <= entryListViewportElBottom
)
}
- const _getScrollTopPosForEntry = function($entryEl) {
+ const _getScrollTopPosForEntry = function ($entryEl) {
const halfViewportElHeight = ctrl.$entryListViewportEl.height() / 2
return $entryEl.offset().top - halfViewportElHeight
}
- ctrl.onEntryLinked = function(entry, $entryEl) {
+ ctrl.onEntryLinked = function (entry, $entryEl) {
if (
!ctrl.rangeSelectionEnabled &&
entry.toV === ctrl.selectedHistoryVersion
diff --git a/services/web/frontend/js/ide/history/components/historyEntry.js b/services/web/frontend/js/ide/history/components/historyEntry.js
index 3f5404e7b9..372aeeeb22 100644
--- a/services/web/frontend/js/ide/history/components/historyEntry.js
+++ b/services/web/frontend/js/ide/history/components/historyEntry.js
@@ -13,13 +13,13 @@ import _ from 'lodash'
import App from '../../../base'
import ColorManager from '../../colors/ColorManager'
import displayNameForUser from '../util/displayNameForUser'
-const historyEntryController = function($scope, $element, $attrs) {
+const historyEntryController = function ($scope, $element, $attrs) {
const ctrl = this
// This method (and maybe the one below) will be removed soon. User details data will be
// injected into the history API responses, so we won't need to fetch user data from other
// local data structures.
const _getUserById = id =>
- _.find(ctrl.users, function(user) {
+ _.find(ctrl.users, function (user) {
const curUserId =
(user != null ? user._id : undefined) ||
(user != null ? user.id : undefined)
@@ -27,7 +27,7 @@ const historyEntryController = function($scope, $element, $attrs) {
})
ctrl.displayName = displayNameForUser
ctrl.displayNameById = id => displayNameForUser(_getUserById(id))
- ctrl.getProjectOpDoc = function(projectOp) {
+ ctrl.getProjectOpDoc = function (projectOp) {
if (projectOp.rename != null) {
return `${projectOp.rename.pathname} → ${projectOp.rename.newPathname}`
} else if (projectOp.add != null) {
@@ -36,7 +36,7 @@ const historyEntryController = function($scope, $element, $attrs) {
return `${projectOp.remove.pathname}`
}
}
- ctrl.getUserCSSStyle = function(user) {
+ ctrl.getUserCSSStyle = function (user) {
const curUserId =
(user != null ? user._id : undefined) ||
(user != null ? user.id : undefined)
@@ -47,7 +47,7 @@ const historyEntryController = function($scope, $element, $attrs) {
return { color: `hsl(${hue}, 70%, 50%)` }
}
}
- ctrl.isEntrySelected = function() {
+ ctrl.isEntrySelected = function () {
if (ctrl.rangeSelectionEnabled) {
return (
ctrl.entry.toV <= ctrl.selectedHistoryRange.toV &&
@@ -58,7 +58,7 @@ const historyEntryController = function($scope, $element, $attrs) {
}
}
- ctrl.isEntryHoverSelected = function() {
+ ctrl.isEntryHoverSelected = function () {
return (
ctrl.rangeSelectionEnabled &&
ctrl.entry.toV <= ctrl.hoveredHistoryRange.toV &&
diff --git a/services/web/frontend/js/ide/history/components/historyFileEntity.js b/services/web/frontend/js/ide/history/components/historyFileEntity.js
index 81f69e5cf0..b53fb584c1 100644
--- a/services/web/frontend/js/ide/history/components/historyFileEntity.js
+++ b/services/web/frontend/js/ide/history/components/historyFileEntity.js
@@ -12,7 +12,7 @@
import App from '../../../base'
import iconTypeFromName from '../../file-tree/util/iconTypeFromName'
import fileOperationI18nNames from '../../file-tree/util/fileOperationI18nNames'
-const historyFileEntityController = function($scope, $element, $attrs) {
+const historyFileEntityController = function ($scope, $element, $attrs) {
const ctrl = this
ctrl.hasOperation = false
ctrl.getRenameTooltip = i18nRenamedStr => {
@@ -54,21 +54,21 @@ const historyFileEntityController = function($scope, $element, $attrs) {
return [path1Parts.join('/'), path2Parts.join('/')]
}
- const _handleFolderClick = function() {
+ const _handleFolderClick = function () {
ctrl.isOpen = !ctrl.isOpen
ctrl.entityTypeIconClass = _getFolderIcon()
}
const _handleFileClick = () =>
ctrl.historyFileTreeController.handleEntityClick(ctrl.fileEntity)
- var _getFolderIcon = function() {
+ var _getFolderIcon = function () {
if (ctrl.isOpen) {
return 'fa-folder-open'
} else {
return 'fa-folder'
}
}
- ctrl.$onInit = function() {
+ ctrl.$onInit = function () {
if (ctrl.fileEntity.type === 'folder') {
ctrl.isOpen = true
ctrl.entityTypeIconClass = _getFolderIcon()
diff --git a/services/web/frontend/js/ide/history/components/historyFileTree.js b/services/web/frontend/js/ide/history/components/historyFileTree.js
index 4a4bb756f7..3e2f382e89 100644
--- a/services/web/frontend/js/ide/history/components/historyFileTree.js
+++ b/services/web/frontend/js/ide/history/components/historyFileTree.js
@@ -8,12 +8,12 @@ import _ from 'lodash'
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
-const historyFileTreeController = function($scope, $element, $attrs) {
+const historyFileTreeController = function ($scope, $element, $attrs) {
const ctrl = this
ctrl.handleEntityClick = file => ctrl.onSelectedFileChange({ file })
ctrl._fileTree = []
- $scope.$watch('$ctrl.files', function(files) {
+ $scope.$watch('$ctrl.files', function (files) {
if (files != null && files.length > 0) {
ctrl._fileTree = _.reduce(files, _reducePathsToTree, [])
}
diff --git a/services/web/frontend/js/ide/history/components/historyLabel.js b/services/web/frontend/js/ide/history/components/historyLabel.js
index 85f3594e38..fa61a8e1d4 100644
--- a/services/web/frontend/js/ide/history/components/historyLabel.js
+++ b/services/web/frontend/js/ide/history/components/historyLabel.js
@@ -10,7 +10,7 @@
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
-const historyLabelController = function($scope, $element, $attrs, $filter) {
+const historyLabelController = function ($scope, $element, $attrs, $filter) {
const ctrl = this
ctrl.$onInit = () => {
if (ctrl.showTooltip == null) {
diff --git a/services/web/frontend/js/ide/history/components/historyLabelsList.js b/services/web/frontend/js/ide/history/components/historyLabelsList.js
index 44b803e8e7..1589993058 100644
--- a/services/web/frontend/js/ide/history/components/historyLabelsList.js
+++ b/services/web/frontend/js/ide/history/components/historyLabelsList.js
@@ -13,11 +13,11 @@ import _ from 'lodash'
import App from '../../../base'
import ColorManager from '../../colors/ColorManager'
import displayNameForUser from '../util/displayNameForUser'
-const historyLabelsListController = function($scope, $element, $attrs) {
+const historyLabelsListController = function ($scope, $element, $attrs) {
const ctrl = this
ctrl.isDragging = false
ctrl.versionsWithLabels = []
- $scope.$watchCollection('$ctrl.labels', function(labels) {
+ $scope.$watchCollection('$ctrl.labels', function (labels) {
if (labels) {
const groupedLabelsHash = _.groupBy(labels, 'version')
ctrl.versionsWithLabels = _.map(groupedLabelsHash, (labels, version) => {
@@ -48,7 +48,7 @@ const historyLabelsListController = function($scope, $element, $attrs) {
}
}
- ctrl.isVersionSelected = function(version) {
+ ctrl.isVersionSelected = function (version) {
if (ctrl.rangeSelectionEnabled) {
return (
version <= ctrl.selectedHistoryRange.toV &&
@@ -58,7 +58,7 @@ const historyLabelsListController = function($scope, $element, $attrs) {
return version === ctrl.selectedHistoryVersion
}
}
- ctrl.isVersionHoverSelected = function(version) {
+ ctrl.isVersionHoverSelected = function (version) {
return (
ctrl.rangeSelectionEnabled &&
version <= ctrl.hoveredHistoryRange.toV &&
@@ -137,7 +137,7 @@ const historyLabelsListController = function($scope, $element, $attrs) {
return user
}
ctrl.displayName = displayNameForUser
- ctrl.getUserCSSStyle = function(user, versionWithLabel) {
+ ctrl.getUserCSSStyle = function (user, versionWithLabel) {
const curUserId =
(user != null ? user._id : undefined) ||
(user != null ? user.id : undefined)
diff --git a/services/web/frontend/js/ide/history/controllers/HistoryDiffController.js b/services/web/frontend/js/ide/history/controllers/HistoryDiffController.js
index 469e49467b..8b9a87d867 100644
--- a/services/web/frontend/js/ide/history/controllers/HistoryDiffController.js
+++ b/services/web/frontend/js/ide/history/controllers/HistoryDiffController.js
@@ -11,62 +11,57 @@
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
-App.controller('HistoryDiffController', function(
- $scope,
- $modal,
- ide,
- eventTracking
-) {
- $scope.restoreDeletedDoc = function() {
- eventTracking.sendMB('history-restore-deleted')
- $scope.history.diff.restoreInProgress = true
- return ide.historyManager
- .restoreDeletedDoc($scope.history.diff.doc)
- .then(function(response) {
- const { data } = response
- $scope.history.diff.restoredDocNewId = data.doc_id
- $scope.history.diff.restoreInProgress = false
- return ($scope.history.diff.restoreDeletedSuccess = true)
- })
- }
+App.controller(
+ 'HistoryDiffController',
+ function ($scope, $modal, ide, eventTracking) {
+ $scope.restoreDeletedDoc = function () {
+ eventTracking.sendMB('history-restore-deleted')
+ $scope.history.diff.restoreInProgress = true
+ return ide.historyManager
+ .restoreDeletedDoc($scope.history.diff.doc)
+ .then(function (response) {
+ const { data } = response
+ $scope.history.diff.restoredDocNewId = data.doc_id
+ $scope.history.diff.restoreInProgress = false
+ return ($scope.history.diff.restoreDeletedSuccess = true)
+ })
+ }
- $scope.openRestoreDiffModal = function() {
- eventTracking.sendMB('history-restore-modal')
- return $modal.open({
- templateUrl: 'historyRestoreDiffModalTemplate',
- controller: 'HistoryRestoreDiffModalController',
- resolve: {
- diff() {
- return $scope.history.diff
+ $scope.openRestoreDiffModal = function () {
+ eventTracking.sendMB('history-restore-modal')
+ return $modal.open({
+ templateUrl: 'historyRestoreDiffModalTemplate',
+ controller: 'HistoryRestoreDiffModalController',
+ resolve: {
+ diff() {
+ return $scope.history.diff
+ }
}
- }
- })
+ })
+ }
+
+ return ($scope.backToEditorAfterRestore = () =>
+ ide.editorManager.openDoc({ id: $scope.history.diff.restoredDocNewId }))
}
+)
- return ($scope.backToEditorAfterRestore = () =>
- ide.editorManager.openDoc({ id: $scope.history.diff.restoredDocNewId }))
-})
+export default App.controller(
+ 'HistoryRestoreDiffModalController',
+ function ($scope, $modalInstance, diff, ide, eventTracking) {
+ $scope.state = { inflight: false }
-export default App.controller('HistoryRestoreDiffModalController', function(
- $scope,
- $modalInstance,
- diff,
- ide,
- eventTracking
-) {
- $scope.state = { inflight: false }
+ $scope.diff = diff
- $scope.diff = diff
+ $scope.restore = function () {
+ eventTracking.sendMB('history-restored')
+ $scope.state.inflight = true
+ return ide.historyManager.restoreDiff(diff).then(function () {
+ $scope.state.inflight = false
+ $modalInstance.close()
+ return ide.editorManager.openDoc(diff.doc)
+ })
+ }
- $scope.restore = function() {
- eventTracking.sendMB('history-restored')
- $scope.state.inflight = true
- return ide.historyManager.restoreDiff(diff).then(function() {
- $scope.state.inflight = false
- $modalInstance.close()
- return ide.editorManager.openDoc(diff.doc)
- })
+ return ($scope.cancel = () => $modalInstance.dismiss())
}
-
- return ($scope.cancel = () => $modalInstance.dismiss())
-})
+)
diff --git a/services/web/frontend/js/ide/history/controllers/HistoryListController.js b/services/web/frontend/js/ide/history/controllers/HistoryListController.js
index 0e9475aa95..32f76a4d45 100644
--- a/services/web/frontend/js/ide/history/controllers/HistoryListController.js
+++ b/services/web/frontend/js/ide/history/controllers/HistoryListController.js
@@ -16,12 +16,12 @@ import _ from 'lodash'
*/
import App from '../../../base'
import displayNameForUser from '../util/displayNameForUser'
-App.controller('HistoryListController', function($scope, $modal, ide) {
+App.controller('HistoryListController', function ($scope, $modal, ide) {
$scope.hoveringOverListSelectors = false
$scope.projectUsers = []
- $scope.$watch('project.members', function(newVal) {
+ $scope.$watch('project.members', function (newVal) {
if (newVal != null) {
return ($scope.projectUsers = newVal.concat($scope.project.owner))
}
@@ -31,7 +31,7 @@ App.controller('HistoryListController', function($scope, $modal, ide) {
// injected into the history API responses, so we won't need to fetch user data from other
// local data structures.
const _getUserById = id =>
- _.find($scope.projectUsers, function(user) {
+ _.find($scope.projectUsers, function (user) {
const curUserId =
(user != null ? user._id : undefined) ||
(user != null ? user.id : undefined)
@@ -55,7 +55,7 @@ App.controller('HistoryListController', function($scope, $modal, ide) {
return ide.historyManager.fetchNextBatchOfUpdates()
}
- $scope.recalculateSelectedUpdates = function() {
+ $scope.recalculateSelectedUpdates = function () {
let beforeSelection = true
let afterSelection = false
$scope.history.selection.updates = []
@@ -87,7 +87,7 @@ App.controller('HistoryListController', function($scope, $modal, ide) {
})()
}
- $scope.recalculateHoveredUpdates = function() {
+ $scope.recalculateHoveredUpdates = function () {
let inHoverSelection
let hoverSelectedFrom = false
let hoverSelectedTo = false
@@ -153,59 +153,62 @@ App.controller('HistoryListController', function($scope, $modal, ide) {
)
})
-export default App.controller('HistoryListItemController', function(
- $scope,
- eventTracking
-) {
- $scope.$watch('update.selectedFrom', function(selectedFrom, oldSelectedFrom) {
- if (selectedFrom) {
- for (let update of Array.from($scope.history.updates)) {
- if (update !== $scope.update) {
- update.selectedFrom = false
+export default App.controller(
+ 'HistoryListItemController',
+ function ($scope, eventTracking) {
+ $scope.$watch(
+ 'update.selectedFrom',
+ function (selectedFrom, oldSelectedFrom) {
+ if (selectedFrom) {
+ for (let update of Array.from($scope.history.updates)) {
+ if (update !== $scope.update) {
+ update.selectedFrom = false
+ }
+ }
+ return $scope.recalculateSelectedUpdates()
}
}
- return $scope.recalculateSelectedUpdates()
- }
- })
+ )
- $scope.$watch('update.selectedTo', function(selectedTo, oldSelectedTo) {
- if (selectedTo) {
- for (let update of Array.from($scope.history.updates)) {
- if (update !== $scope.update) {
- update.selectedTo = false
+ $scope.$watch('update.selectedTo', function (selectedTo, oldSelectedTo) {
+ if (selectedTo) {
+ for (let update of Array.from($scope.history.updates)) {
+ if (update !== $scope.update) {
+ update.selectedTo = false
+ }
}
+ return $scope.recalculateSelectedUpdates()
}
- return $scope.recalculateSelectedUpdates()
+ })
+
+ $scope.select = function () {
+ eventTracking.sendMB('history-view-change')
+ $scope.update.selectedTo = true
+ return ($scope.update.selectedFrom = true)
}
- })
- $scope.select = function() {
- eventTracking.sendMB('history-view-change')
- $scope.update.selectedTo = true
- return ($scope.update.selectedFrom = true)
+ $scope.mouseOverSelectedFrom = function () {
+ $scope.history.hoveringOverListSelectors = true
+ $scope.update.hoverSelectedFrom = true
+ return $scope.recalculateHoveredUpdates()
+ }
+
+ $scope.mouseOutSelectedFrom = function () {
+ $scope.history.hoveringOverListSelectors = false
+ return $scope.resetHoverState()
+ }
+
+ $scope.mouseOverSelectedTo = function () {
+ $scope.history.hoveringOverListSelectors = true
+ $scope.update.hoverSelectedTo = true
+ return $scope.recalculateHoveredUpdates()
+ }
+
+ $scope.mouseOutSelectedTo = function () {
+ $scope.history.hoveringOverListSelectors = false
+ return $scope.resetHoverState()
+ }
+
+ return ($scope.displayName = displayNameForUser)
}
-
- $scope.mouseOverSelectedFrom = function() {
- $scope.history.hoveringOverListSelectors = true
- $scope.update.hoverSelectedFrom = true
- return $scope.recalculateHoveredUpdates()
- }
-
- $scope.mouseOutSelectedFrom = function() {
- $scope.history.hoveringOverListSelectors = false
- return $scope.resetHoverState()
- }
-
- $scope.mouseOverSelectedTo = function() {
- $scope.history.hoveringOverListSelectors = true
- $scope.update.hoverSelectedTo = true
- return $scope.recalculateHoveredUpdates()
- }
-
- $scope.mouseOutSelectedTo = function() {
- $scope.history.hoveringOverListSelectors = false
- return $scope.resetHoverState()
- }
-
- return ($scope.displayName = displayNameForUser)
-})
+)
diff --git a/services/web/frontend/js/ide/history/controllers/HistoryV2AddLabelModalController.js b/services/web/frontend/js/ide/history/controllers/HistoryV2AddLabelModalController.js
index d81c12682c..e67ac77c12 100644
--- a/services/web/frontend/js/ide/history/controllers/HistoryV2AddLabelModalController.js
+++ b/services/web/frontend/js/ide/history/controllers/HistoryV2AddLabelModalController.js
@@ -11,39 +11,37 @@
*/
import App from '../../../base'
-export default App.controller('HistoryV2AddLabelModalController', function(
- $scope,
- $modalInstance,
- ide,
- update
-) {
- $scope.update = update
- $scope.inputs = { labelName: null }
- $scope.state = {
- inflight: false,
- error: false
+export default App.controller(
+ 'HistoryV2AddLabelModalController',
+ function ($scope, $modalInstance, ide, update) {
+ $scope.update = update
+ $scope.inputs = { labelName: null }
+ $scope.state = {
+ inflight: false,
+ error: false
+ }
+
+ $modalInstance.opened.then(() =>
+ $scope.$applyAsync(() => $scope.$broadcast('open'))
+ )
+
+ return ($scope.addLabelModalFormSubmit = function () {
+ $scope.state.inflight = true
+ return ide.historyManager
+ .labelCurrentVersion($scope.inputs.labelName)
+ .then(function (response) {
+ $scope.state.inflight = false
+ return $modalInstance.close()
+ })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.state.inflight = false
+ if (status === 400) {
+ return ($scope.state.error = { message: data })
+ } else {
+ return ($scope.state.error = true)
+ }
+ })
+ })
}
-
- $modalInstance.opened.then(() =>
- $scope.$applyAsync(() => $scope.$broadcast('open'))
- )
-
- return ($scope.addLabelModalFormSubmit = function() {
- $scope.state.inflight = true
- return ide.historyManager
- .labelCurrentVersion($scope.inputs.labelName)
- .then(function(response) {
- $scope.state.inflight = false
- return $modalInstance.close()
- })
- .catch(function(response) {
- const { data, status } = response
- $scope.state.inflight = false
- if (status === 400) {
- return ($scope.state.error = { message: data })
- } else {
- return ($scope.state.error = true)
- }
- })
- })
-})
+)
diff --git a/services/web/frontend/js/ide/history/controllers/HistoryV2DeleteLabelModalController.js b/services/web/frontend/js/ide/history/controllers/HistoryV2DeleteLabelModalController.js
index 85eeeb32f8..44c0df62fd 100644
--- a/services/web/frontend/js/ide/history/controllers/HistoryV2DeleteLabelModalController.js
+++ b/services/web/frontend/js/ide/history/controllers/HistoryV2DeleteLabelModalController.js
@@ -11,34 +11,32 @@
*/
import App from '../../../base'
-export default App.controller('HistoryV2DeleteLabelModalController', function(
- $scope,
- $modalInstance,
- ide,
- labelDetails
-) {
- $scope.labelDetails = labelDetails
- $scope.state = {
- inflight: false,
- error: false
- }
+export default App.controller(
+ 'HistoryV2DeleteLabelModalController',
+ function ($scope, $modalInstance, ide, labelDetails) {
+ $scope.labelDetails = labelDetails
+ $scope.state = {
+ inflight: false,
+ error: false
+ }
- return ($scope.deleteLabel = function() {
- $scope.state.inflight = true
- return ide.historyManager
- .deleteLabel(labelDetails)
- .then(function(response) {
- $scope.state.inflight = false
- return $modalInstance.close()
- })
- .catch(function(response) {
- const { data, status } = response
- $scope.state.inflight = false
- if (status === 400) {
- return ($scope.state.error = { message: data })
- } else {
- return ($scope.state.error = true)
- }
- })
- })
-})
+ return ($scope.deleteLabel = function () {
+ $scope.state.inflight = true
+ return ide.historyManager
+ .deleteLabel(labelDetails)
+ .then(function (response) {
+ $scope.state.inflight = false
+ return $modalInstance.close()
+ })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.state.inflight = false
+ if (status === 400) {
+ return ($scope.state.error = { message: data })
+ } else {
+ return ($scope.state.error = true)
+ }
+ })
+ })
+ }
+)
diff --git a/services/web/frontend/js/ide/history/controllers/HistoryV2FileTreeController.js b/services/web/frontend/js/ide/history/controllers/HistoryV2FileTreeController.js
index 97378422d9..dbf3b49403 100644
--- a/services/web/frontend/js/ide/history/controllers/HistoryV2FileTreeController.js
+++ b/services/web/frontend/js/ide/history/controllers/HistoryV2FileTreeController.js
@@ -12,11 +12,11 @@
*/
import App from '../../../base'
-export default App.controller('HistoryV2FileTreeController', function(
- $scope,
- ide
-) {
- $scope.handleFileSelection = file => {
- ide.historyManager.selectFile(file)
+export default App.controller(
+ 'HistoryV2FileTreeController',
+ function ($scope, ide) {
+ $scope.handleFileSelection = file => {
+ ide.historyManager.selectFile(file)
+ }
}
-})
+)
diff --git a/services/web/frontend/js/ide/history/controllers/HistoryV2ListController.js b/services/web/frontend/js/ide/history/controllers/HistoryV2ListController.js
index b1dc1d21bb..75fabebdb2 100644
--- a/services/web/frontend/js/ide/history/controllers/HistoryV2ListController.js
+++ b/services/web/frontend/js/ide/history/controllers/HistoryV2ListController.js
@@ -12,44 +12,43 @@
*/
import App from '../../../base'
-export default App.controller('HistoryV2ListController', function(
- $scope,
- $modal,
- ide
-) {
- $scope.hoveringOverListSelectors = false
- $scope.listConfig = { showOnlyLabelled: false }
+export default App.controller(
+ 'HistoryV2ListController',
+ function ($scope, $modal, ide) {
+ $scope.hoveringOverListSelectors = false
+ $scope.listConfig = { showOnlyLabelled: false }
- $scope.projectUsers = []
+ $scope.projectUsers = []
- $scope.$watch('project.members', function(newVal) {
- if (newVal != null) {
- return ($scope.projectUsers = newVal.concat($scope.project.owner))
- }
- })
-
- $scope.loadMore = () => {
- return ide.historyManager.fetchNextBatchOfUpdates()
- }
-
- $scope.handleVersionSelect = version =>
- $scope.$applyAsync(() =>
- ide.historyManager.selectVersionForPointInTime(version)
- )
-
- $scope.handleRangeSelect = (selectedToV, selectedFromV) =>
- $scope.$applyAsync(() =>
- ide.historyManager.selectVersionsForCompare(selectedToV, selectedFromV)
- )
-
- return ($scope.handleLabelDelete = labelDetails =>
- $modal.open({
- templateUrl: 'historyV2DeleteLabelModalTemplate',
- controller: 'HistoryV2DeleteLabelModalController',
- resolve: {
- labelDetails() {
- return labelDetails
- }
+ $scope.$watch('project.members', function (newVal) {
+ if (newVal != null) {
+ return ($scope.projectUsers = newVal.concat($scope.project.owner))
}
- }))
-})
+ })
+
+ $scope.loadMore = () => {
+ return ide.historyManager.fetchNextBatchOfUpdates()
+ }
+
+ $scope.handleVersionSelect = version =>
+ $scope.$applyAsync(() =>
+ ide.historyManager.selectVersionForPointInTime(version)
+ )
+
+ $scope.handleRangeSelect = (selectedToV, selectedFromV) =>
+ $scope.$applyAsync(() =>
+ ide.historyManager.selectVersionsForCompare(selectedToV, selectedFromV)
+ )
+
+ return ($scope.handleLabelDelete = labelDetails =>
+ $modal.open({
+ templateUrl: 'historyV2DeleteLabelModalTemplate',
+ controller: 'HistoryV2DeleteLabelModalController',
+ resolve: {
+ labelDetails() {
+ return labelDetails
+ }
+ }
+ }))
+ }
+)
diff --git a/services/web/frontend/js/ide/history/controllers/HistoryV2ToolbarController.js b/services/web/frontend/js/ide/history/controllers/HistoryV2ToolbarController.js
index 9a7d60f468..1222c87096 100644
--- a/services/web/frontend/js/ide/history/controllers/HistoryV2ToolbarController.js
+++ b/services/web/frontend/js/ide/history/controllers/HistoryV2ToolbarController.js
@@ -69,7 +69,7 @@ export default App.controller(
ide.historyManager.toggleHistoryViewMode()
}
- $scope.restoreDeletedFile = function() {
+ $scope.restoreDeletedFile = function () {
const { pathname, deletedAtV } = $scope.history.selection.file
if (pathname == null || deletedAtV == null) {
return
@@ -79,7 +79,7 @@ export default App.controller(
$scope.restoreState.inflight = true
return ide.historyManager
.restoreFile(deletedAtV, pathname)
- .then(function(response) {
+ .then(function (response) {
const { data } = response
return openEntity(data)
})
@@ -103,10 +103,10 @@ export default App.controller(
})
}
- openEntity = function(data) {
+ openEntity = function (data) {
const { id, type } = data
return waitFor(() => ide.fileTreeManager.findEntityById(id), 3000)
- .then(function(entity) {
+ .then(function (entity) {
if (type === 'doc') {
ide.editorManager.openDoc(entity)
ide.$timeout(() => {
diff --git a/services/web/frontend/js/ide/history/directives/infiniteScroll.js b/services/web/frontend/js/ide/history/directives/infiniteScroll.js
index 153361e3df..febd2d4055 100644
--- a/services/web/frontend/js/ide/history/directives/infiniteScroll.js
+++ b/services/web/frontend/js/ide/history/directives/infiniteScroll.js
@@ -16,7 +16,7 @@ export default App.directive('infiniteScroll', () => ({
const innerElement = element.find('.infinite-scroll-inner')
element.css({ 'overflow-y': 'auto' })
- const atEndOfListView = function() {
+ const atEndOfListView = function () {
if (attrs.infiniteScrollUpwards != null) {
return atTopOfListView()
} else {
@@ -32,7 +32,7 @@ export default App.directive('infiniteScroll', () => ({
const listShorterThanContainer = () =>
element.height() > innerElement.height()
- var loadUntilFull = function() {
+ var loadUntilFull = function () {
if (
(listShorterThanContainer() || atEndOfListView()) &&
!scope.$eval(attrs.infiniteScrollDisabled)
@@ -44,7 +44,7 @@ export default App.directive('infiniteScroll', () => ({
element.on('scroll', event => loadUntilFull())
- return scope.$watch(attrs.infiniteScrollInitialize, function(value) {
+ return scope.$watch(attrs.infiniteScrollInitialize, function (value) {
if (value) {
return loadUntilFull()
}
diff --git a/services/web/frontend/js/ide/history/util/displayNameForUser.js b/services/web/frontend/js/ide/history/util/displayNameForUser.js
index 770ccb8a3c..2c72d92e47 100644
--- a/services/web/frontend/js/ide/history/util/displayNameForUser.js
+++ b/services/web/frontend/js/ide/history/util/displayNameForUser.js
@@ -12,7 +12,7 @@
*/
let displayNameForUser
-export default displayNameForUser = function(user) {
+export default displayNameForUser = function (user) {
if (user == null) {
return 'Anonymous'
}
diff --git a/services/web/frontend/js/ide/hotkeys/BackspaceHighjack.js b/services/web/frontend/js/ide/hotkeys/BackspaceHighjack.js
index 4ab4ce2836..d9b792d966 100644
--- a/services/web/frontend/js/ide/hotkeys/BackspaceHighjack.js
+++ b/services/web/frontend/js/ide/hotkeys/BackspaceHighjack.js
@@ -10,7 +10,7 @@
*/
const rx = /INPUT|SELECT|TEXTAREA/i
-export default $(document).bind('keydown keypress', function(e) {
+export default $(document).bind('keydown keypress', function (e) {
if (e.which === 8) {
// 8 == backspace
if (!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly) {
diff --git a/services/web/frontend/js/ide/human-readable-logs/HumanReadableLogs.js b/services/web/frontend/js/ide/human-readable-logs/HumanReadableLogs.js
index 34445d4caa..44a45399fe 100644
--- a/services/web/frontend/js/ide/human-readable-logs/HumanReadableLogs.js
+++ b/services/web/frontend/js/ide/human-readable-logs/HumanReadableLogs.js
@@ -10,7 +10,7 @@ export default {
parsedLogEntries = rawLog
}
- const _getRule = function(logMessage) {
+ const _getRule = function (logMessage) {
for (let rule of ruleset) {
if (rule.regexToMatch.test(logMessage)) {
return rule
diff --git a/services/web/frontend/js/ide/metadata/services/metadata.js b/services/web/frontend/js/ide/metadata/services/metadata.js
index 09d9d6983e..73b26ac6e7 100644
--- a/services/web/frontend/js/ide/metadata/services/metadata.js
+++ b/services/web/frontend/js/ide/metadata/services/metadata.js
@@ -13,26 +13,26 @@ import _ from 'lodash'
*/
import App from '../../../base'
-export default App.factory('metadata', function($http, ide) {
+export default App.factory('metadata', function ($http, ide) {
const debouncer = {} // DocId => Timeout
const state = { documents: {} }
const metadata = { state }
- metadata.onBroadcastDocMeta = function(data) {
+ metadata.onBroadcastDocMeta = function (data) {
if (data.docId != null && data.meta != null) {
return (state.documents[data.docId] = data.meta)
}
}
- metadata.onEntityDeleted = function(e, entity) {
+ metadata.onEntityDeleted = function (e, entity) {
if (entity.type === 'doc') {
return delete state.documents[entity.id]
}
}
- metadata.onFileUploadComplete = function(e, upload) {
+ metadata.onFileUploadComplete = function (e, upload) {
if (upload.entity_type === 'doc') {
return metadata.loadDocMetaFromServer(upload.entity_id)
}
@@ -50,7 +50,7 @@ export default App.factory('metadata', function($http, ide) {
})()
)
- metadata.getAllPackages = function() {
+ metadata.getAllPackages = function () {
const packageCommandMapping = {}
for (let _docId in state.documents) {
const meta = state.documents[_docId]
@@ -65,7 +65,7 @@ export default App.factory('metadata', function($http, ide) {
metadata.loadProjectMetaFromServer = () =>
$http
.get(`/project/${window.project_id}/metadata`)
- .then(function(response) {
+ .then(function (response) {
const { data } = response
if (data.projectMeta) {
return (() => {
@@ -87,14 +87,14 @@ export default App.factory('metadata', function($http, ide) {
broadcast: ide.$scope.onlineUsersCount > 0,
_csrf: window.csrfToken
})
- .then(function(response) {
+ .then(function (response) {
const { data } = response
// handle the POST response like a broadcast event when there are no
// other users in the project.
metadata.onBroadcastDocMeta(data)
})
- metadata.scheduleLoadDocMetaFromServer = function(docId) {
+ metadata.scheduleLoadDocMetaFromServer = function (docId) {
if (ide.$scope.permissionsLevel === 'readOnly') {
// The POST request is blocked for users without write permission.
// The user will not be able to consume the meta data for edits anyways.
diff --git a/services/web/frontend/js/ide/online-users/OnlineUsersManager.js b/services/web/frontend/js/ide/online-users/OnlineUsersManager.js
index 267f13ef2c..7ec9f6dd75 100644
--- a/services/web/frontend/js/ide/online-users/OnlineUsersManager.js
+++ b/services/web/frontend/js/ide/online-users/OnlineUsersManager.js
@@ -20,7 +20,7 @@ import './controllers/OnlineUsersController'
let OnlineUsersManager
-export default OnlineUsersManager = (function() {
+export default OnlineUsersManager = (function () {
OnlineUsersManager = class OnlineUsersManager {
static initClass() {
this.prototype.cursorUpdateInterval = 500
diff --git a/services/web/frontend/js/ide/online-users/controllers/OnlineUsersController.js b/services/web/frontend/js/ide/online-users/controllers/OnlineUsersController.js
index 9110adfceb..7cc8e5b6cc 100644
--- a/services/web/frontend/js/ide/online-users/controllers/OnlineUsersController.js
+++ b/services/web/frontend/js/ide/online-users/controllers/OnlineUsersController.js
@@ -12,14 +12,14 @@
*/
import App from '../../../base'
-export default App.controller('OnlineUsersController', function($scope, ide) {
- $scope.gotoUser = function(user) {
+export default App.controller('OnlineUsersController', function ($scope, ide) {
+ $scope.gotoUser = function (user) {
if (user.doc != null && user.row != null) {
return ide.editorManager.openDoc(user.doc, { gotoLine: user.row + 1 })
}
}
- return ($scope.userInitial = function(user) {
+ return ($scope.userInitial = function (user) {
if (user.user_id === 'anonymous-user') {
return '?'
} else {
diff --git a/services/web/frontend/js/ide/pdf/controllers/PdfController.js b/services/web/frontend/js/ide/pdf/controllers/PdfController.js
index ffe6617ea7..92b7a656a4 100644
--- a/services/web/frontend/js/ide/pdf/controllers/PdfController.js
+++ b/services/web/frontend/js/ide/pdf/controllers/PdfController.js
@@ -15,950 +15,954 @@ const AUTO_COMPILE_DEBOUNCE = 2000
App.filter('trusted', $sce => url => $sce.trustAsResourceUrl(url))
-App.controller('PdfController', function(
- $scope,
- $http,
- ide,
- $modal,
- synctex,
- eventTracking,
- localStorage,
- $q
-) {
- let autoCompile = true
+App.controller(
+ 'PdfController',
+ function (
+ $scope,
+ $http,
+ ide,
+ $modal,
+ synctex,
+ eventTracking,
+ localStorage,
+ $q
+ ) {
+ let autoCompile = true
- // pdf.view = uncompiled | pdf | errors
- $scope.pdf.view = $scope.pdf.url ? 'pdf' : 'uncompiled'
- $scope.pdf.clearingCache = false
- $scope.shouldShowLogs = false
+ // pdf.view = uncompiled | pdf | errors
+ $scope.pdf.view = $scope.pdf.url ? 'pdf' : 'uncompiled'
+ $scope.pdf.clearingCache = false
+ $scope.shouldShowLogs = false
- $scope.logsUISubvariant = window.logsUISubvariant
+ $scope.logsUISubvariant = window.logsUISubvariant
- // view logic to check whether the files dropdown should "drop up" or "drop down"
- $scope.shouldDropUp = false
+ // view logic to check whether the files dropdown should "drop up" or "drop down"
+ $scope.shouldDropUp = false
- // Exposed methods for React layout handling
- $scope.setPdfSplitLayout = function() {
- $scope.$applyAsync(() => $scope.switchToSideBySideLayout('editor'))
- }
- $scope.setPdfFullLayout = function() {
- $scope.$applyAsync(() => $scope.switchToFlatLayout('pdf'))
- }
-
- const logsContainerEl = document.querySelector('.pdf-logs')
- const filesDropdownEl =
- logsContainerEl && logsContainerEl.querySelector('.files-dropdown')
-
- // get the top coordinate of the files dropdown as a ratio (to the logs container height)
- // logs container supports scrollable content, so it's possible that ratio > 1.
- function getFilesDropdownTopCoordAsRatio() {
- if (filesDropdownEl == null || logsContainerEl == null) {
- return 0
+ // Exposed methods for React layout handling
+ $scope.setPdfSplitLayout = function () {
+ $scope.$applyAsync(() => $scope.switchToSideBySideLayout('editor'))
}
- return (
- filesDropdownEl.getBoundingClientRect().top /
- logsContainerEl.getBoundingClientRect().height
- )
- }
-
- $scope.$watch('shouldShowLogs', shouldShow => {
- if (shouldShow) {
- $scope.$applyAsync(() => {
- $scope.shouldDropUp = getFilesDropdownTopCoordAsRatio() > 0.65
- })
- }
- })
-
- $scope.trackLogHintsLearnMore = function() {
- eventTracking.sendMB('logs-hints-learn-more')
- }
-
- if (ace.require('ace/lib/useragent').isMac) {
- $scope.modifierKey = 'Cmd'
- } else {
- $scope.modifierKey = 'Ctrl'
- }
-
- // utility for making a query string from a hash, could use jquery $.param
- function createQueryString(args) {
- const qsArgs = []
- for (const k in args) {
- const v = args[k]
- qsArgs.push(`${k}=${v}`)
- }
- if (qsArgs.length) {
- return `?${qsArgs.join('&')}`
- } else {
- return ''
- }
- }
-
- $scope.$on('project:joined', () => {
- if (!autoCompile) {
- return
- }
- autoCompile = false
- $scope.recompile({ isAutoCompileOnLoad: true })
- $scope.hasPremiumCompile =
- $scope.project.features.compileGroup === 'priority'
- })
-
- $scope.$on('pdf:error:display', function() {
- $scope.pdf.view = 'errors'
- $scope.pdf.renderingError = true
- })
-
- let autoCompileInterval = null
- function autoCompileIfReady() {
- if (
- $scope.pdf.compiling ||
- !$scope.autocompile_enabled ||
- !$scope.pdf.uncompiled
- ) {
- return
+ $scope.setPdfFullLayout = function () {
+ $scope.$applyAsync(() => $scope.switchToFlatLayout('pdf'))
}
- // Only checking linting if syntaxValidation is on and visible to the user
- const autoCompileLintingError =
- ide.$scope.hasLintingError && ide.$scope.settings.syntaxValidation
- if ($scope.autoCompileLintingError !== autoCompileLintingError) {
- $scope.$apply(() => {
- $scope.autoCompileLintingError = autoCompileLintingError
- // We've likely been waiting a while until the user fixed the linting, but we
- // don't want to compile as soon as it is fixed, so reset the timeout.
- $scope.startedTryingAutoCompileAt = Date.now()
- $scope.docLastChangedAt = Date.now()
- })
- }
- if (autoCompileLintingError && $scope.stop_on_validation_error) {
- return
- }
+ const logsContainerEl = document.querySelector('.pdf-logs')
+ const filesDropdownEl =
+ logsContainerEl && logsContainerEl.querySelector('.files-dropdown')
- // If there's a longish compile, don't compile immediately after if user is still typing
- const startedTryingAt = Math.max(
- $scope.startedTryingAutoCompileAt,
- $scope.lastFinishedCompileAt || 0
- )
-
- const timeSinceStartedTrying = Date.now() - startedTryingAt
- const timeSinceLastChange = Date.now() - $scope.docLastChangedAt
-
- let shouldCompile = false
- if (timeSinceLastChange > AUTO_COMPILE_DEBOUNCE) {
- // Don't compile in the middle of the user typing
- shouldCompile = true
- } else if (timeSinceStartedTrying > AUTO_COMPILE_MAX_WAIT) {
- // Unless they type for a long time
- shouldCompile = true
- } else if (timeSinceStartedTrying < 0 || timeSinceLastChange < 0) {
- // If time is non-monotonic, assume that the user's system clock has been
- // changed and continue with compile
- shouldCompile = true
- }
-
- if (shouldCompile) {
- return triggerAutoCompile()
- }
- }
-
- function triggerAutoCompile() {
- $scope.recompile({ isAutoCompileOnChange: true })
- }
-
- function startTryingAutoCompile() {
- if (autoCompileInterval != null) {
- return
- }
- $scope.startedTryingAutoCompileAt = Date.now()
- autoCompileInterval = setInterval(autoCompileIfReady, 200)
- }
-
- function stopTryingAutoCompile() {
- clearInterval(autoCompileInterval)
- autoCompileInterval = null
- }
-
- $scope.changesToAutoCompile = false
- $scope.$watch('pdf.uncompiled', uncompiledChanges => {
- // don't autocompile if disabled or the pdf is not visible
- if (
- $scope.pdf.uncompiled &&
- $scope.autocompile_enabled &&
- !$scope.ui.pdfHidden
- ) {
- $scope.changesToAutoCompile = true
- startTryingAutoCompile()
- } else {
- $scope.changesToAutoCompile = false
- stopTryingAutoCompile()
- }
- })
-
- function recalculateUncompiledChanges() {
- if ($scope.docLastChangedAt == null) {
- $scope.pdf.uncompiled = false
- } else if (
- $scope.lastStartedCompileAt == null ||
- $scope.docLastChangedAt > $scope.lastStartedCompileAt
- ) {
- $scope.pdf.uncompiled = true
- } else {
- $scope.pdf.uncompiled = false
- }
- }
-
- function _updateDocLastChangedAt() {
- $scope.docLastChangedAt = Date.now()
- recalculateUncompiledChanges()
- }
-
- function onDocChanged() {
- _updateDocLastChangedAt()
- }
-
- function onDocSaved() {
- // We use the save as a trigger too, to account for the delay between the client
- // and server. Otherwise, we might have compiled after the user made
- // the change on the client, but before the server had it.
- _updateDocLastChangedAt()
- }
-
- function onCompilingStateChanged(compiling) {
- recalculateUncompiledChanges()
- }
-
- ide.$scope.$on('doc:changed', onDocChanged)
- ide.$scope.$on('doc:saved', onDocSaved)
- $scope.$watch('pdf.compiling', onCompilingStateChanged)
-
- $scope.autocompile_enabled =
- localStorage(`autocompile_enabled:${$scope.project_id}`) || false
- $scope.$watch('autocompile_enabled', (newValue, oldValue) => {
- if (newValue != null && oldValue !== newValue) {
- if (newValue === true) {
- $scope.autoCompileLintingError = false
- autoCompileIfReady()
+ // get the top coordinate of the files dropdown as a ratio (to the logs container height)
+ // logs container supports scrollable content, so it's possible that ratio > 1.
+ function getFilesDropdownTopCoordAsRatio() {
+ if (filesDropdownEl == null || logsContainerEl == null) {
+ return 0
}
- localStorage(`autocompile_enabled:${$scope.project_id}`, newValue)
- eventTracking.sendMB('autocompile-setting-changed', {
- value: newValue
- })
- }
- })
-
- // abort compile if syntax checks fail
- $scope.stop_on_validation_error = localStorage(
- `stop_on_validation_error:${$scope.project_id}`
- )
- if ($scope.stop_on_validation_error == null) {
- $scope.stop_on_validation_error = true
- }
- // turn on for all users by default
- $scope.$watch('stop_on_validation_error', (newValue, oldValue) => {
- if (newValue != null && oldValue !== newValue) {
- localStorage(`stop_on_validation_error:${$scope.project_id}`, newValue)
- }
- })
-
- $scope.draft = localStorage(`draft:${$scope.project_id}`) || false
- $scope.$watch('draft', (newValue, oldValue) => {
- if (newValue != null && oldValue !== newValue) {
- localStorage(`draft:${$scope.project_id}`, newValue)
- }
- })
-
- function sendCompileRequest(options) {
- if (options == null) {
- options = {}
- }
- const url = `/project/${$scope.project_id}/compile`
- const params = {}
- if (options.isAutoCompileOnLoad || options.isAutoCompileOnChange) {
- params.auto_compile = true
- }
- // if the previous run was a check, clear the error logs
- if ($scope.check) {
- $scope.pdf.logEntries = {}
- }
- // keep track of whether this is a compile or check
- $scope.check = !!options.check
- if (options.check) {
- eventTracking.sendMB('syntax-check-request')
- }
- // send appropriate check type to clsi
- let checkType
- if ($scope.check) {
- checkType = 'validate' // validate only
- } else if (options.try) {
- checkType = 'silent' // allow use to try compile once
- } else if ($scope.stop_on_validation_error) {
- checkType = 'error' // try to compile
- } else {
- checkType = 'silent' // ignore errors
- }
-
- // FIXME: Temporarily disable syntax checking as it is causing
- // excessive support requests for projects migrated from v1
- // https://github.com/overleaf/sharelatex/issues/911
- if (checkType === 'error') {
- checkType = 'silent'
- }
-
- return $http.post(
- url,
- {
- rootDoc_id: options.rootDocOverride_id || null,
- draft: $scope.draft,
- check: checkType,
- // use incremental compile for all users but revert to a full
- // compile if there is a server error
- incrementalCompilesEnabled: !$scope.pdf.error,
- _csrf: window.csrfToken
- },
- { params }
- )
- }
-
- function buildPdfDownloadUrl(pdfDownloadDomain, url) {
- if (pdfDownloadDomain) {
- return `${pdfDownloadDomain}${url}`
- } else {
- return url
- }
- }
-
- function parseCompileResponse(response) {
- // keep last url
- const lastPdfUrl = $scope.pdf.url
- const { pdfDownloadDomain } = response
- // Reset everything
- $scope.pdf.error = false
- $scope.pdf.timedout = false
- $scope.pdf.failure = false
- $scope.pdf.url = null
- $scope.pdf.clsiMaintenance = false
- $scope.pdf.tooRecentlyCompiled = false
- $scope.pdf.renderingError = false
- $scope.pdf.projectTooLarge = false
- $scope.pdf.compileTerminated = false
- $scope.pdf.compileExited = false
- $scope.pdf.failedCheck = false
- $scope.pdf.compileInProgress = false
- $scope.pdf.autoCompileDisabled = false
- if (window.showNewLogsUI) {
- $scope.clsiErrors = {}
- }
-
- // make a cache to look up files by name
- const fileByPath = {}
- if (response.outputFiles != null) {
- for (const file of response.outputFiles) {
- fileByPath[file.path] = file
- }
- }
-
- // prepare query string
- let qs = {}
- // add a query string parameter for the compile group
- if (response.compileGroup != null) {
- ide.compileGroup = qs.compileGroup = response.compileGroup
- }
- // add a query string parameter for the clsi server id
- if (response.clsiServerId != null) {
- ide.clsiServerId = qs.clsiserverid = response.clsiServerId
- }
-
- // TODO(das7pad): drop this hack once 2747f0d40af8729304 has landed in clsi
- if (response.status === 'success' && !fileByPath['output.pdf']) {
- response.status = 'failure'
- }
-
- if (response.status === 'success') {
- $scope.pdf.view = 'pdf'
- $scope.shouldShowLogs = false
- $scope.pdf.lastCompileTimestamp = Date.now()
- $scope.pdf.validation = {}
- $scope.pdf.url = buildPdfDownloadUrl(
- pdfDownloadDomain,
- fileByPath['output.pdf'].url
+ return (
+ filesDropdownEl.getBoundingClientRect().top /
+ logsContainerEl.getBoundingClientRect().height
)
- // convert the qs hash into a query string and append it
- $scope.pdf.url += createQueryString(qs)
+ }
- // Save all downloads as files
- qs.popupDownload = true
-
- const { build: buildId } = fileByPath['output.pdf']
- $scope.pdf.downloadUrl =
- `/download/project/${$scope.project_id}/build/${buildId}/output/output.pdf` +
- createQueryString(qs)
- fetchLogs(fileByPath, { pdfDownloadDomain })
- } else if (response.status === 'timedout') {
- $scope.pdf.view = 'errors'
- $scope.pdf.timedout = true
- fetchLogs(fileByPath, { pdfDownloadDomain })
- if (
- !$scope.hasPremiumCompile &&
- ide.$scope.project.owner._id === ide.$scope.user.id
- ) {
- eventTracking.send(
- 'subscription-funnel',
- 'editor-click-feature',
- 'compile-timeout'
- )
- }
- } else if (response.status === 'terminated') {
- $scope.pdf.view = 'errors'
- $scope.pdf.compileTerminated = true
- fetchLogs(fileByPath, { pdfDownloadDomain })
- } else if (
- ['validation-fail', 'validation-pass'].includes(response.status)
- ) {
- $scope.pdf.view = 'pdf'
- $scope.pdf.url = lastPdfUrl
- $scope.shouldShowLogs = true
- if (response.status === 'validation-fail') {
- $scope.pdf.failedCheck = true
- }
- eventTracking.sendMB(`syntax-check-${response.status}`)
- fetchLogs(fileByPath, { validation: true, pdfDownloadDomain })
- } else if (response.status === 'exited') {
- $scope.pdf.view = 'pdf'
- $scope.pdf.compileExited = true
- $scope.pdf.url = lastPdfUrl
- $scope.shouldShowLogs = true
- fetchLogs(fileByPath, { pdfDownloadDomain })
- } else if (response.status === 'autocompile-backoff') {
- if ($scope.pdf.isAutoCompileOnLoad) {
- // initial autocompile
- $scope.pdf.view = 'uncompiled'
- } else {
- // background autocompile from typing
- $scope.pdf.view = 'errors'
- $scope.pdf.autoCompileDisabled = true
- $scope.autocompile_enabled = false // disable any further autocompiles
- eventTracking.sendMB('autocompile-rate-limited', {
- hasPremiumCompile: $scope.hasPremiumCompile
+ $scope.$watch('shouldShowLogs', shouldShow => {
+ if (shouldShow) {
+ $scope.$applyAsync(() => {
+ $scope.shouldDropUp = getFilesDropdownTopCoordAsRatio() > 0.65
})
}
- } else if (response.status === 'project-too-large') {
- $scope.pdf.view = 'errors'
- $scope.pdf.projectTooLarge = true
- } else if (response.status === 'failure') {
- $scope.pdf.view = 'errors'
- $scope.pdf.failure = true
- $scope.shouldShowLogs = true
- fetchLogs(fileByPath, { pdfDownloadDomain })
- } else if (response.status === 'clsi-maintenance') {
- $scope.pdf.view = 'errors'
- $scope.pdf.clsiMaintenance = true
- } else if (response.status === 'unavailable') {
- $scope.pdf.view = 'errors'
- $scope.pdf.clsiUnavailable = true
- } else if (response.status === 'too-recently-compiled') {
- $scope.pdf.view = 'errors'
- $scope.pdf.tooRecentlyCompiled = true
- } else if (response.status === 'validation-problems') {
- $scope.pdf.view = 'validation-problems'
- $scope.pdf.validation = response.validationProblems
- $scope.shouldShowLogs = false
- } else if (response.status === 'compile-in-progress') {
- $scope.pdf.view = 'errors'
- $scope.pdf.compileInProgress = true
- } else {
- // fall back to displaying an error
- $scope.pdf.view = 'errors'
- $scope.pdf.error = true
+ })
+
+ $scope.trackLogHintsLearnMore = function () {
+ eventTracking.sendMB('logs-hints-learn-more')
}
- if (window.showNewLogsUI) {
- $scope.pdf.compileFailed = false
- // `$scope.clsiErrors` stores the error states nested within `$scope.pdf`
- // for use with React's
- $scope.clsiErrors = Object.assign(
- {},
- $scope.pdf.error ? { error: true } : null,
- $scope.pdf.renderingError ? { renderingError: true } : null,
- $scope.pdf.clsiMaintenance ? { clsiMaintenance: true } : null,
- $scope.pdf.clsiUnavailable ? { clsiUnavailable: true } : null,
- $scope.pdf.tooRecentlyCompiled ? { tooRecentlyCompiled: true } : null,
- $scope.pdf.compileTerminated ? { compileTerminated: true } : null,
- $scope.pdf.rateLimited ? { rateLimited: true } : null,
- $scope.pdf.compileInProgress ? { compileInProgress: true } : null,
- $scope.pdf.timedout ? { timedout: true } : null,
- $scope.pdf.autoCompileDisabled ? { autoCompileDisabled: true } : null
- )
+ if (ace.require('ace/lib/useragent').isMac) {
+ $scope.modifierKey = 'Cmd'
+ } else {
+ $scope.modifierKey = 'Ctrl'
+ }
- if (
- $scope.pdf.view === 'errors' ||
- $scope.pdf.view === 'validation-problems'
- ) {
- $scope.shouldShowLogs = true
- $scope.pdf.compileFailed = true
+ // utility for making a query string from a hash, could use jquery $.param
+ function createQueryString(args) {
+ const qsArgs = []
+ for (const k in args) {
+ const v = args[k]
+ qsArgs.push(`${k}=${v}`)
+ }
+ if (qsArgs.length) {
+ return `?${qsArgs.join('&')}`
+ } else {
+ return ''
}
}
- const IGNORE_FILES = ['output.fls', 'output.fdb_latexmk']
- $scope.pdf.outputFiles = []
+ $scope.$on('project:joined', () => {
+ if (!autoCompile) {
+ return
+ }
+ autoCompile = false
+ $scope.recompile({ isAutoCompileOnLoad: true })
+ $scope.hasPremiumCompile =
+ $scope.project.features.compileGroup === 'priority'
+ })
- if (response.outputFiles == null) {
- return
- }
+ $scope.$on('pdf:error:display', function () {
+ $scope.pdf.view = 'errors'
+ $scope.pdf.renderingError = true
+ })
- // prepare list of output files for download dropdown
- qs = {}
- if (response.clsiServerId != null) {
- qs.clsiserverid = response.clsiServerId
- }
- for (const file of response.outputFiles) {
- if (IGNORE_FILES.indexOf(file.path) === -1) {
- const isOutputFile = /^output\./.test(file.path)
- $scope.pdf.outputFiles.push({
- // Turn 'output.blg' into 'blg file'.
- name: isOutputFile
- ? `${file.path.replace(/^output\./, '')} file`
- : file.path,
- url: file.url + createQueryString(qs),
- main: !!isOutputFile,
- fileName: file.path,
- type: file.type
+ let autoCompileInterval = null
+ function autoCompileIfReady() {
+ if (
+ $scope.pdf.compiling ||
+ !$scope.autocompile_enabled ||
+ !$scope.pdf.uncompiled
+ ) {
+ return
+ }
+
+ // Only checking linting if syntaxValidation is on and visible to the user
+ const autoCompileLintingError =
+ ide.$scope.hasLintingError && ide.$scope.settings.syntaxValidation
+ if ($scope.autoCompileLintingError !== autoCompileLintingError) {
+ $scope.$apply(() => {
+ $scope.autoCompileLintingError = autoCompileLintingError
+ // We've likely been waiting a while until the user fixed the linting, but we
+ // don't want to compile as soon as it is fixed, so reset the timeout.
+ $scope.startedTryingAutoCompileAt = Date.now()
+ $scope.docLastChangedAt = Date.now()
})
}
- }
-
- // sort the output files into order, main files first, then others
- $scope.pdf.outputFiles.sort(
- (a, b) => b.main - a.main || a.name.localeCompare(b.name)
- )
- }
-
- function fetchLogs(fileByPath, options) {
- let blgFile, chktexFile, logFile
-
- if (options != null ? options.validation : undefined) {
- chktexFile = fileByPath['output.chktex']
- } else {
- logFile = fileByPath['output.log']
- blgFile = fileByPath['output.blg']
- }
-
- function getFile(name, file) {
- const opts = {
- method: 'GET',
- url: buildPdfDownloadUrl(options.pdfDownloadDomain, file.url),
- params: {
- compileGroup: ide.compileGroup,
- clsiserverid: ide.clsiServerId
- }
+ if (autoCompileLintingError && $scope.stop_on_validation_error) {
+ return
}
- return $http(opts)
- }
- // accumulate the log entries
- const logEntries = {
- all: [],
- errors: [],
- warnings: [],
- typesetting: []
- }
-
- function accumulateResults(newEntries) {
- for (let key of ['all', 'errors', 'warnings', 'typesetting']) {
- if (newEntries[key]) {
- if (newEntries.type != null) {
- for (let entry of newEntries[key]) {
- entry.type = newEntries.type
- }
- }
- logEntries[key] = logEntries[key].concat(newEntries[key])
- }
- }
- }
-
- // use the parsers for each file type
- function processLog(log) {
- $scope.pdf.rawLog = log
- const { errors, warnings, typesetting } = HumanReadableLogs.parse(log, {
- ignoreDuplicates: true
- })
- const all = [].concat(errors, warnings, typesetting)
- accumulateResults({ all, errors, warnings, typesetting })
- }
-
- function processChkTex(log) {
- const errors = []
- const warnings = []
- for (let line of log.split('\n')) {
- var m
- if ((m = line.match(/^(\S+):(\d+):(\d+): (Error|Warning): (.*)/))) {
- const result = {
- file: m[1],
- line: m[2],
- column: m[3],
- level: m[4].toLowerCase(),
- message: `${m[4]}: ${m[5]}`
- }
- if (result.level === 'error') {
- errors.push(result)
- } else {
- warnings.push(result)
- }
- }
- }
- const all = [].concat(errors, warnings)
- const logHints = HumanReadableLogs.parse({
- type: 'Syntax',
- all,
- errors,
- warnings
- })
- eventTracking.sendMB('syntax-check-return-count', {
- errors: errors.length,
- warnings: warnings.length
- })
- accumulateResults(logHints)
- }
-
- function processBiber(log) {
- const { errors, warnings } = BibLogParser.parse(log, {})
- const all = [].concat(errors, warnings)
- accumulateResults({ type: 'BibTeX:', all, errors, warnings })
- }
-
- // output the results
- function handleError() {
- $scope.pdf.logEntries = {}
- $scope.pdf.rawLog = ''
- }
-
- function annotateFiles() {
- $scope.pdf.logEntries = logEntries
- $scope.pdf.logEntryAnnotations = {}
- for (const entry of logEntries.all) {
- if (entry.file != null) {
- entry.file = normalizeFilePath(entry.file)
- const entity = ide.fileTreeManager.findEntityByPath(entry.file)
- if (entity != null) {
- if (!$scope.pdf.logEntryAnnotations[entity.id]) {
- $scope.pdf.logEntryAnnotations[entity.id] = []
- }
- $scope.pdf.logEntryAnnotations[entity.id].push({
- row: entry.line - 1,
- type: entry.level === 'error' ? 'error' : 'warning',
- text: entry.message
- })
- }
- }
- }
- }
-
- // retrieve the logfile and process it
- let response
- if (logFile != null) {
- response = getFile('output.log', logFile).then(response =>
- processLog(response.data)
+ // If there's a longish compile, don't compile immediately after if user is still typing
+ const startedTryingAt = Math.max(
+ $scope.startedTryingAutoCompileAt,
+ $scope.lastFinishedCompileAt || 0
)
- if (blgFile != null) {
- // retrieve the blg file if present
- response = response.then(() =>
- getFile('output.blg', blgFile).then(
- response => processBiber(response.data),
- () => true
- )
- )
+ const timeSinceStartedTrying = Date.now() - startedTryingAt
+ const timeSinceLastChange = Date.now() - $scope.docLastChangedAt
+
+ let shouldCompile = false
+ if (timeSinceLastChange > AUTO_COMPILE_DEBOUNCE) {
+ // Don't compile in the middle of the user typing
+ shouldCompile = true
+ } else if (timeSinceStartedTrying > AUTO_COMPILE_MAX_WAIT) {
+ // Unless they type for a long time
+ shouldCompile = true
+ } else if (timeSinceStartedTrying < 0 || timeSinceLastChange < 0) {
+ // If time is non-monotonic, assume that the user's system clock has been
+ // changed and continue with compile
+ shouldCompile = true
+ }
+
+ if (shouldCompile) {
+ return triggerAutoCompile()
}
}
- if (response != null) {
- response.catch(handleError)
- } else {
- handleError()
+ function triggerAutoCompile() {
+ $scope.recompile({ isAutoCompileOnChange: true })
}
- if (chktexFile != null) {
- const getChkTex = () =>
- getFile('output.chktex', chktexFile).then(response =>
- processChkTex(response.data)
- )
- // always retrieve the chktex file if present
- if (response != null) {
- response = response.then(getChkTex, getChkTex)
+ function startTryingAutoCompile() {
+ if (autoCompileInterval != null) {
+ return
+ }
+ $scope.startedTryingAutoCompileAt = Date.now()
+ autoCompileInterval = setInterval(autoCompileIfReady, 200)
+ }
+
+ function stopTryingAutoCompile() {
+ clearInterval(autoCompileInterval)
+ autoCompileInterval = null
+ }
+
+ $scope.changesToAutoCompile = false
+ $scope.$watch('pdf.uncompiled', uncompiledChanges => {
+ // don't autocompile if disabled or the pdf is not visible
+ if (
+ $scope.pdf.uncompiled &&
+ $scope.autocompile_enabled &&
+ !$scope.ui.pdfHidden
+ ) {
+ $scope.changesToAutoCompile = true
+ startTryingAutoCompile()
} else {
- response = getChkTex()
+ $scope.changesToAutoCompile = false
+ stopTryingAutoCompile()
+ }
+ })
+
+ function recalculateUncompiledChanges() {
+ if ($scope.docLastChangedAt == null) {
+ $scope.pdf.uncompiled = false
+ } else if (
+ $scope.lastStartedCompileAt == null ||
+ $scope.docLastChangedAt > $scope.lastStartedCompileAt
+ ) {
+ $scope.pdf.uncompiled = true
+ } else {
+ $scope.pdf.uncompiled = false
}
}
- // display the combined result
- if (response != null) {
- response.finally(() => {
- annotateFiles()
- sendCompileMetrics()
- })
+ function _updateDocLastChangedAt() {
+ $scope.docLastChangedAt = Date.now()
+ recalculateUncompiledChanges()
}
- }
- function sendCompileMetrics() {
- const hasCompiled =
- $scope.pdf.view !== 'errors' && $scope.pdf.view !== 'validation-problems'
+ function onDocChanged() {
+ _updateDocLastChangedAt()
+ }
- if (hasCompiled && !window.user.alphaProgram) {
- const metadata = {
- errors: $scope.pdf.logEntries.errors.length,
- warnings: $scope.pdf.logEntries.warnings.length,
- typesetting: $scope.pdf.logEntries.typesetting.length,
- newLogsUI: window.showNewLogsUI,
- subvariant: window.showNewLogsUI ? window.logsUISubvariant : null
+ function onDocSaved() {
+ // We use the save as a trigger too, to account for the delay between the client
+ // and server. Otherwise, we might have compiled after the user made
+ // the change on the client, but before the server had it.
+ _updateDocLastChangedAt()
+ }
+
+ function onCompilingStateChanged(compiling) {
+ recalculateUncompiledChanges()
+ }
+
+ ide.$scope.$on('doc:changed', onDocChanged)
+ ide.$scope.$on('doc:saved', onDocSaved)
+ $scope.$watch('pdf.compiling', onCompilingStateChanged)
+
+ $scope.autocompile_enabled =
+ localStorage(`autocompile_enabled:${$scope.project_id}`) || false
+ $scope.$watch('autocompile_enabled', (newValue, oldValue) => {
+ if (newValue != null && oldValue !== newValue) {
+ if (newValue === true) {
+ $scope.autoCompileLintingError = false
+ autoCompileIfReady()
+ }
+ localStorage(`autocompile_enabled:${$scope.project_id}`, newValue)
+ eventTracking.sendMB('autocompile-setting-changed', {
+ value: newValue
+ })
}
- eventTracking.sendMBSampled(
- 'compile-result',
- JSON.stringify(metadata),
- 0.01
+ })
+
+ // abort compile if syntax checks fail
+ $scope.stop_on_validation_error = localStorage(
+ `stop_on_validation_error:${$scope.project_id}`
+ )
+ if ($scope.stop_on_validation_error == null) {
+ $scope.stop_on_validation_error = true
+ }
+ // turn on for all users by default
+ $scope.$watch('stop_on_validation_error', (newValue, oldValue) => {
+ if (newValue != null && oldValue !== newValue) {
+ localStorage(`stop_on_validation_error:${$scope.project_id}`, newValue)
+ }
+ })
+
+ $scope.draft = localStorage(`draft:${$scope.project_id}`) || false
+ $scope.$watch('draft', (newValue, oldValue) => {
+ if (newValue != null && oldValue !== newValue) {
+ localStorage(`draft:${$scope.project_id}`, newValue)
+ }
+ })
+
+ function sendCompileRequest(options) {
+ if (options == null) {
+ options = {}
+ }
+ const url = `/project/${$scope.project_id}/compile`
+ const params = {}
+ if (options.isAutoCompileOnLoad || options.isAutoCompileOnChange) {
+ params.auto_compile = true
+ }
+ // if the previous run was a check, clear the error logs
+ if ($scope.check) {
+ $scope.pdf.logEntries = {}
+ }
+ // keep track of whether this is a compile or check
+ $scope.check = !!options.check
+ if (options.check) {
+ eventTracking.sendMB('syntax-check-request')
+ }
+ // send appropriate check type to clsi
+ let checkType
+ if ($scope.check) {
+ checkType = 'validate' // validate only
+ } else if (options.try) {
+ checkType = 'silent' // allow use to try compile once
+ } else if ($scope.stop_on_validation_error) {
+ checkType = 'error' // try to compile
+ } else {
+ checkType = 'silent' // ignore errors
+ }
+
+ // FIXME: Temporarily disable syntax checking as it is causing
+ // excessive support requests for projects migrated from v1
+ // https://github.com/overleaf/sharelatex/issues/911
+ if (checkType === 'error') {
+ checkType = 'silent'
+ }
+
+ return $http.post(
+ url,
+ {
+ rootDoc_id: options.rootDocOverride_id || null,
+ draft: $scope.draft,
+ check: checkType,
+ // use incremental compile for all users but revert to a full
+ // compile if there is a server error
+ incrementalCompilesEnabled: !$scope.pdf.error,
+ _csrf: window.csrfToken
+ },
+ { params }
)
}
- }
- function getRootDocOverrideId() {
- const rootDocId = $scope.project.rootDoc_id
- const currentDocId = ide.editorManager.getCurrentDocId()
- if (currentDocId === rootDocId) {
- return null // no need to override when in the root doc itself
- }
- const doc = ide.editorManager.getCurrentDocValue()
- if (doc == null) {
- return null
- }
- for (let line of doc.split('\n')) {
- if (/^[^%]*\\documentclass/.test(line)) {
- return ide.editorManager.getCurrentDocId()
+ function buildPdfDownloadUrl(pdfDownloadDomain, url) {
+ if (pdfDownloadDomain) {
+ return `${pdfDownloadDomain}${url}`
+ } else {
+ return url
}
}
- return null
- }
- function normalizeFilePath(path) {
- path = path.replace(
- /^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/,
- ''
- )
- path = path.replace(/^\/compile\//, '')
+ function parseCompileResponse(response) {
+ // keep last url
+ const lastPdfUrl = $scope.pdf.url
+ const { pdfDownloadDomain } = response
+ // Reset everything
+ $scope.pdf.error = false
+ $scope.pdf.timedout = false
+ $scope.pdf.failure = false
+ $scope.pdf.url = null
+ $scope.pdf.clsiMaintenance = false
+ $scope.pdf.tooRecentlyCompiled = false
+ $scope.pdf.renderingError = false
+ $scope.pdf.projectTooLarge = false
+ $scope.pdf.compileTerminated = false
+ $scope.pdf.compileExited = false
+ $scope.pdf.failedCheck = false
+ $scope.pdf.compileInProgress = false
+ $scope.pdf.autoCompileDisabled = false
+ if (window.showNewLogsUI) {
+ $scope.clsiErrors = {}
+ }
- const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
- if (rootDocDirname != null) {
- path = path.replace(/^\.\//, rootDocDirname + '/')
- }
+ // make a cache to look up files by name
+ const fileByPath = {}
+ if (response.outputFiles != null) {
+ for (const file of response.outputFiles) {
+ fileByPath[file.path] = file
+ }
+ }
- return path
- }
+ // prepare query string
+ let qs = {}
+ // add a query string parameter for the compile group
+ if (response.compileGroup != null) {
+ ide.compileGroup = qs.compileGroup = response.compileGroup
+ }
+ // add a query string parameter for the clsi server id
+ if (response.clsiServerId != null) {
+ ide.clsiServerId = qs.clsiserverid = response.clsiServerId
+ }
- $scope.recompile = function(options) {
- if (options == null) {
- options = {}
- }
- if ($scope.pdf.compiling) {
- return
- }
+ // TODO(das7pad): drop this hack once 2747f0d40af8729304 has landed in clsi
+ if (response.status === 'success' && !fileByPath['output.pdf']) {
+ response.status = 'failure'
+ }
- eventTracking.sendMBSampled('editor-recompile-sampled', options)
-
- $scope.lastStartedCompileAt = Date.now()
- $scope.pdf.compiling = true
- $scope.pdf.isAutoCompileOnLoad =
- options != null ? options.isAutoCompileOnLoad : undefined // initial autocompile
-
- if (options != null ? options.force : undefined) {
- // for forced compile, turn off validation check and ignore errors
- $scope.stop_on_validation_error = false
- $scope.shouldShowLogs = false // hide the logs while compiling
- eventTracking.sendMB('syntax-check-turn-off-checking')
- }
-
- if (options != null ? options.try : undefined) {
- $scope.shouldShowLogs = false // hide the logs while compiling
- eventTracking.sendMB('syntax-check-try-compile-anyway')
- }
-
- ide.$scope.$broadcast('flush-changes')
-
- options.rootDocOverride_id = getRootDocOverrideId()
-
- sendCompileRequest(options)
- .then(function(response) {
- const { data } = response
+ if (response.status === 'success') {
$scope.pdf.view = 'pdf'
- $scope.pdf.compiling = false
- parseCompileResponse(data)
- })
- .catch(function(response) {
- const { status } = response
- if (status === 429) {
- $scope.pdf.rateLimited = true
- }
- $scope.pdf.compiling = false
- $scope.pdf.renderingError = false
- $scope.pdf.error = true
+ $scope.shouldShowLogs = false
+ $scope.pdf.lastCompileTimestamp = Date.now()
+ $scope.pdf.validation = {}
+ $scope.pdf.url = buildPdfDownloadUrl(
+ pdfDownloadDomain,
+ fileByPath['output.pdf'].url
+ )
+ // convert the qs hash into a query string and append it
+ $scope.pdf.url += createQueryString(qs)
+
+ // Save all downloads as files
+ qs.popupDownload = true
+
+ const { build: buildId } = fileByPath['output.pdf']
+ $scope.pdf.downloadUrl =
+ `/download/project/${$scope.project_id}/build/${buildId}/output/output.pdf` +
+ createQueryString(qs)
+ fetchLogs(fileByPath, { pdfDownloadDomain })
+ } else if (response.status === 'timedout') {
$scope.pdf.view = 'errors'
- if (window.showNewLogsUI) {
- $scope.clsiErrors = { error: true }
+ $scope.pdf.timedout = true
+ fetchLogs(fileByPath, { pdfDownloadDomain })
+ if (
+ !$scope.hasPremiumCompile &&
+ ide.$scope.project.owner._id === ide.$scope.user.id
+ ) {
+ eventTracking.send(
+ 'subscription-funnel',
+ 'editor-click-feature',
+ 'compile-timeout'
+ )
+ }
+ } else if (response.status === 'terminated') {
+ $scope.pdf.view = 'errors'
+ $scope.pdf.compileTerminated = true
+ fetchLogs(fileByPath, { pdfDownloadDomain })
+ } else if (
+ ['validation-fail', 'validation-pass'].includes(response.status)
+ ) {
+ $scope.pdf.view = 'pdf'
+ $scope.pdf.url = lastPdfUrl
+ $scope.shouldShowLogs = true
+ if (response.status === 'validation-fail') {
+ $scope.pdf.failedCheck = true
+ }
+ eventTracking.sendMB(`syntax-check-${response.status}`)
+ fetchLogs(fileByPath, { validation: true, pdfDownloadDomain })
+ } else if (response.status === 'exited') {
+ $scope.pdf.view = 'pdf'
+ $scope.pdf.compileExited = true
+ $scope.pdf.url = lastPdfUrl
+ $scope.shouldShowLogs = true
+ fetchLogs(fileByPath, { pdfDownloadDomain })
+ } else if (response.status === 'autocompile-backoff') {
+ if ($scope.pdf.isAutoCompileOnLoad) {
+ // initial autocompile
+ $scope.pdf.view = 'uncompiled'
+ } else {
+ // background autocompile from typing
+ $scope.pdf.view = 'errors'
+ $scope.pdf.autoCompileDisabled = true
+ $scope.autocompile_enabled = false // disable any further autocompiles
+ eventTracking.sendMB('autocompile-rate-limited', {
+ hasPremiumCompile: $scope.hasPremiumCompile
+ })
+ }
+ } else if (response.status === 'project-too-large') {
+ $scope.pdf.view = 'errors'
+ $scope.pdf.projectTooLarge = true
+ } else if (response.status === 'failure') {
+ $scope.pdf.view = 'errors'
+ $scope.pdf.failure = true
+ $scope.shouldShowLogs = true
+ fetchLogs(fileByPath, { pdfDownloadDomain })
+ } else if (response.status === 'clsi-maintenance') {
+ $scope.pdf.view = 'errors'
+ $scope.pdf.clsiMaintenance = true
+ } else if (response.status === 'unavailable') {
+ $scope.pdf.view = 'errors'
+ $scope.pdf.clsiUnavailable = true
+ } else if (response.status === 'too-recently-compiled') {
+ $scope.pdf.view = 'errors'
+ $scope.pdf.tooRecentlyCompiled = true
+ } else if (response.status === 'validation-problems') {
+ $scope.pdf.view = 'validation-problems'
+ $scope.pdf.validation = response.validationProblems
+ $scope.shouldShowLogs = false
+ } else if (response.status === 'compile-in-progress') {
+ $scope.pdf.view = 'errors'
+ $scope.pdf.compileInProgress = true
+ } else {
+ // fall back to displaying an error
+ $scope.pdf.view = 'errors'
+ $scope.pdf.error = true
+ }
+
+ if (window.showNewLogsUI) {
+ $scope.pdf.compileFailed = false
+ // `$scope.clsiErrors` stores the error states nested within `$scope.pdf`
+ // for use with React's
+ $scope.clsiErrors = Object.assign(
+ {},
+ $scope.pdf.error ? { error: true } : null,
+ $scope.pdf.renderingError ? { renderingError: true } : null,
+ $scope.pdf.clsiMaintenance ? { clsiMaintenance: true } : null,
+ $scope.pdf.clsiUnavailable ? { clsiUnavailable: true } : null,
+ $scope.pdf.tooRecentlyCompiled ? { tooRecentlyCompiled: true } : null,
+ $scope.pdf.compileTerminated ? { compileTerminated: true } : null,
+ $scope.pdf.rateLimited ? { rateLimited: true } : null,
+ $scope.pdf.compileInProgress ? { compileInProgress: true } : null,
+ $scope.pdf.timedout ? { timedout: true } : null,
+ $scope.pdf.autoCompileDisabled ? { autoCompileDisabled: true } : null
+ )
+
+ if (
+ $scope.pdf.view === 'errors' ||
+ $scope.pdf.view === 'validation-problems'
+ ) {
$scope.shouldShowLogs = true
$scope.pdf.compileFailed = true
}
- })
- .finally(() => {
- $scope.lastFinishedCompileAt = Date.now()
- })
- }
-
- // This needs to be public.
- ide.$scope.recompile = $scope.recompile
- // This method is a simply wrapper and exists only for tracking purposes.
- ide.$scope.recompileViaKey = function() {
- $scope.recompile({ keyShortcut: true })
- }
-
- $scope.stop = function() {
- if (!$scope.pdf.compiling) {
- return
- }
-
- return $http({
- url: `/project/${$scope.project_id}/compile/stop`,
- method: 'POST',
- params: {
- clsiserverid: ide.clsiServerId
- },
- headers: {
- 'X-Csrf-Token': window.csrfToken
}
- })
- }
- $scope.clearCache = function() {
- $scope.pdf.clearingCache = true
- const deferred = $q.defer()
+ const IGNORE_FILES = ['output.fls', 'output.fdb_latexmk']
+ $scope.pdf.outputFiles = []
- // disable various download buttons
- $scope.pdf.url = null
- $scope.pdf.downloadUrl = null
- $scope.pdf.outputFiles = []
-
- $http({
- url: `/project/${$scope.project_id}/output`,
- method: 'DELETE',
- params: {
- clsiserverid: ide.clsiServerId
- },
- headers: {
- 'X-Csrf-Token': window.csrfToken
+ if (response.outputFiles == null) {
+ return
}
- })
- .then(function(response) {
- $scope.pdf.clearingCache = false
- return deferred.resolve()
- })
- .catch(function(response) {
- console.error(response)
- const error = response.data
- $scope.pdf.clearingCache = false
- $scope.pdf.renderingError = false
- $scope.pdf.error = true
- $scope.pdf.view = 'errors'
- return deferred.reject(error)
- })
- return deferred.promise
- }
- $scope.recompileFromScratch = function() {
- $scope.pdf.compiling = true
- return $scope
- .clearCache()
- .then(() => {
- $scope.pdf.compiling = false
- $scope.recompile()
- })
- .catch(error => {
- console.error(error)
- })
- }
-
- $scope.toggleLogs = function() {
- $scope.$applyAsync(() => {
- $scope.shouldShowLogs = !$scope.shouldShowLogs
- if ($scope.shouldShowLogs) {
- eventTracking.sendMBOnce('ide-open-logs-once')
+ // prepare list of output files for download dropdown
+ qs = {}
+ if (response.clsiServerId != null) {
+ qs.clsiserverid = response.clsiServerId
+ }
+ for (const file of response.outputFiles) {
+ if (IGNORE_FILES.indexOf(file.path) === -1) {
+ const isOutputFile = /^output\./.test(file.path)
+ $scope.pdf.outputFiles.push({
+ // Turn 'output.blg' into 'blg file'.
+ name: isOutputFile
+ ? `${file.path.replace(/^output\./, '')} file`
+ : file.path,
+ url: file.url + createQueryString(qs),
+ main: !!isOutputFile,
+ fileName: file.path,
+ type: file.type
+ })
+ }
}
- })
- }
- $scope.showPdf = function() {
- $scope.pdf.view = 'pdf'
- $scope.shouldShowLogs = false
- }
+ // sort the output files into order, main files first, then others
+ $scope.pdf.outputFiles.sort(
+ (a, b) => b.main - a.main || a.name.localeCompare(b.name)
+ )
+ }
- $scope.toggleRawLog = function() {
- $scope.pdf.showRawLog = !$scope.pdf.showRawLog
- if ($scope.pdf.showRawLog) {
- eventTracking.sendMB('logs-view-raw')
+ function fetchLogs(fileByPath, options) {
+ let blgFile, chktexFile, logFile
+
+ if (options != null ? options.validation : undefined) {
+ chktexFile = fileByPath['output.chktex']
+ } else {
+ logFile = fileByPath['output.log']
+ blgFile = fileByPath['output.blg']
+ }
+
+ function getFile(name, file) {
+ const opts = {
+ method: 'GET',
+ url: buildPdfDownloadUrl(options.pdfDownloadDomain, file.url),
+ params: {
+ compileGroup: ide.compileGroup,
+ clsiserverid: ide.clsiServerId
+ }
+ }
+ return $http(opts)
+ }
+
+ // accumulate the log entries
+ const logEntries = {
+ all: [],
+ errors: [],
+ warnings: [],
+ typesetting: []
+ }
+
+ function accumulateResults(newEntries) {
+ for (let key of ['all', 'errors', 'warnings', 'typesetting']) {
+ if (newEntries[key]) {
+ if (newEntries.type != null) {
+ for (let entry of newEntries[key]) {
+ entry.type = newEntries.type
+ }
+ }
+ logEntries[key] = logEntries[key].concat(newEntries[key])
+ }
+ }
+ }
+
+ // use the parsers for each file type
+ function processLog(log) {
+ $scope.pdf.rawLog = log
+ const { errors, warnings, typesetting } = HumanReadableLogs.parse(log, {
+ ignoreDuplicates: true
+ })
+ const all = [].concat(errors, warnings, typesetting)
+ accumulateResults({ all, errors, warnings, typesetting })
+ }
+
+ function processChkTex(log) {
+ const errors = []
+ const warnings = []
+ for (let line of log.split('\n')) {
+ var m
+ if ((m = line.match(/^(\S+):(\d+):(\d+): (Error|Warning): (.*)/))) {
+ const result = {
+ file: m[1],
+ line: m[2],
+ column: m[3],
+ level: m[4].toLowerCase(),
+ message: `${m[4]}: ${m[5]}`
+ }
+ if (result.level === 'error') {
+ errors.push(result)
+ } else {
+ warnings.push(result)
+ }
+ }
+ }
+ const all = [].concat(errors, warnings)
+ const logHints = HumanReadableLogs.parse({
+ type: 'Syntax',
+ all,
+ errors,
+ warnings
+ })
+ eventTracking.sendMB('syntax-check-return-count', {
+ errors: errors.length,
+ warnings: warnings.length
+ })
+ accumulateResults(logHints)
+ }
+
+ function processBiber(log) {
+ const { errors, warnings } = BibLogParser.parse(log, {})
+ const all = [].concat(errors, warnings)
+ accumulateResults({ type: 'BibTeX:', all, errors, warnings })
+ }
+
+ // output the results
+ function handleError() {
+ $scope.pdf.logEntries = {}
+ $scope.pdf.rawLog = ''
+ }
+
+ function annotateFiles() {
+ $scope.pdf.logEntries = logEntries
+ $scope.pdf.logEntryAnnotations = {}
+ for (const entry of logEntries.all) {
+ if (entry.file != null) {
+ entry.file = normalizeFilePath(entry.file)
+ const entity = ide.fileTreeManager.findEntityByPath(entry.file)
+ if (entity != null) {
+ if (!$scope.pdf.logEntryAnnotations[entity.id]) {
+ $scope.pdf.logEntryAnnotations[entity.id] = []
+ }
+ $scope.pdf.logEntryAnnotations[entity.id].push({
+ row: entry.line - 1,
+ type: entry.level === 'error' ? 'error' : 'warning',
+ text: entry.message
+ })
+ }
+ }
+ }
+ }
+
+ // retrieve the logfile and process it
+ let response
+ if (logFile != null) {
+ response = getFile('output.log', logFile).then(response =>
+ processLog(response.data)
+ )
+
+ if (blgFile != null) {
+ // retrieve the blg file if present
+ response = response.then(() =>
+ getFile('output.blg', blgFile).then(
+ response => processBiber(response.data),
+ () => true
+ )
+ )
+ }
+ }
+
+ if (response != null) {
+ response.catch(handleError)
+ } else {
+ handleError()
+ }
+
+ if (chktexFile != null) {
+ const getChkTex = () =>
+ getFile('output.chktex', chktexFile).then(response =>
+ processChkTex(response.data)
+ )
+ // always retrieve the chktex file if present
+ if (response != null) {
+ response = response.then(getChkTex, getChkTex)
+ } else {
+ response = getChkTex()
+ }
+ }
+
+ // display the combined result
+ if (response != null) {
+ response.finally(() => {
+ annotateFiles()
+ sendCompileMetrics()
+ })
+ }
+ }
+
+ function sendCompileMetrics() {
+ const hasCompiled =
+ $scope.pdf.view !== 'errors' &&
+ $scope.pdf.view !== 'validation-problems'
+
+ if (hasCompiled && !window.user.alphaProgram) {
+ const metadata = {
+ errors: $scope.pdf.logEntries.errors.length,
+ warnings: $scope.pdf.logEntries.warnings.length,
+ typesetting: $scope.pdf.logEntries.typesetting.length,
+ newLogsUI: window.showNewLogsUI,
+ subvariant: window.showNewLogsUI ? window.logsUISubvariant : null
+ }
+ eventTracking.sendMBSampled(
+ 'compile-result',
+ JSON.stringify(metadata),
+ 0.01
+ )
+ }
+ }
+
+ function getRootDocOverrideId() {
+ const rootDocId = $scope.project.rootDoc_id
+ const currentDocId = ide.editorManager.getCurrentDocId()
+ if (currentDocId === rootDocId) {
+ return null // no need to override when in the root doc itself
+ }
+ const doc = ide.editorManager.getCurrentDocValue()
+ if (doc == null) {
+ return null
+ }
+ for (let line of doc.split('\n')) {
+ if (/^[^%]*\\documentclass/.test(line)) {
+ return ide.editorManager.getCurrentDocId()
+ }
+ }
+ return null
+ }
+
+ function normalizeFilePath(path) {
+ path = path.replace(
+ /^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/,
+ ''
+ )
+ path = path.replace(/^\/compile\//, '')
+
+ const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
+ if (rootDocDirname != null) {
+ path = path.replace(/^\.\//, rootDocDirname + '/')
+ }
+
+ return path
+ }
+
+ $scope.recompile = function (options) {
+ if (options == null) {
+ options = {}
+ }
+ if ($scope.pdf.compiling) {
+ return
+ }
+
+ eventTracking.sendMBSampled('editor-recompile-sampled', options)
+
+ $scope.lastStartedCompileAt = Date.now()
+ $scope.pdf.compiling = true
+ $scope.pdf.isAutoCompileOnLoad =
+ options != null ? options.isAutoCompileOnLoad : undefined // initial autocompile
+
+ if (options != null ? options.force : undefined) {
+ // for forced compile, turn off validation check and ignore errors
+ $scope.stop_on_validation_error = false
+ $scope.shouldShowLogs = false // hide the logs while compiling
+ eventTracking.sendMB('syntax-check-turn-off-checking')
+ }
+
+ if (options != null ? options.try : undefined) {
+ $scope.shouldShowLogs = false // hide the logs while compiling
+ eventTracking.sendMB('syntax-check-try-compile-anyway')
+ }
+
+ ide.$scope.$broadcast('flush-changes')
+
+ options.rootDocOverride_id = getRootDocOverrideId()
+
+ sendCompileRequest(options)
+ .then(function (response) {
+ const { data } = response
+ $scope.pdf.view = 'pdf'
+ $scope.pdf.compiling = false
+ parseCompileResponse(data)
+ })
+ .catch(function (response) {
+ const { status } = response
+ if (status === 429) {
+ $scope.pdf.rateLimited = true
+ }
+ $scope.pdf.compiling = false
+ $scope.pdf.renderingError = false
+ $scope.pdf.error = true
+ $scope.pdf.view = 'errors'
+ if (window.showNewLogsUI) {
+ $scope.clsiErrors = { error: true }
+ $scope.shouldShowLogs = true
+ $scope.pdf.compileFailed = true
+ }
+ })
+ .finally(() => {
+ $scope.lastFinishedCompileAt = Date.now()
+ })
+ }
+
+ // This needs to be public.
+ ide.$scope.recompile = $scope.recompile
+ // This method is a simply wrapper and exists only for tracking purposes.
+ ide.$scope.recompileViaKey = function () {
+ $scope.recompile({ keyShortcut: true })
+ }
+
+ $scope.stop = function () {
+ if (!$scope.pdf.compiling) {
+ return
+ }
+
+ return $http({
+ url: `/project/${$scope.project_id}/compile/stop`,
+ method: 'POST',
+ params: {
+ clsiserverid: ide.clsiServerId
+ },
+ headers: {
+ 'X-Csrf-Token': window.csrfToken
+ }
+ })
+ }
+
+ $scope.clearCache = function () {
+ $scope.pdf.clearingCache = true
+ const deferred = $q.defer()
+
+ // disable various download buttons
+ $scope.pdf.url = null
+ $scope.pdf.downloadUrl = null
+ $scope.pdf.outputFiles = []
+
+ $http({
+ url: `/project/${$scope.project_id}/output`,
+ method: 'DELETE',
+ params: {
+ clsiserverid: ide.clsiServerId
+ },
+ headers: {
+ 'X-Csrf-Token': window.csrfToken
+ }
+ })
+ .then(function (response) {
+ $scope.pdf.clearingCache = false
+ return deferred.resolve()
+ })
+ .catch(function (response) {
+ console.error(response)
+ const error = response.data
+ $scope.pdf.clearingCache = false
+ $scope.pdf.renderingError = false
+ $scope.pdf.error = true
+ $scope.pdf.view = 'errors'
+ return deferred.reject(error)
+ })
+ return deferred.promise
+ }
+
+ $scope.recompileFromScratch = function () {
+ $scope.pdf.compiling = true
+ return $scope
+ .clearCache()
+ .then(() => {
+ $scope.pdf.compiling = false
+ $scope.recompile()
+ })
+ .catch(error => {
+ console.error(error)
+ })
+ }
+
+ $scope.toggleLogs = function () {
+ $scope.$applyAsync(() => {
+ $scope.shouldShowLogs = !$scope.shouldShowLogs
+ if ($scope.shouldShowLogs) {
+ eventTracking.sendMBOnce('ide-open-logs-once')
+ }
+ })
+ }
+
+ $scope.showPdf = function () {
+ $scope.pdf.view = 'pdf'
+ $scope.shouldShowLogs = false
+ }
+
+ $scope.toggleRawLog = function () {
+ $scope.pdf.showRawLog = !$scope.pdf.showRawLog
+ if ($scope.pdf.showRawLog) {
+ eventTracking.sendMB('logs-view-raw')
+ }
+ }
+
+ $scope.openClearCacheModal = function () {
+ $modal.open({
+ templateUrl: 'clearCacheModalTemplate',
+ controller: 'ClearCacheModalController',
+ scope: $scope
+ })
+ }
+
+ $scope.syncToCode = function (position) {
+ synctex.syncToCode(position).then(function (data) {
+ const { doc, line } = data
+ ide.editorManager.openDoc(doc, { gotoLine: line })
+ })
+ }
+
+ $scope.setAutoCompile = function (isOn) {
+ $scope.$applyAsync(function () {
+ $scope.autocompile_enabled = isOn
+ })
+ }
+ $scope.setDraftMode = function (isOn) {
+ $scope.$applyAsync(function () {
+ $scope.draft = isOn
+ })
+ }
+ $scope.setSyntaxCheck = function (isOn) {
+ $scope.$applyAsync(function () {
+ $scope.stop_on_validation_error = isOn
+ })
+ }
+ $scope.runSyntaxCheckNow = function () {
+ $scope.$applyAsync(function () {
+ $scope.recompile({ check: true })
+ })
+ }
+
+ $scope.openInEditor = function (entry) {
+ let column, line
+ eventTracking.sendMBOnce('logs-jump-to-location-once')
+ const entity = ide.fileTreeManager.findEntityByPath(entry.file)
+ if (entity == null || entity.type !== 'doc') {
+ return
+ }
+ if (entry.line != null) {
+ line = entry.line
+ }
+ if (entry.column != null) {
+ column = entry.column
+ }
+ ide.editorManager.openDoc(entity, {
+ gotoLine: line,
+ gotoColumn: column
+ })
}
}
+)
- $scope.openClearCacheModal = function() {
- $modal.open({
- templateUrl: 'clearCacheModalTemplate',
- controller: 'ClearCacheModalController',
- scope: $scope
- })
- }
-
- $scope.syncToCode = function(position) {
- synctex.syncToCode(position).then(function(data) {
- const { doc, line } = data
- ide.editorManager.openDoc(doc, { gotoLine: line })
- })
- }
-
- $scope.setAutoCompile = function(isOn) {
- $scope.$applyAsync(function() {
- $scope.autocompile_enabled = isOn
- })
- }
- $scope.setDraftMode = function(isOn) {
- $scope.$applyAsync(function() {
- $scope.draft = isOn
- })
- }
- $scope.setSyntaxCheck = function(isOn) {
- $scope.$applyAsync(function() {
- $scope.stop_on_validation_error = isOn
- })
- }
- $scope.runSyntaxCheckNow = function() {
- $scope.$applyAsync(function() {
- $scope.recompile({ check: true })
- })
- }
-
- $scope.openInEditor = function(entry) {
- let column, line
- eventTracking.sendMBOnce('logs-jump-to-location-once')
- const entity = ide.fileTreeManager.findEntityByPath(entry.file)
- if (entity == null || entity.type !== 'doc') {
- return
- }
- if (entry.line != null) {
- line = entry.line
- }
- if (entry.column != null) {
- column = entry.column
- }
- ide.editorManager.openDoc(entity, {
- gotoLine: line,
- gotoColumn: column
- })
- }
-})
-
-App.factory('synctex', function(ide, $http, $q) {
+App.factory('synctex', function (ide, $http, $q) {
const synctex = {
syncToPdfInFlight: false,
syncToCodeInFlight: false,
@@ -1099,7 +1103,7 @@ App.factory('synctex', function(ide, $http, $q) {
return synctex
})
-App.controller('PdfSynctexController', function($scope, synctex, ide) {
+App.controller('PdfSynctexController', function ($scope, synctex, ide) {
this.cursorPosition = null
$scope.$watch(
@@ -1126,31 +1130,31 @@ App.controller('PdfSynctexController', function($scope, synctex, ide) {
ide.$scope.$on('cursor:editor:syncToPdf', $scope.syncToPdf)
- $scope.syncToCode = function() {
+ $scope.syncToCode = function () {
synctex
.syncToCode($scope.pdf.position, {
includeVisualOffset: true,
fromPdfPosition: true
})
- .then(function(data) {
+ .then(function (data) {
const { doc, line } = data
ide.editorManager.openDoc(doc, { gotoLine: line })
})
}
})
-App.controller('ClearCacheModalController', function($scope, $modalInstance) {
+App.controller('ClearCacheModalController', function ($scope, $modalInstance) {
$scope.state = { error: false, inflight: false }
- $scope.clear = function() {
+ $scope.clear = function () {
$scope.state.inflight = true
$scope
.clearCache()
- .then(function() {
+ .then(function () {
$scope.state.inflight = false
$modalInstance.close()
})
- .catch(function() {
+ .catch(function () {
$scope.state.error = true
$scope.state.inflight = false
})
diff --git a/services/web/frontend/js/ide/pdf/controllers/PdfViewToggleController.js b/services/web/frontend/js/ide/pdf/controllers/PdfViewToggleController.js
index 6bd31c55f6..f4f112b6f4 100644
--- a/services/web/frontend/js/ide/pdf/controllers/PdfViewToggleController.js
+++ b/services/web/frontend/js/ide/pdf/controllers/PdfViewToggleController.js
@@ -10,8 +10,8 @@
*/
import App from '../../../base'
-export default App.controller('PdfViewToggleController', function($scope) {
- $scope.togglePdfView = function() {
+export default App.controller('PdfViewToggleController', function ($scope) {
+ $scope.togglePdfView = function () {
if ($scope.ui.view === 'pdf') {
return ($scope.ui.view = 'editor')
} else {
@@ -20,7 +20,7 @@ export default App.controller('PdfViewToggleController', function($scope) {
}
$scope.fileTreeClosed = false
- return $scope.$on('layout:main:resize', function(e, state) {
+ return $scope.$on('layout:main:resize', function (e, state) {
if (state.west.initClosed) {
$scope.fileTreeClosed = true
} else {
diff --git a/services/web/frontend/js/ide/pdfng/directives/pdfAnnotations.js b/services/web/frontend/js/ide/pdfng/directives/pdfAnnotations.js
index 85735f8f87..46769cd215 100644
--- a/services/web/frontend/js/ide/pdfng/directives/pdfAnnotations.js
+++ b/services/web/frontend/js/ide/pdfng/directives/pdfAnnotations.js
@@ -3,7 +3,7 @@ import PDFJS from './pdfJsLoader'
const EXTERNAL_LINK_TARGET = '_blank'
const REL_NOOPENER = 'noreferrer noopener'
-App.factory('pdfAnnotations', function() {
+App.factory('pdfAnnotations', function () {
class pdfAnnotations {
constructor(options) {
this.annotationsLayerDiv = options.annotations
diff --git a/services/web/frontend/js/ide/pdfng/directives/pdfHighlights.js b/services/web/frontend/js/ide/pdfng/directives/pdfHighlights.js
index 4cf05daf32..a705f88987 100644
--- a/services/web/frontend/js/ide/pdfng/directives/pdfHighlights.js
+++ b/services/web/frontend/js/ide/pdfng/directives/pdfHighlights.js
@@ -15,7 +15,7 @@
import App from '../../../base'
import PDFJS from './pdfJsLoader'
-export default App.factory('pdfHighlights', function() {
+export default App.factory('pdfHighlights', function () {
let pdfHighlights
return (pdfHighlights = class pdfHighlights {
constructor(options) {
diff --git a/services/web/frontend/js/ide/pdfng/directives/pdfJs.js b/services/web/frontend/js/ide/pdfng/directives/pdfJs.js
index 103341b0da..63b6e491f5 100644
--- a/services/web/frontend/js/ide/pdfng/directives/pdfJs.js
+++ b/services/web/frontend/js/ide/pdfng/directives/pdfJs.js
@@ -27,7 +27,7 @@ export default App.directive('pdfng', ($timeout, localStorage) => ({
scope.pleaseJumpTo = null
scope.scale = null
let initializedPosition = false
- const initializePosition = function() {
+ const initializePosition = function () {
let position, scale
if (initializedPosition) {
return
@@ -62,7 +62,7 @@ export default App.directive('pdfng', ($timeout, localStorage) => ({
}
const flashControls = () =>
- scope.$evalAsync(function() {
+ scope.$evalAsync(function () {
scope.flashControls = true
return $timeout(() => (scope.flashControls = false), 1000)
})
@@ -78,7 +78,7 @@ export default App.directive('pdfng', ($timeout, localStorage) => ({
scope.$on('flash-controls', () => flashControls())
- scope.$watch('pdfSrc', function(url) {
+ scope.$watch('pdfSrc', function (url) {
if (url) {
scope.loading = true
scope.loaded = false
@@ -88,35 +88,35 @@ export default App.directive('pdfng', ($timeout, localStorage) => ({
}
})
- scope.$on('loaded', function() {
+ scope.$on('loaded', function () {
scope.loaded = true
scope.progress = 100
- return $timeout(function() {
+ return $timeout(function () {
scope.loading = false
return delete scope.progress
}, 500)
})
- scope.fitToHeight = function() {
+ scope.fitToHeight = function () {
const scale = angular.copy(scope.scale)
scale.scaleMode = 'scale_mode_fit_height'
return (scope.scale = scale)
}
- scope.fitToWidth = function() {
+ scope.fitToWidth = function () {
const scale = angular.copy(scope.scale)
scale.scaleMode = 'scale_mode_fit_width'
return (scope.scale = scale)
}
- scope.zoomIn = function() {
+ scope.zoomIn = function () {
const scale = angular.copy(scope.scale)
scale.scaleMode = 'scale_mode_value'
scale.scale = scale.scale * 1.2
return (scope.scale = scale)
}
- scope.zoomOut = function() {
+ scope.zoomOut = function () {
const scale = angular.copy(scope.scale)
scale.scaleMode = 'scale_mode_value'
scale.scale = scale.scale / 1.2
@@ -125,13 +125,13 @@ export default App.directive('pdfng', ($timeout, localStorage) => ({
if (attrs.resizeOn != null) {
for (let event of Array.from(attrs.resizeOn.split(','))) {
- scope.$on(event, function(e) {})
+ scope.$on(event, function (e) {})
}
}
// console.log 'got a resize event', event, e
scope.$on('progress', (event, progress) =>
- scope.$apply(function() {
+ scope.$apply(function () {
if (scope.loaded) {
return
}
@@ -145,7 +145,7 @@ export default App.directive('pdfng', ($timeout, localStorage) => ({
})
)
- return scope.$on('$destroy', function() {})
+ return scope.$on('$destroy', function () {})
},
// console.log 'pdfjs destroy event'
diff --git a/services/web/frontend/js/ide/pdfng/directives/pdfPage.js b/services/web/frontend/js/ide/pdfng/directives/pdfPage.js
index d0208585a7..2344661990 100644
--- a/services/web/frontend/js/ide/pdfng/directives/pdfPage.js
+++ b/services/web/frontend/js/ide/pdfng/directives/pdfPage.js
@@ -33,7 +33,7 @@ export default App.directive(
const annotationsElement = $(element).find('.annotations-layer')
const highlightsElement = $(element).find('.highlights-layer')
- const updatePageSize = function(size) {
+ const updatePageSize = function (size) {
const h = Math.floor(size[0])
const w = Math.floor(size[1])
element.height(h)
@@ -61,15 +61,16 @@ export default App.directive(
} else {
// shouldn't get here - the default page size should now
// always be set before redraw is called
- var handler = scope.$watch('defaultPageSize', function(
- defaultPageSize
- ) {
- if (defaultPageSize == null) {
- return
+ var handler = scope.$watch(
+ 'defaultPageSize',
+ function (defaultPageSize) {
+ if (defaultPageSize == null) {
+ return
+ }
+ updatePageSize(defaultPageSize)
+ return handler()
}
- updatePageSize(defaultPageSize)
- return handler()
- })
+ )
}
}
@@ -81,15 +82,13 @@ export default App.directive(
ctrl.setPdfPosition(scope.page, scope.page.position)
}
- element.on('dblclick', function(e) {
- const offset = $(element)
- .find('.pdf-canvas')
- .offset()
+ element.on('dblclick', function (e) {
+ const offset = $(element).find('.pdf-canvas').offset()
const dx = e.pageX - offset.left
const dy = e.pageY - offset.top
return scope.document
.getPdfViewport(scope.page.pageNum)
- .then(function(viewport) {
+ .then(function (viewport) {
const pdfPoint = viewport.convertToPdfPoint(dx, dy)
const event = {
page: scope.page.pageNum,
@@ -104,7 +103,7 @@ export default App.directive(
highlights: highlightsElement
})
- scope.$on('pdf:highlights', function(event, highlights) {
+ scope.$on('pdf:highlights', function (event, highlights) {
let h
if (highlights == null) {
return
@@ -150,13 +149,13 @@ export default App.directive(
return result1
})()
)
- return (scope.timeoutHandler = $timeout(function() {
+ return (scope.timeoutHandler = $timeout(function () {
highlightsLayer.clearHighlights()
return (scope.timeoutHandler = null)
}, 1000))
})
- return scope.$on('$destroy', function() {
+ return scope.$on('$destroy', function () {
if (scope.timeoutHandler != null) {
$timeout.cancel(scope.timeoutHandler)
return highlightsLayer.clearHighlights()
diff --git a/services/web/frontend/js/ide/pdfng/directives/pdfRenderer.js b/services/web/frontend/js/ide/pdfng/directives/pdfRenderer.js
index db05437fb4..029296f1af 100644
--- a/services/web/frontend/js/ide/pdfng/directives/pdfRenderer.js
+++ b/services/web/frontend/js/ide/pdfng/directives/pdfRenderer.js
@@ -21,499 +21,499 @@ import App from '../../../base'
import PDFJS from './pdfJsLoader'
import { captureMessage } from '../../../infrastructure/error-reporter'
-export default App.factory('PDFRenderer', function(
- $timeout,
- pdfAnnotations,
- pdfTextLayer,
- pdfSpinner
-) {
- let PDFRenderer
- return (PDFRenderer = (function() {
- PDFRenderer = class PDFRenderer {
- static initClass() {
- this.prototype.JOB_QUEUE_INTERVAL = 25
- this.prototype.PAGE_LOAD_TIMEOUT = 60 * 1000
- this.prototype.INDICATOR_DELAY1 = 100 // time to delay before showing the indicator
- this.prototype.INDICATOR_DELAY2 = 250 // time until the indicator starts animating
- this.prototype.TEXTLAYER_TIMEOUT = 100
- }
-
- constructor(url, options) {
- // set up external character mappings - needed for Japanese etc
- this.url = url
- this.options = options
-
- this.scale = this.options.scale || 1
-
- let disableFontFace
- if (
- __guard__(
- window.location != null ? window.location.search : undefined,
- x => x.indexOf('disable-font-face=true')
- ) >= 0
- ) {
- disableFontFace = true
- } else {
- disableFontFace = false
+export default App.factory(
+ 'PDFRenderer',
+ function ($timeout, pdfAnnotations, pdfTextLayer, pdfSpinner) {
+ let PDFRenderer
+ return (PDFRenderer = (function () {
+ PDFRenderer = class PDFRenderer {
+ static initClass() {
+ this.prototype.JOB_QUEUE_INTERVAL = 25
+ this.prototype.PAGE_LOAD_TIMEOUT = 60 * 1000
+ this.prototype.INDICATOR_DELAY1 = 100 // time to delay before showing the indicator
+ this.prototype.INDICATOR_DELAY2 = 250 // time until the indicator starts animating
+ this.prototype.TEXTLAYER_TIMEOUT = 100
}
- this.pdfjs = PDFJS.getDocument({
- url: this.url,
- cMapUrl: window.pdfCMapsPath,
- cMapPacked: true,
- disableFontFace,
- // Enable fetching with Range headers to restrict individual
- // requests to 128kb.
- // To do this correctly we must:
- // a) disable auto-fetching of the whole file upfront
- // b) disable streaming (which in this context means streaming of
- // the response into memory). This isn't supported when using
- // Range headers, but shouldn't be a problem since we are already
- // limiting individual response size through chunked range
- // requests
- rangeChunkSize: 128 * 1024,
- disableAutoFetch: !!this.options.disableAutoFetch,
- disableStream: !!this.options.disableAutoFetch
- })
- this.pdfjs.onProgress = this.options.progressCallback
- this.document = this.pdfjs
- this.navigateFn = this.options.navigateFn
- this.spinner = new pdfSpinner()
- this.resetState()
- this.document.promise.then(pdfDocument => {
- return pdfDocument.getDownloadInfo().then(() => {
- return this.options.loadedCallback()
+
+ constructor(url, options) {
+ // set up external character mappings - needed for Japanese etc
+ this.url = url
+ this.options = options
+
+ this.scale = this.options.scale || 1
+
+ let disableFontFace
+ if (
+ __guard__(
+ window.location != null ? window.location.search : undefined,
+ x => x.indexOf('disable-font-face=true')
+ ) >= 0
+ ) {
+ disableFontFace = true
+ } else {
+ disableFontFace = false
+ }
+ this.pdfjs = PDFJS.getDocument({
+ url: this.url,
+ cMapUrl: window.pdfCMapsPath,
+ cMapPacked: true,
+ disableFontFace,
+ // Enable fetching with Range headers to restrict individual
+ // requests to 128kb.
+ // To do this correctly we must:
+ // a) disable auto-fetching of the whole file upfront
+ // b) disable streaming (which in this context means streaming of
+ // the response into memory). This isn't supported when using
+ // Range headers, but shouldn't be a problem since we are already
+ // limiting individual response size through chunked range
+ // requests
+ rangeChunkSize: 128 * 1024,
+ disableAutoFetch: !!this.options.disableAutoFetch,
+ disableStream: !!this.options.disableAutoFetch
+ })
+ this.pdfjs.onProgress = this.options.progressCallback
+ this.document = this.pdfjs
+ this.navigateFn = this.options.navigateFn
+ this.spinner = new pdfSpinner()
+ this.resetState()
+ this.document.promise.then(pdfDocument => {
+ return pdfDocument.getDownloadInfo().then(() => {
+ return this.options.loadedCallback()
+ })
+ })
+ this.errorCallback = this.options.errorCallback
+ this.pageSizeChangeCallback = this.options.pageSizeChangeCallback
+ this.pdfjs.promise.catch(exception => {
+ // error getting document
+ return this.errorCallback(exception)
})
- })
- this.errorCallback = this.options.errorCallback
- this.pageSizeChangeCallback = this.options.pageSizeChangeCallback
- this.pdfjs.promise.catch(exception => {
- // error getting document
- return this.errorCallback(exception)
- })
- }
-
- resetState() {
- this.renderQueue = []
- if (this.queueTimer != null) {
- clearTimeout(this.queueTimer)
}
- // clear any existing timers, render tasks
- for (let timer of Array.from(this.spinTimer || [])) {
- clearTimeout(timer)
- }
- for (let page of Array.from(this.pageState || [])) {
- __guard__(page != null ? page.loadTask : undefined, x => x.cancel())
- __guard__(page != null ? page.renderTask : undefined, x1 =>
- x1.cancel()
- )
- }
- // initialise/reset the state
- this.pageState = []
- this.spinTimer = [] // timers for starting the spinners (to avoid jitter)
- this.spinTimerDone = [] // array of pages where the spinner has activated
- return (this.jobs = 0)
- }
- getNumPages() {
- return this.document.promise.then(pdfDocument => pdfDocument.numPages)
- }
-
- getPage(pageNum) {
- return this.document.promise.then(pdfDocument =>
- pdfDocument.getPage(pageNum)
- )
- }
-
- getPdfViewport(pageNum, scale) {
- if (scale == null) {
- ;({ scale } = this)
- }
- return this.document.promise.then(pdfDocument => {
- return pdfDocument.getPage(pageNum).then(
- function(page) {
- let viewport
- return (viewport = page.getViewport({ scale: scale }))
- },
- error => {
- return typeof this.errorCallback === 'function'
- ? this.errorCallback(error)
- : undefined
- }
- )
- })
- }
-
- getDestinations() {
- return this.document.promise.then(pdfDocument =>
- pdfDocument.getDestinations()
- )
- }
-
- getDestination(dest) {
- return this.document.promise.then(
- pdfDocument => pdfDocument.getDestination(dest),
- error => {
- return typeof this.errorCallback === 'function'
- ? this.errorCallback(error)
- : undefined
+ resetState() {
+ this.renderQueue = []
+ if (this.queueTimer != null) {
+ clearTimeout(this.queueTimer)
}
- )
- }
+ // clear any existing timers, render tasks
+ for (let timer of Array.from(this.spinTimer || [])) {
+ clearTimeout(timer)
+ }
+ for (let page of Array.from(this.pageState || [])) {
+ __guard__(page != null ? page.loadTask : undefined, x => x.cancel())
+ __guard__(page != null ? page.renderTask : undefined, x1 =>
+ x1.cancel()
+ )
+ }
+ // initialise/reset the state
+ this.pageState = []
+ this.spinTimer = [] // timers for starting the spinners (to avoid jitter)
+ this.spinTimerDone = [] // array of pages where the spinner has activated
+ return (this.jobs = 0)
+ }
- getPageIndex(ref) {
- return this.document.promise.then(pdfDocument => {
- return pdfDocument.getPageIndex(ref).then(
- idx => idx,
+ getNumPages() {
+ return this.document.promise.then(pdfDocument => pdfDocument.numPages)
+ }
+
+ getPage(pageNum) {
+ return this.document.promise.then(pdfDocument =>
+ pdfDocument.getPage(pageNum)
+ )
+ }
+
+ getPdfViewport(pageNum, scale) {
+ if (scale == null) {
+ ;({ scale } = this)
+ }
+ return this.document.promise.then(pdfDocument => {
+ return pdfDocument.getPage(pageNum).then(
+ function (page) {
+ let viewport
+ return (viewport = page.getViewport({ scale: scale }))
+ },
+ error => {
+ return typeof this.errorCallback === 'function'
+ ? this.errorCallback(error)
+ : undefined
+ }
+ )
+ })
+ }
+
+ getDestinations() {
+ return this.document.promise.then(pdfDocument =>
+ pdfDocument.getDestinations()
+ )
+ }
+
+ getDestination(dest) {
+ return this.document.promise.then(
+ pdfDocument => pdfDocument.getDestination(dest),
error => {
return typeof this.errorCallback === 'function'
? this.errorCallback(error)
: undefined
}
)
- })
- }
-
- getScale() {
- return this.scale
- }
-
- setScale(scale) {
- this.scale = scale
- return this.resetState()
- }
-
- triggerRenderQueue(interval) {
- if (interval == null) {
- interval = this.JOB_QUEUE_INTERVAL
}
- if (this.queueTimer != null) {
- clearTimeout(this.queueTimer)
+
+ getPageIndex(ref) {
+ return this.document.promise.then(pdfDocument => {
+ return pdfDocument.getPageIndex(ref).then(
+ idx => idx,
+ error => {
+ return typeof this.errorCallback === 'function'
+ ? this.errorCallback(error)
+ : undefined
+ }
+ )
+ })
}
- return (this.queueTimer = setTimeout(() => {
- this.queueTimer = null
+
+ getScale() {
+ return this.scale
+ }
+
+ setScale(scale) {
+ this.scale = scale
+ return this.resetState()
+ }
+
+ triggerRenderQueue(interval) {
+ if (interval == null) {
+ interval = this.JOB_QUEUE_INTERVAL
+ }
+ if (this.queueTimer != null) {
+ clearTimeout(this.queueTimer)
+ }
+ return (this.queueTimer = setTimeout(() => {
+ this.queueTimer = null
+ return this.processRenderQueue()
+ }, interval))
+ }
+
+ removeCompletedJob(pagenum) {
+ this.jobs = this.jobs - 1
+ return this.triggerRenderQueue(0)
+ }
+
+ renderPages(pages) {
+ if (this.shuttingDown) {
+ return
+ }
+ this.renderQueue = Array.from(pages).map(page => ({
+ element: page.elementChildren,
+ pagenum: page.pageNum
+ }))
+ return this.triggerRenderQueue()
+ }
+
+ renderPage(page) {
+ if (this.shuttingDown) {
+ return
+ }
+ const current = {
+ element: page.elementChildren,
+ pagenum: page.pageNum
+ }
+ this.renderQueue.push(current)
return this.processRenderQueue()
- }, interval))
- }
-
- removeCompletedJob(pagenum) {
- this.jobs = this.jobs - 1
- return this.triggerRenderQueue(0)
- }
-
- renderPages(pages) {
- if (this.shuttingDown) {
- return
}
- this.renderQueue = Array.from(pages).map(page => ({
- element: page.elementChildren,
- pagenum: page.pageNum
- }))
- return this.triggerRenderQueue()
- }
- renderPage(page) {
- if (this.shuttingDown) {
- return
+ getPageDetails(page) {
+ return [page.element.canvas, page.pagenum]
}
- const current = {
- element: page.elementChildren,
- pagenum: page.pageNum
- }
- this.renderQueue.push(current)
- return this.processRenderQueue()
- }
- getPageDetails(page) {
- return [page.element.canvas, page.pagenum]
- }
+ // handle the loading indicators for each page
- // handle the loading indicators for each page
-
- startIndicators() {
- // make an array of the pages in the queue
- this.queuedPages = []
- for (var page of Array.from(this.renderQueue)) {
- this.queuedPages[page.pagenum] = true
- }
- // clear any unfinished spinner timers on pages that aren't in the queue any more
- for (let pagenum in this.spinTimer) {
- if (!this.queuedPages[pagenum]) {
- clearTimeout(this.spinTimer[pagenum])
- delete this.spinTimer[pagenum]
+ startIndicators() {
+ // make an array of the pages in the queue
+ this.queuedPages = []
+ for (var page of Array.from(this.renderQueue)) {
+ this.queuedPages[page.pagenum] = true
}
- }
- // add indicators for any new pages in the current queue
- return (() => {
- const result = []
- for (page of Array.from(this.renderQueue)) {
- if (
- !this.spinTimer[page.pagenum] &&
- !this.spinTimerDone[page.pagenum]
- ) {
- result.push(this.startIndicator(page))
+ // clear any unfinished spinner timers on pages that aren't in the queue any more
+ for (let pagenum in this.spinTimer) {
+ if (!this.queuedPages[pagenum]) {
+ clearTimeout(this.spinTimer[pagenum])
+ delete this.spinTimer[pagenum]
}
}
- return result
- })()
- }
-
- startIndicator(page) {
- const [canvas, pagenum] = Array.from(this.getPageDetails(page))
- canvas.addClass('pdfng-loading')
- return (this.spinTimer[pagenum] = setTimeout(() => {
- for (let queuedPage of Array.from(this.renderQueue)) {
- if (pagenum === queuedPage.pagenum) {
- this.spinner.add(canvas, { static: true })
- this.spinTimerDone[pagenum] = true
- break
+ // add indicators for any new pages in the current queue
+ return (() => {
+ const result = []
+ for (page of Array.from(this.renderQueue)) {
+ if (
+ !this.spinTimer[page.pagenum] &&
+ !this.spinTimerDone[page.pagenum]
+ ) {
+ result.push(this.startIndicator(page))
+ }
}
- }
- return delete this.spinTimer[pagenum]
- }, this.INDICATOR_DELAY1))
- }
+ return result
+ })()
+ }
- updateIndicator(page) {
- const [canvas, pagenum] = Array.from(this.getPageDetails(page))
- // did the spinner insert itself already?
- if (this.spinTimerDone[pagenum]) {
+ startIndicator(page) {
+ const [canvas, pagenum] = Array.from(this.getPageDetails(page))
+ canvas.addClass('pdfng-loading')
return (this.spinTimer[pagenum] = setTimeout(() => {
- this.spinner.start(canvas)
+ for (let queuedPage of Array.from(this.renderQueue)) {
+ if (pagenum === queuedPage.pagenum) {
+ this.spinner.add(canvas, { static: true })
+ this.spinTimerDone[pagenum] = true
+ break
+ }
+ }
return delete this.spinTimer[pagenum]
- }, this.INDICATOR_DELAY2))
- } else {
- // stop the existing spin timer
- clearTimeout(this.spinTimer[pagenum])
- // start a new one which will also start spinning
- return (this.spinTimer[pagenum] = setTimeout(() => {
- this.spinner.add(canvas, { static: true })
- this.spinTimerDone[pagenum] = true
+ }, this.INDICATOR_DELAY1))
+ }
+
+ updateIndicator(page) {
+ const [canvas, pagenum] = Array.from(this.getPageDetails(page))
+ // did the spinner insert itself already?
+ if (this.spinTimerDone[pagenum]) {
return (this.spinTimer[pagenum] = setTimeout(() => {
this.spinner.start(canvas)
return delete this.spinTimer[pagenum]
}, this.INDICATOR_DELAY2))
- }, this.INDICATOR_DELAY1))
- }
- }
-
- clearIndicator(page) {
- const [canvas, pagenum] = Array.from(this.getPageDetails(page))
- this.spinner.stop(canvas)
- clearTimeout(this.spinTimer[pagenum])
- delete this.spinTimer[pagenum]
- return (this.spinTimerDone[pagenum] = true)
- }
-
- // handle the queue of pages to be rendered
-
- processRenderQueue() {
- let pageState
- if (this.shuttingDown) {
- return
- }
- // mark all pages in the queue as loading
- this.startIndicators()
- // bail out if there is already a render job running
- if (this.jobs > 0) {
- return
- }
- // take the first page in the queue
- let page = this.renderQueue.shift()
- // check if it is in action already
- while (page != null && this.pageState[page.pagenum] != null) {
- page = this.renderQueue.shift()
- }
- if (page == null) {
- return
- }
- const [element, pagenum] = Array.from([page.element, page.pagenum])
- this.jobs = this.jobs + 1
-
- // update the spinner to make it spinning (signifies loading has begun)
- this.updateIndicator(page)
-
- let timedOut = false
- const timer = $timeout(() => {
- // page load timed out
- if (loadTask.cancelled) {
- return
- } // return from cancelled page load
- captureMessage(
- `pdfng page load timed out after ${this.PAGE_LOAD_TIMEOUT}ms`
- )
-
- timedOut = true
- this.clearIndicator(page)
- // @jobs = @jobs - 1
- // @triggerRenderQueue(0)
- return typeof this.errorCallback === 'function'
- ? this.errorCallback('timeout')
- : undefined
- }, this.PAGE_LOAD_TIMEOUT)
-
- var loadTask = this.getPage(pagenum)
-
- loadTask.cancel = function() {
- return (this.cancelled = true)
- }
-
- this.pageState[pagenum] = pageState = { loadTask }
-
- return loadTask
- .then(pageObject => {
- // page load success
- $timeout.cancel(timer)
- if (loadTask.cancelled) {
- return
- } // return from cancelled page load
- pageState.renderTask = this.doRender(element, pagenum, pageObject)
- return pageState.renderTask.promise.then(
- () => {
- // render task success
- this.clearIndicator(page)
- pageState.complete = true
- delete pageState.renderTask
- return this.removeCompletedJob(pagenum)
- },
- () => {
- // render task failed
- // could display an error icon
- pageState.complete = false
- delete pageState.renderTask
- return this.removeCompletedJob(pagenum)
- }
- )
- })
- .catch(error => {
- // page load error
- $timeout.cancel(timer)
- return this.clearIndicator(page)
- })
- }
-
- doRender(element, pagenum, page) {
- const self = this
- const { scale } = this
-
- if (scale == null) {
- // scale is undefined, returning
- return
- }
-
- const canvas = $('')
- // In Windows+IE we must have the canvas in the DOM during
- // rendering to see the fonts defined in the DOM. If we try to
- // render 'offscreen' then all the text will be sans-serif.
- // Previously we rendered offscreen and added in the canvas
- // when rendering was complete.
- element.canvas.replaceWith(canvas)
-
- const viewport = page.getViewport({ scale: scale })
-
- const devicePixelRatio = window.devicePixelRatio || 1
-
- const ctx = canvas[0].getContext('2d')
- const backingStoreRatio =
- ctx.webkitBackingStorePixelRatio ||
- ctx.mozBackingStorePixelRatio ||
- ctx.msBackingStorePixelRatio ||
- ctx.oBackingStorePixelRatio ||
- ctx.backingStorePixelRatio ||
- 1
- const pixelRatio = devicePixelRatio / backingStoreRatio
-
- const scaledWidth = (Math.floor(viewport.width) * pixelRatio) | 0
- const scaledHeight = (Math.floor(viewport.height) * pixelRatio) | 0
-
- const newWidth = Math.floor(viewport.width)
- const newHeight = Math.floor(viewport.height)
-
- canvas[0].height = scaledHeight
- canvas[0].width = scaledWidth
-
- canvas.height(newHeight + 'px')
- canvas.width(newWidth + 'px')
-
- const oldHeight = element.canvas.height()
- const oldWidth = element.canvas.width()
- if (newHeight !== oldHeight || newWidth !== oldWidth) {
- element.canvas.height(newHeight + 'px')
- element.canvas.width(newWidth + 'px')
- element.container.height(newHeight + 'px')
- element.container.width(newWidth + 'px')
- if (typeof this.pageSizeChangeCallback === 'function') {
- this.pageSizeChangeCallback(pagenum, newHeight - oldHeight)
+ } else {
+ // stop the existing spin timer
+ clearTimeout(this.spinTimer[pagenum])
+ // start a new one which will also start spinning
+ return (this.spinTimer[pagenum] = setTimeout(() => {
+ this.spinner.add(canvas, { static: true })
+ this.spinTimerDone[pagenum] = true
+ return (this.spinTimer[pagenum] = setTimeout(() => {
+ this.spinner.start(canvas)
+ return delete this.spinTimer[pagenum]
+ }, this.INDICATOR_DELAY2))
+ }, this.INDICATOR_DELAY1))
}
}
- const textLayer = new pdfTextLayer({
- textLayerDiv: element.text[0],
- viewport,
- renderer: PDFJS.renderTextLayer
- })
+ clearIndicator(page) {
+ const [canvas, pagenum] = Array.from(this.getPageDetails(page))
+ this.spinner.stop(canvas)
+ clearTimeout(this.spinTimer[pagenum])
+ delete this.spinTimer[pagenum]
+ return (this.spinTimerDone[pagenum] = true)
+ }
- const annotationsLayer = new pdfAnnotations({
- annotations: element.annotations[0],
- viewport,
- navigateFn: this.navigateFn
- })
+ // handle the queue of pages to be rendered
- const result = page.render({
- canvasContext: ctx,
- viewport,
- transform: [pixelRatio, 0, 0, pixelRatio, 0, 0]
- })
+ processRenderQueue() {
+ let pageState
+ if (this.shuttingDown) {
+ return
+ }
+ // mark all pages in the queue as loading
+ this.startIndicators()
+ // bail out if there is already a render job running
+ if (this.jobs > 0) {
+ return
+ }
+ // take the first page in the queue
+ let page = this.renderQueue.shift()
+ // check if it is in action already
+ while (page != null && this.pageState[page.pagenum] != null) {
+ page = this.renderQueue.shift()
+ }
+ if (page == null) {
+ return
+ }
+ const [element, pagenum] = Array.from([page.element, page.pagenum])
+ this.jobs = this.jobs + 1
- const textLayerTimeout = this.TEXTLAYER_TIMEOUT
+ // update the spinner to make it spinning (signifies loading has begun)
+ this.updateIndicator(page)
- result.promise
- .then(function() {
- // page render success
- canvas.removeClass('pdfng-rendering')
- page.getTextContent({ normalizeWhitespace: true }).then(
- function(textContent) {
- textLayer.setTextContent(textContent)
- return textLayer.render(textLayerTimeout)
- },
- error =>
- typeof self.errorCallback === 'function'
- ? self.errorCallback(error)
- : undefined
+ let timedOut = false
+ const timer = $timeout(() => {
+ // page load timed out
+ if (loadTask.cancelled) {
+ return
+ } // return from cancelled page load
+ captureMessage(
+ `pdfng page load timed out after ${this.PAGE_LOAD_TIMEOUT}ms`
)
- return page.getAnnotations().then(
- annotations => annotationsLayer.setAnnotations(annotations),
- error =>
- typeof self.errorCallback === 'function'
- ? self.errorCallback(error)
- : undefined
- )
- })
- .catch(function(error) {
- // page render failed
- if (error.name === 'RenderingCancelledException') {
- // do nothing when cancelled
- } else {
- return typeof self.errorCallback === 'function'
- ? self.errorCallback(error)
- : undefined
+
+ timedOut = true
+ this.clearIndicator(page)
+ // @jobs = @jobs - 1
+ // @triggerRenderQueue(0)
+ return typeof this.errorCallback === 'function'
+ ? this.errorCallback('timeout')
+ : undefined
+ }, this.PAGE_LOAD_TIMEOUT)
+
+ var loadTask = this.getPage(pagenum)
+
+ loadTask.cancel = function () {
+ return (this.cancelled = true)
+ }
+
+ this.pageState[pagenum] = pageState = { loadTask }
+
+ return loadTask
+ .then(pageObject => {
+ // page load success
+ $timeout.cancel(timer)
+ if (loadTask.cancelled) {
+ return
+ } // return from cancelled page load
+ pageState.renderTask = this.doRender(element, pagenum, pageObject)
+ return pageState.renderTask.promise.then(
+ () => {
+ // render task success
+ this.clearIndicator(page)
+ pageState.complete = true
+ delete pageState.renderTask
+ return this.removeCompletedJob(pagenum)
+ },
+ () => {
+ // render task failed
+ // could display an error icon
+ pageState.complete = false
+ delete pageState.renderTask
+ return this.removeCompletedJob(pagenum)
+ }
+ )
+ })
+ .catch(error => {
+ // page load error
+ $timeout.cancel(timer)
+ return this.clearIndicator(page)
+ })
+ }
+
+ doRender(element, pagenum, page) {
+ const self = this
+ const { scale } = this
+
+ if (scale == null) {
+ // scale is undefined, returning
+ return
+ }
+
+ const canvas = $(
+ ''
+ )
+ // In Windows+IE we must have the canvas in the DOM during
+ // rendering to see the fonts defined in the DOM. If we try to
+ // render 'offscreen' then all the text will be sans-serif.
+ // Previously we rendered offscreen and added in the canvas
+ // when rendering was complete.
+ element.canvas.replaceWith(canvas)
+
+ const viewport = page.getViewport({ scale: scale })
+
+ const devicePixelRatio = window.devicePixelRatio || 1
+
+ const ctx = canvas[0].getContext('2d')
+ const backingStoreRatio =
+ ctx.webkitBackingStorePixelRatio ||
+ ctx.mozBackingStorePixelRatio ||
+ ctx.msBackingStorePixelRatio ||
+ ctx.oBackingStorePixelRatio ||
+ ctx.backingStorePixelRatio ||
+ 1
+ const pixelRatio = devicePixelRatio / backingStoreRatio
+
+ const scaledWidth = (Math.floor(viewport.width) * pixelRatio) | 0
+ const scaledHeight = (Math.floor(viewport.height) * pixelRatio) | 0
+
+ const newWidth = Math.floor(viewport.width)
+ const newHeight = Math.floor(viewport.height)
+
+ canvas[0].height = scaledHeight
+ canvas[0].width = scaledWidth
+
+ canvas.height(newHeight + 'px')
+ canvas.width(newWidth + 'px')
+
+ const oldHeight = element.canvas.height()
+ const oldWidth = element.canvas.width()
+ if (newHeight !== oldHeight || newWidth !== oldWidth) {
+ element.canvas.height(newHeight + 'px')
+ element.canvas.width(newWidth + 'px')
+ element.container.height(newHeight + 'px')
+ element.container.width(newWidth + 'px')
+ if (typeof this.pageSizeChangeCallback === 'function') {
+ this.pageSizeChangeCallback(pagenum, newHeight - oldHeight)
}
+ }
+
+ const textLayer = new pdfTextLayer({
+ textLayerDiv: element.text[0],
+ viewport,
+ renderer: PDFJS.renderTextLayer
})
- return result
- }
+ const annotationsLayer = new pdfAnnotations({
+ annotations: element.annotations[0],
+ viewport,
+ navigateFn: this.navigateFn
+ })
- destroy() {
- this.shuttingDown = true
- this.resetState()
- return this.pdfjs.promise.then(function(document) {
- document.cleanup()
- return document.destroy()
- })
+ const result = page.render({
+ canvasContext: ctx,
+ viewport,
+ transform: [pixelRatio, 0, 0, pixelRatio, 0, 0]
+ })
+
+ const textLayerTimeout = this.TEXTLAYER_TIMEOUT
+
+ result.promise
+ .then(function () {
+ // page render success
+ canvas.removeClass('pdfng-rendering')
+ page.getTextContent({ normalizeWhitespace: true }).then(
+ function (textContent) {
+ textLayer.setTextContent(textContent)
+ return textLayer.render(textLayerTimeout)
+ },
+ error =>
+ typeof self.errorCallback === 'function'
+ ? self.errorCallback(error)
+ : undefined
+ )
+ return page.getAnnotations().then(
+ annotations => annotationsLayer.setAnnotations(annotations),
+ error =>
+ typeof self.errorCallback === 'function'
+ ? self.errorCallback(error)
+ : undefined
+ )
+ })
+ .catch(function (error) {
+ // page render failed
+ if (error.name === 'RenderingCancelledException') {
+ // do nothing when cancelled
+ } else {
+ return typeof self.errorCallback === 'function'
+ ? self.errorCallback(error)
+ : undefined
+ }
+ })
+
+ return result
+ }
+
+ destroy() {
+ this.shuttingDown = true
+ this.resetState()
+ return this.pdfjs.promise.then(function (document) {
+ document.cleanup()
+ return document.destroy()
+ })
+ }
}
- }
- PDFRenderer.initClass()
- return PDFRenderer
- })())
-})
+ PDFRenderer.initClass()
+ return PDFRenderer
+ })())
+ }
+)
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
diff --git a/services/web/frontend/js/ide/pdfng/directives/pdfSpinner.js b/services/web/frontend/js/ide/pdfng/directives/pdfSpinner.js
index 9f09d957fd..f5ec6dab4f 100644
--- a/services/web/frontend/js/ide/pdfng/directives/pdfSpinner.js
+++ b/services/web/frontend/js/ide/pdfng/directives/pdfSpinner.js
@@ -13,7 +13,7 @@
*/
import App from '../../../base'
-export default App.factory('pdfSpinner', function() {
+export default App.factory('pdfSpinner', function () {
let pdfSpinner
return (pdfSpinner = class pdfSpinner {
constructor() {}
diff --git a/services/web/frontend/js/ide/pdfng/directives/pdfTextLayer.js b/services/web/frontend/js/ide/pdfng/directives/pdfTextLayer.js
index 1dcde4f182..1c0945dfed 100644
--- a/services/web/frontend/js/ide/pdfng/directives/pdfTextLayer.js
+++ b/services/web/frontend/js/ide/pdfng/directives/pdfTextLayer.js
@@ -15,7 +15,7 @@ import App from '../../../base'
// uses the PDFJS text layer renderer to provide invisible overlayed
// text for searching
-App.factory('pdfTextLayer', function() {
+App.factory('pdfTextLayer', function () {
let pdfTextLayer
return (pdfTextLayer = class pdfTextLayer {
constructor(options) {
@@ -54,7 +54,7 @@ App.factory('pdfTextLayer', function() {
return (this.renderingDone = true)
}
- const textLayerFailure = function() {
+ const textLayerFailure = function () {
// canceled or failed to render text layer -- skipping errors
}
diff --git a/services/web/frontend/js/ide/pdfng/directives/pdfViewer.js b/services/web/frontend/js/ide/pdfng/directives/pdfViewer.js
index 4daa7438ec..6decaff155 100644
--- a/services/web/frontend/js/ide/pdfng/directives/pdfViewer.js
+++ b/services/web/frontend/js/ide/pdfng/directives/pdfViewer.js
@@ -26,305 +26,297 @@ import pdfHighlights from './pdfHighlights'
import pdfRenderer from './pdfRenderer'
import pdfPage from './pdfPage'
import pdfSpinner from './pdfSpinner'
-App.controller('pdfViewerController', function(
- $scope,
- $q,
- $timeout,
- PDFRenderer,
- $element,
- pdfHighlights,
- pdfSpinner
-) {
- this.load = function() {
- // $scope.pages = []
+App.controller(
+ 'pdfViewerController',
+ function (
+ $scope,
+ $q,
+ $timeout,
+ PDFRenderer,
+ $element,
+ pdfHighlights,
+ pdfSpinner
+ ) {
+ this.load = function () {
+ // $scope.pages = []
- // Ensure previous document is torn down before loading the next one (to
- // prevent race conditions)
- const documentTearDown =
- $scope.document != null ? $scope.document.destroy() : Promise.resolve()
+ // Ensure previous document is torn down before loading the next one (to
+ // prevent race conditions)
+ const documentTearDown =
+ $scope.document != null ? $scope.document.destroy() : Promise.resolve()
- return documentTearDown.then(() => {
- $scope.loadCount = $scope.loadCount != null ? $scope.loadCount + 1 : 1
- // TODO need a proper url manipulation library to add to query string
- let url = $scope.pdfSrc
- // add 'pdfng=true' to show that we are using the angular pdfjs viewer
- const queryStringExists = /\?/.test(url)
- url = url + (!queryStringExists ? '?' : '&') + 'pdfng=true'
- // for isolated compiles, load the pdf on-demand because nobody will overwrite it
- const onDemandLoading = true
- $scope.document = new PDFRenderer(url, {
- scale: 1,
- disableAutoFetch: onDemandLoading ? true : undefined,
- navigateFn(ref) {
- // this function captures clicks on the annotation links
- $scope.navigateTo = ref
- return $scope.$apply()
- },
- progressCallback(progress) {
- return $scope.$emit('progress', progress)
- },
- loadedCallback() {
- return $scope.$emit('loaded')
- },
- errorCallback(error) {
- // MissingPDFException is "expected" as the pdf file can be on a
- // CLSI server that has been cycled out.
- // Currently, there is NO error handling to handle this situation,
- // but we plan to add this in the future
- // (https://github.com/overleaf/issues/issues/2985) and this error
- // is causing noise in Sentry so ignore it
- if (!error || error.name !== 'MissingPDFException') {
- captureMessage(`pdfng error ${error}`)
+ return documentTearDown.then(() => {
+ $scope.loadCount = $scope.loadCount != null ? $scope.loadCount + 1 : 1
+ // TODO need a proper url manipulation library to add to query string
+ let url = $scope.pdfSrc
+ // add 'pdfng=true' to show that we are using the angular pdfjs viewer
+ const queryStringExists = /\?/.test(url)
+ url = url + (!queryStringExists ? '?' : '&') + 'pdfng=true'
+ // for isolated compiles, load the pdf on-demand because nobody will overwrite it
+ const onDemandLoading = true
+ $scope.document = new PDFRenderer(url, {
+ scale: 1,
+ disableAutoFetch: onDemandLoading ? true : undefined,
+ navigateFn(ref) {
+ // this function captures clicks on the annotation links
+ $scope.navigateTo = ref
+ return $scope.$apply()
+ },
+ progressCallback(progress) {
+ return $scope.$emit('progress', progress)
+ },
+ loadedCallback() {
+ return $scope.$emit('loaded')
+ },
+ errorCallback(error) {
+ // MissingPDFException is "expected" as the pdf file can be on a
+ // CLSI server that has been cycled out.
+ // Currently, there is NO error handling to handle this situation,
+ // but we plan to add this in the future
+ // (https://github.com/overleaf/issues/issues/2985) and this error
+ // is causing noise in Sentry so ignore it
+ if (!error || error.name !== 'MissingPDFException') {
+ captureMessage(`pdfng error ${error}`)
+ }
+ return $scope.$emit('pdf:error', error)
+ },
+ pageSizeChangeCallback(pageNum, deltaH) {
+ return $scope.$broadcast('pdf:page:size-change', pageNum, deltaH)
}
- return $scope.$emit('pdf:error', error)
- },
- pageSizeChangeCallback(pageNum, deltaH) {
- return $scope.$broadcast('pdf:page:size-change', pageNum, deltaH)
- }
- })
+ })
- // we will have all the main information needed to start display
- // after the following promise is resolved
- $scope.loaded = $q
- .all({
- numPages: $scope.document.getNumPages(),
- // get size of first page as default @ scale 1
- pdfViewport: $scope.document.getPdfViewport(1, 1)
+ // we will have all the main information needed to start display
+ // after the following promise is resolved
+ $scope.loaded = $q
+ .all({
+ numPages: $scope.document.getNumPages(),
+ // get size of first page as default @ scale 1
+ pdfViewport: $scope.document.getPdfViewport(1, 1)
+ })
+ .then(function (result) {
+ $scope.pdfViewport = result.pdfViewport
+ $scope.pdfPageSize = [
+ result.pdfViewport.height,
+ result.pdfViewport.width
+ ]
+ // console.log 'resolved q.all, page size is', result
+ $scope.$emit('loaded')
+ return ($scope.numPages = result.numPages)
+ })
+ .catch(function (error) {
+ $scope.$emit('pdf:error', error)
+ return $q.reject(error)
+ })
+
+ return $scope.loaded
+ })
+ }
+
+ this.setScale = (scale, containerHeight, containerWidth) =>
+ $scope.loaded
+ .then(function () {
+ let numScale
+ if (scale == null) {
+ scale = {}
+ }
+ if (containerHeight === 0 || containerWidth === 0) {
+ numScale = 1
+ } else if (scale.scaleMode === 'scale_mode_fit_width') {
+ // TODO make this dynamic
+ numScale = (containerWidth - 40) / $scope.pdfPageSize[1]
+ } else if (scale.scaleMode === 'scale_mode_fit_height') {
+ // TODO magic numbers for jquery ui layout
+ numScale = (containerHeight - 20) / $scope.pdfPageSize[0]
+ } else if (scale.scaleMode === 'scale_mode_value') {
+ numScale = scale.scale
+ } else if (scale.scaleMode === 'scale_mode_auto') {
+ // TODO
+ } else {
+ scale.scaleMode = 'scale_mode_fit_width'
+ numScale = (containerWidth - 40) / $scope.pdfPageSize[1]
+ }
+ // TODO
+ $scope.scale.scale = numScale
+ $scope.document.setScale(numScale)
+ return ($scope.defaultPageSize = [
+ numScale * $scope.pdfPageSize[0],
+ numScale * $scope.pdfPageSize[1]
+ ])
})
- .then(function(result) {
- $scope.pdfViewport = result.pdfViewport
- $scope.pdfPageSize = [
- result.pdfViewport.height,
- result.pdfViewport.width
- ]
- // console.log 'resolved q.all, page size is', result
- $scope.$emit('loaded')
- return ($scope.numPages = result.numPages)
- })
- .catch(function(error) {
+ // console.log 'in setScale result', $scope.scale.scale, $scope.defaultPageSize
+ .catch(function (error) {
$scope.$emit('pdf:error', error)
return $q.reject(error)
})
- return $scope.loaded
- })
- }
-
- this.setScale = (scale, containerHeight, containerWidth) =>
- $scope.loaded
- .then(function() {
- let numScale
- if (scale == null) {
- scale = {}
+ this.redraw = function (position) {
+ // console.log 'in redraw'
+ // console.log 'reseting pages array for', $scope.numPages
+ $scope.pages = __range__(0, $scope.numPages - 1, true).map(i => ({
+ pageNum: i + 1
+ }))
+ if (position != null && position.page != null) {
+ // console.log 'position is', position.page, position.offset
+ // console.log 'setting current page', position.page
+ let pagenum = position.page
+ if (pagenum > $scope.numPages - 1) {
+ pagenum = $scope.numPages - 1
}
- if (containerHeight === 0 || containerWidth === 0) {
- numScale = 1
- } else if (scale.scaleMode === 'scale_mode_fit_width') {
- // TODO make this dynamic
- numScale = (containerWidth - 40) / $scope.pdfPageSize[1]
- } else if (scale.scaleMode === 'scale_mode_fit_height') {
- // TODO magic numbers for jquery ui layout
- numScale = (containerHeight - 20) / $scope.pdfPageSize[0]
- } else if (scale.scaleMode === 'scale_mode_value') {
- numScale = scale.scale
- } else if (scale.scaleMode === 'scale_mode_auto') {
- // TODO
- } else {
- scale.scaleMode = 'scale_mode_fit_width'
- numScale = (containerWidth - 40) / $scope.pdfPageSize[1]
+ $scope.pages[pagenum].current = true
+ return ($scope.pages[pagenum].position = position)
+ }
+ }
+
+ this.zoomIn = function () {
+ // console.log 'zoom in'
+ const newScale = $scope.scale.scale * 1.2
+ return ($scope.forceScale = {
+ scaleMode: 'scale_mode_value',
+ scale: newScale
+ })
+ }
+
+ this.zoomOut = function () {
+ // console.log 'zoom out'
+ const newScale = $scope.scale.scale / 1.2
+ return ($scope.forceScale = {
+ scaleMode: 'scale_mode_value',
+ scale: newScale
+ })
+ }
+
+ this.fitWidth = () =>
+ // console.log 'fit width'
+ ($scope.forceScale = { scaleMode: 'scale_mode_fit_width' })
+
+ this.fitHeight = () =>
+ // console.log 'fit height'
+ ($scope.forceScale = { scaleMode: 'scale_mode_fit_height' })
+
+ this.checkPosition = () =>
+ // console.log 'check position'
+ ($scope.forceCheck = ($scope.forceCheck || 0) + 1)
+
+ this.showRandomHighlights = () =>
+ // console.log 'show highlights'
+ ($scope.highlights = [
+ {
+ page: 3,
+ h: 100,
+ v: 100,
+ height: 30,
+ width: 200
+ }
+ ])
+
+ // we work with (pagenumber, % of height down page from top)
+ // pdfListView works with (pagenumber, vertical position up page from
+ // bottom measured in pts)
+
+ this.getPdfPosition = function () {
+ // console.log 'in getPdfPosition'
+ let canvasOffset, pdfOffset, viewport
+ let topPageIdx = 0
+ let topPage = $scope.pages[0]
+ // find first visible page
+ const visible = $scope.pages.some(function (page, i) {
+ if (page.visible) {
+ let ref
+ return ([topPageIdx, topPage] = Array.from((ref = [i, page]))), ref
}
- // TODO
- $scope.scale.scale = numScale
- $scope.document.setScale(numScale)
- return ($scope.defaultPageSize = [
- numScale * $scope.pdfPageSize[0],
- numScale * $scope.pdfPageSize[1]
- ])
})
- // console.log 'in setScale result', $scope.scale.scale, $scope.defaultPageSize
- .catch(function(error) {
- $scope.$emit('pdf:error', error)
- return $q.reject(error)
- })
-
- this.redraw = function(position) {
- // console.log 'in redraw'
- // console.log 'reseting pages array for', $scope.numPages
- $scope.pages = __range__(0, $scope.numPages - 1, true).map(i => ({
- pageNum: i + 1
- }))
- if (position != null && position.page != null) {
- // console.log 'position is', position.page, position.offset
- // console.log 'setting current page', position.page
- let pagenum = position.page
- if (pagenum > $scope.numPages - 1) {
- pagenum = $scope.numPages - 1
+ if (visible && topPage.element != null) {
+ // console.log 'found it', topPageIdx
+ } else {
+ // console.log 'CANNOT FIND TOP PAGE'
+ return
}
- $scope.pages[pagenum].current = true
- return ($scope.pages[pagenum].position = position)
- }
- }
- this.zoomIn = function() {
- // console.log 'zoom in'
- const newScale = $scope.scale.scale * 1.2
- return ($scope.forceScale = {
- scaleMode: 'scale_mode_value',
- scale: newScale
- })
- }
-
- this.zoomOut = function() {
- // console.log 'zoom out'
- const newScale = $scope.scale.scale / 1.2
- return ($scope.forceScale = {
- scaleMode: 'scale_mode_value',
- scale: newScale
- })
- }
-
- this.fitWidth = () =>
- // console.log 'fit width'
- ($scope.forceScale = { scaleMode: 'scale_mode_fit_width' })
-
- this.fitHeight = () =>
- // console.log 'fit height'
- ($scope.forceScale = { scaleMode: 'scale_mode_fit_height' })
-
- this.checkPosition = () =>
- // console.log 'check position'
- ($scope.forceCheck = ($scope.forceCheck || 0) + 1)
-
- this.showRandomHighlights = () =>
- // console.log 'show highlights'
- ($scope.highlights = [
- {
- page: 3,
- h: 100,
- v: 100,
- height: 30,
- width: 200
+ // console.log 'top page is', topPage.pageNum, topPage.elemTop, topPage.elemBottom, topPage
+ const { top } = topPage.element.offset()
+ const bottom = top + topPage.element.innerHeight()
+ const viewportTop = $element.offset().top
+ const viewportBottom = viewportTop + $element.height()
+ const topVisible = top >= viewportTop && top < viewportBottom
+ const someContentVisible = top < viewportTop && bottom > viewportTop
+ // console.log 'in PdfListView', top, topVisible, someContentVisible, viewportTop
+ if (topVisible) {
+ canvasOffset = 0
+ } else if (someContentVisible) {
+ canvasOffset = viewportTop - top
+ } else {
+ canvasOffset = null
}
- ])
-
- // we work with (pagenumber, % of height down page from top)
- // pdfListView works with (pagenumber, vertical position up page from
- // bottom measured in pts)
-
- this.getPdfPosition = function() {
- // console.log 'in getPdfPosition'
- let canvasOffset, pdfOffset, viewport
- let topPageIdx = 0
- let topPage = $scope.pages[0]
- // find first visible page
- const visible = $scope.pages.some(function(page, i) {
- if (page.visible) {
- let ref
- return ([topPageIdx, topPage] = Array.from((ref = [i, page]))), ref
+ // console.log 'pdfListview position = ', canvasOffset
+ // instead of using promise, check if size is known and revert to
+ // default otherwise
+ // console.log 'looking up viewport', topPage.viewport, $scope.pdfViewport
+ if (topPage.viewport) {
+ ;({ viewport } = topPage)
+ pdfOffset = viewport.convertToPdfPoint(0, canvasOffset)
+ } else {
+ // console.log 'WARNING: had to default to global page size'
+ viewport = $scope.pdfViewport
+ const scaledOffset = canvasOffset / $scope.scale.scale
+ pdfOffset = viewport.convertToPdfPoint(0, scaledOffset)
}
- })
- if (visible && topPage.element != null) {
- // console.log 'found it', topPageIdx
- } else {
- // console.log 'CANNOT FIND TOP PAGE'
- return
+ // console.log 'converted to offset = ', pdfOffset
+ const newPosition = {
+ page: topPageIdx,
+ offset: { top: pdfOffset[1], left: 0 },
+ pageSize: { height: viewport.viewBox[3], width: viewport.viewBox[2] }
+ }
+ return newPosition
}
- // console.log 'top page is', topPage.pageNum, topPage.elemTop, topPage.elemBottom, topPage
- const { top } = topPage.element.offset()
- const bottom = top + topPage.element.innerHeight()
- const viewportTop = $element.offset().top
- const viewportBottom = viewportTop + $element.height()
- const topVisible = top >= viewportTop && top < viewportBottom
- const someContentVisible = top < viewportTop && bottom > viewportTop
- // console.log 'in PdfListView', top, topVisible, someContentVisible, viewportTop
- if (topVisible) {
- canvasOffset = 0
- } else if (someContentVisible) {
- canvasOffset = viewportTop - top
- } else {
- canvasOffset = null
- }
- // console.log 'pdfListview position = ', canvasOffset
- // instead of using promise, check if size is known and revert to
- // default otherwise
- // console.log 'looking up viewport', topPage.viewport, $scope.pdfViewport
- if (topPage.viewport) {
- ;({ viewport } = topPage)
- pdfOffset = viewport.convertToPdfPoint(0, canvasOffset)
- } else {
- // console.log 'WARNING: had to default to global page size'
- viewport = $scope.pdfViewport
- const scaledOffset = canvasOffset / $scope.scale.scale
- pdfOffset = viewport.convertToPdfPoint(0, scaledOffset)
- }
- // console.log 'converted to offset = ', pdfOffset
- const newPosition = {
- page: topPageIdx,
- offset: { top: pdfOffset[1], left: 0 },
- pageSize: { height: viewport.viewBox[3], width: viewport.viewBox[2] }
- }
- return newPosition
- }
-
- this.computeOffset = function(page, position) {
- // console.log 'computing offset for', page, position
- const { element } = page
- // console.log 'element =', $(element), 'parent =', $(element).parent()
- const t1 = __guard__($(element).offset(), x => x.top)
- const t2 = __guard__(
- $(element)
- .parent()
- .offset(),
- x1 => x1.top
- )
- if (!(t1 != null && t2 != null)) {
- return $q((resolve, reject) => reject('elements destroyed'))
- }
- const pageTop =
- $(element).offset().top -
- $(element)
- .parent()
- .offset().top
- // console.log('top of page scroll is', pageTop, 'vs', page.elemTop)
- // console.log('inner height is', $(element).innerHeight())
- const currentScroll = $(element)
- .parent()
- .scrollTop()
- const { offset } = position
- // convert offset to pixels
- return $scope.document
- .getPdfViewport(page.pageNum)
- .then(function(viewport) {
- page.viewport = viewport
- const pageOffset = viewport.convertToViewportPoint(
- offset.left,
- offset.top
- )
- // if the passed-in position doesn't have the page height/width add them now
- if (position.pageSize == null) {
- position.pageSize = {
- height: viewport.viewBox[3],
- width: viewport.viewBox[2]
+ this.computeOffset = function (page, position) {
+ // console.log 'computing offset for', page, position
+ const { element } = page
+ // console.log 'element =', $(element), 'parent =', $(element).parent()
+ const t1 = __guard__($(element).offset(), x => x.top)
+ const t2 = __guard__($(element).parent().offset(), x1 => x1.top)
+ if (!(t1 != null && t2 != null)) {
+ return $q((resolve, reject) => reject('elements destroyed'))
+ }
+ const pageTop = $(element).offset().top - $(element).parent().offset().top
+ // console.log('top of page scroll is', pageTop, 'vs', page.elemTop)
+ // console.log('inner height is', $(element).innerHeight())
+ const currentScroll = $(element).parent().scrollTop()
+ const { offset } = position
+ // convert offset to pixels
+ return $scope.document
+ .getPdfViewport(page.pageNum)
+ .then(function (viewport) {
+ page.viewport = viewport
+ const pageOffset = viewport.convertToViewportPoint(
+ offset.left,
+ offset.top
+ )
+ // if the passed-in position doesn't have the page height/width add them now
+ if (position.pageSize == null) {
+ position.pageSize = {
+ height: viewport.viewBox[3],
+ width: viewport.viewBox[2]
+ }
}
- }
- // console.log 'addition offset =', pageOffset
- // console.log 'total', pageTop + pageOffset[1]
- return Math.round(pageTop + pageOffset[1] + currentScroll)
- }) // # 10 is margin
- }
+ // console.log 'addition offset =', pageOffset
+ // console.log 'total', pageTop + pageOffset[1]
+ return Math.round(pageTop + pageOffset[1] + currentScroll)
+ }) // # 10 is margin
+ }
- this.setPdfPosition = function(page, position) {
- // console.log 'required pdf Position is', position
- return this.computeOffset(page, position).then(function(offset) {
- return $scope.$apply(() => {
- $scope.pleaseScrollTo = offset
- $scope.position = position
+ this.setPdfPosition = function (page, position) {
+ // console.log 'required pdf Position is', position
+ return this.computeOffset(page, position).then(function (offset) {
+ return $scope.$apply(() => {
+ $scope.pleaseScrollTo = offset
+ $scope.position = position
+ })
})
- })
+ }
+ return this
}
- return this
-})
+)
export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
controller: 'pdfViewerController',
@@ -345,19 +337,19 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
const spinner = new pdfSpinner()
let layoutReady = $q.defer()
layoutReady.notify('waiting for layout')
- layoutReady.promise.then(function() {})
+ layoutReady.promise.then(function () {})
// console.log 'layoutReady was resolved'
- const renderVisiblePages = function() {
+ const renderVisiblePages = function () {
const visiblePages = getVisiblePages()
const pages = getExtraPages(visiblePages)
return scope.document.renderPages(pages)
}
- var getVisiblePages = function() {
+ var getVisiblePages = function () {
const top = element[0].scrollTop
const bottom = top + element[0].clientHeight
- const visiblePages = _.filter(scope.pages, function(page) {
+ const visiblePages = _.filter(scope.pages, function (page) {
if (page.element == null) {
return false
}
@@ -370,7 +362,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
return visiblePages
}
- var getExtraPages = function(visiblePages) {
+ var getExtraPages = function (visiblePages) {
const extra = []
if (visiblePages.length > 0) {
const firstVisiblePage = visiblePages[0].pageNum
@@ -395,20 +387,20 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
}
let rescaleTimer = null
- const queueRescale = function(scale) {
+ const queueRescale = function (scale) {
// console.log 'call to queueRescale'
if (rescaleTimer != null || layoutTimer != null || elementTimer != null) {
return
}
// console.log 'adding to rescale queue'
- return (rescaleTimer = setTimeout(function() {
+ return (rescaleTimer = setTimeout(function () {
doRescale(scale)
return (rescaleTimer = null)
}, 0))
}
let spinnerTimer = null
- var doRescale = function(scale) {
+ var doRescale = function (scale) {
// console.log 'doRescale', scale
if (scale == null) {
return
@@ -417,19 +409,19 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
// console.log 'origposition', origposition
if (spinnerTimer == null) {
- spinnerTimer = setTimeout(function() {
+ spinnerTimer = setTimeout(function () {
spinner.add(element)
return (spinnerTimer = null)
}, 100)
}
- return layoutReady.promise.then(function(parentSize) {
+ return layoutReady.promise.then(function (parentSize) {
const [h, w] = Array.from(parentSize)
// console.log 'in promise', h, w
return ctrl
.setScale(scale, h, w)
.then(() =>
// console.log 'in setscale then', scale, h, w
- scope.$evalAsync(function() {
+ scope.$evalAsync(function () {
if (spinnerTimer) {
clearTimeout(spinnerTimer)
} else {
@@ -447,21 +439,21 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
}
var elementTimer = null
- var updateLayout = function() {
+ var updateLayout = function () {
// if element is zero-sized keep checking until it is ready
// console.log 'checking element ready', element.height(), element.width()
if (element.height() === 0 || element.width() === 0) {
if (elementTimer != null) {
return
}
- return (elementTimer = setTimeout(function() {
+ return (elementTimer = setTimeout(function () {
elementTimer = null
return updateLayout()
}, 1000))
} else {
scope.parentSize = [element.innerHeight(), element.innerWidth()]
// console.log 'resolving layoutReady with', scope.parentSize
- return $timeout(function() {
+ return $timeout(function () {
layoutReady.resolve(scope.parentSize)
return scope.$emit('flash-controls')
})
@@ -469,14 +461,14 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
}
var layoutTimer = null
- const queueLayout = function() {
+ const queueLayout = function () {
// console.log 'call to queue layout'
if (layoutTimer != null) {
return
}
// console.log 'added to queue layoyt'
layoutReady = $q.defer()
- return (layoutTimer = setTimeout(function() {
+ return (layoutTimer = setTimeout(function () {
// console.log 'calling update layout'
updateLayout()
// console.log 'setting layout timer to null'
@@ -502,7 +494,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
queueLayout()
)
- scope.$on('pdf:error', function(event, error) {
+ scope.$on('pdf:error', function (event, error) {
if (error.name === 'RenderingCancelledException') {
return
}
@@ -530,7 +522,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
}
})
- scope.$on('pdf:page:size-change', function(event, pageNum, delta) {
+ scope.$on('pdf:page:size-change', function (event, pageNum, delta) {
// console.log 'page size change event', pageNum, delta
const origposition = angular.copy(scope.position)
// console.log 'orig position', JSON.stringify(origposition)
@@ -546,7 +538,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
}
})
- element.on('mousedown', function(e) {
+ element.on('mousedown', function (e) {
// We're checking that the event target isn't the directive root element
// to make sure that the click was within a PDF page - no point in showing
// the text layer when the click is outside.
@@ -562,7 +554,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
let mouseUpHandler = null // keep track of the handler to avoid adding multiple times
- var _setMouseUpHandler = function() {
+ var _setMouseUpHandler = function () {
if (mouseUpHandler == null) {
return (mouseUpHandler = $(document.body).one(
'mouseup',
@@ -571,9 +563,9 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
}
}
- var _handleSelectionMouseUp = function() {
+ var _handleSelectionMouseUp = function () {
mouseUpHandler = null // reset handler, has now fired
- window.setTimeout(function() {
+ window.setTimeout(function () {
const removedClass = _removeClassIfNoSelection()
// if we still have a selection we need to keep the handler going
if (!removedClass) {
@@ -583,7 +575,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
return true
}
- var _removeClassIfNoSelection = function() {
+ var _removeClassIfNoSelection = function () {
if (_hasSelection()) {
return false // didn't remove the text layer
} else {
@@ -592,7 +584,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
}
}
- var _hasSelection = function() {
+ var _hasSelection = function () {
const selection =
typeof window.getSelection === 'function'
? window.getSelection()
@@ -607,7 +599,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
)
}
- var _isSelectionWithinPDF = function(selection) {
+ var _isSelectionWithinPDF = function (selection) {
if (selection.rangeCount === 0) {
return false
}
@@ -619,7 +611,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
)
}
- element.on('scroll', function() {
+ element.on('scroll', function () {
// console.log 'scroll event', element.scrollTop(), 'adjusting?', scope.adjustingScroll
// scope.scrollPosition = element.scrollTop()
if (scope.adjustingScroll) {
@@ -633,7 +625,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
return (scope.scrollHandlerTimeout = setTimeout(scrollHandler, 25))
})
- var scrollHandler = function() {
+ var scrollHandler = function () {
renderVisiblePages()
const newPosition = ctrl.getPdfPosition()
if (newPosition != null) {
@@ -642,7 +634,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
return (scope.scrollHandlerTimeout = null)
}
- scope.$watch('pdfSrc', function(newVal, oldVal) {
+ scope.$watch('pdfSrc', function (newVal, oldVal) {
// console.log 'loading pdf', newVal, oldVal
if (newVal == null) {
return
@@ -659,7 +651,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
.catch(error => scope.$emit('pdf:error', error))
})
- scope.$watch('scale', function(newVal, oldVal) {
+ scope.$watch('scale', function (newVal, oldVal) {
// no need to set scale when initialising, done in pdfSrc
if (newVal === oldVal) {
return
@@ -668,7 +660,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
return queueRescale(newVal)
})
- scope.$watch('forceScale', function(newVal, oldVal) {
+ scope.$watch('forceScale', function (newVal, oldVal) {
// console.log 'got change in numscale watcher', newVal, oldVal
if (newVal == null) {
return
@@ -679,7 +671,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
// scope.$watch 'position', (newVal, oldVal) ->
// console.log 'got change in position watcher', newVal, oldVal
- scope.$watch('forceCheck', function(newVal, oldVal) {
+ scope.$watch('forceCheck', function (newVal, oldVal) {
// console.log 'forceCheck', newVal, oldVal
if (newVal == null) {
return
@@ -690,7 +682,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
scope.$watch(
'parentSize',
- function(newVal, oldVal) {
+ function (newVal, oldVal) {
// console.log 'XXX in parentSize watch', newVal, oldVal
// if newVal == oldVal
// console.log 'returning because old and new are the same'
@@ -708,7 +700,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
// scope.$watch 'elementWidth', (newVal, oldVal) ->
// console.log '*** watch INTERVAL element width is', newVal, oldVal
- scope.$watch('pleaseScrollTo', function(newVal, oldVal) {
+ scope.$watch('pleaseScrollTo', function (newVal, oldVal) {
// console.log 'got request to ScrollTo', newVal, 'oldVal', oldVal
if (newVal == null) {
return
@@ -719,7 +711,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
return (scope.pleaseScrollTo = undefined)
})
- scope.$watch('pleaseJumpTo', function(newPosition, oldPosition) {
+ scope.$watch('pleaseJumpTo', function (newPosition, oldPosition) {
// console.log 'in pleaseJumpTo', newPosition, oldPosition
if (newPosition == null) {
return
@@ -727,7 +719,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
return ctrl.setPdfPosition(scope.pages[newPosition.page - 1], newPosition)
})
- scope.$watch('navigateTo', function(newVal, oldVal) {
+ scope.$watch('navigateTo', function (newVal, oldVal) {
if (newVal == null) {
return
}
@@ -738,12 +730,12 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
return scope.document.getDestination(newVal.dest).then(r =>
// console.log 'need to go to', r
// console.log 'page ref is', r[0]
- scope.document.getPageIndex(r[0]).then(function(pidx) {
+ scope.document.getPageIndex(r[0]).then(function (pidx) {
// console.log 'page num is', pidx
const page = scope.pages[pidx]
return scope.document
.getPdfViewport(page.pageNum)
- .then(function(viewport) {
+ .then(function (viewport) {
// console.log 'got viewport', viewport
const coords = viewport.convertToViewportPoint(r[2], r[3])
// console.log 'viewport position', coords
@@ -761,7 +753,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
)
}) // XXX?
- scope.$watch('highlights', function(areas) {
+ scope.$watch('highlights', function (areas) {
// console.log 'got HIGHLIGHTS in pdfViewer', areas
if (areas == null) {
return
@@ -802,7 +794,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
}
// use a visual offset of 72pt to match the offset in PdfController syncToCode
- return scope.document.getPdfViewport(pageNum).then(function(viewport) {
+ return scope.document.getPdfViewport(pageNum).then(function (viewport) {
const position = {
page: first.page,
offset: {
@@ -818,7 +810,7 @@ export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
})
})
- return scope.$on('$destroy', function() {
+ return scope.$on('$destroy', function () {
// console.log 'handle pdfng directive destroy'
if (elementTimer != null) {
clearTimeout(elementTimer)
diff --git a/services/web/frontend/js/ide/preamble/services/preamble.js b/services/web/frontend/js/ide/preamble/services/preamble.js
index 53983afcc3..f8ed22786d 100644
--- a/services/web/frontend/js/ide/preamble/services/preamble.js
+++ b/services/web/frontend/js/ide/preamble/services/preamble.js
@@ -11,7 +11,7 @@
*/
import App from '../../../base'
-export default App.factory('preamble', function(ide) {
+export default App.factory('preamble', function (ide) {
var Preamble = {
getPreambleText() {
const text = ide.editorManager.getCurrentDocValue().slice(0, 5000)
diff --git a/services/web/frontend/js/ide/review-panel/RangesTracker.js b/services/web/frontend/js/ide/review-panel/RangesTracker.js
index 077a635033..948703f4c9 100644
--- a/services/web/frontend/js/ide/review-panel/RangesTracker.js
+++ b/services/web/frontend/js/ide/review-panel/RangesTracker.js
@@ -699,7 +699,7 @@ export default RangesTracker = class RangesTracker {
this.changes.push(change)
// Keep ops in order of offset, with deletes before inserts
- this.changes.sort(function(c1, c2) {
+ this.changes.sort(function (c1, c2) {
const result = c1.op.p - c2.op.p
if (result !== 0) {
return result
@@ -723,7 +723,7 @@ export default RangesTracker = class RangesTracker {
_applyOpModifications(content, op_modifications) {
// Put in descending position order, with deleting first if at the same offset
// (Inserting first would modify the content that the delete will delete)
- op_modifications.sort(function(a, b) {
+ op_modifications.sort(function (a, b) {
const result = b.p - a.p
if (result !== 0) {
return result
diff --git a/services/web/frontend/js/ide/review-panel/controllers/BulkActionsModalController.js b/services/web/frontend/js/ide/review-panel/controllers/BulkActionsModalController.js
index 18c53d8d1a..ab96ab81dd 100644
--- a/services/web/frontend/js/ide/review-panel/controllers/BulkActionsModalController.js
+++ b/services/web/frontend/js/ide/review-panel/controllers/BulkActionsModalController.js
@@ -11,14 +11,12 @@
*/
import App from '../../../base'
-export default App.controller('BulkActionsModalController', function(
- $scope,
- $modalInstance,
- isAccept,
- nChanges
-) {
- $scope.isAccept = isAccept
- $scope.nChanges = nChanges
- $scope.cancel = () => $modalInstance.dismiss()
- return ($scope.confirm = () => $modalInstance.close(isAccept))
-})
+export default App.controller(
+ 'BulkActionsModalController',
+ function ($scope, $modalInstance, isAccept, nChanges) {
+ $scope.isAccept = isAccept
+ $scope.nChanges = nChanges
+ $scope.cancel = () => $modalInstance.dismiss()
+ return ($scope.confirm = () => $modalInstance.close(isAccept))
+ }
+)
diff --git a/services/web/frontend/js/ide/review-panel/controllers/ReviewPanelController.js b/services/web/frontend/js/ide/review-panel/controllers/ReviewPanelController.js
index cd7c2ce885..1fe585c13d 100644
--- a/services/web/frontend/js/ide/review-panel/controllers/ReviewPanelController.js
+++ b/services/web/frontend/js/ide/review-panel/controllers/ReviewPanelController.js
@@ -19,1199 +19,1216 @@ import EventEmitter from '../../../utils/EventEmitter'
import ColorManager from '../../colors/ColorManager'
import RangesTracker from '../RangesTracker'
-export default App.controller('ReviewPanelController', function(
- $scope,
- $element,
- ide,
- $timeout,
- $http,
- $modal,
- eventTracking,
- localStorage
-) {
- let UserTCSyncState
- const $reviewPanelEl = $element.find('#review-panel')
+export default App.controller(
+ 'ReviewPanelController',
+ function (
+ $scope,
+ $element,
+ ide,
+ $timeout,
+ $http,
+ $modal,
+ eventTracking,
+ localStorage
+ ) {
+ let UserTCSyncState
+ const $reviewPanelEl = $element.find('#review-panel')
- const UserTypes = {
- MEMBER: 'member', // Invited, listed in project.members
- GUEST: 'guest', // Not invited, but logged in so has a user_id
- ANONYMOUS: 'anonymous' // No user_id
- }
+ const UserTypes = {
+ MEMBER: 'member', // Invited, listed in project.members
+ GUEST: 'guest', // Not invited, but logged in so has a user_id
+ ANONYMOUS: 'anonymous' // No user_id
+ }
- const currentUserType = function() {
- if ((ide.$scope.user != null ? ide.$scope.user.id : undefined) == null) {
- return UserTypes.ANONYMOUS
- } else {
- const user_id = ide.$scope.user.id
- const { project } = ide.$scope
- if ((project.owner != null ? project.owner.id : undefined) === user_id) {
- return UserTypes.MEMBER
- }
- for (let member of Array.from(project.members)) {
- if (member._id === user_id) {
+ const currentUserType = function () {
+ if ((ide.$scope.user != null ? ide.$scope.user.id : undefined) == null) {
+ return UserTypes.ANONYMOUS
+ } else {
+ const user_id = ide.$scope.user.id
+ const { project } = ide.$scope
+ if (
+ (project.owner != null ? project.owner.id : undefined) === user_id
+ ) {
return UserTypes.MEMBER
}
- }
- return UserTypes.GUEST
- }
- }
-
- $scope.SubViews = {
- CUR_FILE: 'cur_file',
- OVERVIEW: 'overview'
- }
-
- $scope.UserTCSyncState = UserTCSyncState = {
- SYNCED: 'synced',
- PENDING: 'pending'
- }
-
- $scope.reviewPanel = {
- trackChangesState: {},
- trackChangesOnForEveryone: false,
- trackChangesOnForGuests: false,
- trackChangesForGuestsAvailable: false,
- entries: {},
- resolvedComments: {},
- hasEntries: false,
- subView: $scope.SubViews.CUR_FILE,
- openSubView: $scope.SubViews.CUR_FILE,
- overview: {
- loading: false,
- docsCollapsedState:
- JSON.parse(localStorage(`docs_collapsed_state:${$scope.project_id}`)) ||
- {}
- },
- dropdown: {
- loading: false
- },
- commentThreads: {},
- resolvedThreadIds: {},
- rendererData: {},
- formattedProjectMembers: {},
- fullTCStateCollapsed: true,
- loadingThreads: false,
- // All selected changes. If a aggregated change (insertion + deletion) is selection, the two ids
- // will be present. The length of this array will differ from the count below (see explanation).
- selectedEntryIds: [],
- // A count of user-facing selected changes. An aggregated change (insertion + deletion) will count
- // as only one.
- nVisibleSelectedChanges: 0
- }
-
- window.addEventListener('beforeunload', function() {
- const collapsedStates = {}
- for (let doc in $scope.reviewPanel.overview.docsCollapsedState) {
- const state = $scope.reviewPanel.overview.docsCollapsedState[doc]
- if (state) {
- collapsedStates[doc] = state
- }
- }
- const valToStore =
- Object.keys(collapsedStates).length > 0
- ? JSON.stringify(collapsedStates)
- : null
- return localStorage(`docs_collapsed_state:${$scope.project_id}`, valToStore)
- })
-
- $scope.$on('layout:pdf:linked', (event, state) =>
- $scope.$broadcast('review-panel:layout')
- )
-
- $scope.$on('layout:pdf:resize', (event, state) =>
- $scope.$broadcast('review-panel:layout', false)
- )
-
- $scope.$on('expandable-text-area:resize', event =>
- $timeout(() => $scope.$broadcast('review-panel:layout'))
- )
-
- $scope.$on('review-panel:sizes', (e, sizes) =>
- $scope.$broadcast('editor:set-scroll-size', sizes)
- )
-
- $scope.$watch('project.features.trackChangesVisible', function(visible) {
- if (visible == null) {
- return
- }
- if (!visible) {
- return ($scope.ui.reviewPanelOpen = false)
- }
- })
-
- $scope.$watch('project.members', function(members) {
- $scope.reviewPanel.formattedProjectMembers = {}
- if (($scope.project != null ? $scope.project.owner : undefined) != null) {
- $scope.reviewPanel.formattedProjectMembers[
- $scope.project.owner._id
- ] = formatUser($scope.project.owner)
- }
- if (($scope.project != null ? $scope.project.members : undefined) != null) {
- return (() => {
- const result = []
- for (let member of Array.from(members)) {
- if (member.privileges === 'readAndWrite') {
- if ($scope.reviewPanel.trackChangesState[member._id] == null) {
- // An added member will have track changes enabled if track changes is on for everyone
- _setUserTCState(
- member._id,
- $scope.reviewPanel.trackChangesOnForEveryone,
- true
- )
- }
- result.push(
- ($scope.reviewPanel.formattedProjectMembers[
- member._id
- ] = formatUser(member))
- )
- } else {
- result.push(undefined)
+ for (let member of Array.from(project.members)) {
+ if (member._id === user_id) {
+ return UserTypes.MEMBER
}
}
- return result
- })()
+ return UserTypes.GUEST
+ }
}
- })
- $scope.commentState = {
- adding: false,
- content: ''
- }
-
- $scope.users = {}
-
- $scope.reviewPanelEventsBridge = new EventEmitter()
-
- ide.socket.on('new-comment', function(thread_id, comment) {
- const thread = getThread(thread_id)
- delete thread.submitting
- thread.messages.push(formatComment(comment))
- $scope.$apply()
- return $timeout(() => $scope.$broadcast('review-panel:layout'))
- })
-
- ide.socket.on('accept-changes', function(doc_id, change_ids) {
- if (doc_id !== $scope.editor.open_doc_id) {
- getChangeTracker(doc_id).removeChangeIds(change_ids)
- } else {
- $scope.$broadcast('changes:accept', change_ids)
+ $scope.SubViews = {
+ CUR_FILE: 'cur_file',
+ OVERVIEW: 'overview'
}
- updateEntries(doc_id)
- return $scope.$apply(function() {})
- })
- ide.socket.on('resolve-thread', (thread_id, user) =>
- _onCommentResolved(thread_id, user)
- )
-
- ide.socket.on('reopen-thread', thread_id => _onCommentReopened(thread_id))
-
- ide.socket.on('delete-thread', function(thread_id) {
- _onThreadDeleted(thread_id)
- return $scope.$apply(function() {})
- })
-
- ide.socket.on('edit-message', function(thread_id, message_id, content) {
- _onCommentEdited(thread_id, message_id, content)
- return $scope.$apply(function() {})
- })
-
- ide.socket.on('delete-message', function(thread_id, message_id) {
- _onCommentDeleted(thread_id, message_id)
- return $scope.$apply(function() {})
- })
-
- const rangesTrackers = {}
-
- const getDocEntries = function(doc_id) {
- if ($scope.reviewPanel.entries[doc_id] == null) {
- $scope.reviewPanel.entries[doc_id] = {}
+ $scope.UserTCSyncState = UserTCSyncState = {
+ SYNCED: 'synced',
+ PENDING: 'pending'
}
- return $scope.reviewPanel.entries[doc_id]
- }
- const getDocResolvedComments = function(doc_id) {
- if ($scope.reviewPanel.resolvedComments[doc_id] == null) {
- $scope.reviewPanel.resolvedComments[doc_id] = {}
+ $scope.reviewPanel = {
+ trackChangesState: {},
+ trackChangesOnForEveryone: false,
+ trackChangesOnForGuests: false,
+ trackChangesForGuestsAvailable: false,
+ entries: {},
+ resolvedComments: {},
+ hasEntries: false,
+ subView: $scope.SubViews.CUR_FILE,
+ openSubView: $scope.SubViews.CUR_FILE,
+ overview: {
+ loading: false,
+ docsCollapsedState:
+ JSON.parse(
+ localStorage(`docs_collapsed_state:${$scope.project_id}`)
+ ) || {}
+ },
+ dropdown: {
+ loading: false
+ },
+ commentThreads: {},
+ resolvedThreadIds: {},
+ rendererData: {},
+ formattedProjectMembers: {},
+ fullTCStateCollapsed: true,
+ loadingThreads: false,
+ // All selected changes. If a aggregated change (insertion + deletion) is selection, the two ids
+ // will be present. The length of this array will differ from the count below (see explanation).
+ selectedEntryIds: [],
+ // A count of user-facing selected changes. An aggregated change (insertion + deletion) will count
+ // as only one.
+ nVisibleSelectedChanges: 0
}
- return $scope.reviewPanel.resolvedComments[doc_id]
- }
- var getThread = function(thread_id) {
- if ($scope.reviewPanel.commentThreads[thread_id] == null) {
- $scope.reviewPanel.commentThreads[thread_id] = { messages: [] }
- }
- return $scope.reviewPanel.commentThreads[thread_id]
- }
-
- var getChangeTracker = function(doc_id) {
- if (rangesTrackers[doc_id] == null) {
- rangesTrackers[doc_id] = new RangesTracker()
- rangesTrackers[doc_id].resolvedThreadIds =
- $scope.reviewPanel.resolvedThreadIds
- }
- return rangesTrackers[doc_id]
- }
-
- let scrollbar = {}
- $scope.reviewPanelEventsBridge.on('aceScrollbarVisibilityChanged', function(
- isVisible,
- scrollbarWidth
- ) {
- scrollbar = { isVisible, scrollbarWidth }
- return updateScrollbar()
- })
-
- var updateScrollbar = function() {
- if (
- scrollbar.isVisible &&
- $scope.reviewPanel.subView === $scope.SubViews.CUR_FILE &&
- !$scope.editor.showRichText
- ) {
- return $reviewPanelEl.css('right', `${scrollbar.scrollbarWidth}px`)
- } else {
- return $reviewPanelEl.css('right', '0')
- }
- }
-
- $scope.$watch('!ui.reviewPanelOpen && reviewPanel.hasEntries', function(
- open,
- prevVal
- ) {
- if (open == null) {
- return
- }
- $scope.ui.miniReviewPanelVisible = open
- if (open !== prevVal) {
- return $timeout(() => $scope.$broadcast('review-panel:toggle'))
- }
- })
-
- $scope.$watch('ui.reviewPanelOpen', function(open) {
- if (open == null) {
- return
- }
- if (!open) {
- // Always show current file when not open, but save current state
- $scope.reviewPanel.openSubView = $scope.reviewPanel.subView
- $scope.reviewPanel.subView = $scope.SubViews.CUR_FILE
- } else {
- // Reset back to what we had when previously open
- $scope.reviewPanel.subView = $scope.reviewPanel.openSubView
- }
- return $timeout(function() {
- $scope.$broadcast('review-panel:toggle')
- return $scope.$broadcast('review-panel:layout', false)
- })
- })
-
- $scope.$watch('reviewPanel.subView', function(view) {
- if (view == null) {
- return
- }
- updateScrollbar()
- if (view === $scope.SubViews.OVERVIEW) {
- return refreshOverviewPanel()
- }
- })
-
- $scope.$watch('editor.sharejs_doc', function(doc, old_doc) {
- if (doc == null) {
- return
- }
- // The open doc range tracker is kept up to date in real-time so
- // replace any outdated info with this
- rangesTrackers[doc.doc_id] = doc.ranges
- rangesTrackers[doc.doc_id].resolvedThreadIds =
- $scope.reviewPanel.resolvedThreadIds
- $scope.reviewPanel.rangesTracker = rangesTrackers[doc.doc_id]
- if (old_doc != null) {
- old_doc.off('flipped_pending_to_inflight')
- }
- doc.on('flipped_pending_to_inflight', () => regenerateTrackChangesId(doc))
- return regenerateTrackChangesId(doc)
- })
-
- $scope.$watch(
- function() {
- const entries =
- $scope.reviewPanel.entries[$scope.editor.open_doc_id] || {}
- const permEntries = {}
- for (let entry in entries) {
- const entryData = entries[entry]
- if (!['add-comment', 'bulk-actions'].includes(entry)) {
- permEntries[entry] = entryData
+ window.addEventListener('beforeunload', function () {
+ const collapsedStates = {}
+ for (let doc in $scope.reviewPanel.overview.docsCollapsedState) {
+ const state = $scope.reviewPanel.overview.docsCollapsedState[doc]
+ if (state) {
+ collapsedStates[doc] = state
}
}
- return Object.keys(permEntries).length
- },
- nEntries =>
- ($scope.reviewPanel.hasEntries =
- nEntries > 0 && $scope.project.features.trackChangesVisible)
- )
-
- var regenerateTrackChangesId = function(doc) {
- const old_id = getChangeTracker(doc.doc_id).getIdSeed()
- const new_id = RangesTracker.generateIdSeed()
- getChangeTracker(doc.doc_id).setIdSeed(new_id)
- return doc.setTrackChangesIdSeeds({ pending: new_id, inflight: old_id })
- }
-
- const refreshRanges = () =>
- $http.get(`/project/${$scope.project_id}/ranges`).then(function(response) {
- const docs = response.data
- return (() => {
- const result = []
- for (let doc of Array.from(docs)) {
- if ($scope.reviewPanel.overview.docsCollapsedState[doc.id] == null) {
- $scope.reviewPanel.overview.docsCollapsedState[doc.id] = false
- }
- if (doc.id !== $scope.editor.open_doc_id) {
- // this is kept up to date in real-time, don't overwrite
- const rangesTracker = getChangeTracker(doc.id)
- rangesTracker.comments =
- (doc.ranges != null ? doc.ranges.comments : undefined) || []
- rangesTracker.changes =
- (doc.ranges != null ? doc.ranges.changes : undefined) || []
- }
- result.push(updateEntries(doc.id))
- }
- return result
- })()
+ const valToStore =
+ Object.keys(collapsedStates).length > 0
+ ? JSON.stringify(collapsedStates)
+ : null
+ return localStorage(
+ `docs_collapsed_state:${$scope.project_id}`,
+ valToStore
+ )
})
- var refreshOverviewPanel = function() {
- $scope.reviewPanel.overview.loading = true
- return refreshRanges()
- .then(() => ($scope.reviewPanel.overview.loading = false))
- .catch(() => ($scope.reviewPanel.overview.loading = false))
- }
-
- $scope.refreshResolvedCommentsDropdown = function() {
- $scope.reviewPanel.dropdown.loading = true
- const q = refreshRanges()
- q.then(() => ($scope.reviewPanel.dropdown.loading = false))
- q.catch(() => ($scope.reviewPanel.dropdown.loading = false))
- return q
- }
-
- var updateEntries = function(doc_id) {
- let change, entry_id, key, new_entry, value
- const rangesTracker = getChangeTracker(doc_id)
- const entries = getDocEntries(doc_id)
- const resolvedComments = getDocResolvedComments(doc_id)
-
- let changed = false
-
- // Assume we'll delete everything until we see it, then we'll remove it from this object
- const delete_changes = {}
- for (var id in entries) {
- change = entries[id]
- if (!['add-comment', 'bulk-actions'].includes(id)) {
- for (entry_id of Array.from(change.entry_ids)) {
- delete_changes[entry_id] = true
- }
- }
- }
- for (id in resolvedComments) {
- change = resolvedComments[id]
- for (entry_id of Array.from(change.entry_ids)) {
- delete_changes[entry_id] = true
- }
- }
-
- let potential_aggregate = false
- let prev_insertion = null
-
- for (change of Array.from(rangesTracker.changes)) {
- changed = true
-
- if (
- potential_aggregate &&
- change.op.d &&
- change.op.p === prev_insertion.op.p + prev_insertion.op.i.length &&
- change.metadata.user_id === prev_insertion.metadata.user_id
- ) {
- // An actual aggregate op.
- entries[prev_insertion.id].type = 'aggregate-change'
- entries[prev_insertion.id].metadata.replaced_content = change.op.d
- entries[prev_insertion.id].entry_ids.push(change.id)
- } else {
- if (entries[change.id] == null) {
- entries[change.id] = {}
- }
- delete delete_changes[change.id]
- new_entry = {
- type: change.op.i ? 'insert' : 'delete',
- entry_ids: [change.id],
- content: change.op.i || change.op.d,
- offset: change.op.p,
- metadata: change.metadata
- }
- for (key in new_entry) {
- value = new_entry[key]
- entries[change.id][key] = value
- }
- }
-
- if (change.op.i) {
- potential_aggregate = true
- prev_insertion = change
- } else {
- potential_aggregate = false
- prev_insertion = null
- }
-
- if ($scope.users[change.metadata.user_id] == null) {
- refreshChangeUsers(change.metadata.user_id)
- }
- }
-
- if (rangesTracker.comments.length > 0) {
- ensureThreadsAreLoaded()
- }
-
- for (let comment of Array.from(rangesTracker.comments)) {
- var new_comment
- changed = true
- delete delete_changes[comment.id]
- if ($scope.reviewPanel.resolvedThreadIds[comment.op.t]) {
- new_comment =
- resolvedComments[comment.id] != null
- ? resolvedComments[comment.id]
- : (resolvedComments[comment.id] = {})
- delete entries[comment.id]
- } else {
- new_comment =
- entries[comment.id] != null
- ? entries[comment.id]
- : (entries[comment.id] = {})
- delete resolvedComments[comment.id]
- }
- new_entry = {
- type: 'comment',
- thread_id: comment.op.t,
- entry_ids: [comment.id],
- content: comment.op.c,
- offset: comment.op.p
- }
- for (key in new_entry) {
- value = new_entry[key]
- new_comment[key] = value
- }
- }
-
- for (let change_id in delete_changes) {
- const _ = delete_changes[change_id]
- changed = true
- delete entries[change_id]
- delete resolvedComments[change_id]
- }
-
- if (changed) {
- return $scope.$broadcast('entries:changed')
- }
- }
-
- $scope.$on('editor:track-changes:changed', function() {
- const doc_id = $scope.editor.open_doc_id
- updateEntries(doc_id)
-
- // For now, not worrying about entry panels for rich text
- if (!$scope.editor.showRichText) {
- $scope.$broadcast('review-panel:recalculate-screen-positions')
- return $scope.$broadcast('review-panel:layout')
- }
- })
-
- $scope.$on('editor:track-changes:visibility_changed', () =>
- $timeout(() => $scope.$broadcast('review-panel:layout', false))
- )
-
- $scope.$on('editor:focus:changed', function(
- e,
- selection_offset_start,
- selection_offset_end,
- selection
- ) {
- const doc_id = $scope.editor.open_doc_id
- const entries = getDocEntries(doc_id)
- // All selected changes will be added to this array.
- $scope.reviewPanel.selectedEntryIds = []
- // Count of user-visible changes, i.e. an aggregated change will count as one.
- $scope.reviewPanel.nVisibleSelectedChanges = 0
- delete entries['add-comment']
- delete entries['bulk-actions']
-
- if (selection) {
- entries['add-comment'] = {
- type: 'add-comment',
- offset: selection_offset_start,
- length: selection_offset_end - selection_offset_start
- }
- entries['bulk-actions'] = {
- type: 'bulk-actions',
- offset: selection_offset_start,
- length: selection_offset_end - selection_offset_start
- }
- }
-
- for (let id in entries) {
- const entry = entries[id]
- let isChangeEntryAndWithinSelection = false
- if (
- entry.type === 'comment' &&
- !$scope.reviewPanel.resolvedThreadIds[entry.thread_id]
- ) {
- entry.focused =
- entry.offset <= selection_offset_start &&
- selection_offset_start <= entry.offset + entry.content.length
- } else if (entry.type === 'insert') {
- isChangeEntryAndWithinSelection =
- entry.offset >= selection_offset_start &&
- entry.offset + entry.content.length <= selection_offset_end
- entry.focused =
- entry.offset <= selection_offset_start &&
- selection_offset_start <= entry.offset + entry.content.length
- } else if (entry.type === 'delete') {
- isChangeEntryAndWithinSelection =
- selection_offset_start <= entry.offset &&
- entry.offset <= selection_offset_end
- entry.focused = entry.offset === selection_offset_start
- } else if (entry.type === 'aggregate-change') {
- isChangeEntryAndWithinSelection =
- entry.offset >= selection_offset_start &&
- entry.offset + entry.content.length <= selection_offset_end
- entry.focused =
- entry.offset <= selection_offset_start &&
- selection_offset_start <= entry.offset + entry.content.length
- } else if (
- ['add-comment', 'bulk-actions'].includes(entry.type) &&
- selection
- ) {
- entry.focused = true
- }
-
- if (isChangeEntryAndWithinSelection) {
- for (let entry_id of Array.from(entry.entry_ids)) {
- $scope.reviewPanel.selectedEntryIds.push(entry_id)
- }
- $scope.reviewPanel.nVisibleSelectedChanges++
- }
- }
-
- $scope.$broadcast('review-panel:recalculate-screen-positions')
- return $scope.$broadcast('review-panel:layout')
- })
-
- $scope.acceptChanges = function(change_ids) {
- _doAcceptChanges(change_ids)
- return eventTracking.sendMB('rp-changes-accepted', {
- view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini'
- })
- }
-
- $scope.rejectChanges = function(change_ids) {
- _doRejectChanges(change_ids)
- return eventTracking.sendMB('rp-changes-rejected', {
- view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini'
- })
- }
-
- var _doAcceptChanges = function(change_ids) {
- $http.post(
- `/project/${$scope.project_id}/doc/${$scope.editor.open_doc_id}/changes/accept`,
- { change_ids, _csrf: window.csrfToken }
- )
- return $scope.$broadcast('changes:accept', change_ids)
- }
-
- var _doRejectChanges = change_ids =>
- $scope.$broadcast('changes:reject', change_ids)
-
- const bulkAccept = function() {
- _doAcceptChanges($scope.reviewPanel.selectedEntryIds.slice())
- return eventTracking.sendMB('rp-bulk-accept', {
- view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini',
- nEntries: $scope.reviewPanel.nVisibleSelectedChanges
- })
- }
-
- const bulkReject = function() {
- _doRejectChanges($scope.reviewPanel.selectedEntryIds.slice())
- return eventTracking.sendMB('rp-bulk-reject', {
- view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini',
- nEntries: $scope.reviewPanel.nVisibleSelectedChanges
- })
- }
-
- $scope.showBulkAcceptDialog = () => showBulkActionsDialog(true)
-
- $scope.showBulkRejectDialog = () => showBulkActionsDialog(false)
-
- var showBulkActionsDialog = isAccept =>
- $modal
- .open({
- templateUrl: 'bulkActionsModalTemplate',
- controller: 'BulkActionsModalController',
- resolve: {
- isAccept() {
- return isAccept
- },
- nChanges() {
- return $scope.reviewPanel.nVisibleSelectedChanges
- }
- },
- scope: $scope.$new()
- })
- .result.then(function(isAccept) {
- if (isAccept) {
- return bulkAccept()
- } else {
- return bulkReject()
- }
- })
-
- $scope.handleTogglerClick = function(e) {
- e.target.blur()
- return $scope.toggleReviewPanel()
- }
-
- $scope.addNewComment = function() {
- $scope.$broadcast('comment:start_adding')
- return $scope.toggleReviewPanel()
- }
-
- $scope.addNewCommentFromKbdShortcut = function() {
- if (!$scope.project.features.trackChangesVisible) {
- return
- }
- $scope.$broadcast('comment:select_line')
- if (!$scope.ui.reviewPanelOpen) {
- $scope.toggleReviewPanel()
- }
- return $timeout(function() {
+ $scope.$on('layout:pdf:linked', (event, state) =>
$scope.$broadcast('review-panel:layout')
- return $scope.$broadcast('comment:start_adding')
- })
- }
-
- $scope.startNewComment = function() {
- $scope.$broadcast('comment:select_line')
- return $timeout(() => $scope.$broadcast('review-panel:layout'))
- }
-
- $scope.submitNewComment = function(content) {
- if (content == null || content === '') {
- return
- }
- const doc_id = $scope.editor.open_doc_id
- const entries = getDocEntries(doc_id)
- if (entries['add-comment'] == null) {
- return
- }
- const { offset, length } = entries['add-comment']
- const thread_id = RangesTracker.generateId()
- const thread = getThread(thread_id)
- thread.submitting = true
- $scope.$broadcast('comment:add', thread_id, offset, length)
- $http
- .post(`/project/${$scope.project_id}/thread/${thread_id}/messages`, {
- content,
- _csrf: window.csrfToken
- })
- .catch(() =>
- ide.showGenericMessageModal(
- 'Error submitting comment',
- 'Sorry, there was a problem submitting your comment'
- )
- )
- $scope.$broadcast('editor:clearSelection')
- $timeout(() => $scope.$broadcast('review-panel:layout'))
- return eventTracking.sendMB('rp-new-comment', { size: content.length })
- }
-
- $scope.cancelNewComment = entry =>
- $timeout(() => $scope.$broadcast('review-panel:layout'))
-
- $scope.startReply = function(entry) {
- entry.replying = true
- return $timeout(() => $scope.$broadcast('review-panel:layout'))
- }
-
- $scope.submitReply = function(entry, entry_id) {
- const { thread_id } = entry
- const content = entry.replyContent
- $http
- .post(`/project/${$scope.project_id}/thread/${thread_id}/messages`, {
- content,
- _csrf: window.csrfToken
- })
- .catch(() =>
- ide.showGenericMessageModal(
- 'Error submitting comment',
- 'Sorry, there was a problem submitting your comment'
- )
- )
-
- const trackingMetadata = {
- view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini',
- size: entry.replyContent.length,
- thread: thread_id
- }
-
- const thread = getThread(thread_id)
- thread.submitting = true
- entry.replyContent = ''
- entry.replying = false
- $timeout(() => $scope.$broadcast('review-panel:layout'))
- return eventTracking.sendMB('rp-comment-reply', trackingMetadata)
- }
-
- $scope.cancelReply = function(entry) {
- entry.replying = false
- entry.replyContent = ''
- return $scope.$broadcast('review-panel:layout')
- }
-
- $scope.resolveComment = function(entry, entry_id) {
- entry.focused = false
- $http.post(
- `/project/${$scope.project_id}/thread/${entry.thread_id}/resolve`,
- { _csrf: window.csrfToken }
)
- _onCommentResolved(entry.thread_id, ide.$scope.user)
- return eventTracking.sendMB('rp-comment-resolve', {
- view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini'
- })
- }
- $scope.unresolveComment = function(thread_id) {
- _onCommentReopened(thread_id)
- $http.post(`/project/${$scope.project_id}/thread/${thread_id}/reopen`, {
- _csrf: window.csrfToken
- })
- return eventTracking.sendMB('rp-comment-reopen')
- }
-
- var _onCommentResolved = function(thread_id, user) {
- const thread = getThread(thread_id)
- if (thread == null) {
- return
- }
- thread.resolved = true
- thread.resolved_by_user = formatUser(user)
- thread.resolved_at = new Date().toISOString()
- $scope.reviewPanel.resolvedThreadIds[thread_id] = true
- return $scope.$broadcast('comment:resolve_threads', [thread_id])
- }
-
- var _onCommentReopened = function(thread_id) {
- const thread = getThread(thread_id)
- if (thread == null) {
- return
- }
- delete thread.resolved
- delete thread.resolved_by_user
- delete thread.resolved_at
- delete $scope.reviewPanel.resolvedThreadIds[thread_id]
- return $scope.$broadcast('comment:unresolve_thread', thread_id)
- }
-
- var _onThreadDeleted = function(thread_id) {
- delete $scope.reviewPanel.resolvedThreadIds[thread_id]
- delete $scope.reviewPanel.commentThreads[thread_id]
- return $scope.$broadcast('comment:remove', thread_id)
- }
-
- var _onCommentEdited = function(thread_id, comment_id, content) {
- const thread = getThread(thread_id)
- if (thread == null) {
- return
- }
- for (let message of Array.from(thread.messages)) {
- if (message.id === comment_id) {
- message.content = content
- }
- }
- return updateEntries()
- }
-
- var _onCommentDeleted = function(thread_id, comment_id) {
- const thread = getThread(thread_id)
- if (thread == null) {
- return
- }
- thread.messages = thread.messages.filter(m => m.id !== comment_id)
- return updateEntries()
- }
-
- $scope.deleteThread = function(entry_id, doc_id, thread_id) {
- _onThreadDeleted(thread_id)
- $http({
- method: 'DELETE',
- url: `/project/${$scope.project_id}/doc/${doc_id}/thread/${thread_id}`,
- headers: {
- 'X-CSRF-Token': window.csrfToken
- }
- })
- return eventTracking.sendMB('rp-comment-delete')
- }
-
- $scope.saveEdit = function(thread_id, comment) {
- $http.post(
- `/project/${$scope.project_id}/thread/${thread_id}/messages/${comment.id}/edit`,
- {
- content: comment.content,
- _csrf: window.csrfToken
- }
+ $scope.$on('layout:pdf:resize', (event, state) =>
+ $scope.$broadcast('review-panel:layout', false)
)
- return $timeout(() => $scope.$broadcast('review-panel:layout'))
- }
- $scope.deleteComment = function(thread_id, comment) {
- _onCommentDeleted(thread_id, comment.id)
- $http({
- method: 'DELETE',
- url: `/project/${$scope.project_id}/thread/${thread_id}/messages/${comment.id}`,
- headers: {
- 'X-CSRF-Token': window.csrfToken
- }
- })
- return $timeout(() => $scope.$broadcast('review-panel:layout'))
- }
-
- $scope.setSubView = function(subView) {
- $scope.reviewPanel.subView = subView
- return eventTracking.sendMB('rp-subview-change', { subView })
- }
-
- $scope.gotoEntry = (doc_id, entry) =>
- ide.editorManager.openDocId(doc_id, { gotoOffset: entry.offset })
-
- $scope.toggleFullTCStateCollapse = function() {
- if ($scope.project.features.trackChanges) {
- return ($scope.reviewPanel.fullTCStateCollapsed = !$scope.reviewPanel
- .fullTCStateCollapsed)
- } else {
- _sendAnalytics()
- return $scope.openTrackChangesUpgradeModal()
- }
- }
-
- const _sendAnalytics = () => {
- eventTracking.send(
- 'subscription-funnel',
- 'editor-click-feature',
- 'real-time-track-changes'
+ $scope.$on('expandable-text-area:resize', event =>
+ $timeout(() => $scope.$broadcast('review-panel:layout'))
)
- }
- const _setUserTCState = function(userId, newValue, isLocal) {
- if (isLocal == null) {
- isLocal = false
- }
- if ($scope.reviewPanel.trackChangesState[userId] == null) {
- $scope.reviewPanel.trackChangesState[userId] = {}
- }
- const state = $scope.reviewPanel.trackChangesState[userId]
-
- if (state.syncState == null || state.syncState === UserTCSyncState.SYNCED) {
- state.value = newValue
- state.syncState = UserTCSyncState.SYNCED
- } else if (
- state.syncState === UserTCSyncState.PENDING &&
- state.value === newValue
- ) {
- state.syncState = UserTCSyncState.SYNCED
- } else if (isLocal) {
- state.value = newValue
- state.syncState = UserTCSyncState.PENDING
- }
-
- if (userId === ide.$scope.user.id) {
- return ($scope.editor.wantTrackChanges = newValue)
- }
- }
-
- const _setEveryoneTCState = function(newValue, isLocal) {
- if (isLocal == null) {
- isLocal = false
- }
- $scope.reviewPanel.trackChangesOnForEveryone = newValue
- const { project } = $scope
- for (let member of Array.from(project.members)) {
- _setUserTCState(member._id, newValue, isLocal)
- }
- _setGuestsTCState(newValue, isLocal)
- return _setUserTCState(project.owner._id, newValue, isLocal)
- }
-
- var _setGuestsTCState = function(newValue, isLocal) {
- if (isLocal == null) {
- isLocal = false
- }
- $scope.reviewPanel.trackChangesOnForGuests = newValue
- if (
- currentUserType() === UserTypes.GUEST ||
- currentUserType() === UserTypes.ANONYMOUS
- ) {
- return ($scope.editor.wantTrackChanges = newValue)
- }
- }
-
- const applyClientTrackChangesStateToServer = function() {
- const data = {}
- if ($scope.reviewPanel.trackChangesOnForEveryone) {
- data.on = true
- } else {
- data.on_for = {}
- for (let userId in $scope.reviewPanel.trackChangesState) {
- const userState = $scope.reviewPanel.trackChangesState[userId]
- data.on_for[userId] = userState.value
- }
- if ($scope.reviewPanel.trackChangesOnForGuests) {
- data.on_for_guests = true
- }
- }
- data._csrf = window.csrfToken
- return $http.post(`/project/${$scope.project_id}/track_changes`, data)
- }
-
- const applyTrackChangesStateToClient = function(state) {
- if (typeof state === 'boolean') {
- _setEveryoneTCState(state)
- return _setGuestsTCState(state)
- } else {
- const { project } = $scope
- $scope.reviewPanel.trackChangesOnForEveryone = false
- _setGuestsTCState(state.__guests__ === true)
- for (let member of Array.from(project.members)) {
- _setUserTCState(
- member._id,
- state[member._id] != null ? state[member._id] : false
- )
- }
- return _setUserTCState(
- $scope.project.owner._id,
- state[$scope.project.owner._id] != null
- ? state[$scope.project.owner._id]
- : false
- )
- }
- }
-
- $scope.toggleTrackChangesForEveryone = function(onForEveryone) {
- _setEveryoneTCState(onForEveryone, true)
- _setGuestsTCState(onForEveryone, true)
- return applyClientTrackChangesStateToServer()
- }
-
- $scope.toggleTrackChangesForGuests = function(onForGuests) {
- _setGuestsTCState(onForGuests, true)
- return applyClientTrackChangesStateToServer()
- }
-
- $scope.toggleTrackChangesForUser = function(onForUser, userId) {
- _setUserTCState(userId, onForUser, true)
- return applyClientTrackChangesStateToServer()
- }
-
- ide.socket.on('toggle-track-changes', state =>
- $scope.$apply(() => applyTrackChangesStateToClient(state))
- )
-
- $scope.toggleTrackChangesFromKbdShortcut = function() {
- if (
- !(
- $scope.project.features.trackChangesVisible &&
- $scope.project.features.trackChanges
- )
- ) {
- return
- }
- return $scope.toggleTrackChangesForUser(
- !$scope.reviewPanel.trackChangesState[ide.$scope.user.id].value,
- ide.$scope.user.id
+ $scope.$on('review-panel:sizes', (e, sizes) =>
+ $scope.$broadcast('editor:set-scroll-size', sizes)
)
- }
- const setGuestFeatureBasedOnProjectAccessLevel = projectPublicAccessLevel =>
- ($scope.reviewPanel.trackChangesForGuestsAvailable =
- projectPublicAccessLevel === 'tokenBased')
-
- const onToggleTrackChangesForGuestsAvailability = function(available) {
- // If the feature is no longer available we need to turn off the guest flag
- if (available) {
- return
- }
- if (!$scope.reviewPanel.trackChangesOnForGuests) {
- return
- } // Already turned off
- if ($scope.reviewPanel.trackChangesOnForEveryone) {
- return
- } // Overrides guest setting
- return $scope.toggleTrackChangesForGuests(false)
- }
-
- $scope.$watch(
- 'project.publicAccesLevel',
- setGuestFeatureBasedOnProjectAccessLevel
- )
-
- $scope.$watch('reviewPanel.trackChangesForGuestsAvailable', function(
- available
- ) {
- if (available != null) {
- return onToggleTrackChangesForGuestsAvailability(available)
- }
- })
-
- let _inited = false
- ide.$scope.$on('project:joined', function() {
- if (_inited) {
- return
- }
- const { project } = ide.$scope
- if (project.features.trackChanges) {
- applyTrackChangesStateToClient(project.trackChangesState)
- } else {
- applyTrackChangesStateToClient(false)
- }
- setGuestFeatureBasedOnProjectAccessLevel(project.publicAccesLevel)
- return (_inited = true)
- })
-
- let _refreshingRangeUsers = false
- const _refreshedForUserIds = {}
- var refreshChangeUsers = function(refresh_for_user_id) {
- if (refresh_for_user_id != null) {
- if (_refreshedForUserIds[refresh_for_user_id] != null) {
- // We've already tried to refresh to get this user id, so stop it looping
+ $scope.$watch('project.features.trackChangesVisible', function (visible) {
+ if (visible == null) {
return
}
- _refreshedForUserIds[refresh_for_user_id] = true
- }
+ if (!visible) {
+ return ($scope.ui.reviewPanelOpen = false)
+ }
+ })
- // Only do one refresh at once
- if (_refreshingRangeUsers) {
- return
- }
- _refreshingRangeUsers = true
-
- return $http
- .get(`/project/${$scope.project_id}/changes/users`)
- .then(function(response) {
- const users = response.data
- _refreshingRangeUsers = false
- $scope.users = {}
- // Always include ourself, since if we submit an op, we might need to display info
- // about it locally before it has been flushed through the server
- if (
- (ide.$scope.user != null ? ide.$scope.user.id : undefined) != null
- ) {
- $scope.users[ide.$scope.user.id] = formatUser(ide.$scope.user)
- }
+ $scope.$watch('project.members', function (members) {
+ $scope.reviewPanel.formattedProjectMembers = {}
+ if (($scope.project != null ? $scope.project.owner : undefined) != null) {
+ $scope.reviewPanel.formattedProjectMembers[
+ $scope.project.owner._id
+ ] = formatUser($scope.project.owner)
+ }
+ if (
+ ($scope.project != null ? $scope.project.members : undefined) != null
+ ) {
return (() => {
const result = []
- for (let user of Array.from(users)) {
- if (user.id != null) {
- result.push(($scope.users[user.id] = formatUser(user)))
+ for (let member of Array.from(members)) {
+ if (member.privileges === 'readAndWrite') {
+ if ($scope.reviewPanel.trackChangesState[member._id] == null) {
+ // An added member will have track changes enabled if track changes is on for everyone
+ _setUserTCState(
+ member._id,
+ $scope.reviewPanel.trackChangesOnForEveryone,
+ true
+ )
+ }
+ result.push(
+ ($scope.reviewPanel.formattedProjectMembers[
+ member._id
+ ] = formatUser(member))
+ )
} else {
result.push(undefined)
}
}
return result
})()
- })
- .catch(() => (_refreshingRangeUsers = false))
- }
+ }
+ })
- let _threadsLoaded = false
- var ensureThreadsAreLoaded = function() {
- if (_threadsLoaded) {
- // We get any updates in real time so only need to load them once.
- return
+ $scope.commentState = {
+ adding: false,
+ content: ''
}
- _threadsLoaded = true
- $scope.reviewPanel.loadingThreads = true
- return $http
- .get(`/project/${$scope.project_id}/threads`)
- .then(function(response) {
- const threads = response.data
- $scope.reviewPanel.loadingThreads = false
- for (var thread_id in $scope.reviewPanel.resolvedThreadIds) {
- const _ = $scope.reviewPanel.resolvedThreadIds[thread_id]
- delete $scope.reviewPanel.resolvedThreadIds[thread_id]
+
+ $scope.users = {}
+
+ $scope.reviewPanelEventsBridge = new EventEmitter()
+
+ ide.socket.on('new-comment', function (thread_id, comment) {
+ const thread = getThread(thread_id)
+ delete thread.submitting
+ thread.messages.push(formatComment(comment))
+ $scope.$apply()
+ return $timeout(() => $scope.$broadcast('review-panel:layout'))
+ })
+
+ ide.socket.on('accept-changes', function (doc_id, change_ids) {
+ if (doc_id !== $scope.editor.open_doc_id) {
+ getChangeTracker(doc_id).removeChangeIds(change_ids)
+ } else {
+ $scope.$broadcast('changes:accept', change_ids)
+ }
+ updateEntries(doc_id)
+ return $scope.$apply(function () {})
+ })
+
+ ide.socket.on('resolve-thread', (thread_id, user) =>
+ _onCommentResolved(thread_id, user)
+ )
+
+ ide.socket.on('reopen-thread', thread_id => _onCommentReopened(thread_id))
+
+ ide.socket.on('delete-thread', function (thread_id) {
+ _onThreadDeleted(thread_id)
+ return $scope.$apply(function () {})
+ })
+
+ ide.socket.on('edit-message', function (thread_id, message_id, content) {
+ _onCommentEdited(thread_id, message_id, content)
+ return $scope.$apply(function () {})
+ })
+
+ ide.socket.on('delete-message', function (thread_id, message_id) {
+ _onCommentDeleted(thread_id, message_id)
+ return $scope.$apply(function () {})
+ })
+
+ const rangesTrackers = {}
+
+ const getDocEntries = function (doc_id) {
+ if ($scope.reviewPanel.entries[doc_id] == null) {
+ $scope.reviewPanel.entries[doc_id] = {}
+ }
+ return $scope.reviewPanel.entries[doc_id]
+ }
+
+ const getDocResolvedComments = function (doc_id) {
+ if ($scope.reviewPanel.resolvedComments[doc_id] == null) {
+ $scope.reviewPanel.resolvedComments[doc_id] = {}
+ }
+ return $scope.reviewPanel.resolvedComments[doc_id]
+ }
+
+ var getThread = function (thread_id) {
+ if ($scope.reviewPanel.commentThreads[thread_id] == null) {
+ $scope.reviewPanel.commentThreads[thread_id] = { messages: [] }
+ }
+ return $scope.reviewPanel.commentThreads[thread_id]
+ }
+
+ var getChangeTracker = function (doc_id) {
+ if (rangesTrackers[doc_id] == null) {
+ rangesTrackers[doc_id] = new RangesTracker()
+ rangesTrackers[doc_id].resolvedThreadIds =
+ $scope.reviewPanel.resolvedThreadIds
+ }
+ return rangesTrackers[doc_id]
+ }
+
+ let scrollbar = {}
+ $scope.reviewPanelEventsBridge.on(
+ 'aceScrollbarVisibilityChanged',
+ function (isVisible, scrollbarWidth) {
+ scrollbar = { isVisible, scrollbarWidth }
+ return updateScrollbar()
+ }
+ )
+
+ var updateScrollbar = function () {
+ if (
+ scrollbar.isVisible &&
+ $scope.reviewPanel.subView === $scope.SubViews.CUR_FILE &&
+ !$scope.editor.showRichText
+ ) {
+ return $reviewPanelEl.css('right', `${scrollbar.scrollbarWidth}px`)
+ } else {
+ return $reviewPanelEl.css('right', '0')
+ }
+ }
+
+ $scope.$watch(
+ '!ui.reviewPanelOpen && reviewPanel.hasEntries',
+ function (open, prevVal) {
+ if (open == null) {
+ return
}
- for (thread_id in threads) {
- const thread = threads[thread_id]
- for (let comment of Array.from(thread.messages)) {
- formatComment(comment)
- }
- if (thread.resolved_by_user != null) {
- thread.resolved_by_user = formatUser(thread.resolved_by_user)
- $scope.reviewPanel.resolvedThreadIds[thread_id] = true
- $scope.$broadcast('comment:resolve_threads', [thread_id])
- }
+ $scope.ui.miniReviewPanelVisible = open
+ if (open !== prevVal) {
+ return $timeout(() => $scope.$broadcast('review-panel:toggle'))
}
- $scope.reviewPanel.commentThreads = threads
- return $timeout(() => $scope.$broadcast('review-panel:layout'))
+ }
+ )
+
+ $scope.$watch('ui.reviewPanelOpen', function (open) {
+ if (open == null) {
+ return
+ }
+ if (!open) {
+ // Always show current file when not open, but save current state
+ $scope.reviewPanel.openSubView = $scope.reviewPanel.subView
+ $scope.reviewPanel.subView = $scope.SubViews.CUR_FILE
+ } else {
+ // Reset back to what we had when previously open
+ $scope.reviewPanel.subView = $scope.reviewPanel.openSubView
+ }
+ return $timeout(function () {
+ $scope.$broadcast('review-panel:toggle')
+ return $scope.$broadcast('review-panel:layout', false)
})
- }
+ })
- var formatComment = function(comment) {
- comment.user = formatUser(comment.user)
- comment.timestamp = new Date(comment.timestamp)
- return comment
- }
+ $scope.$watch('reviewPanel.subView', function (view) {
+ if (view == null) {
+ return
+ }
+ updateScrollbar()
+ if (view === $scope.SubViews.OVERVIEW) {
+ return refreshOverviewPanel()
+ }
+ })
- var formatUser = function(user) {
- let isSelf, name
- const id =
- (user != null ? user._id : undefined) ||
- (user != null ? user.id : undefined)
+ $scope.$watch('editor.sharejs_doc', function (doc, old_doc) {
+ if (doc == null) {
+ return
+ }
+ // The open doc range tracker is kept up to date in real-time so
+ // replace any outdated info with this
+ rangesTrackers[doc.doc_id] = doc.ranges
+ rangesTrackers[doc.doc_id].resolvedThreadIds =
+ $scope.reviewPanel.resolvedThreadIds
+ $scope.reviewPanel.rangesTracker = rangesTrackers[doc.doc_id]
+ if (old_doc != null) {
+ old_doc.off('flipped_pending_to_inflight')
+ }
+ doc.on('flipped_pending_to_inflight', () => regenerateTrackChangesId(doc))
+ return regenerateTrackChangesId(doc)
+ })
- if (id == null) {
+ $scope.$watch(
+ function () {
+ const entries =
+ $scope.reviewPanel.entries[$scope.editor.open_doc_id] || {}
+ const permEntries = {}
+ for (let entry in entries) {
+ const entryData = entries[entry]
+ if (!['add-comment', 'bulk-actions'].includes(entry)) {
+ permEntries[entry] = entryData
+ }
+ }
+ return Object.keys(permEntries).length
+ },
+ nEntries =>
+ ($scope.reviewPanel.hasEntries =
+ nEntries > 0 && $scope.project.features.trackChangesVisible)
+ )
+
+ var regenerateTrackChangesId = function (doc) {
+ const old_id = getChangeTracker(doc.doc_id).getIdSeed()
+ const new_id = RangesTracker.generateIdSeed()
+ getChangeTracker(doc.doc_id).setIdSeed(new_id)
+ return doc.setTrackChangesIdSeeds({ pending: new_id, inflight: old_id })
+ }
+
+ const refreshRanges = () =>
+ $http
+ .get(`/project/${$scope.project_id}/ranges`)
+ .then(function (response) {
+ const docs = response.data
+ return (() => {
+ const result = []
+ for (let doc of Array.from(docs)) {
+ if (
+ $scope.reviewPanel.overview.docsCollapsedState[doc.id] == null
+ ) {
+ $scope.reviewPanel.overview.docsCollapsedState[doc.id] = false
+ }
+ if (doc.id !== $scope.editor.open_doc_id) {
+ // this is kept up to date in real-time, don't overwrite
+ const rangesTracker = getChangeTracker(doc.id)
+ rangesTracker.comments =
+ (doc.ranges != null ? doc.ranges.comments : undefined) || []
+ rangesTracker.changes =
+ (doc.ranges != null ? doc.ranges.changes : undefined) || []
+ }
+ result.push(updateEntries(doc.id))
+ }
+ return result
+ })()
+ })
+
+ var refreshOverviewPanel = function () {
+ $scope.reviewPanel.overview.loading = true
+ return refreshRanges()
+ .then(() => ($scope.reviewPanel.overview.loading = false))
+ .catch(() => ($scope.reviewPanel.overview.loading = false))
+ }
+
+ $scope.refreshResolvedCommentsDropdown = function () {
+ $scope.reviewPanel.dropdown.loading = true
+ const q = refreshRanges()
+ q.then(() => ($scope.reviewPanel.dropdown.loading = false))
+ q.catch(() => ($scope.reviewPanel.dropdown.loading = false))
+ return q
+ }
+
+ var updateEntries = function (doc_id) {
+ let change, entry_id, key, new_entry, value
+ const rangesTracker = getChangeTracker(doc_id)
+ const entries = getDocEntries(doc_id)
+ const resolvedComments = getDocResolvedComments(doc_id)
+
+ let changed = false
+
+ // Assume we'll delete everything until we see it, then we'll remove it from this object
+ const delete_changes = {}
+ for (var id in entries) {
+ change = entries[id]
+ if (!['add-comment', 'bulk-actions'].includes(id)) {
+ for (entry_id of Array.from(change.entry_ids)) {
+ delete_changes[entry_id] = true
+ }
+ }
+ }
+ for (id in resolvedComments) {
+ change = resolvedComments[id]
+ for (entry_id of Array.from(change.entry_ids)) {
+ delete_changes[entry_id] = true
+ }
+ }
+
+ let potential_aggregate = false
+ let prev_insertion = null
+
+ for (change of Array.from(rangesTracker.changes)) {
+ changed = true
+
+ if (
+ potential_aggregate &&
+ change.op.d &&
+ change.op.p === prev_insertion.op.p + prev_insertion.op.i.length &&
+ change.metadata.user_id === prev_insertion.metadata.user_id
+ ) {
+ // An actual aggregate op.
+ entries[prev_insertion.id].type = 'aggregate-change'
+ entries[prev_insertion.id].metadata.replaced_content = change.op.d
+ entries[prev_insertion.id].entry_ids.push(change.id)
+ } else {
+ if (entries[change.id] == null) {
+ entries[change.id] = {}
+ }
+ delete delete_changes[change.id]
+ new_entry = {
+ type: change.op.i ? 'insert' : 'delete',
+ entry_ids: [change.id],
+ content: change.op.i || change.op.d,
+ offset: change.op.p,
+ metadata: change.metadata
+ }
+ for (key in new_entry) {
+ value = new_entry[key]
+ entries[change.id][key] = value
+ }
+ }
+
+ if (change.op.i) {
+ potential_aggregate = true
+ prev_insertion = change
+ } else {
+ potential_aggregate = false
+ prev_insertion = null
+ }
+
+ if ($scope.users[change.metadata.user_id] == null) {
+ refreshChangeUsers(change.metadata.user_id)
+ }
+ }
+
+ if (rangesTracker.comments.length > 0) {
+ ensureThreadsAreLoaded()
+ }
+
+ for (let comment of Array.from(rangesTracker.comments)) {
+ var new_comment
+ changed = true
+ delete delete_changes[comment.id]
+ if ($scope.reviewPanel.resolvedThreadIds[comment.op.t]) {
+ new_comment =
+ resolvedComments[comment.id] != null
+ ? resolvedComments[comment.id]
+ : (resolvedComments[comment.id] = {})
+ delete entries[comment.id]
+ } else {
+ new_comment =
+ entries[comment.id] != null
+ ? entries[comment.id]
+ : (entries[comment.id] = {})
+ delete resolvedComments[comment.id]
+ }
+ new_entry = {
+ type: 'comment',
+ thread_id: comment.op.t,
+ entry_ids: [comment.id],
+ content: comment.op.c,
+ offset: comment.op.p
+ }
+ for (key in new_entry) {
+ value = new_entry[key]
+ new_comment[key] = value
+ }
+ }
+
+ for (let change_id in delete_changes) {
+ const _ = delete_changes[change_id]
+ changed = true
+ delete entries[change_id]
+ delete resolvedComments[change_id]
+ }
+
+ if (changed) {
+ return $scope.$broadcast('entries:changed')
+ }
+ }
+
+ $scope.$on('editor:track-changes:changed', function () {
+ const doc_id = $scope.editor.open_doc_id
+ updateEntries(doc_id)
+
+ // For now, not worrying about entry panels for rich text
+ if (!$scope.editor.showRichText) {
+ $scope.$broadcast('review-panel:recalculate-screen-positions')
+ return $scope.$broadcast('review-panel:layout')
+ }
+ })
+
+ $scope.$on('editor:track-changes:visibility_changed', () =>
+ $timeout(() => $scope.$broadcast('review-panel:layout', false))
+ )
+
+ $scope.$on(
+ 'editor:focus:changed',
+ function (e, selection_offset_start, selection_offset_end, selection) {
+ const doc_id = $scope.editor.open_doc_id
+ const entries = getDocEntries(doc_id)
+ // All selected changes will be added to this array.
+ $scope.reviewPanel.selectedEntryIds = []
+ // Count of user-visible changes, i.e. an aggregated change will count as one.
+ $scope.reviewPanel.nVisibleSelectedChanges = 0
+ delete entries['add-comment']
+ delete entries['bulk-actions']
+
+ if (selection) {
+ entries['add-comment'] = {
+ type: 'add-comment',
+ offset: selection_offset_start,
+ length: selection_offset_end - selection_offset_start
+ }
+ entries['bulk-actions'] = {
+ type: 'bulk-actions',
+ offset: selection_offset_start,
+ length: selection_offset_end - selection_offset_start
+ }
+ }
+
+ for (let id in entries) {
+ const entry = entries[id]
+ let isChangeEntryAndWithinSelection = false
+ if (
+ entry.type === 'comment' &&
+ !$scope.reviewPanel.resolvedThreadIds[entry.thread_id]
+ ) {
+ entry.focused =
+ entry.offset <= selection_offset_start &&
+ selection_offset_start <= entry.offset + entry.content.length
+ } else if (entry.type === 'insert') {
+ isChangeEntryAndWithinSelection =
+ entry.offset >= selection_offset_start &&
+ entry.offset + entry.content.length <= selection_offset_end
+ entry.focused =
+ entry.offset <= selection_offset_start &&
+ selection_offset_start <= entry.offset + entry.content.length
+ } else if (entry.type === 'delete') {
+ isChangeEntryAndWithinSelection =
+ selection_offset_start <= entry.offset &&
+ entry.offset <= selection_offset_end
+ entry.focused = entry.offset === selection_offset_start
+ } else if (entry.type === 'aggregate-change') {
+ isChangeEntryAndWithinSelection =
+ entry.offset >= selection_offset_start &&
+ entry.offset + entry.content.length <= selection_offset_end
+ entry.focused =
+ entry.offset <= selection_offset_start &&
+ selection_offset_start <= entry.offset + entry.content.length
+ } else if (
+ ['add-comment', 'bulk-actions'].includes(entry.type) &&
+ selection
+ ) {
+ entry.focused = true
+ }
+
+ if (isChangeEntryAndWithinSelection) {
+ for (let entry_id of Array.from(entry.entry_ids)) {
+ $scope.reviewPanel.selectedEntryIds.push(entry_id)
+ }
+ $scope.reviewPanel.nVisibleSelectedChanges++
+ }
+ }
+
+ $scope.$broadcast('review-panel:recalculate-screen-positions')
+ return $scope.$broadcast('review-panel:layout')
+ }
+ )
+
+ $scope.acceptChanges = function (change_ids) {
+ _doAcceptChanges(change_ids)
+ return eventTracking.sendMB('rp-changes-accepted', {
+ view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini'
+ })
+ }
+
+ $scope.rejectChanges = function (change_ids) {
+ _doRejectChanges(change_ids)
+ return eventTracking.sendMB('rp-changes-rejected', {
+ view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini'
+ })
+ }
+
+ var _doAcceptChanges = function (change_ids) {
+ $http.post(
+ `/project/${$scope.project_id}/doc/${$scope.editor.open_doc_id}/changes/accept`,
+ { change_ids, _csrf: window.csrfToken }
+ )
+ return $scope.$broadcast('changes:accept', change_ids)
+ }
+
+ var _doRejectChanges = change_ids =>
+ $scope.$broadcast('changes:reject', change_ids)
+
+ const bulkAccept = function () {
+ _doAcceptChanges($scope.reviewPanel.selectedEntryIds.slice())
+ return eventTracking.sendMB('rp-bulk-accept', {
+ view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini',
+ nEntries: $scope.reviewPanel.nVisibleSelectedChanges
+ })
+ }
+
+ const bulkReject = function () {
+ _doRejectChanges($scope.reviewPanel.selectedEntryIds.slice())
+ return eventTracking.sendMB('rp-bulk-reject', {
+ view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini',
+ nEntries: $scope.reviewPanel.nVisibleSelectedChanges
+ })
+ }
+
+ $scope.showBulkAcceptDialog = () => showBulkActionsDialog(true)
+
+ $scope.showBulkRejectDialog = () => showBulkActionsDialog(false)
+
+ var showBulkActionsDialog = isAccept =>
+ $modal
+ .open({
+ templateUrl: 'bulkActionsModalTemplate',
+ controller: 'BulkActionsModalController',
+ resolve: {
+ isAccept() {
+ return isAccept
+ },
+ nChanges() {
+ return $scope.reviewPanel.nVisibleSelectedChanges
+ }
+ },
+ scope: $scope.$new()
+ })
+ .result.then(function (isAccept) {
+ if (isAccept) {
+ return bulkAccept()
+ } else {
+ return bulkReject()
+ }
+ })
+
+ $scope.handleTogglerClick = function (e) {
+ e.target.blur()
+ return $scope.toggleReviewPanel()
+ }
+
+ $scope.addNewComment = function () {
+ $scope.$broadcast('comment:start_adding')
+ return $scope.toggleReviewPanel()
+ }
+
+ $scope.addNewCommentFromKbdShortcut = function () {
+ if (!$scope.project.features.trackChangesVisible) {
+ return
+ }
+ $scope.$broadcast('comment:select_line')
+ if (!$scope.ui.reviewPanelOpen) {
+ $scope.toggleReviewPanel()
+ }
+ return $timeout(function () {
+ $scope.$broadcast('review-panel:layout')
+ return $scope.$broadcast('comment:start_adding')
+ })
+ }
+
+ $scope.startNewComment = function () {
+ $scope.$broadcast('comment:select_line')
+ return $timeout(() => $scope.$broadcast('review-panel:layout'))
+ }
+
+ $scope.submitNewComment = function (content) {
+ if (content == null || content === '') {
+ return
+ }
+ const doc_id = $scope.editor.open_doc_id
+ const entries = getDocEntries(doc_id)
+ if (entries['add-comment'] == null) {
+ return
+ }
+ const { offset, length } = entries['add-comment']
+ const thread_id = RangesTracker.generateId()
+ const thread = getThread(thread_id)
+ thread.submitting = true
+ $scope.$broadcast('comment:add', thread_id, offset, length)
+ $http
+ .post(`/project/${$scope.project_id}/thread/${thread_id}/messages`, {
+ content,
+ _csrf: window.csrfToken
+ })
+ .catch(() =>
+ ide.showGenericMessageModal(
+ 'Error submitting comment',
+ 'Sorry, there was a problem submitting your comment'
+ )
+ )
+ $scope.$broadcast('editor:clearSelection')
+ $timeout(() => $scope.$broadcast('review-panel:layout'))
+ return eventTracking.sendMB('rp-new-comment', { size: content.length })
+ }
+
+ $scope.cancelNewComment = entry =>
+ $timeout(() => $scope.$broadcast('review-panel:layout'))
+
+ $scope.startReply = function (entry) {
+ entry.replying = true
+ return $timeout(() => $scope.$broadcast('review-panel:layout'))
+ }
+
+ $scope.submitReply = function (entry, entry_id) {
+ const { thread_id } = entry
+ const content = entry.replyContent
+ $http
+ .post(`/project/${$scope.project_id}/thread/${thread_id}/messages`, {
+ content,
+ _csrf: window.csrfToken
+ })
+ .catch(() =>
+ ide.showGenericMessageModal(
+ 'Error submitting comment',
+ 'Sorry, there was a problem submitting your comment'
+ )
+ )
+
+ const trackingMetadata = {
+ view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini',
+ size: entry.replyContent.length,
+ thread: thread_id
+ }
+
+ const thread = getThread(thread_id)
+ thread.submitting = true
+ entry.replyContent = ''
+ entry.replying = false
+ $timeout(() => $scope.$broadcast('review-panel:layout'))
+ return eventTracking.sendMB('rp-comment-reply', trackingMetadata)
+ }
+
+ $scope.cancelReply = function (entry) {
+ entry.replying = false
+ entry.replyContent = ''
+ return $scope.$broadcast('review-panel:layout')
+ }
+
+ $scope.resolveComment = function (entry, entry_id) {
+ entry.focused = false
+ $http.post(
+ `/project/${$scope.project_id}/thread/${entry.thread_id}/resolve`,
+ { _csrf: window.csrfToken }
+ )
+ _onCommentResolved(entry.thread_id, ide.$scope.user)
+ return eventTracking.sendMB('rp-comment-resolve', {
+ view: $scope.ui.reviewPanelOpen ? $scope.reviewPanel.subView : 'mini'
+ })
+ }
+
+ $scope.unresolveComment = function (thread_id) {
+ _onCommentReopened(thread_id)
+ $http.post(`/project/${$scope.project_id}/thread/${thread_id}/reopen`, {
+ _csrf: window.csrfToken
+ })
+ return eventTracking.sendMB('rp-comment-reopen')
+ }
+
+ var _onCommentResolved = function (thread_id, user) {
+ const thread = getThread(thread_id)
+ if (thread == null) {
+ return
+ }
+ thread.resolved = true
+ thread.resolved_by_user = formatUser(user)
+ thread.resolved_at = new Date().toISOString()
+ $scope.reviewPanel.resolvedThreadIds[thread_id] = true
+ return $scope.$broadcast('comment:resolve_threads', [thread_id])
+ }
+
+ var _onCommentReopened = function (thread_id) {
+ const thread = getThread(thread_id)
+ if (thread == null) {
+ return
+ }
+ delete thread.resolved
+ delete thread.resolved_by_user
+ delete thread.resolved_at
+ delete $scope.reviewPanel.resolvedThreadIds[thread_id]
+ return $scope.$broadcast('comment:unresolve_thread', thread_id)
+ }
+
+ var _onThreadDeleted = function (thread_id) {
+ delete $scope.reviewPanel.resolvedThreadIds[thread_id]
+ delete $scope.reviewPanel.commentThreads[thread_id]
+ return $scope.$broadcast('comment:remove', thread_id)
+ }
+
+ var _onCommentEdited = function (thread_id, comment_id, content) {
+ const thread = getThread(thread_id)
+ if (thread == null) {
+ return
+ }
+ for (let message of Array.from(thread.messages)) {
+ if (message.id === comment_id) {
+ message.content = content
+ }
+ }
+ return updateEntries()
+ }
+
+ var _onCommentDeleted = function (thread_id, comment_id) {
+ const thread = getThread(thread_id)
+ if (thread == null) {
+ return
+ }
+ thread.messages = thread.messages.filter(m => m.id !== comment_id)
+ return updateEntries()
+ }
+
+ $scope.deleteThread = function (entry_id, doc_id, thread_id) {
+ _onThreadDeleted(thread_id)
+ $http({
+ method: 'DELETE',
+ url: `/project/${$scope.project_id}/doc/${doc_id}/thread/${thread_id}`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken
+ }
+ })
+ return eventTracking.sendMB('rp-comment-delete')
+ }
+
+ $scope.saveEdit = function (thread_id, comment) {
+ $http.post(
+ `/project/${$scope.project_id}/thread/${thread_id}/messages/${comment.id}/edit`,
+ {
+ content: comment.content,
+ _csrf: window.csrfToken
+ }
+ )
+ return $timeout(() => $scope.$broadcast('review-panel:layout'))
+ }
+
+ $scope.deleteComment = function (thread_id, comment) {
+ _onCommentDeleted(thread_id, comment.id)
+ $http({
+ method: 'DELETE',
+ url: `/project/${$scope.project_id}/thread/${thread_id}/messages/${comment.id}`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken
+ }
+ })
+ return $timeout(() => $scope.$broadcast('review-panel:layout'))
+ }
+
+ $scope.setSubView = function (subView) {
+ $scope.reviewPanel.subView = subView
+ return eventTracking.sendMB('rp-subview-change', { subView })
+ }
+
+ $scope.gotoEntry = (doc_id, entry) =>
+ ide.editorManager.openDocId(doc_id, { gotoOffset: entry.offset })
+
+ $scope.toggleFullTCStateCollapse = function () {
+ if ($scope.project.features.trackChanges) {
+ return ($scope.reviewPanel.fullTCStateCollapsed = !$scope.reviewPanel
+ .fullTCStateCollapsed)
+ } else {
+ _sendAnalytics()
+ return $scope.openTrackChangesUpgradeModal()
+ }
+ }
+
+ const _sendAnalytics = () => {
+ eventTracking.send(
+ 'subscription-funnel',
+ 'editor-click-feature',
+ 'real-time-track-changes'
+ )
+ }
+
+ const _setUserTCState = function (userId, newValue, isLocal) {
+ if (isLocal == null) {
+ isLocal = false
+ }
+ if ($scope.reviewPanel.trackChangesState[userId] == null) {
+ $scope.reviewPanel.trackChangesState[userId] = {}
+ }
+ const state = $scope.reviewPanel.trackChangesState[userId]
+
+ if (
+ state.syncState == null ||
+ state.syncState === UserTCSyncState.SYNCED
+ ) {
+ state.value = newValue
+ state.syncState = UserTCSyncState.SYNCED
+ } else if (
+ state.syncState === UserTCSyncState.PENDING &&
+ state.value === newValue
+ ) {
+ state.syncState = UserTCSyncState.SYNCED
+ } else if (isLocal) {
+ state.value = newValue
+ state.syncState = UserTCSyncState.PENDING
+ }
+
+ if (userId === ide.$scope.user.id) {
+ return ($scope.editor.wantTrackChanges = newValue)
+ }
+ }
+
+ const _setEveryoneTCState = function (newValue, isLocal) {
+ if (isLocal == null) {
+ isLocal = false
+ }
+ $scope.reviewPanel.trackChangesOnForEveryone = newValue
+ const { project } = $scope
+ for (let member of Array.from(project.members)) {
+ _setUserTCState(member._id, newValue, isLocal)
+ }
+ _setGuestsTCState(newValue, isLocal)
+ return _setUserTCState(project.owner._id, newValue, isLocal)
+ }
+
+ var _setGuestsTCState = function (newValue, isLocal) {
+ if (isLocal == null) {
+ isLocal = false
+ }
+ $scope.reviewPanel.trackChangesOnForGuests = newValue
+ if (
+ currentUserType() === UserTypes.GUEST ||
+ currentUserType() === UserTypes.ANONYMOUS
+ ) {
+ return ($scope.editor.wantTrackChanges = newValue)
+ }
+ }
+
+ const applyClientTrackChangesStateToServer = function () {
+ const data = {}
+ if ($scope.reviewPanel.trackChangesOnForEveryone) {
+ data.on = true
+ } else {
+ data.on_for = {}
+ for (let userId in $scope.reviewPanel.trackChangesState) {
+ const userState = $scope.reviewPanel.trackChangesState[userId]
+ data.on_for[userId] = userState.value
+ }
+ if ($scope.reviewPanel.trackChangesOnForGuests) {
+ data.on_for_guests = true
+ }
+ }
+ data._csrf = window.csrfToken
+ return $http.post(`/project/${$scope.project_id}/track_changes`, data)
+ }
+
+ const applyTrackChangesStateToClient = function (state) {
+ if (typeof state === 'boolean') {
+ _setEveryoneTCState(state)
+ return _setGuestsTCState(state)
+ } else {
+ const { project } = $scope
+ $scope.reviewPanel.trackChangesOnForEveryone = false
+ _setGuestsTCState(state.__guests__ === true)
+ for (let member of Array.from(project.members)) {
+ _setUserTCState(
+ member._id,
+ state[member._id] != null ? state[member._id] : false
+ )
+ }
+ return _setUserTCState(
+ $scope.project.owner._id,
+ state[$scope.project.owner._id] != null
+ ? state[$scope.project.owner._id]
+ : false
+ )
+ }
+ }
+
+ $scope.toggleTrackChangesForEveryone = function (onForEveryone) {
+ _setEveryoneTCState(onForEveryone, true)
+ _setGuestsTCState(onForEveryone, true)
+ return applyClientTrackChangesStateToServer()
+ }
+
+ $scope.toggleTrackChangesForGuests = function (onForGuests) {
+ _setGuestsTCState(onForGuests, true)
+ return applyClientTrackChangesStateToServer()
+ }
+
+ $scope.toggleTrackChangesForUser = function (onForUser, userId) {
+ _setUserTCState(userId, onForUser, true)
+ return applyClientTrackChangesStateToServer()
+ }
+
+ ide.socket.on('toggle-track-changes', state =>
+ $scope.$apply(() => applyTrackChangesStateToClient(state))
+ )
+
+ $scope.toggleTrackChangesFromKbdShortcut = function () {
+ if (
+ !(
+ $scope.project.features.trackChangesVisible &&
+ $scope.project.features.trackChanges
+ )
+ ) {
+ return
+ }
+ return $scope.toggleTrackChangesForUser(
+ !$scope.reviewPanel.trackChangesState[ide.$scope.user.id].value,
+ ide.$scope.user.id
+ )
+ }
+
+ const setGuestFeatureBasedOnProjectAccessLevel = projectPublicAccessLevel =>
+ ($scope.reviewPanel.trackChangesForGuestsAvailable =
+ projectPublicAccessLevel === 'tokenBased')
+
+ const onToggleTrackChangesForGuestsAvailability = function (available) {
+ // If the feature is no longer available we need to turn off the guest flag
+ if (available) {
+ return
+ }
+ if (!$scope.reviewPanel.trackChangesOnForGuests) {
+ return
+ } // Already turned off
+ if ($scope.reviewPanel.trackChangesOnForEveryone) {
+ return
+ } // Overrides guest setting
+ return $scope.toggleTrackChangesForGuests(false)
+ }
+
+ $scope.$watch(
+ 'project.publicAccesLevel',
+ setGuestFeatureBasedOnProjectAccessLevel
+ )
+
+ $scope.$watch(
+ 'reviewPanel.trackChangesForGuestsAvailable',
+ function (available) {
+ if (available != null) {
+ return onToggleTrackChangesForGuestsAvailability(available)
+ }
+ }
+ )
+
+ let _inited = false
+ ide.$scope.$on('project:joined', function () {
+ if (_inited) {
+ return
+ }
+ const { project } = ide.$scope
+ if (project.features.trackChanges) {
+ applyTrackChangesStateToClient(project.trackChangesState)
+ } else {
+ applyTrackChangesStateToClient(false)
+ }
+ setGuestFeatureBasedOnProjectAccessLevel(project.publicAccesLevel)
+ return (_inited = true)
+ })
+
+ let _refreshingRangeUsers = false
+ const _refreshedForUserIds = {}
+ var refreshChangeUsers = function (refresh_for_user_id) {
+ if (refresh_for_user_id != null) {
+ if (_refreshedForUserIds[refresh_for_user_id] != null) {
+ // We've already tried to refresh to get this user id, so stop it looping
+ return
+ }
+ _refreshedForUserIds[refresh_for_user_id] = true
+ }
+
+ // Only do one refresh at once
+ if (_refreshingRangeUsers) {
+ return
+ }
+ _refreshingRangeUsers = true
+
+ return $http
+ .get(`/project/${$scope.project_id}/changes/users`)
+ .then(function (response) {
+ const users = response.data
+ _refreshingRangeUsers = false
+ $scope.users = {}
+ // Always include ourself, since if we submit an op, we might need to display info
+ // about it locally before it has been flushed through the server
+ if (
+ (ide.$scope.user != null ? ide.$scope.user.id : undefined) != null
+ ) {
+ $scope.users[ide.$scope.user.id] = formatUser(ide.$scope.user)
+ }
+ return (() => {
+ const result = []
+ for (let user of Array.from(users)) {
+ if (user.id != null) {
+ result.push(($scope.users[user.id] = formatUser(user)))
+ } else {
+ result.push(undefined)
+ }
+ }
+ return result
+ })()
+ })
+ .catch(() => (_refreshingRangeUsers = false))
+ }
+
+ let _threadsLoaded = false
+ var ensureThreadsAreLoaded = function () {
+ if (_threadsLoaded) {
+ // We get any updates in real time so only need to load them once.
+ return
+ }
+ _threadsLoaded = true
+ $scope.reviewPanel.loadingThreads = true
+ return $http
+ .get(`/project/${$scope.project_id}/threads`)
+ .then(function (response) {
+ const threads = response.data
+ $scope.reviewPanel.loadingThreads = false
+ for (var thread_id in $scope.reviewPanel.resolvedThreadIds) {
+ const _ = $scope.reviewPanel.resolvedThreadIds[thread_id]
+ delete $scope.reviewPanel.resolvedThreadIds[thread_id]
+ }
+ for (thread_id in threads) {
+ const thread = threads[thread_id]
+ for (let comment of Array.from(thread.messages)) {
+ formatComment(comment)
+ }
+ if (thread.resolved_by_user != null) {
+ thread.resolved_by_user = formatUser(thread.resolved_by_user)
+ $scope.reviewPanel.resolvedThreadIds[thread_id] = true
+ $scope.$broadcast('comment:resolve_threads', [thread_id])
+ }
+ }
+ $scope.reviewPanel.commentThreads = threads
+ return $timeout(() => $scope.$broadcast('review-panel:layout'))
+ })
+ }
+
+ var formatComment = function (comment) {
+ comment.user = formatUser(comment.user)
+ comment.timestamp = new Date(comment.timestamp)
+ return comment
+ }
+
+ var formatUser = function (user) {
+ let isSelf, name
+ const id =
+ (user != null ? user._id : undefined) ||
+ (user != null ? user.id : undefined)
+
+ if (id == null) {
+ return {
+ email: null,
+ name: 'Anonymous',
+ isSelf: false,
+ hue: ColorManager.ANONYMOUS_HUE,
+ avatar_text: 'A'
+ }
+ }
+ if (id === window.user_id) {
+ name = 'You'
+ isSelf = true
+ } else {
+ name = [user.first_name, user.last_name]
+ .filter(n => n != null && n !== '')
+ .join(' ')
+ if (name === '') {
+ name =
+ (user.email != null ? user.email.split('@')[0] : undefined) ||
+ 'Unknown'
+ }
+ isSelf = false
+ }
return {
- email: null,
- name: 'Anonymous',
- isSelf: false,
- hue: ColorManager.ANONYMOUS_HUE,
- avatar_text: 'A'
+ id,
+ email: user.email,
+ name,
+ isSelf,
+ hue: ColorManager.getHueForUserId(id),
+ avatar_text: [user.first_name, user.last_name]
+ .filter(n => n != null)
+ .map(n => n[0])
+ .join('')
}
}
- if (id === window.user_id) {
- name = 'You'
- isSelf = true
- } else {
- name = [user.first_name, user.last_name]
- .filter(n => n != null && n !== '')
- .join(' ')
- if (name === '') {
- name =
- (user.email != null ? user.email.split('@')[0] : undefined) ||
- 'Unknown'
- }
- isSelf = false
- }
- return {
- id,
- email: user.email,
- name,
- isSelf,
- hue: ColorManager.getHueForUserId(id),
- avatar_text: [user.first_name, user.last_name]
- .filter(n => n != null)
- .map(n => n[0])
- .join('')
- }
- }
- return ($scope.openTrackChangesUpgradeModal = () =>
- $modal.open({
- templateUrl: 'trackChangesUpgradeModalTemplate',
- controller: 'TrackChangesUpgradeModalController',
- scope: $scope.$new()
- }))
-})
+ return ($scope.openTrackChangesUpgradeModal = () =>
+ $modal.open({
+ templateUrl: 'trackChangesUpgradeModalTemplate',
+ controller: 'TrackChangesUpgradeModalController',
+ scope: $scope.$new()
+ }))
+ }
+)
diff --git a/services/web/frontend/js/ide/review-panel/directives/addCommentEntry.js b/services/web/frontend/js/ide/review-panel/directives/addCommentEntry.js
index afbcdcfd09..45883483fc 100644
--- a/services/web/frontend/js/ide/review-panel/directives/addCommentEntry.js
+++ b/services/web/frontend/js/ide/review-panel/directives/addCommentEntry.js
@@ -15,23 +15,23 @@ App.directive('addCommentEntry', () => ({
}
scope.$on('comment:start_adding', () => scope.startNewComment())
- scope.$on('$destroy', function() {
+ scope.$on('$destroy', function () {
content = scope.state.content
})
- scope.startNewComment = function() {
+ scope.startNewComment = function () {
scope.state.isAdding = true
scope.onStartNew()
setTimeout(() => scope.$broadcast('comment:new:open'))
}
- scope.cancelNewComment = function() {
+ scope.cancelNewComment = function () {
scope.state.isAdding = false
scope.state.content = ''
scope.onCancel()
}
- scope.handleCommentKeyPress = function(ev) {
+ scope.handleCommentKeyPress = function (ev) {
if (ev.keyCode === 13 && !ev.shiftKey && !ev.ctrlKey && !ev.metaKey) {
ev.preventDefault()
if (scope.state.content.length > 0) {
@@ -40,7 +40,7 @@ App.directive('addCommentEntry', () => ({
}
}
- scope.submitNewComment = function(event) {
+ scope.submitNewComment = function (event) {
scope.onSubmit({ content: scope.state.content })
content = scope.state.content
scope.state.isAdding = false
diff --git a/services/web/frontend/js/ide/review-panel/directives/aggregateChangeEntry.js b/services/web/frontend/js/ide/review-panel/directives/aggregateChangeEntry.js
index af5505ce20..4f286eec9b 100644
--- a/services/web/frontend/js/ide/review-panel/directives/aggregateChangeEntry.js
+++ b/services/web/frontend/js/ide/review-panel/directives/aggregateChangeEntry.js
@@ -30,7 +30,7 @@ export default App.directive('aggregateChangeEntry', $timeout => ({
scope.deletionNeedsCollapsing = false
scope.insertionNeedsCollapsing = false
- element.on('click', function(e) {
+ element.on('click', function (e) {
if (
$(e.target).is(
'.rp-entry, .rp-entry-description, .rp-entry-body, .rp-entry-action-icon i'
@@ -40,12 +40,12 @@ export default App.directive('aggregateChangeEntry', $timeout => ({
}
})
- scope.toggleDeletionCollapse = function() {
+ scope.toggleDeletionCollapse = function () {
scope.isDeletionCollapsed = !scope.isDeletionCollapsed
return $timeout(() => scope.$emit('review-panel:layout'))
}
- scope.toggleInsertionCollapse = function() {
+ scope.toggleInsertionCollapse = function () {
scope.isInsertionCollapsed = !scope.isInsertionCollapsed
return $timeout(() => scope.$emit('review-panel:layout'))
}
diff --git a/services/web/frontend/js/ide/review-panel/directives/changeEntry.js b/services/web/frontend/js/ide/review-panel/directives/changeEntry.js
index 9d43669495..39018ca17b 100644
--- a/services/web/frontend/js/ide/review-panel/directives/changeEntry.js
+++ b/services/web/frontend/js/ide/review-panel/directives/changeEntry.js
@@ -28,7 +28,7 @@ export default App.directive('changeEntry', $timeout => ({
scope.isCollapsed = true
scope.needsCollapsing = false
- element.on('click', function(e) {
+ element.on('click', function (e) {
if (
$(e.target).is(
'.rp-entry, .rp-entry-description, .rp-entry-body, .rp-entry-action-icon i'
@@ -38,7 +38,7 @@ export default App.directive('changeEntry', $timeout => ({
}
})
- scope.toggleCollapse = function() {
+ scope.toggleCollapse = function () {
scope.isCollapsed = !scope.isCollapsed
return $timeout(() => scope.$emit('review-panel:layout'))
}
diff --git a/services/web/frontend/js/ide/review-panel/directives/commentEntry.js b/services/web/frontend/js/ide/review-panel/directives/commentEntry.js
index 66cd3e276f..56ad15d0a5 100644
--- a/services/web/frontend/js/ide/review-panel/directives/commentEntry.js
+++ b/services/web/frontend/js/ide/review-panel/directives/commentEntry.js
@@ -28,7 +28,7 @@ export default App.directive('commentEntry', $timeout => ({
link(scope, element, attrs) {
scope.state = { animating: false }
- element.on('click', function(e) {
+ element.on('click', function (e) {
if (
$(e.target).is(
'.rp-entry, .rp-comment-loaded, .rp-comment-content, .rp-comment-reply, .rp-entry-metadata'
@@ -38,7 +38,7 @@ export default App.directive('commentEntry', $timeout => ({
}
})
- scope.handleCommentReplyKeyPress = function(ev) {
+ scope.handleCommentReplyKeyPress = function (ev) {
if (ev.keyCode === 13 && !ev.shiftKey && !ev.ctrlKey && !ev.metaKey) {
ev.preventDefault()
if (scope.entry.replyContent.length > 0) {
@@ -48,39 +48,39 @@ export default App.directive('commentEntry', $timeout => ({
}
}
- scope.animateAndCallOnResolve = function() {
+ scope.animateAndCallOnResolve = function () {
scope.state.animating = true
element.find('.rp-entry').css('top', 0)
$timeout(() => scope.onResolve(), 350)
return true
}
- scope.startEditing = function(comment) {
+ scope.startEditing = function (comment) {
comment.editing = true
return setTimeout(() => scope.$emit('review-panel:layout'))
}
- scope.saveEdit = function(comment) {
+ scope.saveEdit = function (comment) {
comment.editing = false
return scope.onSaveEdit({ comment })
}
- scope.confirmDelete = function(comment) {
+ scope.confirmDelete = function (comment) {
comment.deleting = true
return setTimeout(() => scope.$emit('review-panel:layout'))
}
- scope.cancelDelete = function(comment) {
+ scope.cancelDelete = function (comment) {
comment.deleting = false
return setTimeout(() => scope.$emit('review-panel:layout'))
}
- scope.doDelete = function(comment) {
+ scope.doDelete = function (comment) {
comment.deleting = false
return scope.onDelete({ comment })
}
- return (scope.saveEditOnEnter = function(ev, comment) {
+ return (scope.saveEditOnEnter = function (ev, comment) {
if (ev.keyCode === 13 && !ev.shiftKey && !ev.ctrlKey && !ev.metaKey) {
ev.preventDefault()
return scope.saveEdit(comment)
diff --git a/services/web/frontend/js/ide/review-panel/directives/resolvedCommentsDropdown.js b/services/web/frontend/js/ide/review-panel/directives/resolvedCommentsDropdown.js
index e282f23aed..a617bc1a23 100644
--- a/services/web/frontend/js/ide/review-panel/directives/resolvedCommentsDropdown.js
+++ b/services/web/frontend/js/ide/review-panel/directives/resolvedCommentsDropdown.js
@@ -33,7 +33,7 @@ export default App.directive('resolvedCommentsDropdown', () => ({
let filterResolvedComments
scope.state = { isOpen: false }
- scope.toggleOpenState = function() {
+ scope.toggleOpenState = function () {
scope.state.isOpen = !scope.state.isOpen
if (scope.state.isOpen) {
return scope.onOpen().then(() => filterResolvedComments())
@@ -42,21 +42,21 @@ export default App.directive('resolvedCommentsDropdown', () => ({
scope.resolvedComments = []
- scope.handleUnresolve = function(threadId) {
+ scope.handleUnresolve = function (threadId) {
scope.onUnresolve({ threadId })
return (scope.resolvedComments = scope.resolvedComments.filter(
c => c.threadId !== threadId
))
}
- scope.handleDelete = function(entryId, docId, threadId) {
+ scope.handleDelete = function (entryId, docId, threadId) {
scope.onDelete({ entryId, docId, threadId })
return (scope.resolvedComments = scope.resolvedComments.filter(
c => c.threadId !== threadId
))
}
- const getDocNameById = function(docId) {
+ const getDocNameById = function (docId) {
const doc = _.find(scope.docs, doc => doc.doc.id === docId)
if (doc != null) {
return doc.path
@@ -65,7 +65,7 @@ export default App.directive('resolvedCommentsDropdown', () => ({
}
}
- return (filterResolvedComments = function() {
+ return (filterResolvedComments = function () {
scope.resolvedComments = []
return (() => {
diff --git a/services/web/frontend/js/ide/review-panel/directives/reviewPanelCollapseHeight.js b/services/web/frontend/js/ide/review-panel/directives/reviewPanelCollapseHeight.js
index 66637a14fd..f8243b3024 100644
--- a/services/web/frontend/js/ide/review-panel/directives/reviewPanelCollapseHeight.js
+++ b/services/web/frontend/js/ide/review-panel/directives/reviewPanelCollapseHeight.js
@@ -15,7 +15,7 @@ export default App.directive('reviewPanelCollapseHeight', $parse => ({
link(scope, element, attrs) {
return scope.$watch(
() => $parse(attrs.reviewPanelCollapseHeight)(scope),
- function(shouldCollapse) {
+ function (shouldCollapse) {
const neededHeight = element.prop('scrollHeight')
if (neededHeight > 0) {
if (shouldCollapse) {
diff --git a/services/web/frontend/js/ide/review-panel/directives/reviewPanelSorted.js b/services/web/frontend/js/ide/review-panel/directives/reviewPanelSorted.js
index a12b6f83cc..dc1eb1c6f9 100644
--- a/services/web/frontend/js/ide/review-panel/directives/reviewPanelSorted.js
+++ b/services/web/frontend/js/ide/review-panel/directives/reviewPanelSorted.js
@@ -19,7 +19,7 @@ export default App.directive('reviewPanelSorted', $timeout => ({
link(scope, element, attrs) {
let previous_focused_entry_index = 0
- const layout = function(animate) {
+ const layout = function (animate) {
let entry,
height,
i,
@@ -89,7 +89,7 @@ export default App.directive('reviewPanelSorted', $timeout => ({
sl_console.log('focused_entry_index', focused_entry_index)
- const positionLayoutEl = function($callout_el, original_top, top) {
+ const positionLayoutEl = function ($callout_el, original_top, top) {
if (original_top <= top) {
$callout_el.removeClass('rp-entry-callout-inverted')
return $callout_el.css({
@@ -177,7 +177,7 @@ export default App.directive('reviewPanelSorted', $timeout => ({
scope.$applyAsync(() => layout())
- scope.$on('review-panel:layout', function(e, animate) {
+ scope.$on('review-panel:layout', function (e, animate) {
if (animate == null) {
animate = true
}
@@ -198,7 +198,7 @@ export default App.directive('reviewPanelSorted', $timeout => ({
// noticeable, but keeps it perfectly in step with Ace.
ace
.require('ace/lib/event')
- .addMouseWheelListener(scroller[0], function(e) {
+ .addMouseWheelListener(scroller[0], function (e) {
const deltaY = e.wheelY
const old_top = parseInt(list.css('top'))
const top = old_top - deltaY * 4
@@ -211,7 +211,7 @@ export default App.directive('reviewPanelSorted', $timeout => ({
// when it overflows.
let ignoreNextAceEvent = false
- const scrollPanel = function(scrollTop, height) {
+ const scrollPanel = function (scrollTop, height) {
if (ignoreNextAceEvent) {
return (ignoreNextAceEvent = false)
} else {
diff --git a/services/web/frontend/js/ide/review-panel/directives/reviewPanelToggle.js b/services/web/frontend/js/ide/review-panel/directives/reviewPanelToggle.js
index 04b7bf646f..27add514f2 100644
--- a/services/web/frontend/js/ide/review-panel/directives/reviewPanelToggle.js
+++ b/services/web/frontend/js/ide/review-panel/directives/reviewPanelToggle.js
@@ -27,13 +27,13 @@ export default App.directive('reviewPanelToggle', () => ({
scope.disabled = false
}
scope.onChange = (...args) => scope.onToggle({ isOn: scope.localModel })
- scope.handleClick = function() {
+ scope.handleClick = function () {
if (scope.disabled && scope.onDisabledClick != null) {
return scope.onDisabledClick()
}
}
scope.localModel = scope.ngModel
- return scope.$watch('ngModel', function(value) {
+ return scope.$watch('ngModel', function (value) {
if (scope.valWhenUndefined != null && value == null) {
value = scope.valWhenUndefined
}
diff --git a/services/web/frontend/js/ide/review-panel/filters/numKeys.js b/services/web/frontend/js/ide/review-panel/filters/numKeys.js
index 18be141637..862fd46f4e 100644
--- a/services/web/frontend/js/ide/review-panel/filters/numKeys.js
+++ b/services/web/frontend/js/ide/review-panel/filters/numKeys.js
@@ -11,7 +11,7 @@ import App from '../../../base'
export default App.filter(
'numKeys',
() =>
- function(object) {
+ function (object) {
if (object != null) {
return Object.keys(object).length
} else {
diff --git a/services/web/frontend/js/ide/review-panel/filters/orderOverviewEntries.js b/services/web/frontend/js/ide/review-panel/filters/orderOverviewEntries.js
index 1607dd7f15..f8526bd54a 100644
--- a/services/web/frontend/js/ide/review-panel/filters/orderOverviewEntries.js
+++ b/services/web/frontend/js/ide/review-panel/filters/orderOverviewEntries.js
@@ -10,7 +10,7 @@ import App from '../../../base'
export default App.filter(
'orderOverviewEntries',
() =>
- function(items) {
+ function (items) {
const array = []
for (let key in items) {
const value = items[key]
diff --git a/services/web/frontend/js/ide/services/ide.js b/services/web/frontend/js/ide/services/ide.js
index ca77175dea..bbf8eaf4b2 100644
--- a/services/web/frontend/js/ide/services/ide.js
+++ b/services/web/frontend/js/ide/services/ide.js
@@ -16,160 +16,150 @@ import App from '../../base'
import EditorWatchdogManager from '../connection/EditorWatchdogManager'
// We create and provide this as service so that we can access the global ide
// from within other parts of the angular app.
-App.factory('ide', function(
- $http,
- queuedHttp,
- $modal,
- $q,
- $filter,
- $timeout,
- eventTracking
-) {
- const ide = {}
- ide.$http = $http
- ide.queuedHttp = queuedHttp
- ide.$q = $q
- ide.$filter = $filter
- ide.$timeout = $timeout
- ide.globalEditorWatchdogManager = new EditorWatchdogManager({
- onTimeoutHandler: meta => {
- eventTracking.sendMB('losing-edits', meta)
- // clone the meta object, reportError adds additional fields into it
- ide.reportError('losing-edits', Object.assign({}, meta))
- }
- })
+App.factory(
+ 'ide',
+ function ($http, queuedHttp, $modal, $q, $filter, $timeout, eventTracking) {
+ const ide = {}
+ ide.$http = $http
+ ide.queuedHttp = queuedHttp
+ ide.$q = $q
+ ide.$filter = $filter
+ ide.$timeout = $timeout
+ ide.globalEditorWatchdogManager = new EditorWatchdogManager({
+ onTimeoutHandler: meta => {
+ eventTracking.sendMB('losing-edits', meta)
+ // clone the meta object, reportError adds additional fields into it
+ ide.reportError('losing-edits', Object.assign({}, meta))
+ }
+ })
- this.recentEvents = []
- ide.pushEvent = (type, meta) => {
- if (meta == null) {
- meta = {}
+ this.recentEvents = []
+ ide.pushEvent = (type, meta) => {
+ if (meta == null) {
+ meta = {}
+ }
+ sl_console.log('event', type, meta)
+ this.recentEvents.push({ type, meta, date: new Date() })
+ if (this.recentEvents.length > 100) {
+ return this.recentEvents.shift()
+ }
}
- sl_console.log('event', type, meta)
- this.recentEvents.push({ type, meta, date: new Date() })
- if (this.recentEvents.length > 100) {
- return this.recentEvents.shift()
- }
- }
- ide.reportError = (error, meta) => {
- if (meta == null) {
- meta = {}
- }
- meta.user_id = window.user_id
- meta.project_id = window.project_id
- meta.client_id = __guard__(
- ide.socket != null ? ide.socket.socket : undefined,
- x => x.sessionid
- )
- meta.transport = __guard__(
- __guard__(
+ ide.reportError = (error, meta) => {
+ if (meta == null) {
+ meta = {}
+ }
+ meta.user_id = window.user_id
+ meta.project_id = window.project_id
+ meta.client_id = __guard__(
ide.socket != null ? ide.socket.socket : undefined,
- x2 => x2.transport
- ),
- x1 => x1.name
- )
- meta.client_now = new Date()
- meta.recent_events = this.recentEvents
- const errorObj = {}
- if (typeof error === 'object') {
- for (let key of Array.from(Object.getOwnPropertyNames(error))) {
- errorObj[key] = error[key]
+ x => x.sessionid
+ )
+ meta.transport = __guard__(
+ __guard__(
+ ide.socket != null ? ide.socket.socket : undefined,
+ x2 => x2.transport
+ ),
+ x1 => x1.name
+ )
+ meta.client_now = new Date()
+ meta.recent_events = this.recentEvents
+ const errorObj = {}
+ if (typeof error === 'object') {
+ for (let key of Array.from(Object.getOwnPropertyNames(error))) {
+ errorObj[key] = error[key]
+ }
+ } else if (typeof error === 'string') {
+ errorObj.message = error
}
- } else if (typeof error === 'string') {
- errorObj.message = error
+ return $http.post('/error/client', {
+ error: errorObj,
+ meta,
+ _csrf: window.csrfToken
+ })
}
- return $http.post('/error/client', {
- error: errorObj,
- meta,
- _csrf: window.csrfToken
- })
+
+ ide.showGenericMessageModal = (title, message) =>
+ $modal.open({
+ templateUrl: 'genericMessageModalTemplate',
+ controller: 'GenericMessageModalController',
+ resolve: {
+ title() {
+ return title
+ },
+ message() {
+ return message
+ }
+ }
+ })
+
+ ide.showOutOfSyncModal = (title, message, editorContent) =>
+ $modal.open({
+ templateUrl: 'outOfSyncModalTemplate',
+ controller: 'OutOfSyncModalController',
+ backdrop: false, // not dismissable by clicking background
+ keyboard: false, // prevent dismiss via keyboard
+ resolve: {
+ title() {
+ return title
+ },
+ message() {
+ return message
+ },
+ editorContent() {
+ return editorContent
+ }
+ },
+ windowClass: 'out-of-sync-modal'
+ })
+
+ ide.showLockEditorMessageModal = (title, message) =>
+ // modal to block the editor when connection is down
+ $modal.open({
+ templateUrl: 'lockEditorModalTemplate',
+ controller: 'GenericMessageModalController',
+ backdrop: false, // not dismissable by clicking background
+ keyboard: false, // prevent dismiss via keyboard
+ resolve: {
+ title() {
+ return title
+ },
+ message() {
+ return message
+ }
+ },
+ windowClass: 'lock-editor-modal'
+ })
+
+ return ide
}
+)
- ide.showGenericMessageModal = (title, message) =>
- $modal.open({
- templateUrl: 'genericMessageModalTemplate',
- controller: 'GenericMessageModalController',
- resolve: {
- title() {
- return title
- },
- message() {
- return message
- }
- }
- })
+App.controller(
+ 'GenericMessageModalController',
+ function ($scope, $modalInstance, title, message) {
+ $scope.title = title
+ $scope.message = message
- ide.showOutOfSyncModal = (title, message, editorContent) =>
- $modal.open({
- templateUrl: 'outOfSyncModalTemplate',
- controller: 'OutOfSyncModalController',
- backdrop: false, // not dismissable by clicking background
- keyboard: false, // prevent dismiss via keyboard
- resolve: {
- title() {
- return title
- },
- message() {
- return message
- },
- editorContent() {
- return editorContent
- }
- },
- windowClass: 'out-of-sync-modal'
- })
-
- ide.showLockEditorMessageModal = (title, message) =>
- // modal to block the editor when connection is down
- $modal.open({
- templateUrl: 'lockEditorModalTemplate',
- controller: 'GenericMessageModalController',
- backdrop: false, // not dismissable by clicking background
- keyboard: false, // prevent dismiss via keyboard
- resolve: {
- title() {
- return title
- },
- message() {
- return message
- }
- },
- windowClass: 'lock-editor-modal'
- })
-
- return ide
-})
-
-App.controller('GenericMessageModalController', function(
- $scope,
- $modalInstance,
- title,
- message
-) {
- $scope.title = title
- $scope.message = message
-
- return ($scope.done = () => $modalInstance.close())
-})
-
-App.controller('OutOfSyncModalController', function(
- $scope,
- $window,
- title,
- message,
- editorContent
-) {
- $scope.title = title
- $scope.message = message
- $scope.editorContent = editorContent
- $scope.editorContentRows = editorContent.split('\n').length
-
- $scope.done = () => {
- // Reload the page to avoid staying in an inconsistent state.
- // https://github.com/overleaf/issues/issues/3694
- $window.location.reload()
+ return ($scope.done = () => $modalInstance.close())
}
-})
+)
+
+App.controller(
+ 'OutOfSyncModalController',
+ function ($scope, $window, title, message, editorContent) {
+ $scope.title = title
+ $scope.message = message
+ $scope.editorContent = editorContent
+ $scope.editorContentRows = editorContent.split('\n').length
+
+ $scope.done = () => {
+ // Reload the page to avoid staying in an inconsistent state.
+ // https://github.com/overleaf/issues/issues/3694
+ $window.location.reload()
+ }
+ }
+)
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
diff --git a/services/web/frontend/js/ide/settings/controllers/ProjectNameController.js b/services/web/frontend/js/ide/settings/controllers/ProjectNameController.js
index a149cb9094..a49aab0326 100644
--- a/services/web/frontend/js/ide/settings/controllers/ProjectNameController.js
+++ b/services/web/frontend/js/ide/settings/controllers/ProjectNameController.js
@@ -14,66 +14,64 @@
import App from '../../../base'
const MAX_PROJECT_NAME_LENGTH = 150
-export default App.controller('ProjectNameController', function(
- $scope,
- $element,
- settings,
- ide
-) {
- const projectNameReadOnlyEl = $element.find('.name')[0]
+export default App.controller(
+ 'ProjectNameController',
+ function ($scope, $element, settings, ide) {
+ const projectNameReadOnlyEl = $element.find('.name')[0]
- $scope.state = {
- renaming: false,
- overflowed: false
- }
-
- $scope.inputs = {}
-
- $scope.startRenaming = function() {
- $scope.inputs.name = $scope.project.name
- $scope.state.renaming = true
- return $scope.$emit('project:rename:start')
- }
-
- $scope.finishRenaming = function() {
- $scope.state.renaming = false
- const newName = $scope.inputs.name
- if ($scope.project.name === newName) {
- return
+ $scope.state = {
+ renaming: false,
+ overflowed: false
}
- const oldName = $scope.project.name
- $scope.project.name = newName
- return settings
- .saveProjectSettings({ name: $scope.project.name })
- .catch(function(response) {
- const { data, status } = response
- $scope.project.name = oldName
- if (status === 400) {
- return ide.showGenericMessageModal('Error renaming project', data)
- } else {
- return ide.showGenericMessageModal(
- 'Error renaming project',
- 'Please try again in a moment'
- )
- }
- })
- }
- ide.socket.on('projectNameUpdated', name =>
- $scope.$apply(() => ($scope.project.name = name))
- )
+ $scope.inputs = {}
- return $scope.$watch('project.name', function(name) {
- if (name != null) {
- window.document.title =
- name + ` - Online LaTeX Editor ${ExposedSettings.appName}`
- return $scope.$applyAsync(
- () =>
- // This ensures that the element is measured *after* the binding is done (i.e. project name is rendered).
- ($scope.state.overflowed =
- projectNameReadOnlyEl.scrollWidth >
- projectNameReadOnlyEl.clientWidth)
- )
+ $scope.startRenaming = function () {
+ $scope.inputs.name = $scope.project.name
+ $scope.state.renaming = true
+ return $scope.$emit('project:rename:start')
}
- })
-})
+
+ $scope.finishRenaming = function () {
+ $scope.state.renaming = false
+ const newName = $scope.inputs.name
+ if ($scope.project.name === newName) {
+ return
+ }
+ const oldName = $scope.project.name
+ $scope.project.name = newName
+ return settings
+ .saveProjectSettings({ name: $scope.project.name })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.project.name = oldName
+ if (status === 400) {
+ return ide.showGenericMessageModal('Error renaming project', data)
+ } else {
+ return ide.showGenericMessageModal(
+ 'Error renaming project',
+ 'Please try again in a moment'
+ )
+ }
+ })
+ }
+
+ ide.socket.on('projectNameUpdated', name =>
+ $scope.$apply(() => ($scope.project.name = name))
+ )
+
+ return $scope.$watch('project.name', function (name) {
+ if (name != null) {
+ window.document.title =
+ name + ` - Online LaTeX Editor ${ExposedSettings.appName}`
+ return $scope.$applyAsync(
+ () =>
+ // This ensures that the element is measured *after* the binding is done (i.e. project name is rendered).
+ ($scope.state.overflowed =
+ projectNameReadOnlyEl.scrollWidth >
+ projectNameReadOnlyEl.clientWidth)
+ )
+ }
+ })
+ }
+)
diff --git a/services/web/frontend/js/ide/settings/controllers/SettingsController.js b/services/web/frontend/js/ide/settings/controllers/SettingsController.js
index 357d770358..70954bdeec 100644
--- a/services/web/frontend/js/ide/settings/controllers/SettingsController.js
+++ b/services/web/frontend/js/ide/settings/controllers/SettingsController.js
@@ -15,220 +15,219 @@ import _ from 'lodash'
import App from '../../../base'
import isValidTeXFile from '../../../main/is-valid-tex-file'
-export default App.controller('SettingsController', function(
- $scope,
- settings,
- ide
-) {
- $scope.overallThemesList = window.overallThemes
- $scope.ui = { loadingStyleSheet: false }
+export default App.controller(
+ 'SettingsController',
+ function ($scope, settings, ide) {
+ $scope.overallThemesList = window.overallThemes
+ $scope.ui = { loadingStyleSheet: false }
- const _updateCSSFile = function(theme) {
- $scope.ui.loadingStyleSheet = true
- const docHeadEl = document.querySelector('head')
- const oldStyleSheetEl = document.getElementById('main-stylesheet')
- const newStyleSheetEl = document.createElement('link')
- newStyleSheetEl.addEventListener('load', e => {
- return $scope.$applyAsync(() => {
- $scope.ui.loadingStyleSheet = false
- return docHeadEl.removeChild(oldStyleSheetEl)
+ const _updateCSSFile = function (theme) {
+ $scope.ui.loadingStyleSheet = true
+ const docHeadEl = document.querySelector('head')
+ const oldStyleSheetEl = document.getElementById('main-stylesheet')
+ const newStyleSheetEl = document.createElement('link')
+ newStyleSheetEl.addEventListener('load', e => {
+ return $scope.$applyAsync(() => {
+ $scope.ui.loadingStyleSheet = false
+ return docHeadEl.removeChild(oldStyleSheetEl)
+ })
})
+ newStyleSheetEl.setAttribute('rel', 'stylesheet')
+ newStyleSheetEl.setAttribute('id', 'main-stylesheet')
+ newStyleSheetEl.setAttribute('href', theme.path)
+ return docHeadEl.appendChild(newStyleSheetEl)
+ }
+
+ if (!['default', 'vim', 'emacs'].includes($scope.settings.mode)) {
+ $scope.settings.mode = 'default'
+ }
+
+ if (!['pdfjs', 'native'].includes($scope.settings.pdfViewer)) {
+ $scope.settings.pdfViewer = 'pdfjs'
+ }
+
+ if (
+ $scope.settings.fontFamily != null &&
+ !['monaco', 'lucida'].includes($scope.settings.fontFamily)
+ ) {
+ delete $scope.settings.fontFamily
+ }
+
+ if (
+ $scope.settings.lineHeight != null &&
+ !['compact', 'normal', 'wide'].includes($scope.settings.lineHeight)
+ ) {
+ delete $scope.settings.lineHeight
+ }
+
+ $scope.fontSizeAsStr = function (newVal) {
+ if (newVal != null) {
+ $scope.settings.fontSize = newVal
+ }
+ return $scope.settings.fontSize.toString()
+ }
+
+ $scope.getValidMainDocs = () => {
+ let filteredDocs = []
+ if ($scope.docs) {
+ // Filter the existing docs (editable files) by accepted file extensions.
+ // It's possible that an existing project has an invalid file selected as the main one.
+ // To gracefully handle that case, make sure we also show the current main file (ignoring extension).
+ filteredDocs = $scope.docs.filter(
+ doc =>
+ isValidTeXFile(doc.doc.name) ||
+ $scope.project.rootDoc_id === doc.doc.id
+ )
+ }
+ return filteredDocs
+ }
+
+ $scope.$watch('settings.editorTheme', (editorTheme, oldEditorTheme) => {
+ if (editorTheme !== oldEditorTheme) {
+ return settings.saveSettings({ editorTheme })
+ }
})
- newStyleSheetEl.setAttribute('rel', 'stylesheet')
- newStyleSheetEl.setAttribute('id', 'main-stylesheet')
- newStyleSheetEl.setAttribute('href', theme.path)
- return docHeadEl.appendChild(newStyleSheetEl)
- }
- if (!['default', 'vim', 'emacs'].includes($scope.settings.mode)) {
- $scope.settings.mode = 'default'
- }
-
- if (!['pdfjs', 'native'].includes($scope.settings.pdfViewer)) {
- $scope.settings.pdfViewer = 'pdfjs'
- }
-
- if (
- $scope.settings.fontFamily != null &&
- !['monaco', 'lucida'].includes($scope.settings.fontFamily)
- ) {
- delete $scope.settings.fontFamily
- }
-
- if (
- $scope.settings.lineHeight != null &&
- !['compact', 'normal', 'wide'].includes($scope.settings.lineHeight)
- ) {
- delete $scope.settings.lineHeight
- }
-
- $scope.fontSizeAsStr = function(newVal) {
- if (newVal != null) {
- $scope.settings.fontSize = newVal
- }
- return $scope.settings.fontSize.toString()
- }
-
- $scope.getValidMainDocs = () => {
- let filteredDocs = []
- if ($scope.docs) {
- // Filter the existing docs (editable files) by accepted file extensions.
- // It's possible that an existing project has an invalid file selected as the main one.
- // To gracefully handle that case, make sure we also show the current main file (ignoring extension).
- filteredDocs = $scope.docs.filter(
- doc =>
- isValidTeXFile(doc.doc.name) ||
- $scope.project.rootDoc_id === doc.doc.id
- )
- }
- return filteredDocs
- }
-
- $scope.$watch('settings.editorTheme', (editorTheme, oldEditorTheme) => {
- if (editorTheme !== oldEditorTheme) {
- return settings.saveSettings({ editorTheme })
- }
- })
-
- $scope.$watch('settings.overallTheme', (overallTheme, oldOverallTheme) => {
- if (overallTheme !== oldOverallTheme) {
- const chosenTheme = _.find(
- $scope.overallThemesList,
- theme => theme.val === overallTheme
- )
- if (chosenTheme != null) {
- _updateCSSFile(chosenTheme)
- return settings.saveSettings({ overallTheme })
+ $scope.$watch('settings.overallTheme', (overallTheme, oldOverallTheme) => {
+ if (overallTheme !== oldOverallTheme) {
+ const chosenTheme = _.find(
+ $scope.overallThemesList,
+ theme => theme.val === overallTheme
+ )
+ if (chosenTheme != null) {
+ _updateCSSFile(chosenTheme)
+ return settings.saveSettings({ overallTheme })
+ }
}
- }
- })
+ })
- $scope.$watch('settings.fontSize', (fontSize, oldFontSize) => {
- if (fontSize !== oldFontSize) {
- return settings.saveSettings({ fontSize: parseInt(fontSize, 10) })
- }
- })
-
- $scope.$watch('settings.mode', (mode, oldMode) => {
- if (mode !== oldMode) {
- return settings.saveSettings({ mode })
- }
- })
-
- $scope.$watch('settings.autoComplete', (autoComplete, oldAutoComplete) => {
- if (autoComplete !== oldAutoComplete) {
- return settings.saveSettings({ autoComplete })
- }
- })
-
- $scope.$watch(
- 'settings.autoPairDelimiters',
- (autoPairDelimiters, oldAutoPairDelimiters) => {
- if (autoPairDelimiters !== oldAutoPairDelimiters) {
- return settings.saveSettings({ autoPairDelimiters })
+ $scope.$watch('settings.fontSize', (fontSize, oldFontSize) => {
+ if (fontSize !== oldFontSize) {
+ return settings.saveSettings({ fontSize: parseInt(fontSize, 10) })
}
- }
- )
+ })
- $scope.$watch('settings.pdfViewer', (pdfViewer, oldPdfViewer) => {
- if (pdfViewer !== oldPdfViewer) {
- return settings.saveSettings({ pdfViewer })
- }
- })
-
- $scope.$watch(
- 'settings.syntaxValidation',
- (syntaxValidation, oldSyntaxValidation) => {
- if (syntaxValidation !== oldSyntaxValidation) {
- return settings.saveSettings({ syntaxValidation })
+ $scope.$watch('settings.mode', (mode, oldMode) => {
+ if (mode !== oldMode) {
+ return settings.saveSettings({ mode })
}
- }
- )
+ })
- $scope.$watch('settings.fontFamily', (fontFamily, oldFontFamily) => {
- if (fontFamily !== oldFontFamily) {
- return settings.saveSettings({ fontFamily })
- }
- })
+ $scope.$watch('settings.autoComplete', (autoComplete, oldAutoComplete) => {
+ if (autoComplete !== oldAutoComplete) {
+ return settings.saveSettings({ autoComplete })
+ }
+ })
- $scope.$watch('settings.lineHeight', (lineHeight, oldLineHeight) => {
- if (lineHeight !== oldLineHeight) {
- return settings.saveSettings({ lineHeight })
- }
- })
+ $scope.$watch(
+ 'settings.autoPairDelimiters',
+ (autoPairDelimiters, oldAutoPairDelimiters) => {
+ if (autoPairDelimiters !== oldAutoPairDelimiters) {
+ return settings.saveSettings({ autoPairDelimiters })
+ }
+ }
+ )
- $scope.$watch('project.spellCheckLanguage', (language, oldLanguage) => {
- if (this.ignoreUpdates) {
- return
- }
- if (oldLanguage != null && language !== oldLanguage) {
- settings.saveProjectSettings({ spellCheckLanguage: language })
- // Also set it as the default for the user
- return settings.saveSettings({ spellCheckLanguage: language })
- }
- })
+ $scope.$watch('settings.pdfViewer', (pdfViewer, oldPdfViewer) => {
+ if (pdfViewer !== oldPdfViewer) {
+ return settings.saveSettings({ pdfViewer })
+ }
+ })
- $scope.$watch('project.compiler', (compiler, oldCompiler) => {
- if (this.ignoreUpdates) {
- return
- }
- if (oldCompiler != null && compiler !== oldCompiler) {
- return settings.saveProjectSettings({ compiler })
- }
- })
+ $scope.$watch(
+ 'settings.syntaxValidation',
+ (syntaxValidation, oldSyntaxValidation) => {
+ if (syntaxValidation !== oldSyntaxValidation) {
+ return settings.saveSettings({ syntaxValidation })
+ }
+ }
+ )
- $scope.$watch('project.imageName', (imageName, oldImageName) => {
- if (this.ignoreUpdates) {
- return
- }
- if (oldImageName != null && imageName !== oldImageName) {
- return settings.saveProjectSettings({ imageName })
- }
- })
+ $scope.$watch('settings.fontFamily', (fontFamily, oldFontFamily) => {
+ if (fontFamily !== oldFontFamily) {
+ return settings.saveSettings({ fontFamily })
+ }
+ })
- $scope.$watch('project.rootDoc_id', (rootDoc_id, oldRootDoc_id) => {
- if (this.ignoreUpdates) {
- return
- }
- // don't save on initialisation, Angular passes oldRootDoc_id as
- // undefined in this case.
- if (typeof oldRootDoc_id === 'undefined') {
- return
- }
- if ($scope.permissionsLevel === 'readOnly') {
- // The user is unauthorized to persist rootDoc changes.
- // Use the new value for this very editor session only.
- return
- }
- // otherwise only save changes, null values are allowed
- if (rootDoc_id !== oldRootDoc_id) {
- settings.saveProjectSettings({ rootDocId: rootDoc_id }).catch(() => {
- $scope.project.rootDoc_id = oldRootDoc_id
+ $scope.$watch('settings.lineHeight', (lineHeight, oldLineHeight) => {
+ if (lineHeight !== oldLineHeight) {
+ return settings.saveSettings({ lineHeight })
+ }
+ })
+
+ $scope.$watch('project.spellCheckLanguage', (language, oldLanguage) => {
+ if (this.ignoreUpdates) {
+ return
+ }
+ if (oldLanguage != null && language !== oldLanguage) {
+ settings.saveProjectSettings({ spellCheckLanguage: language })
+ // Also set it as the default for the user
+ return settings.saveSettings({ spellCheckLanguage: language })
+ }
+ })
+
+ $scope.$watch('project.compiler', (compiler, oldCompiler) => {
+ if (this.ignoreUpdates) {
+ return
+ }
+ if (oldCompiler != null && compiler !== oldCompiler) {
+ return settings.saveProjectSettings({ compiler })
+ }
+ })
+
+ $scope.$watch('project.imageName', (imageName, oldImageName) => {
+ if (this.ignoreUpdates) {
+ return
+ }
+ if (oldImageName != null && imageName !== oldImageName) {
+ return settings.saveProjectSettings({ imageName })
+ }
+ })
+
+ $scope.$watch('project.rootDoc_id', (rootDoc_id, oldRootDoc_id) => {
+ if (this.ignoreUpdates) {
+ return
+ }
+ // don't save on initialisation, Angular passes oldRootDoc_id as
+ // undefined in this case.
+ if (typeof oldRootDoc_id === 'undefined') {
+ return
+ }
+ if ($scope.permissionsLevel === 'readOnly') {
+ // The user is unauthorized to persist rootDoc changes.
+ // Use the new value for this very editor session only.
+ return
+ }
+ // otherwise only save changes, null values are allowed
+ if (rootDoc_id !== oldRootDoc_id) {
+ settings.saveProjectSettings({ rootDocId: rootDoc_id }).catch(() => {
+ $scope.project.rootDoc_id = oldRootDoc_id
+ })
+ }
+ })
+
+ ide.socket.on('compilerUpdated', compiler => {
+ this.ignoreUpdates = true
+ $scope.$apply(() => {
+ return ($scope.project.compiler = compiler)
})
- }
- })
-
- ide.socket.on('compilerUpdated', compiler => {
- this.ignoreUpdates = true
- $scope.$apply(() => {
- return ($scope.project.compiler = compiler)
+ return delete this.ignoreUpdates
})
- return delete this.ignoreUpdates
- })
- ide.socket.on('imageNameUpdated', imageName => {
- this.ignoreUpdates = true
- $scope.$apply(() => {
- return ($scope.project.imageName = imageName)
+ ide.socket.on('imageNameUpdated', imageName => {
+ this.ignoreUpdates = true
+ $scope.$apply(() => {
+ return ($scope.project.imageName = imageName)
+ })
+ return delete this.ignoreUpdates
})
- return delete this.ignoreUpdates
- })
- return ide.socket.on('spellCheckLanguageUpdated', languageCode => {
- this.ignoreUpdates = true
- $scope.$apply(() => {
- return ($scope.project.spellCheckLanguage = languageCode)
+ return ide.socket.on('spellCheckLanguageUpdated', languageCode => {
+ this.ignoreUpdates = true
+ $scope.$apply(() => {
+ return ($scope.project.spellCheckLanguage = languageCode)
+ })
+ return delete this.ignoreUpdates
})
- return delete this.ignoreUpdates
- })
-})
+ }
+)
diff --git a/services/web/frontend/js/ide/share/controllers/OwnershipTransferConfirmModalController.js b/services/web/frontend/js/ide/share/controllers/OwnershipTransferConfirmModalController.js
index 74f6345a30..4ef74ea8de 100644
--- a/services/web/frontend/js/ide/share/controllers/OwnershipTransferConfirmModalController.js
+++ b/services/web/frontend/js/ide/share/controllers/OwnershipTransferConfirmModalController.js
@@ -1,37 +1,35 @@
import App from '../../../base'
-App.controller('OwnershipTransferConfirmModalController', function(
- $scope,
- $window,
- $modalInstance,
- projectMembers
-) {
- $scope.state = {
- inflight: false,
- error: false
- }
+App.controller(
+ 'OwnershipTransferConfirmModalController',
+ function ($scope, $window, $modalInstance, projectMembers) {
+ $scope.state = {
+ inflight: false,
+ error: false
+ }
- $scope.confirm = function() {
- const userId = $scope.member._id
- transferOwnership(userId)
- }
+ $scope.confirm = function () {
+ const userId = $scope.member._id
+ transferOwnership(userId)
+ }
- $scope.cancel = function() {
- $modalInstance.dismiss()
- }
+ $scope.cancel = function () {
+ $modalInstance.dismiss()
+ }
- function transferOwnership(userId) {
- $scope.state.inflight = true
- $scope.state.error = false
- projectMembers
- .transferOwnership(userId)
- .then(() => {
- $scope.state.inflight = false
- $scope.state.error = false
- $window.location.reload()
- })
- .catch(() => {
- $scope.state.inflight = false
- $scope.state.error = true
- })
+ function transferOwnership(userId) {
+ $scope.state.inflight = true
+ $scope.state.error = false
+ projectMembers
+ .transferOwnership(userId)
+ .then(() => {
+ $scope.state.inflight = false
+ $scope.state.error = false
+ $window.location.reload()
+ })
+ .catch(() => {
+ $scope.state.inflight = false
+ $scope.state.error = true
+ })
+ }
}
-})
+)
diff --git a/services/web/frontend/js/ide/share/controllers/ShareController.js b/services/web/frontend/js/ide/share/controllers/ShareController.js
index f130f87697..842e40a7a3 100644
--- a/services/web/frontend/js/ide/share/controllers/ShareController.js
+++ b/services/web/frontend/js/ide/share/controllers/ShareController.js
@@ -1,5 +1,5 @@
import App from '../../../base'
-App.controller('ShareController', function(
+App.controller('ShareController', function (
$scope,
$modal,
ide,
@@ -8,7 +8,7 @@ App.controller('ShareController', function(
// eslint-disable-next-line camelcase
eventTracking
) {
- $scope.openShareProjectModal = function(isAdmin) {
+ $scope.openShareProjectModal = function (isAdmin) {
$scope.isAdmin = isAdmin
eventTracking.sendMBOnce('ide-open-share-modal-once')
diff --git a/services/web/frontend/js/ide/share/controllers/ShareProjectModalController.js b/services/web/frontend/js/ide/share/controllers/ShareProjectModalController.js
index 6f048caf98..a848d533db 100644
--- a/services/web/frontend/js/ide/share/controllers/ShareProjectModalController.js
+++ b/services/web/frontend/js/ide/share/controllers/ShareProjectModalController.js
@@ -1,6 +1,6 @@
import _ from 'lodash'
import App from '../../../base'
-App.controller('ShareProjectModalController', function(
+App.controller('ShareProjectModalController', function (
$scope,
$modalInstance,
$timeout,
@@ -33,7 +33,7 @@ App.controller('ShareProjectModalController', function(
const INFINITE_COLLABORATORS = -1
- $scope.refreshCanAddCollaborators = function() {
+ $scope.refreshCanAddCollaborators = function () {
const allowedNoOfMembers = $scope.project.features.collaborators
$scope.canAddCollaborators =
$scope.project.members.length + $scope.project.invites.length <
@@ -41,7 +41,7 @@ App.controller('ShareProjectModalController', function(
}
$scope.refreshCanAddCollaborators()
- $scope.$watch('canAddCollaborators', function() {
+ $scope.$watch('canAddCollaborators', function () {
if (!$scope.canAddCollaborators) {
eventTracking.send(
'subscription-funnel',
@@ -94,9 +94,9 @@ App.controller('ShareProjectModalController', function(
const getCurrentInviteEmails = () =>
($scope.project.invites || []).map(u => u.email)
- $scope.filterAutocompleteUsers = function($query) {
+ $scope.filterAutocompleteUsers = function ($query) {
const currentMemberEmails = getCurrentMemberEmails()
- return $scope.autocompleteContacts.filter(function(contact) {
+ return $scope.autocompleteContacts.filter(function (contact) {
if (
contact.email != null &&
currentMemberEmails.includes(contact.email)
@@ -115,8 +115,8 @@ App.controller('ShareProjectModalController', function(
})
}
- $scope.addMembers = function() {
- const addMembers = function() {
+ $scope.addMembers = function () {
+ const addMembers = function () {
if ($scope.inputs.contacts.length === 0) {
return
}
@@ -159,7 +159,7 @@ App.controller('ShareProjectModalController', function(
validateCaptchaV3('invite')
// do v2 captcha
const ExposedSettings = window.ExposedSettings
- validateCaptcha(function(response) {
+ validateCaptcha(function (response) {
$scope.grecaptchaResponse = response
const invites = $scope.project.invites || []
const invite = _.find(invites, invite => invite.email === email)
@@ -175,7 +175,7 @@ App.controller('ShareProjectModalController', function(
}
request
- .then(function(response) {
+ .then(function (response) {
const { data } = response
if (data.error) {
$scope.setError(data.error)
@@ -204,7 +204,7 @@ App.controller('ShareProjectModalController', function(
0
)
})
- .catch(function(httpResponse) {
+ .catch(function (httpResponse) {
const { data } = httpResponse
$scope.state.inflight = false
$scope.setError(data.errorReason)
@@ -216,9 +216,9 @@ App.controller('ShareProjectModalController', function(
$timeout(addMembers, 50) // Give email list a chance to update
}
- $scope.removeMember = function(member) {
+ $scope.removeMember = function (member) {
$scope.monitorRequest(
- projectMembers.removeMember(member).then(function() {
+ projectMembers.removeMember(member).then(function () {
const index = $scope.project.members.indexOf(member)
if (index === -1) {
return
@@ -228,9 +228,9 @@ App.controller('ShareProjectModalController', function(
)
}
- $scope.revokeInvite = function(invite) {
+ $scope.revokeInvite = function (invite) {
$scope.monitorRequest(
- projectInvites.revokeInvite(invite._id).then(function() {
+ projectInvites.revokeInvite(invite._id).then(function () {
const index = $scope.project.invites.indexOf(invite)
if (index === -1) {
return
@@ -240,31 +240,31 @@ App.controller('ShareProjectModalController', function(
)
}
- $scope.resendInvite = function(invite, event) {
+ $scope.resendInvite = function (invite, event) {
$scope.monitorRequest(
projectInvites
.resendInvite(invite._id)
- .then(function() {
+ .then(function () {
event.target.blur()
})
- .catch(function() {
+ .catch(function () {
event.target.blur()
})
)
}
- $scope.makeTokenBased = function() {
+ $scope.makeTokenBased = function () {
$scope.project.publicAccesLevel = 'tokenBased'
settings.saveProjectAdminSettings({ publicAccessLevel: 'tokenBased' })
eventTracking.sendMB('project-make-token-based')
}
- $scope.makePrivate = function() {
+ $scope.makePrivate = function () {
$scope.project.publicAccesLevel = 'private'
settings.saveProjectAdminSettings({ publicAccessLevel: 'private' })
}
- $scope.$watch('project.tokens.readAndWrite', function(token) {
+ $scope.$watch('project.tokens.readAndWrite', function (token) {
if (token != null) {
$scope.readAndWriteTokenLink = `${location.origin}/${token}`
} else {
@@ -272,7 +272,7 @@ App.controller('ShareProjectModalController', function(
}
})
- $scope.$watch('project.tokens.readOnly', function(token) {
+ $scope.$watch('project.tokens.readOnly', function (token) {
if (token != null) {
$scope.readOnlyTokenLink = `${location.origin}/read/${token}`
} else {
diff --git a/services/web/frontend/js/ide/share/controllers/ShareProjectModalMemberRowController.js b/services/web/frontend/js/ide/share/controllers/ShareProjectModalMemberRowController.js
index 43cc4c9b9f..b8230080d9 100644
--- a/services/web/frontend/js/ide/share/controllers/ShareProjectModalMemberRowController.js
+++ b/services/web/frontend/js/ide/share/controllers/ShareProjectModalMemberRowController.js
@@ -1,47 +1,46 @@
import App from '../../../base'
-App.controller('ShareProjectModalMemberRowController', function(
- $scope,
- $modal,
- projectMembers
-) {
- $scope.form = {
- privileges: $scope.member.privileges,
+App.controller(
+ 'ShareProjectModalMemberRowController',
+ function ($scope, $modal, projectMembers) {
+ $scope.form = {
+ privileges: $scope.member.privileges,
- isModified() {
- return this.privileges !== $scope.member.privileges
- },
+ isModified() {
+ return this.privileges !== $scope.member.privileges
+ },
- submit() {
- const userId = $scope.member._id
- const privilegeLevel = $scope.form.privileges
- if (privilegeLevel === 'owner') {
- openOwnershipTransferConfirmModal(userId)
- } else {
- setPrivilegeLevel(userId, privilegeLevel)
+ submit() {
+ const userId = $scope.member._id
+ const privilegeLevel = $scope.form.privileges
+ if (privilegeLevel === 'owner') {
+ openOwnershipTransferConfirmModal(userId)
+ } else {
+ setPrivilegeLevel(userId, privilegeLevel)
+ }
+ },
+
+ reset() {
+ this.privileges = $scope.member.privileges
+ $scope.clearError()
}
- },
+ }
- reset() {
- this.privileges = $scope.member.privileges
- $scope.clearError()
+ function setPrivilegeLevel(userId, privilegeLevel) {
+ $scope.monitorRequest(
+ projectMembers
+ .setMemberPrivilegeLevel(userId, privilegeLevel)
+ .then(() => {
+ $scope.member.privileges = privilegeLevel
+ })
+ )
+ }
+
+ function openOwnershipTransferConfirmModal(userId) {
+ $modal.open({
+ templateUrl: 'ownershipTransferConfirmTemplate',
+ controller: 'OwnershipTransferConfirmModalController',
+ scope: $scope
+ })
}
}
-
- function setPrivilegeLevel(userId, privilegeLevel) {
- $scope.monitorRequest(
- projectMembers
- .setMemberPrivilegeLevel(userId, privilegeLevel)
- .then(() => {
- $scope.member.privileges = privilegeLevel
- })
- )
- }
-
- function openOwnershipTransferConfirmModal(userId) {
- $modal.open({
- templateUrl: 'ownershipTransferConfirmTemplate',
- controller: 'OwnershipTransferConfirmModalController',
- scope: $scope
- })
- }
-})
+)
diff --git a/services/web/frontend/js/infrastructure/error-boundary.js b/services/web/frontend/js/infrastructure/error-boundary.js
index ba7fe972c2..a8d84f8bf1 100644
--- a/services/web/frontend/js/infrastructure/error-boundary.js
+++ b/services/web/frontend/js/infrastructure/error-boundary.js
@@ -26,9 +26,9 @@ function withErrorBoundary(WrappedComponent, FallbackComponent) {
)
}
ErrorBoundaryWrapper.propTypes = WrappedComponent.propTypes
- ErrorBoundaryWrapper.displayName = `WithErrorBoundaryWrapper${WrappedComponent.displayName ||
- WrappedComponent.name ||
- 'Component'}`
+ ErrorBoundaryWrapper.displayName = `WithErrorBoundaryWrapper${
+ WrappedComponent.displayName || WrappedComponent.name || 'Component'
+ }`
return ErrorBoundaryWrapper
}
diff --git a/services/web/frontend/js/infrastructure/local-storage.js b/services/web/frontend/js/infrastructure/local-storage.js
index 8e4f0fb6ab..68ca9ec6e3 100644
--- a/services/web/frontend/js/infrastructure/local-storage.js
+++ b/services/web/frontend/js/infrastructure/local-storage.js
@@ -10,7 +10,7 @@
* @param {string?} key Key passed to the localStorage function (if any)
* @param {any?} value Value passed to the localStorage function (if any)
*/
-const callSafe = function(fn, key, value) {
+const callSafe = function (fn, key, value) {
try {
return fn(key, value)
} catch (e) {
@@ -19,19 +19,19 @@ const callSafe = function(fn, key, value) {
}
}
-const getItem = function(key) {
+const getItem = function (key) {
return JSON.parse(localStorage.getItem(key))
}
-const setItem = function(key, value) {
+const setItem = function (key, value) {
localStorage.setItem(key, JSON.stringify(value))
}
-const clear = function() {
+const clear = function () {
localStorage.clear()
}
-const removeItem = function(key) {
+const removeItem = function (key) {
return localStorage.removeItem(key)
}
diff --git a/services/web/frontend/js/main.js b/services/web/frontend/js/main.js
index ec37527ddb..df02c5a1a8 100644
--- a/services/web/frontend/js/main.js
+++ b/services/web/frontend/js/main.js
@@ -54,7 +54,7 @@ import './services/validateCaptcha'
import './services/validateCaptchaV3'
import './filters/formatDate'
import '../../modules/modules-main.js'
-angular.module('SharelatexApp').config(function($locationProvider) {
+angular.module('SharelatexApp').config(function ($locationProvider) {
try {
return $locationProvider.html5Mode({
enabled: true,
diff --git a/services/web/frontend/js/main/account-settings.js b/services/web/frontend/js/main/account-settings.js
index 948be4c4cd..f003c6ba50 100644
--- a/services/web/frontend/js/main/account-settings.js
+++ b/services/web/frontend/js/main/account-settings.js
@@ -1,5 +1,5 @@
import App from '../base'
-App.controller('AccountSettingsController', function(
+App.controller('AccountSettingsController', function (
$scope,
$http,
$modal,
@@ -9,7 +9,7 @@ App.controller('AccountSettingsController', function(
) {
$scope.subscribed = true
- $scope.unsubscribe = function() {
+ $scope.unsubscribe = function () {
$scope.unsubscribing = true
return $http({
method: 'DELETE',
@@ -18,14 +18,14 @@ App.controller('AccountSettingsController', function(
'X-CSRF-Token': window.csrfToken
}
})
- .then(function() {
+ .then(function () {
$scope.unsubscribing = false
$scope.subscribed = false
})
.catch(() => ($scope.unsubscribing = true))
}
- $scope.deleteAccount = function() {
+ $scope.deleteAccount = function () {
$modal.open({
templateUrl: 'deleteAccountModalTemplate',
controller: 'DeleteAccountModalController',
@@ -48,69 +48,66 @@ App.controller('AccountSettingsController', function(
eventTracking.send('subscription-funnel', 'settings-page', service)
})
-App.controller('DeleteAccountModalController', function(
- $scope,
- $modalInstance,
- $timeout,
- $http,
- userDefaultEmail
-) {
- $scope.state = {
- isValid: false,
- deleteText: '',
- password: '',
- confirmSharelatexDelete: false,
- inflight: false,
- error: null
- }
+App.controller(
+ 'DeleteAccountModalController',
+ function ($scope, $modalInstance, $timeout, $http, userDefaultEmail) {
+ $scope.state = {
+ isValid: false,
+ deleteText: '',
+ password: '',
+ confirmSharelatexDelete: false,
+ inflight: false,
+ error: null
+ }
- $scope.userDefaultEmail = userDefaultEmail
+ $scope.userDefaultEmail = userDefaultEmail
- $modalInstance.opened.then(() =>
- $timeout(() => $scope.$broadcast('open'), 700)
- )
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 700)
+ )
- $scope.checkValidation = () =>
- ($scope.state.isValid =
- userDefaultEmail != null &&
- $scope.state.deleteText.toLowerCase() ===
- userDefaultEmail.toLowerCase() &&
- $scope.state.password.length > 0 &&
- $scope.state.confirmSharelatexDelete)
+ $scope.checkValidation = () =>
+ ($scope.state.isValid =
+ userDefaultEmail != null &&
+ $scope.state.deleteText.toLowerCase() ===
+ userDefaultEmail.toLowerCase() &&
+ $scope.state.password.length > 0 &&
+ $scope.state.confirmSharelatexDelete)
- $scope.delete = function() {
- $scope.state.inflight = true
- $scope.state.error = null
- return $http({
- method: 'POST',
- url: '/user/delete',
- headers: {
- 'X-CSRF-Token': window.csrfToken,
- 'Content-Type': 'application/json'
- },
- data: {
- password: $scope.state.password
- },
- disableAutoLoginRedirect: true // we want to handle errors ourselves
- })
- .then(function() {
- $modalInstance.close()
- $scope.state.inflight = false
- $scope.state.error = null
- setTimeout(() => (window.location = '/login'), 1000)
+ $scope.delete = function () {
+ $scope.state.inflight = true
+ $scope.state.error = null
+ return $http({
+ method: 'POST',
+ url: '/user/delete',
+ headers: {
+ 'X-CSRF-Token': window.csrfToken,
+ 'Content-Type': 'application/json'
+ },
+ data: {
+ password: $scope.state.password
+ },
+ disableAutoLoginRedirect: true // we want to handle errors ourselves
})
- .catch(function(response) {
- const { data, status } = response
- $scope.state.inflight = false
- if (status === 403) {
- $scope.state.error = { code: 'InvalidCredentialsError' }
- } else if (data.error) {
- $scope.state.error = { code: data.error }
- } else {
- $scope.state.error = { code: 'UserDeletionError' }
- }
- })
- }
+ .then(function () {
+ $modalInstance.close()
+ $scope.state.inflight = false
+ $scope.state.error = null
+ setTimeout(() => (window.location = '/login'), 1000)
+ })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.state.inflight = false
+ if (status === 403) {
+ $scope.state.error = { code: 'InvalidCredentialsError' }
+ } else if (data.error) {
+ $scope.state.error = { code: data.error }
+ } else {
+ $scope.state.error = { code: 'UserDeletionError' }
+ }
+ })
+ }
- $scope.cancel = () => $modalInstance.dismiss('cancel')
-})
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
+ }
+)
diff --git a/services/web/frontend/js/main/account-upgrade-angular.js b/services/web/frontend/js/main/account-upgrade-angular.js
index 0af5fba4c1..3a3c94a786 100644
--- a/services/web/frontend/js/main/account-upgrade-angular.js
+++ b/services/web/frontend/js/main/account-upgrade-angular.js
@@ -1,13 +1,13 @@
import App from '../base'
import { startFreeTrial, upgradePlan } from './account-upgrade'
-App.controller('FreeTrialModalController', function($scope, eventTracking) {
+App.controller('FreeTrialModalController', function ($scope, eventTracking) {
$scope.buttonClass = 'btn-primary'
$scope.startFreeTrial = (source, version) =>
startFreeTrial(source, version, $scope, eventTracking)
})
-App.controller('UpgradeModalController', function($scope, eventTracking) {
+App.controller('UpgradeModalController', function ($scope, eventTracking) {
$scope.buttonClass = 'btn-primary'
$scope.upgradePlan = source => upgradePlan(source, $scope)
})
diff --git a/services/web/frontend/js/main/account-upgrade.js b/services/web/frontend/js/main/account-upgrade.js
index 5f8bb4e37c..feda5129b6 100644
--- a/services/web/frontend/js/main/account-upgrade.js
+++ b/services/web/frontend/js/main/account-upgrade.js
@@ -2,7 +2,7 @@ function startFreeTrial(source, version, $scope, eventTracking) {
const plan = 'collaborator_free_trial_7_days'
const w = window.open()
- const go = function() {
+ const go = function () {
let url
if (typeof ga === 'function') {
ga('send', 'event', 'subscription-funnel', 'upgraded-free-trial', source)
@@ -29,7 +29,7 @@ function startFreeTrial(source, version, $scope, eventTracking) {
function upgradePlan(source, $scope) {
const w = window.open()
- const go = function() {
+ const go = function () {
let url
if (typeof ga === 'function') {
ga('send', 'event', 'subscription-funnel', 'upgraded-plan', source)
diff --git a/services/web/frontend/js/main/affiliations/components/affiliationForm.js b/services/web/frontend/js/main/affiliations/components/affiliationForm.js
index c60cc3f7d9..a0beb35a15 100644
--- a/services/web/frontend/js/main/affiliations/components/affiliationForm.js
+++ b/services/web/frontend/js/main/affiliations/components/affiliationForm.js
@@ -12,7 +12,7 @@ import _ from 'lodash'
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
-const affiliationFormController = function(
+const affiliationFormController = function (
$scope,
$element,
$attrs,
@@ -29,7 +29,7 @@ const affiliationFormController = function(
name: universityName,
isUserSuggested: true
})
- ctrl.handleFreeformInputChange = function($select, propertyToMatch) {
+ ctrl.handleFreeformInputChange = function ($select, propertyToMatch) {
if ($select.search == null || $select.search === '') {
return
}
@@ -62,39 +62,39 @@ const affiliationFormController = function(
departments => (_defaultDepartments = departments)
)
// Populates the universities dropdown (after selecting a country)
- $scope.$watch('$ctrl.affiliationData.country', function(
- newSelectedCountry,
- prevSelectedCountry
- ) {
- if (
- newSelectedCountry != null &&
- newSelectedCountry !== prevSelectedCountry
- ) {
- ctrl.affiliationData.university = null
- ctrl.affiliationData.role = null
- ctrl.affiliationData.department = null
- return UserAffiliationsDataService.getUniversitiesFromCountry(
- newSelectedCountry
- ).then(universities => (ctrl.universities = universities))
+ $scope.$watch(
+ '$ctrl.affiliationData.country',
+ function (newSelectedCountry, prevSelectedCountry) {
+ if (
+ newSelectedCountry != null &&
+ newSelectedCountry !== prevSelectedCountry
+ ) {
+ ctrl.affiliationData.university = null
+ ctrl.affiliationData.role = null
+ ctrl.affiliationData.department = null
+ return UserAffiliationsDataService.getUniversitiesFromCountry(
+ newSelectedCountry
+ ).then(universities => (ctrl.universities = universities))
+ }
}
- })
+ )
// Populates the departments dropdown (after selecting a university)
- $scope.$watch('$ctrl.affiliationData.university', function(
- newSelectedUniversity,
- prevSelectedUniversity
- ) {
- if (
- newSelectedUniversity != null &&
- newSelectedUniversity !== prevSelectedUniversity &&
- (newSelectedUniversity.departments != null
- ? newSelectedUniversity.departments.length
- : undefined) > 0
- ) {
- return (ctrl.departments = _.uniq(newSelectedUniversity.departments))
- } else {
- return (ctrl.departments = _defaultDepartments)
+ $scope.$watch(
+ '$ctrl.affiliationData.university',
+ function (newSelectedUniversity, prevSelectedUniversity) {
+ if (
+ newSelectedUniversity != null &&
+ newSelectedUniversity !== prevSelectedUniversity &&
+ (newSelectedUniversity.departments != null
+ ? newSelectedUniversity.departments.length
+ : undefined) > 0
+ ) {
+ return (ctrl.departments = _.uniq(newSelectedUniversity.departments))
+ } else {
+ return (ctrl.departments = _defaultDepartments)
+ }
}
- })
+ )
}
export default App.component('affiliationForm', {
diff --git a/services/web/frontend/js/main/affiliations/components/inputSuggestions.js b/services/web/frontend/js/main/affiliations/components/inputSuggestions.js
index fa6d9e3776..faa1deab2a 100644
--- a/services/web/frontend/js/main/affiliations/components/inputSuggestions.js
+++ b/services/web/frontend/js/main/affiliations/components/inputSuggestions.js
@@ -11,21 +11,21 @@
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
-const inputSuggestionsController = function($scope, $element, $attrs, Keys) {
+const inputSuggestionsController = function ($scope, $element, $attrs, Keys) {
const ctrl = this
ctrl.showHint = false
ctrl.hasFocus = false
- ctrl.handleFocus = function() {
+ ctrl.handleFocus = function () {
ctrl.hasFocus = true
return (ctrl.suggestion = null)
}
- ctrl.handleBlur = function() {
+ ctrl.handleBlur = function () {
ctrl.showHint = false
ctrl.hasFocus = false
ctrl.suggestion = null
return ctrl.onBlur()
}
- ctrl.handleKeyDown = function($event) {
+ ctrl.handleKeyDown = function ($event) {
if (
($event.which === Keys.TAB || $event.which === Keys.ENTER) &&
ctrl.suggestion != null &&
@@ -37,13 +37,13 @@ const inputSuggestionsController = function($scope, $element, $attrs, Keys) {
ctrl.suggestion = null
return (ctrl.showHint = false)
}
- $scope.$watch('$ctrl.localNgModel', function(newVal, oldVal) {
+ $scope.$watch('$ctrl.localNgModel', function (newVal, oldVal) {
if (ctrl.hasFocus && newVal !== oldVal) {
ctrl.suggestion = null
ctrl.showHint = false
return ctrl
.getSuggestion({ userInput: newVal })
- .then(function(suggestion) {
+ .then(function (suggestion) {
if (suggestion != null && newVal === ctrl.localNgModel) {
ctrl.showHint = true
return (ctrl.suggestion = suggestion.replace(newVal, ''))
diff --git a/services/web/frontend/js/main/affiliations/controllers/UserAffiliationsController.js b/services/web/frontend/js/main/affiliations/controllers/UserAffiliationsController.js
index f96a424091..95dad3348d 100644
--- a/services/web/frontend/js/main/affiliations/controllers/UserAffiliationsController.js
+++ b/services/web/frontend/js/main/affiliations/controllers/UserAffiliationsController.js
@@ -8,317 +8,315 @@ import _ from 'lodash'
import App from '../../../base'
import getMeta from '../../../utils/meta'
-export default App.controller('UserAffiliationsController', function(
- $scope,
- $rootScope,
- UserAffiliationsDataService,
- $q,
- $window
-) {
- $scope.userEmails = []
- $scope.linkedInstitutionIds = []
- $scope.hideInstitutionNotifications = {}
- $scope.closeInstitutionNotification = type => {
- $scope.hideInstitutionNotifications[type] = true
- }
- $scope.samlBetaSession = ExposedSettings.hasSamlBeta
- $scope.samlInitPath = ExposedSettings.samlInitPath
- $scope.reconfirmationRemoveEmail = getMeta('ol-reconfirmationRemoveEmail')
- $scope.reconfirmedViaSAML = getMeta('ol-reconfirmedViaSAML')
-
- const LOCAL_AND_DOMAIN_REGEX = /([^@]+)@(.+)/
- const EMAIL_REGEX = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
-
- const _matchLocalAndDomain = function(userEmailInput) {
- const match = userEmailInput
- ? userEmailInput.match(LOCAL_AND_DOMAIN_REGEX)
- : undefined
- if (match) {
- return { local: match[1], domain: match[2] }
- } else {
- return { local: null, domain: null }
+export default App.controller(
+ 'UserAffiliationsController',
+ function ($scope, $rootScope, UserAffiliationsDataService, $q, $window) {
+ $scope.userEmails = []
+ $scope.linkedInstitutionIds = []
+ $scope.hideInstitutionNotifications = {}
+ $scope.closeInstitutionNotification = type => {
+ $scope.hideInstitutionNotifications[type] = true
}
- }
+ $scope.samlBetaSession = ExposedSettings.hasSamlBeta
+ $scope.samlInitPath = ExposedSettings.samlInitPath
+ $scope.reconfirmationRemoveEmail = getMeta('ol-reconfirmationRemoveEmail')
+ $scope.reconfirmedViaSAML = getMeta('ol-reconfirmedViaSAML')
- const _ssoAvailableForAffiliation = affiliation => {
- if (!affiliation) return false
- const institution = affiliation.institution
- if (!_ssoAvailableForInstitution(institution)) return false
- if (!institution.confirmed) return false // domain is confirmed, not the email
- return true
- }
+ const LOCAL_AND_DOMAIN_REGEX = /([^@]+)@(.+)/
+ const EMAIL_REGEX = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
- const _ssoAvailableForDomain = domain => {
- if (!domain) return false
- if (!domain.confirmed) return false // domain is confirmed, not the email
- const institution = domain.university
- if (!_ssoAvailableForInstitution(institution)) return false
- return true
- }
+ const _matchLocalAndDomain = function (userEmailInput) {
+ const match = userEmailInput
+ ? userEmailInput.match(LOCAL_AND_DOMAIN_REGEX)
+ : undefined
+ if (match) {
+ return { local: match[1], domain: match[2] }
+ } else {
+ return { local: null, domain: null }
+ }
+ }
- const _ssoAvailableForInstitution = institution => {
- if (!ExposedSettings.hasSamlFeature) return false
- if (!institution) return false
- if (institution.ssoEnabled) return true
- if ($scope.samlBetaSession && institution.ssoBeta) return true
- return false
- }
+ const _ssoAvailableForAffiliation = affiliation => {
+ if (!affiliation) return false
+ const institution = affiliation.institution
+ if (!_ssoAvailableForInstitution(institution)) return false
+ if (!institution.confirmed) return false // domain is confirmed, not the email
+ return true
+ }
- $scope.getEmailSuggestion = function(userInput) {
- const userInputLocalAndDomain = _matchLocalAndDomain(userInput)
- $scope.ui.isValidEmail = EMAIL_REGEX.test(userInput)
- $scope.ui.isBlacklistedEmail = false
- $scope.ui.showManualUniversitySelectionUI = false
- if (userInputLocalAndDomain.domain) {
- $scope.ui.isBlacklistedEmail = UserAffiliationsDataService.isDomainBlacklisted(
- userInputLocalAndDomain.domain
- )
- return UserAffiliationsDataService.getUniversityDomainFromPartialDomainInput(
- userInputLocalAndDomain.domain
- )
- .then(function(universityDomain) {
- const currentUserInputLocalAndDomain = _matchLocalAndDomain(
- $scope.newAffiliation.email
- )
- if (
- currentUserInputLocalAndDomain.domain === universityDomain.hostname
- ) {
- $scope.newAffiliation.university = universityDomain.university
- $scope.newAffiliation.department = universityDomain.department
- $scope.newAffiliation.ssoAvailable = _ssoAvailableForDomain(
- universityDomain
+ const _ssoAvailableForDomain = domain => {
+ if (!domain) return false
+ if (!domain.confirmed) return false // domain is confirmed, not the email
+ const institution = domain.university
+ if (!_ssoAvailableForInstitution(institution)) return false
+ return true
+ }
+
+ const _ssoAvailableForInstitution = institution => {
+ if (!ExposedSettings.hasSamlFeature) return false
+ if (!institution) return false
+ if (institution.ssoEnabled) return true
+ if ($scope.samlBetaSession && institution.ssoBeta) return true
+ return false
+ }
+
+ $scope.getEmailSuggestion = function (userInput) {
+ const userInputLocalAndDomain = _matchLocalAndDomain(userInput)
+ $scope.ui.isValidEmail = EMAIL_REGEX.test(userInput)
+ $scope.ui.isBlacklistedEmail = false
+ $scope.ui.showManualUniversitySelectionUI = false
+ if (userInputLocalAndDomain.domain) {
+ $scope.ui.isBlacklistedEmail = UserAffiliationsDataService.isDomainBlacklisted(
+ userInputLocalAndDomain.domain
+ )
+ return UserAffiliationsDataService.getUniversityDomainFromPartialDomainInput(
+ userInputLocalAndDomain.domain
+ )
+ .then(function (universityDomain) {
+ const currentUserInputLocalAndDomain = _matchLocalAndDomain(
+ $scope.newAffiliation.email
)
- } else {
+ if (
+ currentUserInputLocalAndDomain.domain ===
+ universityDomain.hostname
+ ) {
+ $scope.newAffiliation.university = universityDomain.university
+ $scope.newAffiliation.department = universityDomain.department
+ $scope.newAffiliation.ssoAvailable = _ssoAvailableForDomain(
+ universityDomain
+ )
+ } else {
+ _resetAffiliationSuggestion()
+ }
+ return $q.resolve(
+ `${userInputLocalAndDomain.local}@${universityDomain.hostname}`
+ )
+ })
+ .catch(function () {
_resetAffiliationSuggestion()
- }
- return $q.resolve(
- `${userInputLocalAndDomain.local}@${universityDomain.hostname}`
- )
- })
- .catch(function() {
- _resetAffiliationSuggestion()
- return $q.reject(null)
- })
- } else {
+ return $q.reject(null)
+ })
+ } else {
+ _resetAffiliationSuggestion()
+ return $q.reject(null)
+ }
+ }
+
+ $scope.linkInstitutionAcct = function (email, institutionId) {
+ _resetMakingRequestType()
+ $scope.ui.isMakingRequest = true
+ $scope.ui.isProcessing = true
+ $window.location.href = `${$scope.samlInitPath}?university_id=${institutionId}&auto=/user/settings&email=${email}`
+ }
+
+ $scope.selectUniversityManually = function () {
_resetAffiliationSuggestion()
- return $q.reject(null)
- }
- }
-
- $scope.linkInstitutionAcct = function(email, institutionId) {
- _resetMakingRequestType()
- $scope.ui.isMakingRequest = true
- $scope.ui.isProcessing = true
- $window.location.href = `${$scope.samlInitPath}?university_id=${institutionId}&auto=/user/settings&email=${email}`
- }
-
- $scope.selectUniversityManually = function() {
- _resetAffiliationSuggestion()
- $scope.ui.showManualUniversitySelectionUI = true
- }
-
- $scope.changeAffiliation = function(userEmail) {
- if (_.get(userEmail, ['affiliation', 'institution', 'id'])) {
- UserAffiliationsDataService.getUniversityDetails(
- userEmail.affiliation.institution.id
- ).then(
- universityDetails =>
- ($scope.affiliationToChange.university = universityDetails)
- )
+ $scope.ui.showManualUniversitySelectionUI = true
}
- $scope.affiliationToChange.email = userEmail.email
- $scope.affiliationToChange.role = userEmail.affiliation.role
- $scope.affiliationToChange.department = userEmail.affiliation.department
- }
+ $scope.changeAffiliation = function (userEmail) {
+ if (_.get(userEmail, ['affiliation', 'institution', 'id'])) {
+ UserAffiliationsDataService.getUniversityDetails(
+ userEmail.affiliation.institution.id
+ ).then(
+ universityDetails =>
+ ($scope.affiliationToChange.university = universityDetails)
+ )
+ }
- $scope.saveAffiliationChange = function(userEmail) {
- userEmail.affiliation.role = $scope.affiliationToChange.role
- userEmail.affiliation.department = $scope.affiliationToChange.department
- _resetAffiliationToChange()
- return _monitorRequest(
- UserAffiliationsDataService.addRoleAndDepartment(
- userEmail.email,
- userEmail.affiliation.role,
- userEmail.affiliation.department
- )
- ).then(() => setTimeout(() => _getUserEmails()))
- }
+ $scope.affiliationToChange.email = userEmail.email
+ $scope.affiliationToChange.role = userEmail.affiliation.role
+ $scope.affiliationToChange.department = userEmail.affiliation.department
+ }
- $scope.cancelAffiliationChange = email => _resetAffiliationToChange()
+ $scope.saveAffiliationChange = function (userEmail) {
+ userEmail.affiliation.role = $scope.affiliationToChange.role
+ userEmail.affiliation.department = $scope.affiliationToChange.department
+ _resetAffiliationToChange()
+ return _monitorRequest(
+ UserAffiliationsDataService.addRoleAndDepartment(
+ userEmail.email,
+ userEmail.affiliation.role,
+ userEmail.affiliation.department
+ )
+ ).then(() => setTimeout(() => _getUserEmails()))
+ }
- $scope.isChangingAffiliation = email =>
- $scope.affiliationToChange.email === email
+ $scope.cancelAffiliationChange = email => _resetAffiliationToChange()
- $scope.showAddEmailForm = () => ($scope.ui.showAddEmailUI = true)
+ $scope.isChangingAffiliation = email =>
+ $scope.affiliationToChange.email === email
- $scope.addNewEmail = function() {
- let addEmailPromise
- if (!$scope.newAffiliation.university) {
- addEmailPromise = UserAffiliationsDataService.addUserEmail(
- $scope.newAffiliation.email
- )
- } else {
- if ($scope.newAffiliation.university.isUserSuggested) {
- addEmailPromise = UserAffiliationsDataService.addUserAffiliationWithUnknownUniversity(
- $scope.newAffiliation.email,
- $scope.newAffiliation.university.name,
- $scope.newAffiliation.country.code,
- $scope.newAffiliation.role,
- $scope.newAffiliation.department
+ $scope.showAddEmailForm = () => ($scope.ui.showAddEmailUI = true)
+
+ $scope.addNewEmail = function () {
+ let addEmailPromise
+ if (!$scope.newAffiliation.university) {
+ addEmailPromise = UserAffiliationsDataService.addUserEmail(
+ $scope.newAffiliation.email
)
} else {
- addEmailPromise = UserAffiliationsDataService.addUserAffiliation(
- $scope.newAffiliation.email,
- $scope.newAffiliation.university.id,
- $scope.newAffiliation.role,
- $scope.newAffiliation.department
- )
+ if ($scope.newAffiliation.university.isUserSuggested) {
+ addEmailPromise = UserAffiliationsDataService.addUserAffiliationWithUnknownUniversity(
+ $scope.newAffiliation.email,
+ $scope.newAffiliation.university.name,
+ $scope.newAffiliation.country.code,
+ $scope.newAffiliation.role,
+ $scope.newAffiliation.department
+ )
+ } else {
+ addEmailPromise = UserAffiliationsDataService.addUserAffiliation(
+ $scope.newAffiliation.email,
+ $scope.newAffiliation.university.id,
+ $scope.newAffiliation.role,
+ $scope.newAffiliation.department
+ )
+ }
}
- }
- $scope.ui.isAddingNewEmail = true
- $scope.ui.showAddEmailUI = false
- return _monitorRequest(addEmailPromise)
- .then(function() {
- _resetNewAffiliation()
- _resetAddingEmail()
- setTimeout(() => _getUserEmails())
- })
- .finally(() => ($scope.ui.isAddingNewEmail = false))
- }
-
- $scope.setDefaultUserEmail = userEmail =>
- _monitorRequest(
- UserAffiliationsDataService.setDefaultUserEmail(userEmail.email)
- ).then(function() {
- for (let email of $scope.userEmails || []) {
- email.default = false
- }
- userEmail.default = true
- window.usersEmail = userEmail.email
- $rootScope.usersEmail = userEmail.email
- })
-
- $scope.removeUserEmail = function(userEmail) {
- $scope.userEmails = $scope.userEmails.filter(ue => ue !== userEmail)
- return _monitorRequest(
- UserAffiliationsDataService.removeUserEmail(userEmail.email)
- )
- }
-
- $scope.resendConfirmationEmail = function(userEmail) {
- _resetMakingRequestType()
- $scope.ui.isResendingConfirmation = true
- return _monitorRequest(
- UserAffiliationsDataService.resendConfirmationEmail(userEmail.email)
- ).finally(() => ($scope.ui.isResendingConfirmation = false))
- }
-
- $scope.acknowledgeError = function() {
- _reset()
- return _getUserEmails()
- }
-
- var _resetAffiliationToChange = () =>
- ($scope.affiliationToChange = {
- email: '',
- university: null,
- role: null,
- department: null
- })
-
- var _resetNewAffiliation = () =>
- ($scope.newAffiliation = {
- email: '',
- country: null,
- university: null,
- role: null,
- department: null
- })
-
- var _resetAddingEmail = function() {
- $scope.ui.showAddEmailUI = false
- $scope.ui.isValidEmail = false
- $scope.ui.isBlacklistedEmail = false
- $scope.ui.showManualUniversitySelectionUI = false
- }
-
- var _resetAffiliationSuggestion = () => {
- $scope.newAffiliation = {
- email: $scope.newAffiliation.email
- }
- }
-
- var _resetMakingRequestType = function() {
- $scope.ui.isLoadingEmails = false
- $scope.ui.isProcessing = false
- $scope.ui.isResendingConfirmation = false
- }
-
- var _reset = function() {
- $scope.ui = {
- hasError: false,
- errorMessage: '',
- showChangeAffiliationUI: false,
- isMakingRequest: false,
- isLoadingEmails: false,
- isAddingNewEmail: false
- }
- _resetAffiliationToChange()
- _resetNewAffiliation()
- return _resetAddingEmail()
- }
- _reset()
-
- var _monitorRequest = function(promise) {
- $scope.ui.hasError = false
- $scope.ui.isMakingRequest = true
- promise
- .catch(function(response) {
- $scope.ui.hasError = true
- $scope.ui.errorMessage = _.get(response, ['data', 'message'])
- })
- .finally(() => ($scope.ui.isMakingRequest = false))
- return promise
- }
-
- $scope.inReconfirmNotificationPeriod = function(emailData) {
- return _.get(emailData, ['affiliation', 'inReconfirmNotificationPeriod'])
- }
-
- $scope.institutionAlreadyLinked = function(emailData) {
- const institutionId =
- emailData.affiliation &&
- emailData.affiliation.institution &&
- emailData.affiliation.institution &&
- emailData.affiliation.institution.id
- ? emailData.affiliation.institution.id.toString()
- : undefined
- return $scope.linkedInstitutionIds.indexOf(institutionId) !== -1
- }
-
- // Populates the emails table
- var _getUserEmails = function() {
- _resetMakingRequestType()
- $scope.ui.isLoadingEmails = true
- _monitorRequest(
- UserAffiliationsDataService.getUserEmailsEnsureAffiliation()
- )
- .then(emails => {
- $scope.userEmails = emails.map(email => {
- email.ssoAvailable = _ssoAvailableForAffiliation(email.affiliation)
- return email
+ $scope.ui.isAddingNewEmail = true
+ $scope.ui.showAddEmailUI = false
+ return _monitorRequest(addEmailPromise)
+ .then(function () {
+ _resetNewAffiliation()
+ _resetAddingEmail()
+ setTimeout(() => _getUserEmails())
})
- $scope.linkedInstitutionIds = emails
- .filter(email => {
- if (email.samlProviderId) {
- return email.samlProviderId
- }
- })
- .map(email => email.samlProviderId)
+ .finally(() => ($scope.ui.isAddingNewEmail = false))
+ }
+
+ $scope.setDefaultUserEmail = userEmail =>
+ _monitorRequest(
+ UserAffiliationsDataService.setDefaultUserEmail(userEmail.email)
+ ).then(function () {
+ for (let email of $scope.userEmails || []) {
+ email.default = false
+ }
+ userEmail.default = true
+ window.usersEmail = userEmail.email
+ $rootScope.usersEmail = userEmail.email
})
- .finally(() => ($scope.ui.isLoadingEmails = false))
+
+ $scope.removeUserEmail = function (userEmail) {
+ $scope.userEmails = $scope.userEmails.filter(ue => ue !== userEmail)
+ return _monitorRequest(
+ UserAffiliationsDataService.removeUserEmail(userEmail.email)
+ )
+ }
+
+ $scope.resendConfirmationEmail = function (userEmail) {
+ _resetMakingRequestType()
+ $scope.ui.isResendingConfirmation = true
+ return _monitorRequest(
+ UserAffiliationsDataService.resendConfirmationEmail(userEmail.email)
+ ).finally(() => ($scope.ui.isResendingConfirmation = false))
+ }
+
+ $scope.acknowledgeError = function () {
+ _reset()
+ return _getUserEmails()
+ }
+
+ var _resetAffiliationToChange = () =>
+ ($scope.affiliationToChange = {
+ email: '',
+ university: null,
+ role: null,
+ department: null
+ })
+
+ var _resetNewAffiliation = () =>
+ ($scope.newAffiliation = {
+ email: '',
+ country: null,
+ university: null,
+ role: null,
+ department: null
+ })
+
+ var _resetAddingEmail = function () {
+ $scope.ui.showAddEmailUI = false
+ $scope.ui.isValidEmail = false
+ $scope.ui.isBlacklistedEmail = false
+ $scope.ui.showManualUniversitySelectionUI = false
+ }
+
+ var _resetAffiliationSuggestion = () => {
+ $scope.newAffiliation = {
+ email: $scope.newAffiliation.email
+ }
+ }
+
+ var _resetMakingRequestType = function () {
+ $scope.ui.isLoadingEmails = false
+ $scope.ui.isProcessing = false
+ $scope.ui.isResendingConfirmation = false
+ }
+
+ var _reset = function () {
+ $scope.ui = {
+ hasError: false,
+ errorMessage: '',
+ showChangeAffiliationUI: false,
+ isMakingRequest: false,
+ isLoadingEmails: false,
+ isAddingNewEmail: false
+ }
+ _resetAffiliationToChange()
+ _resetNewAffiliation()
+ return _resetAddingEmail()
+ }
+ _reset()
+
+ var _monitorRequest = function (promise) {
+ $scope.ui.hasError = false
+ $scope.ui.isMakingRequest = true
+ promise
+ .catch(function (response) {
+ $scope.ui.hasError = true
+ $scope.ui.errorMessage = _.get(response, ['data', 'message'])
+ })
+ .finally(() => ($scope.ui.isMakingRequest = false))
+ return promise
+ }
+
+ $scope.inReconfirmNotificationPeriod = function (emailData) {
+ return _.get(emailData, ['affiliation', 'inReconfirmNotificationPeriod'])
+ }
+
+ $scope.institutionAlreadyLinked = function (emailData) {
+ const institutionId =
+ emailData.affiliation &&
+ emailData.affiliation.institution &&
+ emailData.affiliation.institution &&
+ emailData.affiliation.institution.id
+ ? emailData.affiliation.institution.id.toString()
+ : undefined
+ return $scope.linkedInstitutionIds.indexOf(institutionId) !== -1
+ }
+
+ // Populates the emails table
+ var _getUserEmails = function () {
+ _resetMakingRequestType()
+ $scope.ui.isLoadingEmails = true
+ _monitorRequest(
+ UserAffiliationsDataService.getUserEmailsEnsureAffiliation()
+ )
+ .then(emails => {
+ $scope.userEmails = emails.map(email => {
+ email.ssoAvailable = _ssoAvailableForAffiliation(email.affiliation)
+ return email
+ })
+ $scope.linkedInstitutionIds = emails
+ .filter(email => {
+ if (email.samlProviderId) {
+ return email.samlProviderId
+ }
+ })
+ .map(email => email.samlProviderId)
+ })
+ .finally(() => ($scope.ui.isLoadingEmails = false))
+ }
+ _getUserEmails()
}
- _getUserEmails()
-})
+)
diff --git a/services/web/frontend/js/main/affiliations/controllers/UserAffiliationsReconfirmController.js b/services/web/frontend/js/main/affiliations/controllers/UserAffiliationsReconfirmController.js
index 85b3d4c3a2..fa292b37e7 100644
--- a/services/web/frontend/js/main/affiliations/controllers/UserAffiliationsReconfirmController.js
+++ b/services/web/frontend/js/main/affiliations/controllers/UserAffiliationsReconfirmController.js
@@ -2,66 +2,69 @@ import _ from 'lodash'
import App from '../../../base'
import getMeta from '../../../utils/meta'
-export default App.controller('UserAffiliationsReconfirmController', function(
- $scope,
- UserAffiliationsDataService,
- $window
-) {
- const samlInitPath = ExposedSettings.samlInitPath
- $scope.reconfirm = {}
- $scope.ui = $scope.ui || {} // $scope.ui inherited on settings page
- $scope.userEmails = getMeta('ol-userEmails')
- $scope.reconfirmedViaSAML = getMeta('ol-reconfirmedViaSAML')
+export default App.controller(
+ 'UserAffiliationsReconfirmController',
+ function ($scope, UserAffiliationsDataService, $window) {
+ const samlInitPath = ExposedSettings.samlInitPath
+ $scope.reconfirm = {}
+ $scope.ui = $scope.ui || {} // $scope.ui inherited on settings page
+ $scope.userEmails = getMeta('ol-userEmails')
+ $scope.reconfirmedViaSAML = getMeta('ol-reconfirmedViaSAML')
- // For portals:
- const portalAffiliation = getMeta('ol-portalAffiliation')
- if (portalAffiliation) {
- $scope.portalInReconfirmNotificationPeriod =
- portalAffiliation && portalAffiliation.inReconfirmNotificationPeriod
- $scope.userEmail = $scope.portalInReconfirmNotificationPeriod // mixin to show notification uses userEmail
- }
+ // For portals:
+ const portalAffiliation = getMeta('ol-portalAffiliation')
+ if (portalAffiliation) {
+ $scope.portalInReconfirmNotificationPeriod =
+ portalAffiliation && portalAffiliation.inReconfirmNotificationPeriod
+ $scope.userEmail = $scope.portalInReconfirmNotificationPeriod // mixin to show notification uses userEmail
+ }
- // For settings page:
- $scope.reconfirmationRemoveEmail = getMeta('ol-reconfirmationRemoveEmail')
+ // For settings page:
+ $scope.reconfirmationRemoveEmail = getMeta('ol-reconfirmationRemoveEmail')
- // For dashboard:
- $scope.allInReconfirmNotificationPeriods = getMeta(
- 'ol-allInReconfirmNotificationPeriods'
- )
+ // For dashboard:
+ $scope.allInReconfirmNotificationPeriods = getMeta(
+ 'ol-allInReconfirmNotificationPeriods'
+ )
- function sendReconfirmEmail(email) {
- $scope.ui.hasError = false
- $scope.ui.isMakingRequest = true
- UserAffiliationsDataService.resendConfirmationEmail(email)
- .then(() => {
- $scope.reconfirm[email].reconfirmationSent = true
- })
- .catch(error => {
- $scope.ui.hasError = true
- })
- .finally(() => ($scope.ui.isMakingRequest = false))
- }
+ function sendReconfirmEmail(email) {
+ $scope.ui.hasError = false
+ $scope.ui.isMakingRequest = true
+ UserAffiliationsDataService.resendConfirmationEmail(email)
+ .then(() => {
+ $scope.reconfirm[email].reconfirmationSent = true
+ })
+ .catch(error => {
+ $scope.ui.hasError = true
+ })
+ .finally(() => ($scope.ui.isMakingRequest = false))
+ }
- $scope.requestReconfirmation = function(obj, userEmail) {
- const email = userEmail.email
- // For the settings page, disable other parts of affiliation UI
- $scope.ui.isMakingRequest = true
- $scope.ui.isProcessing = true
- // create UI scope for requested email
- $scope.reconfirm[email] = $scope.reconfirm[email] || {} // keep existing scope for resend email requests
+ $scope.requestReconfirmation = function (obj, userEmail) {
+ const email = userEmail.email
+ // For the settings page, disable other parts of affiliation UI
+ $scope.ui.isMakingRequest = true
+ $scope.ui.isProcessing = true
+ // create UI scope for requested email
+ $scope.reconfirm[email] = $scope.reconfirm[email] || {} // keep existing scope for resend email requests
- const location = obj.currentTarget.getAttribute('data-location')
- const institutionId = _.get(userEmail, ['affiliation', 'institution', 'id'])
- const ssoEnabled = _.get(userEmail, [
- 'affiliation',
- 'institution',
- 'ssoEnabled'
- ])
+ const location = obj.currentTarget.getAttribute('data-location')
+ const institutionId = _.get(userEmail, [
+ 'affiliation',
+ 'institution',
+ 'id'
+ ])
+ const ssoEnabled = _.get(userEmail, [
+ 'affiliation',
+ 'institution',
+ 'ssoEnabled'
+ ])
- if (ssoEnabled) {
- $window.location.href = `${samlInitPath}?university_id=${institutionId}&reconfirm=${location}`
- } else {
- sendReconfirmEmail(email)
+ if (ssoEnabled) {
+ $window.location.href = `${samlInitPath}?university_id=${institutionId}&reconfirm=${location}`
+ } else {
+ sendReconfirmEmail(email)
+ }
}
}
-})
+)
diff --git a/services/web/frontend/js/main/affiliations/factories/UserAffiliationsDataService.js b/services/web/frontend/js/main/affiliations/factories/UserAffiliationsDataService.js
index 60d3ce0558..acfbda72f3 100644
--- a/services/web/frontend/js/main/affiliations/factories/UserAffiliationsDataService.js
+++ b/services/web/frontend/js/main/affiliations/factories/UserAffiliationsDataService.js
@@ -406,7 +406,7 @@ for (let domain of commonDomains) {
}
}
-App.factory('UserAffiliationsDataService', function($http, $q) {
+App.factory('UserAffiliationsDataService', function ($http, $q) {
const getCountries = () => $q.resolve(countriesList)
const getDefaultRoleHints = () => $q.resolve(defaultRoleHints)
@@ -426,7 +426,7 @@ App.factory('UserAffiliationsDataService', function($http, $q) {
_.find(userEmails, userEmail => userEmail.default)
)
- const getUniversitiesFromCountry = function(country) {
+ const getUniversitiesFromCountry = function (country) {
let universitiesFromCountry
if (universities[country.code] != null) {
universitiesFromCountry = universities[country.code]
@@ -440,7 +440,7 @@ App.factory('UserAffiliationsDataService', function($http, $q) {
return $q.resolve(universitiesFromCountry)
}
- const getUniversityDomainFromPartialDomainInput = function(
+ const getUniversityDomainFromPartialDomainInput = function (
partialDomainInput
) {
if (universitiesByDomain[partialDomainInput] != null) {
@@ -450,7 +450,7 @@ App.factory('UserAffiliationsDataService', function($http, $q) {
.get('/institutions/domains', {
params: { hostname: partialDomainInput, limit: 1 }
})
- .then(function(response) {
+ .then(function (response) {
const university = response.data[0]
if (university != null && !isDomainBlacklisted(university.hostname)) {
universitiesByDomain[university.hostname] = university
diff --git a/services/web/frontend/js/main/annual-upgrade.js b/services/web/frontend/js/main/annual-upgrade.js
index 8c806c62fe..9ceed01940 100644
--- a/services/web/frontend/js/main/annual-upgrade.js
+++ b/services/web/frontend/js/main/annual-upgrade.js
@@ -11,35 +11,34 @@
*/
import App from '../base'
-export default App.controller('AnnualUpgradeController', function(
- $scope,
- $http,
- $modal
-) {
- const MESSAGES_URL = '/user/subscription/upgrade-annual'
+export default App.controller(
+ 'AnnualUpgradeController',
+ function ($scope, $http, $modal) {
+ const MESSAGES_URL = '/user/subscription/upgrade-annual'
- $scope.upgradeComplete = false
- const savings = {
- student: '19.2',
- collaborator: '36'
+ $scope.upgradeComplete = false
+ const savings = {
+ student: '19.2',
+ collaborator: '36'
+ }
+ $scope.$watch($scope.planName, function () {
+ $scope.yearlySaving = savings[$scope.planName]
+ if ($scope.planName === 'annual') {
+ return ($scope.upgradeComplete = true)
+ }
+ })
+ return ($scope.completeAnnualUpgrade = function () {
+ const body = {
+ planName: $scope.planName,
+ _csrf: window.csrfToken
+ }
+
+ $scope.inflight = true
+
+ return $http
+ .post(MESSAGES_URL, body)
+ .then(() => ($scope.upgradeComplete = true))
+ .catch(() => console.log('something went wrong changing plan'))
+ })
}
- $scope.$watch($scope.planName, function() {
- $scope.yearlySaving = savings[$scope.planName]
- if ($scope.planName === 'annual') {
- return ($scope.upgradeComplete = true)
- }
- })
- return ($scope.completeAnnualUpgrade = function() {
- const body = {
- planName: $scope.planName,
- _csrf: window.csrfToken
- }
-
- $scope.inflight = true
-
- return $http
- .post(MESSAGES_URL, body)
- .then(() => ($scope.upgradeComplete = true))
- .catch(() => console.log('something went wrong changing plan'))
- })
-})
+)
diff --git a/services/web/frontend/js/main/clear-sessions.js b/services/web/frontend/js/main/clear-sessions.js
index 676141ebe9..b7b647d1af 100644
--- a/services/web/frontend/js/main/clear-sessions.js
+++ b/services/web/frontend/js/main/clear-sessions.js
@@ -12,28 +12,28 @@
import App from '../base'
import getMeta from '../utils/meta'
-export default App.controller('ClearSessionsController', function(
- $scope,
- $http
-) {
- $scope.state = {
- otherSessions: getMeta('ol-otherSessions'),
- error: false,
- success: false
- }
+export default App.controller(
+ 'ClearSessionsController',
+ function ($scope, $http) {
+ $scope.state = {
+ otherSessions: getMeta('ol-otherSessions'),
+ error: false,
+ success: false
+ }
- return ($scope.clearSessions = function() {
- console.log('>> clearing all sessions')
- return $http({
- method: 'POST',
- url: '/user/sessions/clear',
- headers: { 'X-CSRF-Token': window.csrfToken }
- })
- .then(function() {
- $scope.state.otherSessions = []
- $scope.state.error = false
- return ($scope.state.success = true)
+ return ($scope.clearSessions = function () {
+ console.log('>> clearing all sessions')
+ return $http({
+ method: 'POST',
+ url: '/user/sessions/clear',
+ headers: { 'X-CSRF-Token': window.csrfToken }
})
- .catch(() => ($scope.state.error = true))
- })
-})
+ .then(function () {
+ $scope.state.otherSessions = []
+ $scope.state.error = false
+ return ($scope.state.success = true)
+ })
+ .catch(() => ($scope.state.error = true))
+ })
+ }
+)
diff --git a/services/web/frontend/js/main/event.js b/services/web/frontend/js/main/event.js
index c568b0b07e..0bd994bbdb 100644
--- a/services/web/frontend/js/main/event.js
+++ b/services/web/frontend/js/main/event.js
@@ -22,8 +22,8 @@ const CACHE_KEY = 'mbEvents'
let heartbeatsSent = 0
let nextHeartbeat = new Date()
-App.factory('eventTracking', function($http, localStorage) {
- const _getEventCache = function() {
+App.factory('eventTracking', function ($http, localStorage) {
+ const _getEventCache = function () {
let eventCache = localStorage(CACHE_KEY)
// Initialize as an empy object if the event cache is still empty.
@@ -35,12 +35,12 @@ App.factory('eventTracking', function($http, localStorage) {
return eventCache
}
- const _eventInCache = function(key) {
+ const _eventInCache = function (key) {
const curCache = _getEventCache()
return curCache[key] || false
}
- const _addEventToCache = function(key) {
+ const _addEventToCache = function (key) {
const curCache = _getEventCache()
curCache[key] = true
@@ -86,9 +86,7 @@ App.factory('eventTracking', function($http, localStorage) {
? (heartbeatsSent - 2) * 60
: 300
- return (nextHeartbeat = moment()
- .add(backoffSecs, 'seconds')
- .toDate())
+ return (nextHeartbeat = moment().add(backoffSecs, 'seconds').toDate())
},
sendMB(key, segmentation) {
@@ -124,7 +122,7 @@ App.factory('eventTracking', function($http, localStorage) {
}
})
-export default $('.navbar a').on('click', function(e) {
+export default $('.navbar a').on('click', function (e) {
const href = $(e.target).attr('href')
if (href != null) {
return ga('send', 'event', 'navigation', 'top menu bar', href)
diff --git a/services/web/frontend/js/main/importing.js b/services/web/frontend/js/main/importing.js
index 8710474369..bc7cdbee9a 100644
--- a/services/web/frontend/js/main/importing.js
+++ b/services/web/frontend/js/main/importing.js
@@ -1,20 +1,18 @@
import App from '../base'
-App.controller('ImportingController', function(
- $interval,
- $scope,
- $timeout,
- $window
-) {
- $interval(function() {
- $scope.state.load_progress += 5
- if ($scope.state.load_progress > 100) {
- $scope.state.load_progress = 20
+App.controller(
+ 'ImportingController',
+ function ($interval, $scope, $timeout, $window) {
+ $interval(function () {
+ $scope.state.load_progress += 5
+ if ($scope.state.load_progress > 100) {
+ $scope.state.load_progress = 20
+ }
+ }, 500)
+ $timeout(function () {
+ $window.location.reload()
+ }, 5000)
+ $scope.state = {
+ load_progress: 20
}
- }, 500)
- $timeout(function() {
- $window.location.reload()
- }, 5000)
- $scope.state = {
- load_progress: 20
}
-})
+)
diff --git a/services/web/frontend/js/main/learn.js b/services/web/frontend/js/main/learn.js
index d7650b4854..1f93990ace 100644
--- a/services/web/frontend/js/main/learn.js
+++ b/services/web/frontend/js/main/learn.js
@@ -17,93 +17,96 @@ import _ from 'lodash'
import App from '../base'
import '../directives/mathjax'
import '../services/algolia-search'
-App.controller('SearchWikiController', function($scope, algoliaSearch, $modal) {
- $scope.hits = []
- $scope.hits_total = 0
- $scope.config_hits_per_page = 20
- $scope.processingSearch = false
+App.controller(
+ 'SearchWikiController',
+ function ($scope, algoliaSearch, $modal) {
+ $scope.hits = []
+ $scope.hits_total = 0
+ $scope.config_hits_per_page = 20
+ $scope.processingSearch = false
- $scope.clearSearchText = function() {
- $scope.searchQueryText = ''
- return updateHits([])
- }
-
- $scope.safeApply = function(fn) {
- const phase = $scope.$root.$$phase
- if (phase === '$apply' || phase === '$digest') {
- return $scope.$eval(fn)
- } else {
- return $scope.$apply(fn)
- }
- }
-
- const buildHitViewModel = function(hit) {
- const pagePath = hit.kb ? 'how-to/' : 'latex/'
- const pageSlug = encodeURIComponent(hit.pageName.replace(/\s/g, '_'))
- let section_underscored = ''
- if (hit.sectionName && hit.sectionName !== '') {
- section_underscored = '#' + hit.sectionName.replace(/\s/g, '_')
- }
- const section = hit._highlightResult.sectionName
- let pageName = hit._highlightResult.pageName.value
- if (section && section.value && section !== '') {
- pageName += ' - ' + section.value
+ $scope.clearSearchText = function () {
+ $scope.searchQueryText = ''
+ return updateHits([])
}
- let content = hit._highlightResult.content.value
- // Replace many new lines
- content = content.replace(/\n\n+/g, '\n\n')
- const lines = content.split('\n')
- // Only show the lines that have a highlighted match
- const matching_lines = []
- for (let line of Array.from(lines)) {
- if (!/^\[edit\]/.test(line)) {
- content += line + '\n'
- if (//.test(line)) {
- matching_lines.push(line)
- }
+ $scope.safeApply = function (fn) {
+ const phase = $scope.$root.$$phase
+ if (phase === '$apply' || phase === '$digest') {
+ return $scope.$eval(fn)
+ } else {
+ return $scope.$apply(fn)
}
}
- content = matching_lines.join('\n...\n')
- const result = {
- name: pageName,
- url: `/learn/${pagePath}${pageSlug}${section_underscored}`,
- content
- }
- return result
- }
- var updateHits = (hits, hits_total = 0) => {
- $scope.safeApply(() => {
- $scope.hits = hits
- $scope.hits_total = hits_total
- })
- }
+ const buildHitViewModel = function (hit) {
+ const pagePath = hit.kb ? 'how-to/' : 'latex/'
+ const pageSlug = encodeURIComponent(hit.pageName.replace(/\s/g, '_'))
+ let section_underscored = ''
+ if (hit.sectionName && hit.sectionName !== '') {
+ section_underscored = '#' + hit.sectionName.replace(/\s/g, '_')
+ }
+ const section = hit._highlightResult.sectionName
+ let pageName = hit._highlightResult.pageName.value
+ if (section && section.value && section !== '') {
+ pageName += ' - ' + section.value
+ }
- $scope.search = function() {
- $scope.processingSearch = true
- const query = $scope.searchQueryText
- if (query == null || query.length === 0) {
- updateHits([])
- return
- }
-
- return algoliaSearch.searchWiki(
- query,
- {
- hitsPerPage: $scope.config_hits_per_page
- },
- function(err, response) {
- $scope.processingSearch = false
- if (response.hits.length === 0) {
- return updateHits([])
- } else {
- const hits = _.map(response.hits, buildHitViewModel)
- return updateHits(hits, response.nbHits)
+ let content = hit._highlightResult.content.value
+ // Replace many new lines
+ content = content.replace(/\n\n+/g, '\n\n')
+ const lines = content.split('\n')
+ // Only show the lines that have a highlighted match
+ const matching_lines = []
+ for (let line of Array.from(lines)) {
+ if (!/^\[edit\]/.test(line)) {
+ content += line + '\n'
+ if (//.test(line)) {
+ matching_lines.push(line)
+ }
}
}
- )
- }
-})
+ content = matching_lines.join('\n...\n')
+ const result = {
+ name: pageName,
+ url: `/learn/${pagePath}${pageSlug}${section_underscored}`,
+ content
+ }
+ return result
+ }
-export default App.controller('LearnController', function() {})
+ var updateHits = (hits, hits_total = 0) => {
+ $scope.safeApply(() => {
+ $scope.hits = hits
+ $scope.hits_total = hits_total
+ })
+ }
+
+ $scope.search = function () {
+ $scope.processingSearch = true
+ const query = $scope.searchQueryText
+ if (query == null || query.length === 0) {
+ updateHits([])
+ return
+ }
+
+ return algoliaSearch.searchWiki(
+ query,
+ {
+ hitsPerPage: $scope.config_hits_per_page
+ },
+ function (err, response) {
+ $scope.processingSearch = false
+ if (response.hits.length === 0) {
+ return updateHits([])
+ } else {
+ const hits = _.map(response.hits, buildHitViewModel)
+ return updateHits(hits, response.nbHits)
+ }
+ }
+ )
+ }
+ }
+)
+
+export default App.controller('LearnController', function () {})
diff --git a/services/web/frontend/js/main/new-subscription.js b/services/web/frontend/js/main/new-subscription.js
index eeb5aa182a..c337338872 100644
--- a/services/web/frontend/js/main/new-subscription.js
+++ b/services/web/frontend/js/main/new-subscription.js
@@ -7,629 +7,626 @@ import _ from 'lodash'
/* global recurly */
import App from '../base'
-export default App.controller('NewSubscriptionController', function(
- $scope,
- MultiCurrencyPricing,
- $http,
- $location,
- eventTracking
-) {
- window.couponCode = $location.search().cc || ''
- window.plan_code = $location.search().planCode || ''
- window.ITMCampaign = $location.search().itm_campaign || ''
- window.ITMContent = $location.search().itm_content || ''
+export default App.controller(
+ 'NewSubscriptionController',
+ function ($scope, MultiCurrencyPricing, $http, $location, eventTracking) {
+ window.couponCode = $location.search().cc || ''
+ window.plan_code = $location.search().planCode || ''
+ window.ITMCampaign = $location.search().itm_campaign || ''
+ window.ITMContent = $location.search().itm_content || ''
- if (typeof recurly === 'undefined' || !recurly) {
- $scope.recurlyLoadError = true
- return
- }
-
- $scope.ui = {
- addCompanyDetails: false
- }
-
- $scope.recurlyLoadError = false
- $scope.currencyCode = MultiCurrencyPricing.currencyCode
- $scope.allCurrencies = MultiCurrencyPricing.plans
- $scope.availableCurrencies = {}
- $scope.planCode = window.plan_code
-
- $scope.switchToStudent = function() {
- const currentPlanCode = window.plan_code
- const planCode = currentPlanCode.replace('collaborator', 'student')
- eventTracking.sendMB('subscription-form-switch-to-student', {
- plan: window.plan_code
- })
- eventTracking.send(
- 'subscription-funnel',
- 'subscription-form-switch-to-student',
- window.plan_code
- )
- window.location = `/user/subscription/new?planCode=${planCode}¤cy=${$scope.currencyCode}&cc=${$scope.data.coupon}&itm_campaign=${window.ITMCampaign}&itm_content=${window.ITMContent}`
- }
-
- eventTracking.sendMB('subscription-form', { plan: window.plan_code })
- eventTracking.send(
- 'subscription-funnel',
- 'subscription-form-viewed',
- window.plan_code
- )
-
- $scope.paymentMethod = { value: 'credit_card' }
-
- $scope.data = {
- first_name: '',
- last_name: '',
- postal_code: '',
- address1: '',
- address2: '',
- state: '',
- city: '',
- company: '',
- vat_number: '',
- country: window.countryCode,
- coupon: window.couponCode
- }
-
- $scope.validation = {}
-
- $scope.processing = false
-
- $scope.threeDSecureFlow = false
- $scope.threeDSecureContainer = document.querySelector(
- '.three-d-secure-container'
- )
- $scope.threeDSecureRecurlyContainer = document.querySelector(
- '.three-d-secure-recurly-container'
- )
-
- recurly.configure({
- publicKey: window.recurlyApiKey,
- style: {
- all: {
- fontFamily: '"Open Sans", sans-serif',
- fontSize: '16px',
- fontColor: '#7a7a7a'
- },
- month: {
- placeholder: 'MM'
- },
- year: {
- placeholder: 'YY'
- },
- cvv: {
- placeholder: 'CVV'
- }
- }
- })
-
- const pricing = recurly.Pricing()
- window.pricing = pricing
-
- pricing
- .plan(window.plan_code, { quantity: 1 })
- .address({
- country: $scope.data.country
- })
- .tax({ tax_code: 'digital', vat_number: '' })
- .currency($scope.currencyCode)
- .coupon($scope.data.coupon)
- .done()
-
- pricing.on('change', () => {
- $scope.planName = pricing.items.plan.name
-
- if (pricing.items.plan.trial) {
- $scope.trialLength = pricing.items.plan.trial.length
+ if (typeof recurly === 'undefined' || !recurly) {
+ $scope.recurlyLoadError = true
+ return
}
- $scope.price = $scope.trialLength ? pricing.price.next : pricing.price.now
- $scope.taxes = pricing.price.taxes
- $scope.monthlyBilling = pricing.items.plan.period.length === 1
+ $scope.ui = {
+ addCompanyDetails: false
+ }
+ $scope.recurlyLoadError = false
+ $scope.currencyCode = MultiCurrencyPricing.currencyCode
+ $scope.allCurrencies = MultiCurrencyPricing.plans
$scope.availableCurrencies = {}
- for (let currencyCode in pricing.items.plan.price) {
- if (MultiCurrencyPricing.plans[currencyCode]) {
- $scope.availableCurrencies[currencyCode] =
- MultiCurrencyPricing.plans[currencyCode]
- }
- }
+ $scope.planCode = window.plan_code
- if (
- pricing.items &&
- pricing.items.coupon &&
- pricing.items.coupon.discount &&
- pricing.items.coupon.discount.type === 'percent'
- ) {
- const basePrice = parseInt(pricing.price.base.plan.unit, 10)
- $scope.coupon = {
- singleUse: pricing.items.coupon.single_use,
- normalPrice: basePrice
- }
- if (
- pricing.items.coupon.applies_for_months > 0 &&
- pricing.items.coupon.discount.rate &&
- pricing.items.coupon.applies_for_months
- ) {
- $scope.coupon.discountMonths = pricing.items.coupon.applies_for_months
- $scope.coupon.discountRate = pricing.items.coupon.discount.rate * 100
- }
-
- if (pricing.price.taxes[0] && pricing.price.taxes[0].rate) {
- $scope.coupon.normalPrice += basePrice * pricing.price.taxes[0].rate
- }
- } else {
- $scope.coupon = null
- }
- $scope.$apply()
- })
-
- $scope.applyCoupon = () => pricing.coupon($scope.data.coupon).done()
-
- $scope.applyVatNumber = () =>
- pricing
- .tax({ tax_code: 'digital', vat_number: $scope.data.vat_number })
- .done()
-
- $scope.changeCurrency = function(newCurrency) {
- $scope.currencyCode = newCurrency
- return pricing.currency(newCurrency).done()
- }
-
- $scope.inputHasError = function(formItem) {
- if (formItem == null) {
- return false
- }
-
- return formItem.$touched && formItem.$invalid
- }
-
- $scope.isFormValid = function(form) {
- if ($scope.paymentMethod.value === 'paypal') {
- return $scope.data.country !== ''
- } else {
- return form.$valid
- }
- }
-
- $scope.updateCountry = () =>
- pricing.address({ country: $scope.data.country }).done()
-
- $scope.setPaymentMethod = function(method) {
- $scope.paymentMethod.value = method
- $scope.validation.errorFields = {}
- $scope.genericError = ''
- }
-
- let cachedRecurlyBillingToken
- const completeSubscription = function(
- err,
- recurlyBillingToken,
- recurly3DSecureResultToken
- ) {
- if (recurlyBillingToken) {
- // temporary store the billing token as it might be needed when
- // re-sending the request after SCA authentication
- cachedRecurlyBillingToken = recurlyBillingToken
- }
- $scope.validation.errorFields = {}
- if (err != null) {
- eventTracking.sendMB('subscription-error', err)
- eventTracking.send('subscription-funnel', 'subscription-error')
- // We may or may not be in a digest loop here depending on
- // whether recurly could do validation locally, so do it async
- $scope.$evalAsync(function() {
- $scope.processing = false
- $scope.genericError = err.message
- _.each(
- err.fields,
- field => ($scope.validation.errorFields[field] = true)
- )
- })
- } else {
- const postData = {
- _csrf: window.csrfToken,
- recurly_token_id: cachedRecurlyBillingToken.id,
- recurly_three_d_secure_action_result_token_id:
- recurly3DSecureResultToken && recurly3DSecureResultToken.id,
- subscriptionDetails: {
- currencyCode: pricing.items.currency,
- plan_code: pricing.items.plan.code,
- coupon_code: pricing.items.coupon ? pricing.items.coupon.code : '',
- first_name: $scope.data.first_name,
- last_name: $scope.data.last_name,
- isPaypal: $scope.paymentMethod.value === 'paypal',
- address: {
- address1: $scope.data.address1,
- address2: $scope.data.address2,
- country: $scope.data.country,
- state: $scope.data.state,
- zip: $scope.data.postal_code
- },
- ITMCampaign: window.ITMCampaign,
- ITMContent: window.ITMContent
- }
- }
-
- if (
- postData.subscriptionDetails.isPaypal &&
- $scope.ui.addCompanyDetails
- ) {
- postData.subscriptionDetails.billing_info = {}
- if ($scope.data.company && $scope.data.company !== '') {
- postData.subscriptionDetails.billing_info.company =
- $scope.data.company
- }
- if ($scope.data.vat_number && $scope.data.vat_number !== '') {
- postData.subscriptionDetails.billing_info.vat_number =
- $scope.data.vat_number
- }
- }
-
- eventTracking.sendMB('subscription-form-submitted', {
- currencyCode: postData.subscriptionDetails.currencyCode,
- plan_code: postData.subscriptionDetails.plan_code,
- coupon_code: postData.subscriptionDetails.coupon_code,
- isPaypal: postData.subscriptionDetails.isPaypal
+ $scope.switchToStudent = function () {
+ const currentPlanCode = window.plan_code
+ const planCode = currentPlanCode.replace('collaborator', 'student')
+ eventTracking.sendMB('subscription-form-switch-to-student', {
+ plan: window.plan_code
})
eventTracking.send(
'subscription-funnel',
- 'subscription-form-submitted',
- postData.subscriptionDetails.plan_code
+ 'subscription-form-switch-to-student',
+ window.plan_code
)
- return $http
- .post('/user/subscription/create', postData)
- .then(function() {
- eventTracking.sendMB('subscription-submission-success')
- eventTracking.send(
- 'subscription-funnel',
- 'subscription-submission-success',
- postData.subscriptionDetails.plan_code
- )
- window.location.href = '/user/subscription/thank-you'
- })
- .catch(response => {
- $scope.processing = false
- const { data } = response
- $scope.genericError =
- (data && data.message) ||
- 'Something went wrong processing the request'
-
- if (data.threeDSecureActionTokenId) {
- initThreeDSecure(data.threeDSecureActionTokenId)
- }
- })
+ window.location = `/user/subscription/new?planCode=${planCode}¤cy=${$scope.currencyCode}&cc=${$scope.data.coupon}&itm_campaign=${window.ITMCampaign}&itm_content=${window.ITMContent}`
}
- }
- $scope.submit = function() {
- $scope.processing = true
- if ($scope.paymentMethod.value === 'paypal') {
- const opts = { description: $scope.planName }
- recurly.paypal(opts, completeSubscription)
- } else {
- const tokenData = _.cloneDeep($scope.data)
- if (!$scope.ui.addCompanyDetails) {
- delete tokenData.company
- delete tokenData.vat_number
+ eventTracking.sendMB('subscription-form', { plan: window.plan_code })
+ eventTracking.send(
+ 'subscription-funnel',
+ 'subscription-form-viewed',
+ window.plan_code
+ )
+
+ $scope.paymentMethod = { value: 'credit_card' }
+
+ $scope.data = {
+ first_name: '',
+ last_name: '',
+ postal_code: '',
+ address1: '',
+ address2: '',
+ state: '',
+ city: '',
+ company: '',
+ vat_number: '',
+ country: window.countryCode,
+ coupon: window.couponCode
+ }
+
+ $scope.validation = {}
+
+ $scope.processing = false
+
+ $scope.threeDSecureFlow = false
+ $scope.threeDSecureContainer = document.querySelector(
+ '.three-d-secure-container'
+ )
+ $scope.threeDSecureRecurlyContainer = document.querySelector(
+ '.three-d-secure-recurly-container'
+ )
+
+ recurly.configure({
+ publicKey: window.recurlyApiKey,
+ style: {
+ all: {
+ fontFamily: '"Open Sans", sans-serif',
+ fontSize: '16px',
+ fontColor: '#7a7a7a'
+ },
+ month: {
+ placeholder: 'MM'
+ },
+ year: {
+ placeholder: 'YY'
+ },
+ cvv: {
+ placeholder: 'CVV'
+ }
}
- recurly.token(tokenData, completeSubscription)
+ })
+
+ const pricing = recurly.Pricing()
+ window.pricing = pricing
+
+ pricing
+ .plan(window.plan_code, { quantity: 1 })
+ .address({
+ country: $scope.data.country
+ })
+ .tax({ tax_code: 'digital', vat_number: '' })
+ .currency($scope.currencyCode)
+ .coupon($scope.data.coupon)
+ .done()
+
+ pricing.on('change', () => {
+ $scope.planName = pricing.items.plan.name
+
+ if (pricing.items.plan.trial) {
+ $scope.trialLength = pricing.items.plan.trial.length
+ }
+
+ $scope.price = $scope.trialLength ? pricing.price.next : pricing.price.now
+ $scope.taxes = pricing.price.taxes
+ $scope.monthlyBilling = pricing.items.plan.period.length === 1
+
+ $scope.availableCurrencies = {}
+ for (let currencyCode in pricing.items.plan.price) {
+ if (MultiCurrencyPricing.plans[currencyCode]) {
+ $scope.availableCurrencies[currencyCode] =
+ MultiCurrencyPricing.plans[currencyCode]
+ }
+ }
+
+ if (
+ pricing.items &&
+ pricing.items.coupon &&
+ pricing.items.coupon.discount &&
+ pricing.items.coupon.discount.type === 'percent'
+ ) {
+ const basePrice = parseInt(pricing.price.base.plan.unit, 10)
+ $scope.coupon = {
+ singleUse: pricing.items.coupon.single_use,
+ normalPrice: basePrice
+ }
+ if (
+ pricing.items.coupon.applies_for_months > 0 &&
+ pricing.items.coupon.discount.rate &&
+ pricing.items.coupon.applies_for_months
+ ) {
+ $scope.coupon.discountMonths = pricing.items.coupon.applies_for_months
+ $scope.coupon.discountRate = pricing.items.coupon.discount.rate * 100
+ }
+
+ if (pricing.price.taxes[0] && pricing.price.taxes[0].rate) {
+ $scope.coupon.normalPrice += basePrice * pricing.price.taxes[0].rate
+ }
+ } else {
+ $scope.coupon = null
+ }
+ $scope.$apply()
+ })
+
+ $scope.applyCoupon = () => pricing.coupon($scope.data.coupon).done()
+
+ $scope.applyVatNumber = () =>
+ pricing
+ .tax({ tax_code: 'digital', vat_number: $scope.data.vat_number })
+ .done()
+
+ $scope.changeCurrency = function (newCurrency) {
+ $scope.currencyCode = newCurrency
+ return pricing.currency(newCurrency).done()
}
- }
- const initThreeDSecure = function(threeDSecureActionTokenId) {
- // instanciate and configure Recurly 3DSecure flow
- const risk = recurly.Risk()
- const threeDSecure = risk.ThreeDSecure({
- actionTokenId: threeDSecureActionTokenId
- })
+ $scope.inputHasError = function (formItem) {
+ if (formItem == null) {
+ return false
+ }
- // on SCA verification error: show payment UI with the error message
- threeDSecure.on('error', error => {
- $scope.genericError = `Error: ${error.message}`
- $scope.threeDSecureFlow = false
- $scope.$apply()
- })
+ return formItem.$touched && formItem.$invalid
+ }
- // on SCA verification success: show payment UI in processing mode and
- // resubmit the payment with the new token final success or error will be
- // handled by `completeSubscription`
- threeDSecure.on('token', recurly3DSecureResultToken => {
- completeSubscription(null, null, recurly3DSecureResultToken)
- $scope.genericError = null
- $scope.threeDSecureFlow = false
+ $scope.isFormValid = function (form) {
+ if ($scope.paymentMethod.value === 'paypal') {
+ return $scope.data.country !== ''
+ } else {
+ return form.$valid
+ }
+ }
+
+ $scope.updateCountry = () =>
+ pricing.address({ country: $scope.data.country }).done()
+
+ $scope.setPaymentMethod = function (method) {
+ $scope.paymentMethod.value = method
+ $scope.validation.errorFields = {}
+ $scope.genericError = ''
+ }
+
+ let cachedRecurlyBillingToken
+ const completeSubscription = function (
+ err,
+ recurlyBillingToken,
+ recurly3DSecureResultToken
+ ) {
+ if (recurlyBillingToken) {
+ // temporary store the billing token as it might be needed when
+ // re-sending the request after SCA authentication
+ cachedRecurlyBillingToken = recurlyBillingToken
+ }
+ $scope.validation.errorFields = {}
+ if (err != null) {
+ eventTracking.sendMB('subscription-error', err)
+ eventTracking.send('subscription-funnel', 'subscription-error')
+ // We may or may not be in a digest loop here depending on
+ // whether recurly could do validation locally, so do it async
+ $scope.$evalAsync(function () {
+ $scope.processing = false
+ $scope.genericError = err.message
+ _.each(
+ err.fields,
+ field => ($scope.validation.errorFields[field] = true)
+ )
+ })
+ } else {
+ const postData = {
+ _csrf: window.csrfToken,
+ recurly_token_id: cachedRecurlyBillingToken.id,
+ recurly_three_d_secure_action_result_token_id:
+ recurly3DSecureResultToken && recurly3DSecureResultToken.id,
+ subscriptionDetails: {
+ currencyCode: pricing.items.currency,
+ plan_code: pricing.items.plan.code,
+ coupon_code: pricing.items.coupon ? pricing.items.coupon.code : '',
+ first_name: $scope.data.first_name,
+ last_name: $scope.data.last_name,
+ isPaypal: $scope.paymentMethod.value === 'paypal',
+ address: {
+ address1: $scope.data.address1,
+ address2: $scope.data.address2,
+ country: $scope.data.country,
+ state: $scope.data.state,
+ zip: $scope.data.postal_code
+ },
+ ITMCampaign: window.ITMCampaign,
+ ITMContent: window.ITMContent
+ }
+ }
+
+ if (
+ postData.subscriptionDetails.isPaypal &&
+ $scope.ui.addCompanyDetails
+ ) {
+ postData.subscriptionDetails.billing_info = {}
+ if ($scope.data.company && $scope.data.company !== '') {
+ postData.subscriptionDetails.billing_info.company =
+ $scope.data.company
+ }
+ if ($scope.data.vat_number && $scope.data.vat_number !== '') {
+ postData.subscriptionDetails.billing_info.vat_number =
+ $scope.data.vat_number
+ }
+ }
+
+ eventTracking.sendMB('subscription-form-submitted', {
+ currencyCode: postData.subscriptionDetails.currencyCode,
+ plan_code: postData.subscriptionDetails.plan_code,
+ coupon_code: postData.subscriptionDetails.coupon_code,
+ isPaypal: postData.subscriptionDetails.isPaypal
+ })
+ eventTracking.send(
+ 'subscription-funnel',
+ 'subscription-form-submitted',
+ postData.subscriptionDetails.plan_code
+ )
+ return $http
+ .post('/user/subscription/create', postData)
+ .then(function () {
+ eventTracking.sendMB('subscription-submission-success')
+ eventTracking.send(
+ 'subscription-funnel',
+ 'subscription-submission-success',
+ postData.subscriptionDetails.plan_code
+ )
+ window.location.href = '/user/subscription/thank-you'
+ })
+ .catch(response => {
+ $scope.processing = false
+ const { data } = response
+ $scope.genericError =
+ (data && data.message) ||
+ 'Something went wrong processing the request'
+
+ if (data.threeDSecureActionTokenId) {
+ initThreeDSecure(data.threeDSecureActionTokenId)
+ }
+ })
+ }
+ }
+
+ $scope.submit = function () {
$scope.processing = true
- $scope.$apply()
- })
+ if ($scope.paymentMethod.value === 'paypal') {
+ const opts = { description: $scope.planName }
+ recurly.paypal(opts, completeSubscription)
+ } else {
+ const tokenData = _.cloneDeep($scope.data)
+ if (!$scope.ui.addCompanyDetails) {
+ delete tokenData.company
+ delete tokenData.vat_number
+ }
+ recurly.token(tokenData, completeSubscription)
+ }
+ }
- // make sure the threeDSecureRecurlyContainer is empty (in case of
- // retries) and show 3DSecure UI
- $scope.threeDSecureRecurlyContainer.innerHTML = ''
- $scope.threeDSecureFlow = true
- threeDSecure.attach($scope.threeDSecureRecurlyContainer)
+ const initThreeDSecure = function (threeDSecureActionTokenId) {
+ // instanciate and configure Recurly 3DSecure flow
+ const risk = recurly.Risk()
+ const threeDSecure = risk.ThreeDSecure({
+ actionTokenId: threeDSecureActionTokenId
+ })
- // scroll the UI into view (timeout needed to make sure the element is
- // visible)
- window.setTimeout(() => {
- $scope.threeDSecureContainer.scrollIntoView()
- }, 0)
+ // on SCA verification error: show payment UI with the error message
+ threeDSecure.on('error', error => {
+ $scope.genericError = `Error: ${error.message}`
+ $scope.threeDSecureFlow = false
+ $scope.$apply()
+ })
+
+ // on SCA verification success: show payment UI in processing mode and
+ // resubmit the payment with the new token final success or error will be
+ // handled by `completeSubscription`
+ threeDSecure.on('token', recurly3DSecureResultToken => {
+ completeSubscription(null, null, recurly3DSecureResultToken)
+ $scope.genericError = null
+ $scope.threeDSecureFlow = false
+ $scope.processing = true
+ $scope.$apply()
+ })
+
+ // make sure the threeDSecureRecurlyContainer is empty (in case of
+ // retries) and show 3DSecure UI
+ $scope.threeDSecureRecurlyContainer.innerHTML = ''
+ $scope.threeDSecureFlow = true
+ threeDSecure.attach($scope.threeDSecureRecurlyContainer)
+
+ // scroll the UI into view (timeout needed to make sure the element is
+ // visible)
+ window.setTimeout(() => {
+ $scope.threeDSecureContainer.scrollIntoView()
+ }, 0)
+ }
+
+ // list taken from Recurly (see https://docs.recurly.com/docs/countries-provinces-and-states). Country code must exist on Recurly, so update with care
+ $scope.countries = [
+ { code: 'AF', name: 'Afghanistan' },
+ { code: 'AX', name: 'Ã…land Islands' },
+ { code: 'AL', name: 'Albania' },
+ { code: 'DZ', name: 'Algeria' },
+ { code: 'AS', name: 'American Samoa' },
+ { code: 'AD', name: 'Andorra' },
+ { code: 'AO', name: 'Angola' },
+ { code: 'AI', name: 'Anguilla' },
+ { code: 'AQ', name: 'Antarctica' },
+ { code: 'AG', name: 'Antigua and Barbuda' },
+ { code: 'AR', name: 'Argentina' },
+ { code: 'AM', name: 'Armenia' },
+ { code: 'AW', name: 'Aruba' },
+ { code: 'AC', name: 'Ascension Island' },
+ { code: 'AU', name: 'Australia' },
+ { code: 'AT', name: 'Austria' },
+ { code: 'AZ', name: 'Azerbaijan' },
+ { code: 'BS', name: 'Bahamas' },
+ { code: 'BH', name: 'Bahrain' },
+ { code: 'BD', name: 'Bangladesh' },
+ { code: 'BB', name: 'Barbados' },
+ { code: 'BY', name: 'Belarus' },
+ { code: 'BE', name: 'Belgium' },
+ { code: 'BZ', name: 'Belize' },
+ { code: 'BJ', name: 'Benin' },
+ { code: 'BM', name: 'Bermuda' },
+ { code: 'BT', name: 'Bhutan' },
+ { code: 'BO', name: 'Bolivia' },
+ { code: 'BA', name: 'Bosnia and Herzegovina' },
+ { code: 'BW', name: 'Botswana' },
+ { code: 'BV', name: 'Bouvet Island' },
+ { code: 'BR', name: 'Brazil' },
+ { code: 'BQ', name: 'British Antarctic Territory' },
+ { code: 'IO', name: 'British Indian Ocean Territory' },
+ { code: 'VG', name: 'British Virgin Islands' },
+ { code: 'BN', name: 'Brunei' },
+ { code: 'BG', name: 'Bulgaria' },
+ { code: 'BF', name: 'Burkina Faso' },
+ { code: 'BI', name: 'Burundi' },
+ { code: 'CV', name: 'Cabo Verde' },
+ { code: 'KH', name: 'Cambodia' },
+ { code: 'CM', name: 'Cameroon' },
+ { code: 'CA', name: 'Canada' },
+ { code: 'IC', name: 'Canary Islands' },
+ { code: 'CT', name: 'Canton and Enderbury Islands' },
+ { code: 'KY', name: 'Cayman Islands' },
+ { code: 'CF', name: 'Central African Republic' },
+ { code: 'EA', name: 'Ceuta and Melilla' },
+ { code: 'TD', name: 'Chad' },
+ { code: 'CL', name: 'Chile' },
+ { code: 'CN', name: 'China' },
+ { code: 'CX', name: 'Christmas Island' },
+ { code: 'CP', name: 'Clipperton Island' },
+ { code: 'CC', name: 'Cocos [Keeling] Islands' },
+ { code: 'CO', name: 'Colombia' },
+ { code: 'KM', name: 'Comoros' },
+ { code: 'CG', name: 'Congo - Brazzaville' },
+ { code: 'CD', name: 'Congo - Kinshasa' },
+ { code: 'CD', name: 'Congo [DRC]' },
+ { code: 'CG', name: 'Congo [Republic]' },
+ { code: 'CK', name: 'Cook Islands' },
+ { code: 'CR', name: 'Costa Rica' },
+ { code: 'CI', name: 'Côte d’Ivoire' },
+ { code: 'HR', name: 'Croatia' },
+ { code: 'CU', name: 'Cuba' },
+ { code: 'CY', name: 'Cyprus' },
+ { code: 'CZ', name: 'Czech Republic' },
+ { code: 'DK', name: 'Denmark' },
+ { code: 'DG', name: 'Diego Garcia' },
+ { code: 'DJ', name: 'Djibouti' },
+ { code: 'DM', name: 'Dominica' },
+ { code: 'DO', name: 'Dominican Republic' },
+ { code: 'NQ', name: 'Dronning Maud Land' },
+ { code: 'TL', name: 'East Timor' },
+ { code: 'EC', name: 'Ecuador' },
+ { code: 'EG', name: 'Egypt' },
+ { code: 'SV', name: 'El Salvador' },
+ { code: 'GQ', name: 'Equatorial Guinea' },
+ { code: 'ER', name: 'Eritrea' },
+ { code: 'EE', name: 'Estonia' },
+ { code: 'ET', name: 'Ethiopia' },
+ { code: 'FK', name: 'Falkland Islands [Islas Malvinas]' },
+ { code: 'FK', name: 'Falkland Islands' },
+ { code: 'FO', name: 'Faroe Islands' },
+ { code: 'FJ', name: 'Fiji' },
+ { code: 'FI', name: 'Finland' },
+ { code: 'FR', name: 'France' },
+ { code: 'GF', name: 'French Guiana' },
+ { code: 'PF', name: 'French Polynesia' },
+ { code: 'FQ', name: 'French Southern and Antarctic Territories' },
+ { code: 'TF', name: 'French Southern Territories' },
+ { code: 'GA', name: 'Gabon' },
+ { code: 'GM', name: 'Gambia' },
+ { code: 'GE', name: 'Georgia' },
+ { code: 'DE', name: 'Germany' },
+ { code: 'GH', name: 'Ghana' },
+ { code: 'GI', name: 'Gibraltar' },
+ { code: 'GR', name: 'Greece' },
+ { code: 'GL', name: 'Greenland' },
+ { code: 'GD', name: 'Grenada' },
+ { code: 'GP', name: 'Guadeloupe' },
+ { code: 'GU', name: 'Guam' },
+ { code: 'GT', name: 'Guatemala' },
+ { code: 'GG', name: 'Guernsey' },
+ { code: 'GW', name: 'Guinea-Bissau' },
+ { code: 'GN', name: 'Guinea' },
+ { code: 'GY', name: 'Guyana' },
+ { code: 'HT', name: 'Haiti' },
+ { code: 'HM', name: 'Heard Island and McDonald Islands' },
+ { code: 'HN', name: 'Honduras' },
+ { code: 'HK', name: 'Hong Kong' },
+ { code: 'HU', name: 'Hungary' },
+ { code: 'IS', name: 'Iceland' },
+ { code: 'IN', name: 'India' },
+ { code: 'ID', name: 'Indonesia' },
+ { code: 'IR', name: 'Iran' },
+ { code: 'IQ', name: 'Iraq' },
+ { code: 'IE', name: 'Ireland' },
+ { code: 'IM', name: 'Isle of Man' },
+ { code: 'IL', name: 'Israel' },
+ { code: 'IT', name: 'Italy' },
+ { code: 'CI', name: 'Ivory Coast' },
+ { code: 'JM', name: 'Jamaica' },
+ { code: 'JP', name: 'Japan' },
+ { code: 'JE', name: 'Jersey' },
+ { code: 'JT', name: 'Johnston Island' },
+ { code: 'JO', name: 'Jordan' },
+ { code: 'KZ', name: 'Kazakhstan' },
+ { code: 'KE', name: 'Kenya' },
+ { code: 'KI', name: 'Kiribati' },
+ { code: 'KW', name: 'Kuwait' },
+ { code: 'KG', name: 'Kyrgyzstan' },
+ { code: 'LA', name: 'Laos' },
+ { code: 'LV', name: 'Latvia' },
+ { code: 'LB', name: 'Lebanon' },
+ { code: 'LS', name: 'Lesotho' },
+ { code: 'LR', name: 'Liberia' },
+ { code: 'LY', name: 'Libya' },
+ { code: 'LI', name: 'Liechtenstein' },
+ { code: 'LT', name: 'Lithuania' },
+ { code: 'LU', name: 'Luxembourg' },
+ { code: 'MO', name: 'Macau SAR China' },
+ { code: 'MO', name: 'Macau' },
+ { code: 'MK', name: 'Macedonia [FYROM]' },
+ { code: 'MK', name: 'Macedonia' },
+ { code: 'MG', name: 'Madagascar' },
+ { code: 'MW', name: 'Malawi' },
+ { code: 'MY', name: 'Malaysia' },
+ { code: 'MV', name: 'Maldives' },
+ { code: 'ML', name: 'Mali' },
+ { code: 'MT', name: 'Malta' },
+ { code: 'MH', name: 'Marshall Islands' },
+ { code: 'MQ', name: 'Martinique' },
+ { code: 'MR', name: 'Mauritania' },
+ { code: 'MU', name: 'Mauritius' },
+ { code: 'YT', name: 'Mayotte' },
+ { code: 'FX', name: 'Metropolitan France' },
+ { code: 'MX', name: 'Mexico' },
+ { code: 'FM', name: 'Micronesia' },
+ { code: 'MI', name: 'Midway Islands' },
+ { code: 'MD', name: 'Moldova' },
+ { code: 'MC', name: 'Monaco' },
+ { code: 'MN', name: 'Mongolia' },
+ { code: 'ME', name: 'Montenegro' },
+ { code: 'MS', name: 'Montserrat' },
+ { code: 'MA', name: 'Morocco' },
+ { code: 'MZ', name: 'Mozambique' },
+ { code: 'MM', name: 'Myanmar [Burma]' },
+ { code: 'NA', name: 'Namibia' },
+ { code: 'NR', name: 'Nauru' },
+ { code: 'NP', name: 'Nepal' },
+ { code: 'AN', name: 'Netherlands Antilles' },
+ { code: 'NL', name: 'Netherlands' },
+ { code: 'NC', name: 'New Caledonia' },
+ { code: 'NZ', name: 'New Zealand' },
+ { code: 'NI', name: 'Nicaragua' },
+ { code: 'NE', name: 'Niger' },
+ { code: 'NG', name: 'Nigeria' },
+ { code: 'NU', name: 'Niue' },
+ { code: 'NF', name: 'Norfolk Island' },
+ { code: 'KP', name: 'North Korea' },
+ { code: 'VD', name: 'North Vietnam' },
+ { code: 'MP', name: 'Northern Mariana Islands' },
+ { code: 'NO', name: 'Norway' },
+ { code: 'OM', name: 'Oman' },
+ { code: 'QO', name: 'Outlying Oceania' },
+ { code: 'PC', name: 'Pacific Islands Trust Territory' },
+ { code: 'PK', name: 'Pakistan' },
+ { code: 'PW', name: 'Palau' },
+ { code: 'PS', name: 'Palestinian Territories' },
+ { code: 'PZ', name: 'Panama Canal Zone' },
+ { code: 'PA', name: 'Panama' },
+ { code: 'PG', name: 'Papua New Guinea' },
+ { code: 'PY', name: 'Paraguay' },
+ { code: 'YD', name: "People's Democratic Republic of Yemen" },
+ { code: 'PE', name: 'Peru' },
+ { code: 'PH', name: 'Philippines' },
+ { code: 'PN', name: 'Pitcairn Islands' },
+ { code: 'PL', name: 'Poland' },
+ { code: 'PT', name: 'Portugal' },
+ { code: 'PR', name: 'Puerto Rico' },
+ { code: 'QA', name: 'Qatar' },
+ { code: 'RE', name: 'Réunion' },
+ { code: 'RO', name: 'Romania' },
+ { code: 'RU', name: 'Russia' },
+ { code: 'RW', name: 'Rwanda' },
+ { code: 'BL', name: 'Saint Barthélemy' },
+ { code: 'SH', name: 'Saint Helena' },
+ { code: 'KN', name: 'Saint Kitts and Nevis' },
+ { code: 'LC', name: 'Saint Lucia' },
+ { code: 'MF', name: 'Saint Martin' },
+ { code: 'PM', name: 'Saint Pierre and Miquelon' },
+ { code: 'VC', name: 'Saint Vincent and the Grenadines' },
+ { code: 'WS', name: 'Samoa' },
+ { code: 'SM', name: 'San Marino' },
+ { code: 'ST', name: 'São Tomé and PrÃncipe' },
+ { code: 'SA', name: 'Saudi Arabia' },
+ { code: 'SN', name: 'Senegal' },
+ { code: 'CS', name: 'Serbia and Montenegro' },
+ { code: 'RS', name: 'Serbia' },
+ { code: 'SC', name: 'Seychelles' },
+ { code: 'SL', name: 'Sierra Leone' },
+ { code: 'SG', name: 'Singapore' },
+ { code: 'SK', name: 'Slovakia' },
+ { code: 'SI', name: 'Slovenia' },
+ { code: 'SB', name: 'Solomon Islands' },
+ { code: 'SO', name: 'Somalia' },
+ { code: 'ZA', name: 'South Africa' },
+ { code: 'GS', name: 'South Georgia and the South Sandwich Islands' },
+ { code: 'KR', name: 'South Korea' },
+ { code: 'ES', name: 'Spain' },
+ { code: 'LK', name: 'Sri Lanka' },
+ { code: 'SD', name: 'Sudan' },
+ { code: 'SR', name: 'Suriname' },
+ { code: 'SJ', name: 'Svalbard and Jan Mayen' },
+ { code: 'SZ', name: 'Swaziland' },
+ { code: 'SE', name: 'Sweden' },
+ { code: 'CH', name: 'Switzerland' },
+ { code: 'SY', name: 'Syria' },
+ { code: 'TW', name: 'Taiwan' },
+ { code: 'TJ', name: 'Tajikistan' },
+ { code: 'TZ', name: 'Tanzania' },
+ { code: 'TH', name: 'Thailand' },
+ { code: 'TL', name: 'Timor-Leste' },
+ { code: 'TG', name: 'Togo' },
+ { code: 'TK', name: 'Tokelau' },
+ { code: 'TO', name: 'Tonga' },
+ { code: 'TT', name: 'Trinidad and Tobago' },
+ { code: 'TA', name: 'Tristan da Cunha' },
+ { code: 'TN', name: 'Tunisia' },
+ { code: 'TR', name: 'Turkey' },
+ { code: 'TM', name: 'Turkmenistan' },
+ { code: 'TC', name: 'Turks and Caicos Islands' },
+ { code: 'TV', name: 'Tuvalu' },
+ { code: 'UM', name: 'U.S. Minor Outlying Islands' },
+ { code: 'PU', name: 'U.S. Miscellaneous Pacific Islands' },
+ { code: 'VI', name: 'U.S. Virgin Islands' },
+ { code: 'UG', name: 'Uganda' },
+ { code: 'UA', name: 'Ukraine' },
+ { code: 'AE', name: 'United Arab Emirates' },
+ { code: 'GB', name: 'United Kingdom' },
+ { code: 'US', name: 'United States' },
+ { code: 'UY', name: 'Uruguay' },
+ { code: 'UZ', name: 'Uzbekistan' },
+ { code: 'VU', name: 'Vanuatu' },
+ { code: 'VA', name: 'Vatican City' },
+ { code: 'VE', name: 'Venezuela' },
+ { code: 'VN', name: 'Vietnam' },
+ { code: 'WK', name: 'Wake Island' },
+ { code: 'WF', name: 'Wallis and Futuna' },
+ { code: 'EH', name: 'Western Sahara' },
+ { code: 'YE', name: 'Yemen' },
+ { code: 'ZM', name: 'Zambia' },
+ { code: 'ZW', name: 'Zimbabwe' }
+ ]
}
-
- // list taken from Recurly (see https://docs.recurly.com/docs/countries-provinces-and-states). Country code must exist on Recurly, so update with care
- $scope.countries = [
- { code: 'AF', name: 'Afghanistan' },
- { code: 'AX', name: 'Ã…land Islands' },
- { code: 'AL', name: 'Albania' },
- { code: 'DZ', name: 'Algeria' },
- { code: 'AS', name: 'American Samoa' },
- { code: 'AD', name: 'Andorra' },
- { code: 'AO', name: 'Angola' },
- { code: 'AI', name: 'Anguilla' },
- { code: 'AQ', name: 'Antarctica' },
- { code: 'AG', name: 'Antigua and Barbuda' },
- { code: 'AR', name: 'Argentina' },
- { code: 'AM', name: 'Armenia' },
- { code: 'AW', name: 'Aruba' },
- { code: 'AC', name: 'Ascension Island' },
- { code: 'AU', name: 'Australia' },
- { code: 'AT', name: 'Austria' },
- { code: 'AZ', name: 'Azerbaijan' },
- { code: 'BS', name: 'Bahamas' },
- { code: 'BH', name: 'Bahrain' },
- { code: 'BD', name: 'Bangladesh' },
- { code: 'BB', name: 'Barbados' },
- { code: 'BY', name: 'Belarus' },
- { code: 'BE', name: 'Belgium' },
- { code: 'BZ', name: 'Belize' },
- { code: 'BJ', name: 'Benin' },
- { code: 'BM', name: 'Bermuda' },
- { code: 'BT', name: 'Bhutan' },
- { code: 'BO', name: 'Bolivia' },
- { code: 'BA', name: 'Bosnia and Herzegovina' },
- { code: 'BW', name: 'Botswana' },
- { code: 'BV', name: 'Bouvet Island' },
- { code: 'BR', name: 'Brazil' },
- { code: 'BQ', name: 'British Antarctic Territory' },
- { code: 'IO', name: 'British Indian Ocean Territory' },
- { code: 'VG', name: 'British Virgin Islands' },
- { code: 'BN', name: 'Brunei' },
- { code: 'BG', name: 'Bulgaria' },
- { code: 'BF', name: 'Burkina Faso' },
- { code: 'BI', name: 'Burundi' },
- { code: 'CV', name: 'Cabo Verde' },
- { code: 'KH', name: 'Cambodia' },
- { code: 'CM', name: 'Cameroon' },
- { code: 'CA', name: 'Canada' },
- { code: 'IC', name: 'Canary Islands' },
- { code: 'CT', name: 'Canton and Enderbury Islands' },
- { code: 'KY', name: 'Cayman Islands' },
- { code: 'CF', name: 'Central African Republic' },
- { code: 'EA', name: 'Ceuta and Melilla' },
- { code: 'TD', name: 'Chad' },
- { code: 'CL', name: 'Chile' },
- { code: 'CN', name: 'China' },
- { code: 'CX', name: 'Christmas Island' },
- { code: 'CP', name: 'Clipperton Island' },
- { code: 'CC', name: 'Cocos [Keeling] Islands' },
- { code: 'CO', name: 'Colombia' },
- { code: 'KM', name: 'Comoros' },
- { code: 'CG', name: 'Congo - Brazzaville' },
- { code: 'CD', name: 'Congo - Kinshasa' },
- { code: 'CD', name: 'Congo [DRC]' },
- { code: 'CG', name: 'Congo [Republic]' },
- { code: 'CK', name: 'Cook Islands' },
- { code: 'CR', name: 'Costa Rica' },
- { code: 'CI', name: 'Côte d’Ivoire' },
- { code: 'HR', name: 'Croatia' },
- { code: 'CU', name: 'Cuba' },
- { code: 'CY', name: 'Cyprus' },
- { code: 'CZ', name: 'Czech Republic' },
- { code: 'DK', name: 'Denmark' },
- { code: 'DG', name: 'Diego Garcia' },
- { code: 'DJ', name: 'Djibouti' },
- { code: 'DM', name: 'Dominica' },
- { code: 'DO', name: 'Dominican Republic' },
- { code: 'NQ', name: 'Dronning Maud Land' },
- { code: 'TL', name: 'East Timor' },
- { code: 'EC', name: 'Ecuador' },
- { code: 'EG', name: 'Egypt' },
- { code: 'SV', name: 'El Salvador' },
- { code: 'GQ', name: 'Equatorial Guinea' },
- { code: 'ER', name: 'Eritrea' },
- { code: 'EE', name: 'Estonia' },
- { code: 'ET', name: 'Ethiopia' },
- { code: 'FK', name: 'Falkland Islands [Islas Malvinas]' },
- { code: 'FK', name: 'Falkland Islands' },
- { code: 'FO', name: 'Faroe Islands' },
- { code: 'FJ', name: 'Fiji' },
- { code: 'FI', name: 'Finland' },
- { code: 'FR', name: 'France' },
- { code: 'GF', name: 'French Guiana' },
- { code: 'PF', name: 'French Polynesia' },
- { code: 'FQ', name: 'French Southern and Antarctic Territories' },
- { code: 'TF', name: 'French Southern Territories' },
- { code: 'GA', name: 'Gabon' },
- { code: 'GM', name: 'Gambia' },
- { code: 'GE', name: 'Georgia' },
- { code: 'DE', name: 'Germany' },
- { code: 'GH', name: 'Ghana' },
- { code: 'GI', name: 'Gibraltar' },
- { code: 'GR', name: 'Greece' },
- { code: 'GL', name: 'Greenland' },
- { code: 'GD', name: 'Grenada' },
- { code: 'GP', name: 'Guadeloupe' },
- { code: 'GU', name: 'Guam' },
- { code: 'GT', name: 'Guatemala' },
- { code: 'GG', name: 'Guernsey' },
- { code: 'GW', name: 'Guinea-Bissau' },
- { code: 'GN', name: 'Guinea' },
- { code: 'GY', name: 'Guyana' },
- { code: 'HT', name: 'Haiti' },
- { code: 'HM', name: 'Heard Island and McDonald Islands' },
- { code: 'HN', name: 'Honduras' },
- { code: 'HK', name: 'Hong Kong' },
- { code: 'HU', name: 'Hungary' },
- { code: 'IS', name: 'Iceland' },
- { code: 'IN', name: 'India' },
- { code: 'ID', name: 'Indonesia' },
- { code: 'IR', name: 'Iran' },
- { code: 'IQ', name: 'Iraq' },
- { code: 'IE', name: 'Ireland' },
- { code: 'IM', name: 'Isle of Man' },
- { code: 'IL', name: 'Israel' },
- { code: 'IT', name: 'Italy' },
- { code: 'CI', name: 'Ivory Coast' },
- { code: 'JM', name: 'Jamaica' },
- { code: 'JP', name: 'Japan' },
- { code: 'JE', name: 'Jersey' },
- { code: 'JT', name: 'Johnston Island' },
- { code: 'JO', name: 'Jordan' },
- { code: 'KZ', name: 'Kazakhstan' },
- { code: 'KE', name: 'Kenya' },
- { code: 'KI', name: 'Kiribati' },
- { code: 'KW', name: 'Kuwait' },
- { code: 'KG', name: 'Kyrgyzstan' },
- { code: 'LA', name: 'Laos' },
- { code: 'LV', name: 'Latvia' },
- { code: 'LB', name: 'Lebanon' },
- { code: 'LS', name: 'Lesotho' },
- { code: 'LR', name: 'Liberia' },
- { code: 'LY', name: 'Libya' },
- { code: 'LI', name: 'Liechtenstein' },
- { code: 'LT', name: 'Lithuania' },
- { code: 'LU', name: 'Luxembourg' },
- { code: 'MO', name: 'Macau SAR China' },
- { code: 'MO', name: 'Macau' },
- { code: 'MK', name: 'Macedonia [FYROM]' },
- { code: 'MK', name: 'Macedonia' },
- { code: 'MG', name: 'Madagascar' },
- { code: 'MW', name: 'Malawi' },
- { code: 'MY', name: 'Malaysia' },
- { code: 'MV', name: 'Maldives' },
- { code: 'ML', name: 'Mali' },
- { code: 'MT', name: 'Malta' },
- { code: 'MH', name: 'Marshall Islands' },
- { code: 'MQ', name: 'Martinique' },
- { code: 'MR', name: 'Mauritania' },
- { code: 'MU', name: 'Mauritius' },
- { code: 'YT', name: 'Mayotte' },
- { code: 'FX', name: 'Metropolitan France' },
- { code: 'MX', name: 'Mexico' },
- { code: 'FM', name: 'Micronesia' },
- { code: 'MI', name: 'Midway Islands' },
- { code: 'MD', name: 'Moldova' },
- { code: 'MC', name: 'Monaco' },
- { code: 'MN', name: 'Mongolia' },
- { code: 'ME', name: 'Montenegro' },
- { code: 'MS', name: 'Montserrat' },
- { code: 'MA', name: 'Morocco' },
- { code: 'MZ', name: 'Mozambique' },
- { code: 'MM', name: 'Myanmar [Burma]' },
- { code: 'NA', name: 'Namibia' },
- { code: 'NR', name: 'Nauru' },
- { code: 'NP', name: 'Nepal' },
- { code: 'AN', name: 'Netherlands Antilles' },
- { code: 'NL', name: 'Netherlands' },
- { code: 'NC', name: 'New Caledonia' },
- { code: 'NZ', name: 'New Zealand' },
- { code: 'NI', name: 'Nicaragua' },
- { code: 'NE', name: 'Niger' },
- { code: 'NG', name: 'Nigeria' },
- { code: 'NU', name: 'Niue' },
- { code: 'NF', name: 'Norfolk Island' },
- { code: 'KP', name: 'North Korea' },
- { code: 'VD', name: 'North Vietnam' },
- { code: 'MP', name: 'Northern Mariana Islands' },
- { code: 'NO', name: 'Norway' },
- { code: 'OM', name: 'Oman' },
- { code: 'QO', name: 'Outlying Oceania' },
- { code: 'PC', name: 'Pacific Islands Trust Territory' },
- { code: 'PK', name: 'Pakistan' },
- { code: 'PW', name: 'Palau' },
- { code: 'PS', name: 'Palestinian Territories' },
- { code: 'PZ', name: 'Panama Canal Zone' },
- { code: 'PA', name: 'Panama' },
- { code: 'PG', name: 'Papua New Guinea' },
- { code: 'PY', name: 'Paraguay' },
- { code: 'YD', name: "People's Democratic Republic of Yemen" },
- { code: 'PE', name: 'Peru' },
- { code: 'PH', name: 'Philippines' },
- { code: 'PN', name: 'Pitcairn Islands' },
- { code: 'PL', name: 'Poland' },
- { code: 'PT', name: 'Portugal' },
- { code: 'PR', name: 'Puerto Rico' },
- { code: 'QA', name: 'Qatar' },
- { code: 'RE', name: 'Réunion' },
- { code: 'RO', name: 'Romania' },
- { code: 'RU', name: 'Russia' },
- { code: 'RW', name: 'Rwanda' },
- { code: 'BL', name: 'Saint Barthélemy' },
- { code: 'SH', name: 'Saint Helena' },
- { code: 'KN', name: 'Saint Kitts and Nevis' },
- { code: 'LC', name: 'Saint Lucia' },
- { code: 'MF', name: 'Saint Martin' },
- { code: 'PM', name: 'Saint Pierre and Miquelon' },
- { code: 'VC', name: 'Saint Vincent and the Grenadines' },
- { code: 'WS', name: 'Samoa' },
- { code: 'SM', name: 'San Marino' },
- { code: 'ST', name: 'São Tomé and PrÃncipe' },
- { code: 'SA', name: 'Saudi Arabia' },
- { code: 'SN', name: 'Senegal' },
- { code: 'CS', name: 'Serbia and Montenegro' },
- { code: 'RS', name: 'Serbia' },
- { code: 'SC', name: 'Seychelles' },
- { code: 'SL', name: 'Sierra Leone' },
- { code: 'SG', name: 'Singapore' },
- { code: 'SK', name: 'Slovakia' },
- { code: 'SI', name: 'Slovenia' },
- { code: 'SB', name: 'Solomon Islands' },
- { code: 'SO', name: 'Somalia' },
- { code: 'ZA', name: 'South Africa' },
- { code: 'GS', name: 'South Georgia and the South Sandwich Islands' },
- { code: 'KR', name: 'South Korea' },
- { code: 'ES', name: 'Spain' },
- { code: 'LK', name: 'Sri Lanka' },
- { code: 'SD', name: 'Sudan' },
- { code: 'SR', name: 'Suriname' },
- { code: 'SJ', name: 'Svalbard and Jan Mayen' },
- { code: 'SZ', name: 'Swaziland' },
- { code: 'SE', name: 'Sweden' },
- { code: 'CH', name: 'Switzerland' },
- { code: 'SY', name: 'Syria' },
- { code: 'TW', name: 'Taiwan' },
- { code: 'TJ', name: 'Tajikistan' },
- { code: 'TZ', name: 'Tanzania' },
- { code: 'TH', name: 'Thailand' },
- { code: 'TL', name: 'Timor-Leste' },
- { code: 'TG', name: 'Togo' },
- { code: 'TK', name: 'Tokelau' },
- { code: 'TO', name: 'Tonga' },
- { code: 'TT', name: 'Trinidad and Tobago' },
- { code: 'TA', name: 'Tristan da Cunha' },
- { code: 'TN', name: 'Tunisia' },
- { code: 'TR', name: 'Turkey' },
- { code: 'TM', name: 'Turkmenistan' },
- { code: 'TC', name: 'Turks and Caicos Islands' },
- { code: 'TV', name: 'Tuvalu' },
- { code: 'UM', name: 'U.S. Minor Outlying Islands' },
- { code: 'PU', name: 'U.S. Miscellaneous Pacific Islands' },
- { code: 'VI', name: 'U.S. Virgin Islands' },
- { code: 'UG', name: 'Uganda' },
- { code: 'UA', name: 'Ukraine' },
- { code: 'AE', name: 'United Arab Emirates' },
- { code: 'GB', name: 'United Kingdom' },
- { code: 'US', name: 'United States' },
- { code: 'UY', name: 'Uruguay' },
- { code: 'UZ', name: 'Uzbekistan' },
- { code: 'VU', name: 'Vanuatu' },
- { code: 'VA', name: 'Vatican City' },
- { code: 'VE', name: 'Venezuela' },
- { code: 'VN', name: 'Vietnam' },
- { code: 'WK', name: 'Wake Island' },
- { code: 'WF', name: 'Wallis and Futuna' },
- { code: 'EH', name: 'Western Sahara' },
- { code: 'YE', name: 'Yemen' },
- { code: 'ZM', name: 'Zambia' },
- { code: 'ZW', name: 'Zimbabwe' }
- ]
-})
+)
diff --git a/services/web/frontend/js/main/oauth/controllers/UserOauthController.js b/services/web/frontend/js/main/oauth/controllers/UserOauthController.js
index 424143ce2f..f6fec29061 100644
--- a/services/web/frontend/js/main/oauth/controllers/UserOauthController.js
+++ b/services/web/frontend/js/main/oauth/controllers/UserOauthController.js
@@ -1,53 +1,52 @@
import App from '../../../base'
-export default App.controller('UserOauthController', function(
- $http,
- $scope,
- $q
-) {
- const _reset = function() {
- $scope.ui = {
- hasError: false,
- errorMessage: ''
- }
- $scope.providers = window.oauthProviders
- $scope.thirdPartyIds = window.thirdPartyIds
- }
- const _unlinkError = (providerId, err) => {
- $scope.providers[providerId].ui.hasError = true
- $scope.providers[providerId].ui.errorMessage =
- err && err.data && err.data.message ? err.data.message : 'error'
- }
-
- $scope.unlink = providerId => {
- if (window.ExposedSettings.isOverleaf) {
- // UI
- $scope.providers[providerId].ui = {
+export default App.controller(
+ 'UserOauthController',
+ function ($http, $scope, $q) {
+ const _reset = function () {
+ $scope.ui = {
hasError: false,
- isProcessing: true
+ errorMessage: ''
}
- // Data for update
- const data = {
- _csrf: window.csrfToken,
- link: false,
- providerId
- }
- $http
- .post('/user/oauth-unlink', data)
- .catch(error => {
- $scope.providers[providerId].ui.isProcessing = false
- _unlinkError(providerId, error)
- })
- .then(response => {
- $scope.providers[providerId].ui.isProcessing = false
- if (response.status === 200) {
- $scope.thirdPartyIds[providerId] = null
- } else {
- _unlinkError(providerId, response)
- }
- })
+ $scope.providers = window.oauthProviders
+ $scope.thirdPartyIds = window.thirdPartyIds
+ }
+ const _unlinkError = (providerId, err) => {
+ $scope.providers[providerId].ui.hasError = true
+ $scope.providers[providerId].ui.errorMessage =
+ err && err.data && err.data.message ? err.data.message : 'error'
}
- }
- _reset()
-})
+ $scope.unlink = providerId => {
+ if (window.ExposedSettings.isOverleaf) {
+ // UI
+ $scope.providers[providerId].ui = {
+ hasError: false,
+ isProcessing: true
+ }
+ // Data for update
+ const data = {
+ _csrf: window.csrfToken,
+ link: false,
+ providerId
+ }
+ $http
+ .post('/user/oauth-unlink', data)
+ .catch(error => {
+ $scope.providers[providerId].ui.isProcessing = false
+ _unlinkError(providerId, error)
+ })
+ .then(response => {
+ $scope.providers[providerId].ui.isProcessing = false
+ if (response.status === 200) {
+ $scope.thirdPartyIds[providerId] = null
+ } else {
+ _unlinkError(providerId, response)
+ }
+ })
+ }
+ }
+
+ _reset()
+ }
+)
diff --git a/services/web/frontend/js/main/plans.js b/services/web/frontend/js/main/plans.js
index 73c28e16e6..67b4d0b908 100644
--- a/services/web/frontend/js/main/plans.js
+++ b/services/web/frontend/js/main/plans.js
@@ -3,7 +3,7 @@
max-len
*/
import App from '../base'
-App.factory('MultiCurrencyPricing', function() {
+App.factory('MultiCurrencyPricing', function () {
const currencyCode = window.recomendedCurrency
return {
@@ -232,232 +232,233 @@ App.factory('MultiCurrencyPricing', function() {
}
})
-App.controller('PlansController', function(
- $scope,
- $modal,
- eventTracking,
- MultiCurrencyPricing,
- $http,
- $filter,
- $location
-) {
- let switchEvent
+App.controller(
+ 'PlansController',
+ function (
+ $scope,
+ $modal,
+ eventTracking,
+ MultiCurrencyPricing,
+ $http,
+ $filter,
+ $location
+ ) {
+ let switchEvent
- $scope.plans = MultiCurrencyPricing.plans
+ $scope.plans = MultiCurrencyPricing.plans
- $scope.currencyCode = MultiCurrencyPricing.currencyCode
+ $scope.currencyCode = MultiCurrencyPricing.currencyCode
- $scope.trial_len = 7
+ $scope.trial_len = 7
- $scope.planQueryString = '_free_trial_7_days'
+ $scope.planQueryString = '_free_trial_7_days'
- $scope.ui = { view: 'monthly' }
+ $scope.ui = { view: 'monthly' }
- $scope.changeCurreny = function(e, newCurrency) {
- e.preventDefault()
- $scope.currencyCode = newCurrency
- }
-
- // because ternary logic in angular bindings is hard
- $scope.getCollaboratorPlanCode = function() {
- const { view } = $scope.ui
- if (view === 'annual') {
- return 'collaborator-annual'
- } else {
- return `collaborator${$scope.planQueryString}`
+ $scope.changeCurreny = function (e, newCurrency) {
+ e.preventDefault()
+ $scope.currencyCode = newCurrency
}
- }
- $scope.getPersonalPlanCode = function() {
- const { view } = $scope.ui
- if (view === 'annual') {
- return 'paid-personal-annual'
- } else {
- return `paid-personal${$scope.planQueryString}`
+ // because ternary logic in angular bindings is hard
+ $scope.getCollaboratorPlanCode = function () {
+ const { view } = $scope.ui
+ if (view === 'annual') {
+ return 'collaborator-annual'
+ } else {
+ return `collaborator${$scope.planQueryString}`
+ }
}
- }
- $scope.signUpNowClicked = function(plan, location) {
- if ($scope.ui.view === 'annual') {
- plan = `${plan}_annual`
+ $scope.getPersonalPlanCode = function () {
+ const { view } = $scope.ui
+ if (view === 'annual') {
+ return 'paid-personal-annual'
+ } else {
+ return `paid-personal${$scope.planQueryString}`
+ }
}
- plan = eventLabel(plan, location)
- eventTracking.sendMB('plans-page-start-trial')
- eventTracking.send('subscription-funnel', 'sign_up_now_button', plan)
- }
- $scope.switchToMonthly = function(e, location) {
- const uiView = 'monthly'
- switchEvent(e, uiView + '-prices', location)
- $scope.ui.view = uiView
- }
+ $scope.signUpNowClicked = function (plan, location) {
+ if ($scope.ui.view === 'annual') {
+ plan = `${plan}_annual`
+ }
+ plan = eventLabel(plan, location)
+ eventTracking.sendMB('plans-page-start-trial')
+ eventTracking.send('subscription-funnel', 'sign_up_now_button', plan)
+ }
- $scope.switchToStudent = function(e, location) {
- const uiView = 'student'
- switchEvent(e, uiView + '-prices', location)
- $scope.ui.view = uiView
- }
+ $scope.switchToMonthly = function (e, location) {
+ const uiView = 'monthly'
+ switchEvent(e, uiView + '-prices', location)
+ $scope.ui.view = uiView
+ }
- $scope.switchToAnnual = function(e, location) {
- const uiView = 'annual'
- switchEvent(e, uiView + '-prices', location)
- $scope.ui.view = uiView
- }
+ $scope.switchToStudent = function (e, location) {
+ const uiView = 'student'
+ switchEvent(e, uiView + '-prices', location)
+ $scope.ui.view = uiView
+ }
- $scope.openGroupPlanModal = function() {
- const path = `${window.location.pathname}${window.location.search}`
- history.replaceState(null, document.title, path + '#groups')
- $modal
- .open({
- templateUrl: 'groupPlanModalPurchaseTemplate',
- controller: 'GroupPlansModalPurchaseController'
- })
- .result.finally(() =>
- history.replaceState(null, document.title, window.location.pathname)
+ $scope.switchToAnnual = function (e, location) {
+ const uiView = 'annual'
+ switchEvent(e, uiView + '-prices', location)
+ $scope.ui.view = uiView
+ }
+
+ $scope.openGroupPlanModal = function () {
+ const path = `${window.location.pathname}${window.location.search}`
+ history.replaceState(null, document.title, path + '#groups')
+ $modal
+ .open({
+ templateUrl: 'groupPlanModalPurchaseTemplate',
+ controller: 'GroupPlansModalPurchaseController'
+ })
+ .result.finally(() =>
+ history.replaceState(null, document.title, window.location.pathname)
+ )
+ eventTracking.send(
+ 'subscription-funnel',
+ 'plans-page',
+ 'group-inquiry-potential'
)
- eventTracking.send(
- 'subscription-funnel',
- 'plans-page',
- 'group-inquiry-potential'
- )
+ }
+
+ if ($location.hash() === 'groups') {
+ $scope.openGroupPlanModal()
+ }
+
+ var eventLabel = (label, location) => label
+
+ switchEvent = function (e, label, location) {
+ e.preventDefault()
+ const gaLabel = eventLabel(label, location)
+ eventTracking.send('subscription-funnel', 'plans-page', gaLabel)
+ }
}
+)
- if ($location.hash() === 'groups') {
- $scope.openGroupPlanModal()
- }
-
- var eventLabel = (label, location) => label
-
- switchEvent = function(e, label, location) {
- e.preventDefault()
- const gaLabel = eventLabel(label, location)
- eventTracking.send('subscription-funnel', 'plans-page', gaLabel)
- }
-})
-
-App.controller('GroupPlansModalPurchaseController', function(
- $scope,
- $modal,
- $location,
- $httpParamSerializer
-) {
- $scope.options = {
- plan_codes: [
- {
- display: 'Collaborator',
- code: 'collaborator'
- },
- {
- display: 'Professional',
- code: 'professional'
- }
- ],
- currencies: [
- {
- display: 'USD ($)',
- code: 'USD'
- },
- {
- display: 'GBP (£)',
- code: 'GBP'
- },
- {
- display: 'EUR (€)',
- code: 'EUR'
- }
- ],
- currencySymbols: {
- USD: '$',
- EUR: '€',
- GBP: '£'
- },
- sizes: [2, 3, 4, 5, 10, 20, 50],
- usages: [
- {
- display: 'Enterprise',
- code: 'enterprise'
- },
- {
- display: 'Educational',
- code: 'educational'
- }
- ]
- }
-
- $scope.prices = window.groupPlans
-
- let currency = 'USD'
- if (['USD', 'GBP', 'EUR'].includes(window.recomendedCurrency)) {
- currency = window.recomendedCurrency
- }
-
- // default selected
- $scope.selected = {
- plan_code: 'collaborator',
- currency,
- size: '10',
- usage: 'educational'
- }
- // selected via query
- if ($location.search()) {
- // usage
- if ($location.search().usage) {
- $scope.options.usages.forEach(usage => {
- if (usage.code === $location.search().usage) {
- $scope.selected.usage = usage.code
+App.controller(
+ 'GroupPlansModalPurchaseController',
+ function ($scope, $modal, $location, $httpParamSerializer) {
+ $scope.options = {
+ plan_codes: [
+ {
+ display: 'Collaborator',
+ code: 'collaborator'
+ },
+ {
+ display: 'Professional',
+ code: 'professional'
}
- })
- }
- // plan
- if ($location.search().plan) {
- $scope.options.plan_codes.forEach(plan => {
- if (plan.code === $location.search().plan) {
- $scope.selected.plan_code = plan.code
+ ],
+ currencies: [
+ {
+ display: 'USD ($)',
+ code: 'USD'
+ },
+ {
+ display: 'GBP (£)',
+ code: 'GBP'
+ },
+ {
+ display: 'EUR (€)',
+ code: 'EUR'
}
- })
- }
- // number
- if ($location.search().number) {
- // $location.search().number is a string,
- // but $scope.options.sizes are numbers
- // and $scope.selected.size is a string
- const groupCount = parseInt($location.search().number, 10)
- if ($scope.options.sizes.indexOf(groupCount) !== -1) {
- $scope.selected.size = $location.search().number
- }
- }
- // currency
- if ($location.search().currency) {
- $scope.options.currencies.forEach(currency => {
- if (currency.code === $location.search().currency) {
- $scope.selected.currency = currency.code
+ ],
+ currencySymbols: {
+ USD: '$',
+ EUR: '€',
+ GBP: '£'
+ },
+ sizes: [2, 3, 4, 5, 10, 20, 50],
+ usages: [
+ {
+ display: 'Enterprise',
+ code: 'enterprise'
+ },
+ {
+ display: 'Educational',
+ code: 'educational'
}
- })
+ ]
}
- }
- $scope.recalculatePrice = function() {
- let { usage, plan_code, currency, size } = $scope.selected
- const price = $scope.prices[usage][plan_code][currency][size]
- const currencySymbol = $scope.options.currencySymbols[currency]
- $scope.displayPrice = `${currencySymbol}${price}`
- }
+ $scope.prices = window.groupPlans
- $scope.$watch('selected', $scope.recalculatePrice, true)
- $scope.recalculatePrice()
+ let currency = 'USD'
+ if (['USD', 'GBP', 'EUR'].includes(window.recomendedCurrency)) {
+ currency = window.recomendedCurrency
+ }
- $scope.purchase = function() {
- const { plan_code, size, usage, currency } = $scope.selected
- const queryParams = {
- planCode: `group_${plan_code}_${size}_${usage}`,
+ // default selected
+ $scope.selected = {
+ plan_code: 'collaborator',
currency,
- itm_campaign: 'groups'
+ size: '10',
+ usage: 'educational'
}
- if ($location.search().itm_content) {
- queryParams.itm_content = $location.search().itm_content
+ // selected via query
+ if ($location.search()) {
+ // usage
+ if ($location.search().usage) {
+ $scope.options.usages.forEach(usage => {
+ if (usage.code === $location.search().usage) {
+ $scope.selected.usage = usage.code
+ }
+ })
+ }
+ // plan
+ if ($location.search().plan) {
+ $scope.options.plan_codes.forEach(plan => {
+ if (plan.code === $location.search().plan) {
+ $scope.selected.plan_code = plan.code
+ }
+ })
+ }
+ // number
+ if ($location.search().number) {
+ // $location.search().number is a string,
+ // but $scope.options.sizes are numbers
+ // and $scope.selected.size is a string
+ const groupCount = parseInt($location.search().number, 10)
+ if ($scope.options.sizes.indexOf(groupCount) !== -1) {
+ $scope.selected.size = $location.search().number
+ }
+ }
+ // currency
+ if ($location.search().currency) {
+ $scope.options.currencies.forEach(currency => {
+ if (currency.code === $location.search().currency) {
+ $scope.selected.currency = currency.code
+ }
+ })
+ }
+ }
+
+ $scope.recalculatePrice = function () {
+ let { usage, plan_code, currency, size } = $scope.selected
+ const price = $scope.prices[usage][plan_code][currency][size]
+ const currencySymbol = $scope.options.currencySymbols[currency]
+ $scope.displayPrice = `${currencySymbol}${price}`
+ }
+
+ $scope.$watch('selected', $scope.recalculatePrice, true)
+ $scope.recalculatePrice()
+
+ $scope.purchase = function () {
+ const { plan_code, size, usage, currency } = $scope.selected
+ const queryParams = {
+ planCode: `group_${plan_code}_${size}_${usage}`,
+ currency,
+ itm_campaign: 'groups'
+ }
+ if ($location.search().itm_content) {
+ queryParams.itm_content = $location.search().itm_content
+ }
+ window.location = `/user/subscription/new?${$httpParamSerializer(
+ queryParams
+ )}`
}
- window.location = `/user/subscription/new?${$httpParamSerializer(
- queryParams
- )}`
}
-})
+)
diff --git a/services/web/frontend/js/main/post-gateway.js b/services/web/frontend/js/main/post-gateway.js
index 95cd277110..370be46b3a 100644
--- a/services/web/frontend/js/main/post-gateway.js
+++ b/services/web/frontend/js/main/post-gateway.js
@@ -1,7 +1,7 @@
import App from '../base'
-export default App.controller('PostGatewayController', function($scope) {
- $scope.handleGateway = function() {
+export default App.controller('PostGatewayController', function ($scope) {
+ $scope.handleGateway = function () {
const { params } = JSON.parse($('#gateway-data').text())
params.viaGateway = 'true'
Object.keys(params).forEach(param => {
diff --git a/services/web/frontend/js/main/project-list/left-hand-menu-promo-controller.js b/services/web/frontend/js/main/project-list/left-hand-menu-promo-controller.js
index 513c7faed3..6f0c92eab4 100644
--- a/services/web/frontend/js/main/project-list/left-hand-menu-promo-controller.js
+++ b/services/web/frontend/js/main/project-list/left-hand-menu-promo-controller.js
@@ -1,27 +1,26 @@
import App from '../../base'
-export default App.controller('LeftHandMenuPromoController', function(
- $scope,
- UserAffiliationsDataService,
- eventTracking
-) {
- $scope.hasProjects = window.data.projects.length > 0
- $scope.userHasNoSubscription = window.userHasNoSubscription
+export default App.controller(
+ 'LeftHandMenuPromoController',
+ function ($scope, UserAffiliationsDataService, eventTracking) {
+ $scope.hasProjects = window.data.projects.length > 0
+ $scope.userHasNoSubscription = window.userHasNoSubscription
- $scope.upgradeSubscription = function() {
- eventTracking.send('subscription-funnel', 'project-page', 'upgrade')
+ $scope.upgradeSubscription = function () {
+ eventTracking.send('subscription-funnel', 'project-page', 'upgrade')
+ }
+
+ $scope.share = function () {
+ eventTracking.send('subscription-funnel', 'project-page', 'sharing')
+ }
+
+ const _userHasNoAffiliation = function () {
+ $scope.withAffiliations = window.data.userAffiliations.length > 0
+ $scope.userOnPayingUniversity = window.data.userAffiliations.some(
+ affiliation => affiliation.licence && affiliation.licence !== 'free'
+ )
+ }
+
+ _userHasNoAffiliation()
}
-
- $scope.share = function() {
- eventTracking.send('subscription-funnel', 'project-page', 'sharing')
- }
-
- const _userHasNoAffiliation = function() {
- $scope.withAffiliations = window.data.userAffiliations.length > 0
- $scope.userOnPayingUniversity = window.data.userAffiliations.some(
- affiliation => affiliation.licence && affiliation.licence !== 'free'
- )
- }
-
- _userHasNoAffiliation()
-})
+)
diff --git a/services/web/frontend/js/main/project-list/modal-controllers.js b/services/web/frontend/js/main/project-list/modal-controllers.js
index 8844f28f32..bbb25a5801 100644
--- a/services/web/frontend/js/main/project-list/modal-controllers.js
+++ b/services/web/frontend/js/main/project-list/modal-controllers.js
@@ -12,173 +12,160 @@
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../base'
-App.controller('RenameProjectModalController', function(
- $scope,
- $modalInstance,
- $timeout,
- project,
- queuedHttp
-) {
- $scope.inputs = { projectName: project.name }
+App.controller(
+ 'RenameProjectModalController',
+ function ($scope, $modalInstance, $timeout, project, queuedHttp) {
+ $scope.inputs = { projectName: project.name }
- $scope.state = {
- inflight: false,
- error: false
- }
-
- $modalInstance.opened.then(() =>
- $timeout(() => $scope.$broadcast('open'), 200)
- )
-
- $scope.rename = function() {
- $scope.state.inflight = true
- $scope.state.error = false
- return $scope
- .renameProject(project, $scope.inputs.projectName)
- .then(function() {
- $scope.state.inflight = false
- $scope.state.error = false
- return $modalInstance.close()
- })
- .catch(function(response) {
- const { data, status } = response
- $scope.state.inflight = false
- if (status === 400) {
- return ($scope.state.error = { message: data })
- } else {
- return ($scope.state.error = true)
- }
- })
- }
-
- return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
-})
-
-App.controller('CloneProjectModalController', function(
- $scope,
- $modalInstance,
- $timeout,
- project
-) {
- $scope.inputs = { projectName: project.name + ' (Copy)' }
- $scope.state = {
- inflight: false,
- error: false
- }
-
- $modalInstance.opened.then(() =>
- $timeout(() => $scope.$broadcast('open'), 200)
- )
-
- $scope.clone = function() {
- $scope.state.inflight = true
- return $scope
- .cloneProject(project, $scope.inputs.projectName)
- .then(function() {
- $scope.state.inflight = false
- $scope.state.error = false
- return $modalInstance.close()
- })
- .catch(function(response) {
- const { data, status } = response
- $scope.state.inflight = false
- if (status === 400) {
- return ($scope.state.error = { message: data })
- } else {
- return ($scope.state.error = true)
- }
- })
- }
-
- return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
-})
-
-App.controller('NewProjectModalController', function(
- $scope,
- $modalInstance,
- $timeout,
- template
-) {
- $scope.inputs = { projectName: '' }
- $scope.state = {
- inflight: false,
- error: false
- }
-
- $modalInstance.opened.then(() =>
- $timeout(() => $scope.$broadcast('open'), 200)
- )
-
- $scope.create = function() {
- $scope.state.inflight = true
- $scope.state.error = false
- return $scope
- .createProject($scope.inputs.projectName, template)
- .then(function(response) {
- const { data } = response
- $scope.state.inflight = false
- $scope.state.error = false
- return $modalInstance.close(data.project_id)
- })
- .catch(function(response) {
- const { data, status } = response
- $scope.state.inflight = false
- if (status === 400) {
- return ($scope.state.error = { message: data })
- } else {
- return ($scope.state.error = true)
- }
- })
- }
-
- return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
-})
-
-App.controller('ArchiveTrashLeaveOrDeleteProjectsModalController', function(
- $scope,
- $modalInstance,
- $timeout,
- projects,
- action
-) {
- $scope.projects = projects
-
- $scope.action = action
-
- $scope.confirm = () => $modalInstance.close({ projects, action })
-
- $scope.cancel = () => $modalInstance.dismiss('cancel')
-})
-
-App.controller('UploadProjectModalController', function(
- $scope,
- $modalInstance,
- $timeout
-) {
- $scope.cancel = () => $modalInstance.dismiss('cancel')
-
- return ($scope.onComplete = function(error, name, response) {
- if (response.project_id != null) {
- return (window.location = `/project/${response.project_id}`)
+ $scope.state = {
+ inflight: false,
+ error: false
}
- })
-})
-App.controller('V1ImportModalController', function(
- $scope,
- $modalInstance,
- project
-) {
- $scope.project = project
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
- return ($scope.dismiss = () => $modalInstance.dismiss('cancel'))
-})
+ $scope.rename = function () {
+ $scope.state.inflight = true
+ $scope.state.error = false
+ return $scope
+ .renameProject(project, $scope.inputs.projectName)
+ .then(function () {
+ $scope.state.inflight = false
+ $scope.state.error = false
+ return $modalInstance.close()
+ })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.state.inflight = false
+ if (status === 400) {
+ return ($scope.state.error = { message: data })
+ } else {
+ return ($scope.state.error = true)
+ }
+ })
+ }
-export default App.controller('ShowErrorModalController', function(
- $scope,
- $modalInstance,
- error
-) {
- $scope.error = error
- return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
-})
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller(
+ 'CloneProjectModalController',
+ function ($scope, $modalInstance, $timeout, project) {
+ $scope.inputs = { projectName: project.name + ' (Copy)' }
+ $scope.state = {
+ inflight: false,
+ error: false
+ }
+
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
+
+ $scope.clone = function () {
+ $scope.state.inflight = true
+ return $scope
+ .cloneProject(project, $scope.inputs.projectName)
+ .then(function () {
+ $scope.state.inflight = false
+ $scope.state.error = false
+ return $modalInstance.close()
+ })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.state.inflight = false
+ if (status === 400) {
+ return ($scope.state.error = { message: data })
+ } else {
+ return ($scope.state.error = true)
+ }
+ })
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller(
+ 'NewProjectModalController',
+ function ($scope, $modalInstance, $timeout, template) {
+ $scope.inputs = { projectName: '' }
+ $scope.state = {
+ inflight: false,
+ error: false
+ }
+
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
+
+ $scope.create = function () {
+ $scope.state.inflight = true
+ $scope.state.error = false
+ return $scope
+ .createProject($scope.inputs.projectName, template)
+ .then(function (response) {
+ const { data } = response
+ $scope.state.inflight = false
+ $scope.state.error = false
+ return $modalInstance.close(data.project_id)
+ })
+ .catch(function (response) {
+ const { data, status } = response
+ $scope.state.inflight = false
+ if (status === 400) {
+ return ($scope.state.error = { message: data })
+ } else {
+ return ($scope.state.error = true)
+ }
+ })
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller(
+ 'ArchiveTrashLeaveOrDeleteProjectsModalController',
+ function ($scope, $modalInstance, $timeout, projects, action) {
+ $scope.projects = projects
+
+ $scope.action = action
+
+ $scope.confirm = () => $modalInstance.close({ projects, action })
+
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
+ }
+)
+
+App.controller(
+ 'UploadProjectModalController',
+ function ($scope, $modalInstance, $timeout) {
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
+
+ return ($scope.onComplete = function (error, name, response) {
+ if (response.project_id != null) {
+ return (window.location = `/project/${response.project_id}`)
+ }
+ })
+ }
+)
+
+App.controller(
+ 'V1ImportModalController',
+ function ($scope, $modalInstance, project) {
+ $scope.project = project
+
+ return ($scope.dismiss = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+export default App.controller(
+ 'ShowErrorModalController',
+ function ($scope, $modalInstance, error) {
+ $scope.error = error
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
diff --git a/services/web/frontend/js/main/project-list/notifications-controller.js b/services/web/frontend/js/main/project-list/notifications-controller.js
index 2969a3e3fd..079a6978ff 100644
--- a/services/web/frontend/js/main/project-list/notifications-controller.js
+++ b/services/web/frontend/js/main/project-list/notifications-controller.js
@@ -1,7 +1,7 @@
import App from '../../base'
const ExposedSettings = window.ExposedSettings
-App.controller('NotificationsController', function($scope, $http) {
+App.controller('NotificationsController', function ($scope, $http) {
for (let notification of $scope.notifications || []) {
notification.hide = false
}
@@ -23,25 +23,25 @@ App.controller('NotificationsController', function($scope, $http) {
}
})
-App.controller('DismissableNotificationsController', function(
- $scope,
- localStorage
-) {
- $scope.shouldShowNotification =
- localStorage('dismissed-covid-19-notification-extended') !== true
+App.controller(
+ 'DismissableNotificationsController',
+ function ($scope, localStorage) {
+ $scope.shouldShowNotification =
+ localStorage('dismissed-covid-19-notification-extended') !== true
- $scope.dismiss = () => {
- localStorage('dismissed-covid-19-notification-extended', true)
- $scope.shouldShowNotification = false
+ $scope.dismiss = () => {
+ localStorage('dismissed-covid-19-notification-extended', true)
+ $scope.shouldShowNotification = false
+ }
}
-})
+)
-App.controller('ProjectInviteNotificationController', function($scope, $http) {
+App.controller('ProjectInviteNotificationController', function ($scope, $http) {
// Shortcuts for translation keys
$scope.projectName = $scope.notification.messageOpts.projectName
$scope.userName = $scope.notification.messageOpts.userName
- $scope.accept = function() {
+ $scope.accept = function () {
$scope.notification.inflight = true
return $http({
url: `/project/${$scope.notification.messageOpts.projectId}/invite/token/${$scope.notification.messageOpts.token}/accept`,
@@ -69,55 +69,57 @@ App.controller('ProjectInviteNotificationController', function($scope, $http) {
}
})
-App.controller('EmailNotificationController', function(
- $scope,
- $http,
- UserAffiliationsDataService
-) {
- $scope.userEmails = window.data.userEmails
- const _ssoAvailable = email => {
- if (!ExposedSettings.hasSamlFeature) return false
- if (email.samlProviderId) return true
- if (!email.affiliation || !email.affiliation.institution) return false
- if (email.affiliation.institution.ssoEnabled) return true
- if (ExposedSettings.hasSamlBeta && email.affiliation.institution.ssoBeta) {
- return true
- }
- return false
- }
- $scope.showConfirmEmail = email => {
- if (ExposedSettings.emailConfirmationDisabled) {
+App.controller(
+ 'EmailNotificationController',
+ function ($scope, $http, UserAffiliationsDataService) {
+ $scope.userEmails = window.data.userEmails
+ const _ssoAvailable = email => {
+ if (!ExposedSettings.hasSamlFeature) return false
+ if (email.samlProviderId) return true
+ if (!email.affiliation || !email.affiliation.institution) return false
+ if (email.affiliation.institution.ssoEnabled) return true
+ if (
+ ExposedSettings.hasSamlBeta &&
+ email.affiliation.institution.ssoBeta
+ ) {
+ return true
+ }
return false
}
- if (!email.confirmedAt && !email.hide) {
- if (_ssoAvailable(email)) {
+ $scope.showConfirmEmail = email => {
+ if (ExposedSettings.emailConfirmationDisabled) {
return false
}
- return true
+ if (!email.confirmedAt && !email.hide) {
+ if (_ssoAvailable(email)) {
+ return false
+ }
+ return true
+ }
+ return false
+ }
+ for (let userEmail of $scope.userEmails) {
+ userEmail.hide = false
}
- return false
- }
- for (let userEmail of $scope.userEmails) {
- userEmail.hide = false
- }
- $scope.resendConfirmationEmail = function(userEmail) {
- userEmail.confirmationInflight = true
- userEmail.error = false
- userEmail.errorMessage = null
- UserAffiliationsDataService.resendConfirmationEmail(userEmail.email)
- .then(() => {
- userEmail.hide = true
- $scope.$emit('project-list:notifications-received')
- })
- .catch(error => {
- userEmail.error = true
- userEmail.errorMessage = error.data.message
- console.error(error)
- $scope.$emit('project-list:notifications-received')
- })
- .finally(() => {
- userEmail.confirmationInflight = false
- })
+ $scope.resendConfirmationEmail = function (userEmail) {
+ userEmail.confirmationInflight = true
+ userEmail.error = false
+ userEmail.errorMessage = null
+ UserAffiliationsDataService.resendConfirmationEmail(userEmail.email)
+ .then(() => {
+ userEmail.hide = true
+ $scope.$emit('project-list:notifications-received')
+ })
+ .catch(error => {
+ userEmail.error = true
+ userEmail.errorMessage = error.data.message
+ console.error(error)
+ $scope.$emit('project-list:notifications-received')
+ })
+ .finally(() => {
+ userEmail.confirmationInflight = false
+ })
+ }
}
-})
+)
diff --git a/services/web/frontend/js/main/project-list/project-list.js b/services/web/frontend/js/main/project-list/project-list.js
index 236eec1d87..f2b48a1cdd 100644
--- a/services/web/frontend/js/main/project-list/project-list.js
+++ b/services/web/frontend/js/main/project-list/project-list.js
@@ -1,7 +1,7 @@
import _ from 'lodash'
import App from '../../base'
import './services/project-list'
-App.controller('ProjectPageController', function(
+App.controller('ProjectPageController', function (
$scope,
$modal,
$window,
@@ -22,7 +22,7 @@ App.controller('ProjectPageController', function(
$scope.nUntagged = 0
$scope.reverse = true
$scope.searchText = { value: '' }
- $scope.$watch('predicate', function(newValue) {
+ $scope.$watch('predicate', function (newValue) {
$scope.comparator =
newValue === 'ownerName' ? ownerNameComparator : defaultComparator
})
@@ -40,7 +40,7 @@ App.controller('ProjectPageController', function(
newVal => ($scope.nUntagged = newVal)
)
- var recalculateProjectListHeight = function() {
+ var recalculateProjectListHeight = function () {
const $projListCard = $('.project-list-card')
if (!$projListCard || !$projListCard.offset()) return
@@ -112,7 +112,7 @@ App.controller('ProjectPageController', function(
}
}
- angular.element($window).bind('resize', function() {
+ angular.element($window).bind('resize', function () {
recalculateProjectListHeight()
$scope.$apply()
})
@@ -141,14 +141,14 @@ App.controller('ProjectPageController', function(
}
}
- $scope.changePredicate = function(newPredicate) {
+ $scope.changePredicate = function (newPredicate) {
if ($scope.predicate === newPredicate) {
$scope.reverse = !$scope.reverse
}
$scope.predicate = newPredicate
}
- $scope.getSortIconClass = function(column) {
+ $scope.getSortIconClass = function (column) {
if (column === $scope.predicate && $scope.reverse) {
return 'fa-caret-down'
} else if (column === $scope.predicate && !$scope.reverse) {
@@ -158,7 +158,7 @@ App.controller('ProjectPageController', function(
}
}
- $scope.searchProjects = function() {
+ $scope.searchProjects = function () {
eventTracking.send(
'project-list-page-interaction',
'project-search',
@@ -167,19 +167,19 @@ App.controller('ProjectPageController', function(
$scope.updateVisibleProjects()
}
- $scope.clearSearchText = function() {
+ $scope.clearSearchText = function () {
$scope.searchText.value = ''
$scope.filter = 'all'
$scope.$emit('search:clear')
$scope.updateVisibleProjects()
}
- $scope.setFilter = function(filter) {
+ $scope.setFilter = function (filter) {
$scope.filter = filter
$scope.updateVisibleProjects()
}
- $scope.updateSelectedProjects = function() {
+ $scope.updateSelectedProjects = function () {
$scope.selectedProjects = $scope.projects.filter(
project => project.selected
)
@@ -204,7 +204,7 @@ App.controller('ProjectPageController', function(
project => project.accessLevel === 'owner' && project.trashed
)
- $scope.updateVisibleProjects = function() {
+ $scope.updateVisibleProjects = function () {
$scope.visibleProjects = []
const selectedTag = $scope.getSelectedTag()
for (let project of $scope.projects) {
@@ -288,7 +288,7 @@ App.controller('ProjectPageController', function(
$scope.updateSelectedProjects()
}
- $scope.getSelectedTag = function() {
+ $scope.getSelectedTag = function () {
for (let tag of $scope.tags) {
if (tag.selected) {
return tag
@@ -297,7 +297,7 @@ App.controller('ProjectPageController', function(
return null
}
- $scope._removeProjectIdsFromTagArray = function(tag, removeProjectIds) {
+ $scope._removeProjectIdsFromTagArray = function (tag, removeProjectIds) {
// Remove project_id from tag.project_ids
const remainingProjectIds = []
const removedProjectIds = []
@@ -312,14 +312,14 @@ App.controller('ProjectPageController', function(
return removedProjectIds
}
- $scope._removeProjectFromList = function(project) {
+ $scope._removeProjectFromList = function (project) {
const index = $scope.projects.indexOf(project)
if (index > -1) {
$scope.projects.splice(index, 1)
}
}
- $scope.removeSelectedProjectsFromTag = function(tag) {
+ $scope.removeSelectedProjectsFromTag = function (tag) {
tag.showWhenEmpty = true
const selectedProjectIds = $scope.getSelectedProjectIds()
@@ -356,7 +356,7 @@ App.controller('ProjectPageController', function(
$scope.updateVisibleProjects()
}
- $scope.removeProjectFromTag = function(project, tag) {
+ $scope.removeProjectFromTag = function (project, tag) {
tag.showWhenEmpty = true
if (!project.tags) {
@@ -378,7 +378,7 @@ App.controller('ProjectPageController', function(
}
}
- $scope.addSelectedProjectsToTag = function(tag) {
+ $scope.addSelectedProjectsToTag = function (tag) {
const selectedProjects = $scope.getSelectedProjects()
eventTracking.send(
'project-list-page-interaction',
@@ -412,14 +412,14 @@ App.controller('ProjectPageController', function(
}
}
- $scope.openNewTagModal = function(e) {
+ $scope.openNewTagModal = function (e) {
const modalInstance = $modal.open({
templateUrl: 'newTagModalTemplate',
controller: 'NewTagModalController'
})
- modalInstance.result.then(function(tag) {
- const tagIsDuplicate = $scope.tags.find(function(existingTag) {
+ modalInstance.result.then(function (tag) {
+ const tagIsDuplicate = $scope.tags.find(function (existingTag) {
return tag.name === existingTag.name
})
@@ -430,7 +430,7 @@ App.controller('ProjectPageController', function(
})
}
- $scope.createProject = function(name, template) {
+ $scope.createProject = function (name, template) {
if (template == null) {
template = 'none'
}
@@ -440,7 +440,7 @@ App.controller('ProjectPageController', function(
projectName: name,
template
})
- .then(function(response) {
+ .then(function (response) {
const { data } = response
$scope.projects.push({
name,
@@ -454,7 +454,7 @@ App.controller('ProjectPageController', function(
})
}
- $scope.openCreateProjectModal = function(template) {
+ $scope.openCreateProjectModal = function (template) {
if (template == null) {
template = 'none'
}
@@ -483,7 +483,7 @@ App.controller('ProjectPageController', function(
})
.then(() => (project.name = newName))
- $scope.openRenameProjectModal = function() {
+ $scope.openRenameProjectModal = function () {
let project = $scope.getFirstSelectedProject()
if (!project || project.accessLevel !== 'owner') {
return
@@ -505,7 +505,7 @@ App.controller('ProjectPageController', function(
})
}
- $scope.cloneProject = function(project, cloneName) {
+ $scope.cloneProject = function (project, cloneName) {
eventTracking.send(
'project-list-page-interaction',
'project action',
@@ -516,7 +516,7 @@ App.controller('ProjectPageController', function(
_csrf: window.csrfToken,
projectName: cloneName
})
- .then(function(response) {
+ .then(function (response) {
const { data } = response
$scope.projects.push({
name: data.name,
@@ -530,7 +530,7 @@ App.controller('ProjectPageController', function(
})
}
- $scope.openCloneProjectModal = function(project) {
+ $scope.openCloneProjectModal = function (project) {
if (!project) {
return
}
@@ -548,7 +548,7 @@ App.controller('ProjectPageController', function(
}
// Methods to create modals for archiving, trashing, leaving and deleting projects
- const _createArchiveTrashLeaveOrDeleteProjectsModal = function(
+ const _createArchiveTrashLeaveOrDeleteProjectsModal = function (
action,
projects
) {
@@ -571,23 +571,23 @@ App.controller('ProjectPageController', function(
})
}
- $scope.createArchiveProjectsModal = function(projects) {
+ $scope.createArchiveProjectsModal = function (projects) {
return _createArchiveTrashLeaveOrDeleteProjectsModal('archive', projects)
}
- $scope.createTrashProjectsModal = function(projects) {
+ $scope.createTrashProjectsModal = function (projects) {
return _createArchiveTrashLeaveOrDeleteProjectsModal('trash', projects)
}
- $scope.createLeaveProjectsModal = function(projects) {
+ $scope.createLeaveProjectsModal = function (projects) {
return _createArchiveTrashLeaveOrDeleteProjectsModal('leave', projects)
}
- $scope.createDeleteProjectsModal = function(projects) {
+ $scope.createDeleteProjectsModal = function (projects) {
return _createArchiveTrashLeaveOrDeleteProjectsModal('delete', projects)
}
- $scope.createLeaveOrDeleteProjectsModal = function(projects) {
+ $scope.createLeaveOrDeleteProjectsModal = function (projects) {
return _createArchiveTrashLeaveOrDeleteProjectsModal(
'leaveOrDelete',
projects
@@ -595,14 +595,14 @@ App.controller('ProjectPageController', function(
}
//
- $scope.openArchiveProjectsModal = function() {
+ $scope.openArchiveProjectsModal = function () {
const modalInstance = $scope.createArchiveProjectsModal(
$scope.getSelectedProjects()
)
modalInstance.result.then(() => $scope.archiveSelectedProjects())
}
- $scope.openTrashProjectsModal = function() {
+ $scope.openTrashProjectsModal = function () {
const modalInstance = $scope.createTrashProjectsModal(
$scope.getSelectedProjects()
)
@@ -610,21 +610,21 @@ App.controller('ProjectPageController', function(
modalInstance.result.then(() => $scope.trashSelectedProjects())
}
- $scope.openLeaveProjectsModal = function() {
+ $scope.openLeaveProjectsModal = function () {
const modalInstance = $scope.createLeaveProjectsModal(
$scope.getSelectedProjects()
)
modalInstance.result.then(() => $scope.leaveSelectedProjects())
}
- $scope.openDeleteProjectsModal = function() {
+ $scope.openDeleteProjectsModal = function () {
const modalInstance = $scope.createDeleteProjectsModal(
$scope.getSelectedProjects()
)
modalInstance.result.then(() => $scope.deleteSelectedProjects())
}
- $scope.openLeaveOrDeleteProjectsModal = function() {
+ $scope.openLeaveOrDeleteProjectsModal = function () {
const modalInstance = $scope.createLeaveOrDeleteProjectsModal(
$scope.getSelectedProjects()
)
@@ -654,7 +654,7 @@ App.controller('ProjectPageController', function(
$scope.leaveOrDeleteProjects($scope.getSelectedProjects())
//
- $scope.archiveProjects = function(projects) {
+ $scope.archiveProjects = function (projects) {
for (let project of projects) {
project.archived = true
project.trashed = false
@@ -663,7 +663,7 @@ App.controller('ProjectPageController', function(
$scope.updateVisibleProjects()
}
- $scope.unarchiveProjects = function(projects) {
+ $scope.unarchiveProjects = function (projects) {
for (let project of projects) {
project.archived = false
_unarchiveProject(project)
@@ -671,7 +671,7 @@ App.controller('ProjectPageController', function(
$scope.updateVisibleProjects()
}
- $scope.trashProjects = function(projects) {
+ $scope.trashProjects = function (projects) {
for (let project of projects) {
project.trashed = true
project.archived = false
@@ -680,7 +680,7 @@ App.controller('ProjectPageController', function(
$scope.updateVisibleProjects()
}
- $scope.untrashProjects = function(projects) {
+ $scope.untrashProjects = function (projects) {
for (let project of projects) {
project.trashed = false
_untrashProject(project)
@@ -688,7 +688,7 @@ App.controller('ProjectPageController', function(
$scope.updateVisibleProjects()
}
- $scope.leaveProjects = function(projects) {
+ $scope.leaveProjects = function (projects) {
_deleteOrLeaveProjectsLocally(projects)
for (let project of projects) {
_leaveProject(project)
@@ -696,7 +696,7 @@ App.controller('ProjectPageController', function(
$scope.updateVisibleProjects()
}
- $scope.deleteProjects = function(projects) {
+ $scope.deleteProjects = function (projects) {
_deleteOrLeaveProjectsLocally(projects)
for (let project of projects) {
_deleteProject(project)
@@ -704,7 +704,7 @@ App.controller('ProjectPageController', function(
$scope.updateVisibleProjects()
}
- $scope.leaveOrDeleteProjects = function(projects) {
+ $scope.leaveOrDeleteProjects = function (projects) {
_deleteOrLeaveProjectsLocally(projects)
for (let project of projects) {
if (project.accessLevel === 'owner') {
@@ -717,7 +717,7 @@ App.controller('ProjectPageController', function(
}
// Actual interaction with the backend---we could move this into a service
- const _archiveProject = function(project) {
+ const _archiveProject = function (project) {
return queuedHttp({
method: 'POST',
url: `/project/${project.id}/archive`,
@@ -727,7 +727,7 @@ App.controller('ProjectPageController', function(
})
}
- const _unarchiveProject = function(project) {
+ const _unarchiveProject = function (project) {
return queuedHttp({
method: 'DELETE',
url: `/project/${project.id}/archive`,
@@ -737,7 +737,7 @@ App.controller('ProjectPageController', function(
})
}
- const _trashProject = function(project) {
+ const _trashProject = function (project) {
return queuedHttp({
method: 'POST',
url: `/project/${project.id}/trash`,
@@ -747,7 +747,7 @@ App.controller('ProjectPageController', function(
})
}
- const _untrashProject = function(project) {
+ const _untrashProject = function (project) {
return queuedHttp({
method: 'DELETE',
url: `/project/${project.id}/trash`,
@@ -757,7 +757,7 @@ App.controller('ProjectPageController', function(
})
}
- const _leaveProject = function(project) {
+ const _leaveProject = function (project) {
return queuedHttp({
method: 'POST',
url: `/project/${project.id}/leave`,
@@ -767,7 +767,7 @@ App.controller('ProjectPageController', function(
})
}
- const _deleteProject = function(project) {
+ const _deleteProject = function (project) {
return queuedHttp({
method: 'DELETE',
url: `/project/${project.id}`,
@@ -777,7 +777,7 @@ App.controller('ProjectPageController', function(
})
}
- const _deleteOrLeaveProjectsLocally = function(projects) {
+ const _deleteOrLeaveProjectsLocally = function (projects) {
const projectIds = projects.map(p => p.id)
for (let tag of $scope.tags || []) {
$scope._removeProjectIdsFromTagArray(tag, projectIds)
@@ -787,7 +787,7 @@ App.controller('ProjectPageController', function(
}
}
- $scope.getValueForCurrentPredicate = function(project) {
+ $scope.getValueForCurrentPredicate = function (project) {
if ($scope.predicate === 'ownerName') {
return ProjectListService.getOwnerName(project)
} else {
@@ -795,7 +795,7 @@ App.controller('ProjectPageController', function(
}
}
- $scope.openUploadProjectModal = function() {
+ $scope.openUploadProjectModal = function () {
$modal.open({
templateUrl: 'uploadProjectModalTemplate',
controller: 'UploadProjectModalController'
@@ -805,7 +805,7 @@ App.controller('ProjectPageController', function(
$scope.downloadSelectedProjects = () =>
$scope.downloadProjectsById($scope.getSelectedProjectIds())
- $scope.downloadProjectsById = function(projectIds) {
+ $scope.downloadProjectsById = function (projectIds) {
let path
eventTracking.send(
'project-list-page-interaction',
@@ -842,83 +842,81 @@ App.controller('ProjectPageController', function(
}
})
-App.controller('ProjectListItemController', function(
- $scope,
- $modal,
- queuedHttp,
- ProjectListService
-) {
- $scope.projectLink = function(project) {
- return `/project/${project.id}`
- }
-
- $scope.isLinkSharingProject = project => project.source === 'token'
-
- $scope.hasGenericOwnerName = () => {
- /* eslint-disable camelcase */
- const { first_name, last_name, email } = $scope.project.owner
- return !first_name && !last_name && !email
- /* eslint-enable camelcase */
- }
-
- $scope.getOwnerName = ProjectListService.getOwnerName
-
- $scope.getUserName = ProjectListService.getUserName
-
- $scope.isOwner = () =>
- $scope.project.owner && window.user_id === $scope.project.owner._id
-
- $scope.$watch('project.selected', function(value) {
- if (value != null) {
- $scope.updateSelectedProjects()
+App.controller(
+ 'ProjectListItemController',
+ function ($scope, $modal, queuedHttp, ProjectListService) {
+ $scope.projectLink = function (project) {
+ return `/project/${project.id}`
}
- })
- $scope.clone = function(e) {
- e.stopPropagation()
- $scope.openCloneProjectModal($scope.project)
- }
+ $scope.isLinkSharingProject = project => project.source === 'token'
- $scope.download = function(e) {
- e.stopPropagation()
- $scope.downloadProjectsById([$scope.project.id])
- }
+ $scope.hasGenericOwnerName = () => {
+ /* eslint-disable camelcase */
+ const { first_name, last_name, email } = $scope.project.owner
+ return !first_name && !last_name && !email
+ /* eslint-enable camelcase */
+ }
- $scope.archive = function(e) {
- e.stopPropagation()
- $scope.createArchiveProjectsModal([$scope.project]).result.then(() => {
- $scope.archiveProjects([$scope.project])
+ $scope.getOwnerName = ProjectListService.getOwnerName
+
+ $scope.getUserName = ProjectListService.getUserName
+
+ $scope.isOwner = () =>
+ $scope.project.owner && window.user_id === $scope.project.owner._id
+
+ $scope.$watch('project.selected', function (value) {
+ if (value != null) {
+ $scope.updateSelectedProjects()
+ }
})
- }
- $scope.unarchive = function(e) {
- e.stopPropagation()
- $scope.unarchiveProjects([$scope.project])
- }
+ $scope.clone = function (e) {
+ e.stopPropagation()
+ $scope.openCloneProjectModal($scope.project)
+ }
- $scope.trash = function(e) {
- e.stopPropagation()
- $scope.createTrashProjectsModal([$scope.project]).result.then(() => {
- $scope.trashProjects([$scope.project])
- })
- }
+ $scope.download = function (e) {
+ e.stopPropagation()
+ $scope.downloadProjectsById([$scope.project.id])
+ }
- $scope.untrash = function(e) {
- e.stopPropagation()
- $scope.untrashProjects([$scope.project])
- }
+ $scope.archive = function (e) {
+ e.stopPropagation()
+ $scope.createArchiveProjectsModal([$scope.project]).result.then(() => {
+ $scope.archiveProjects([$scope.project])
+ })
+ }
- $scope.leave = function(e) {
- e.stopPropagation()
- $scope.createLeaveProjectsModal([$scope.project]).result.then(() => {
- $scope.leaveProjects([$scope.project])
- })
- }
+ $scope.unarchive = function (e) {
+ e.stopPropagation()
+ $scope.unarchiveProjects([$scope.project])
+ }
- $scope.delete = function(e) {
- e.stopPropagation()
- $scope.createDeleteProjectsModal([$scope.project]).result.then(() => {
- $scope.deleteProjects([$scope.project])
- })
+ $scope.trash = function (e) {
+ e.stopPropagation()
+ $scope.createTrashProjectsModal([$scope.project]).result.then(() => {
+ $scope.trashProjects([$scope.project])
+ })
+ }
+
+ $scope.untrash = function (e) {
+ e.stopPropagation()
+ $scope.untrashProjects([$scope.project])
+ }
+
+ $scope.leave = function (e) {
+ e.stopPropagation()
+ $scope.createLeaveProjectsModal([$scope.project]).result.then(() => {
+ $scope.leaveProjects([$scope.project])
+ })
+ }
+
+ $scope.delete = function (e) {
+ e.stopPropagation()
+ $scope.createDeleteProjectsModal([$scope.project]).result.then(() => {
+ $scope.deleteProjects([$scope.project])
+ })
+ }
}
-})
+)
diff --git a/services/web/frontend/js/main/project-list/services/project-list.js b/services/web/frontend/js/main/project-list/services/project-list.js
index d06a19af78..458a9bd4ff 100644
--- a/services/web/frontend/js/main/project-list/services/project-list.js
+++ b/services/web/frontend/js/main/project-list/services/project-list.js
@@ -3,7 +3,7 @@
*/
import App from '../../../base'
-export default App.service('ProjectListService', function() {
+export default App.service('ProjectListService', function () {
return {
getOwnerName(project) {
if (project.accessLevel === 'owner') {
diff --git a/services/web/frontend/js/main/project-list/tag-controllers.js b/services/web/frontend/js/main/project-list/tag-controllers.js
index c049a7b5a8..e30129da92 100644
--- a/services/web/frontend/js/main/project-list/tag-controllers.js
+++ b/services/web/frontend/js/main/project-list/tag-controllers.js
@@ -1,7 +1,7 @@
import App from '../../base'
import ColorManager from '../../ide/colors/ColorManager'
-App.controller('TagListController', function($scope, $modal) {
- $scope.filterProjects = function(filter = 'all') {
+App.controller('TagListController', function ($scope, $modal) {
+ $scope.filterProjects = function (filter = 'all') {
$scope._clearTags()
$scope.setFilter(filter)
}
@@ -11,18 +11,18 @@ App.controller('TagListController', function($scope, $modal) {
tag.selected = false
})
- $scope.selectTag = function(tag) {
+ $scope.selectTag = function (tag) {
$scope._clearTags()
tag.selected = true
$scope.setFilter('tag')
}
- $scope.selectUntagged = function() {
+ $scope.selectUntagged = function () {
$scope._clearTags()
$scope.setFilter('untagged')
}
- $scope.countProjectsForTag = function(tag) {
+ $scope.countProjectsForTag = function (tag) {
return tag.project_ids.reduce((acc, projectId) => {
const project = $scope.getProjectById(projectId)
@@ -42,7 +42,7 @@ App.controller('TagListController', function($scope, $modal) {
$scope.getHueForTagId = tagId => ColorManager.getHueForTagId(tagId)
- $scope.deleteTag = function(tag) {
+ $scope.deleteTag = function (tag) {
const modalInstance = $modal.open({
templateUrl: 'deleteTagModalTemplate',
controller: 'DeleteTagModalController',
@@ -52,7 +52,7 @@ App.controller('TagListController', function($scope, $modal) {
}
}
})
- modalInstance.result.then(function() {
+ modalInstance.result.then(function () {
// Remove tag from projects
for (let project of $scope.projects) {
if (!project.tags) {
@@ -69,7 +69,7 @@ App.controller('TagListController', function($scope, $modal) {
})
}
- $scope.renameTag = function(tag) {
+ $scope.renameTag = function (tag) {
const modalInstance = $modal.open({
templateUrl: 'renameTagModalTemplate',
controller: 'RenameTagModalController',
@@ -83,8 +83,8 @@ App.controller('TagListController', function($scope, $modal) {
}
})
-App.controller('TagDropdownItemController', function($scope) {
- $scope.recalculateProjectsInTag = function() {
+App.controller('TagDropdownItemController', function ($scope) {
+ $scope.recalculateProjectsInTag = function () {
let partialSelection
$scope.areSelectedProjectsInTag = false
for (let projectId of $scope.getSelectedProjectIds()) {
@@ -100,7 +100,7 @@ App.controller('TagDropdownItemController', function($scope) {
}
}
- $scope.addOrRemoveProjectsFromTag = function() {
+ $scope.addOrRemoveProjectsFromTag = function () {
if ($scope.areSelectedProjectsInTag === true) {
$scope.removeSelectedProjectsFromTag($scope.tag)
$scope.areSelectedProjectsInTag = false
@@ -117,117 +117,110 @@ App.controller('TagDropdownItemController', function($scope) {
$scope.recalculateProjectsInTag()
})
-App.controller('NewTagModalController', function(
- $scope,
- $modalInstance,
- $timeout,
- $http
-) {
- $scope.inputs = { newTagName: '' }
+App.controller(
+ 'NewTagModalController',
+ function ($scope, $modalInstance, $timeout, $http) {
+ $scope.inputs = { newTagName: '' }
- $scope.state = {
- inflight: false,
- error: false
+ $scope.state = {
+ inflight: false,
+ error: false
+ }
+
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
+
+ $scope.create = function () {
+ const name = $scope.inputs.newTagName
+ $scope.state.inflight = true
+ $scope.state.error = false
+ $http
+ .post('/tag', {
+ _csrf: window.csrfToken,
+ name
+ })
+ .then(function (response) {
+ const { data } = response
+ $scope.state.inflight = false
+ $modalInstance.close(data)
+ })
+ .catch(function () {
+ $scope.state.inflight = false
+ $scope.state.error = true
+ })
+ }
+
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
}
+)
- $modalInstance.opened.then(() =>
- $timeout(() => $scope.$broadcast('open'), 200)
- )
+App.controller(
+ 'RenameTagModalController',
+ function ($scope, $modalInstance, $timeout, $http, tag) {
+ $scope.inputs = { tagName: tag.name }
- $scope.create = function() {
- const name = $scope.inputs.newTagName
- $scope.state.inflight = true
- $scope.state.error = false
- $http
- .post('/tag', {
- _csrf: window.csrfToken,
- name
- })
- .then(function(response) {
- const { data } = response
- $scope.state.inflight = false
- $modalInstance.close(data)
- })
- .catch(function() {
- $scope.state.inflight = false
- $scope.state.error = true
- })
+ $scope.state = {
+ inflight: false,
+ error: false
+ }
+
+ $modalInstance.opened.then(() =>
+ $timeout(() => $scope.$broadcast('open'), 200)
+ )
+
+ $scope.rename = function () {
+ const name = $scope.inputs.tagName
+ $scope.state.inflight = true
+ $scope.state.error = false
+ return $http
+ .post(`/tag/${tag._id}/rename`, {
+ _csrf: window.csrfToken,
+ name
+ })
+ .then(function () {
+ $scope.state.inflight = false
+ $modalInstance.close(name)
+ })
+ .catch(function () {
+ $scope.state.inflight = false
+ $scope.state.error = true
+ })
+ }
+
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
}
+)
- $scope.cancel = () => $modalInstance.dismiss('cancel')
-})
+export default App.controller(
+ 'DeleteTagModalController',
+ function ($scope, $modalInstance, $http, tag) {
+ $scope.tag = tag
+ $scope.state = {
+ inflight: false,
+ error: false
+ }
-App.controller('RenameTagModalController', function(
- $scope,
- $modalInstance,
- $timeout,
- $http,
- tag
-) {
- $scope.inputs = { tagName: tag.name }
+ $scope.delete = function () {
+ $scope.state.inflight = true
+ $scope.state.error = false
+ return $http({
+ method: 'DELETE',
+ url: `/tag/${tag._id}`,
+ headers: {
+ 'X-CSRF-Token': window.csrfToken
+ }
+ })
+ .then(function () {
+ $scope.state.inflight = false
+ $modalInstance.close()
+ })
+ .catch(function () {
+ $scope.state.inflight = false
+ $scope.state.error = true
+ })
+ }
- $scope.state = {
- inflight: false,
- error: false
+ $scope.cancel = () => $modalInstance.dismiss('cancel')
}
-
- $modalInstance.opened.then(() =>
- $timeout(() => $scope.$broadcast('open'), 200)
- )
-
- $scope.rename = function() {
- const name = $scope.inputs.tagName
- $scope.state.inflight = true
- $scope.state.error = false
- return $http
- .post(`/tag/${tag._id}/rename`, {
- _csrf: window.csrfToken,
- name
- })
- .then(function() {
- $scope.state.inflight = false
- $modalInstance.close(name)
- })
- .catch(function() {
- $scope.state.inflight = false
- $scope.state.error = true
- })
- }
-
- $scope.cancel = () => $modalInstance.dismiss('cancel')
-})
-
-export default App.controller('DeleteTagModalController', function(
- $scope,
- $modalInstance,
- $http,
- tag
-) {
- $scope.tag = tag
- $scope.state = {
- inflight: false,
- error: false
- }
-
- $scope.delete = function() {
- $scope.state.inflight = true
- $scope.state.error = false
- return $http({
- method: 'DELETE',
- url: `/tag/${tag._id}`,
- headers: {
- 'X-CSRF-Token': window.csrfToken
- }
- })
- .then(function() {
- $scope.state.inflight = false
- $modalInstance.close()
- })
- .catch(function() {
- $scope.state.inflight = false
- $scope.state.error = true
- })
- }
-
- $scope.cancel = () => $modalInstance.dismiss('cancel')
-})
+)
diff --git a/services/web/frontend/js/main/register-users.js b/services/web/frontend/js/main/register-users.js
index b0aea28fb8..76c1495926 100644
--- a/services/web/frontend/js/main/register-users.js
+++ b/services/web/frontend/js/main/register-users.js
@@ -13,38 +13,38 @@ import _ from 'lodash'
*/
import App from '../base'
-export default App.controller('RegisterUsersController', function(
- $scope,
- queuedHttp
-) {
- $scope.users = []
+export default App.controller(
+ 'RegisterUsersController',
+ function ($scope, queuedHttp) {
+ $scope.users = []
- $scope.inputs = { emails: '' }
+ $scope.inputs = { emails: '' }
- const parseEmails = function(emailsString) {
- const regexBySpaceOrComma = /[\s,]+/
- let emails = emailsString.split(regexBySpaceOrComma)
- emails = _.map(emails, email => (email = email.trim()))
- emails = _.filter(emails, email => email.indexOf('@') !== -1)
- return emails
+ const parseEmails = function (emailsString) {
+ const regexBySpaceOrComma = /[\s,]+/
+ let emails = emailsString.split(regexBySpaceOrComma)
+ emails = _.map(emails, email => (email = email.trim()))
+ emails = _.filter(emails, email => email.indexOf('@') !== -1)
+ return emails
+ }
+
+ return ($scope.registerUsers = function () {
+ const emails = parseEmails($scope.inputs.emails)
+ $scope.error = false
+ return Array.from(emails).map(email =>
+ queuedHttp
+ .post('/admin/register', {
+ email,
+ _csrf: window.csrfToken
+ })
+ .then(function (response) {
+ const { data } = response
+ const user = data
+ $scope.users.push(user)
+ return ($scope.inputs.emails = '')
+ })
+ .catch(() => ($scope.error = true))
+ )
+ })
}
-
- return ($scope.registerUsers = function() {
- const emails = parseEmails($scope.inputs.emails)
- $scope.error = false
- return Array.from(emails).map(email =>
- queuedHttp
- .post('/admin/register', {
- email,
- _csrf: window.csrfToken
- })
- .then(function(response) {
- const { data } = response
- const user = data
- $scope.users.push(user)
- return ($scope.inputs.emails = '')
- })
- .catch(() => ($scope.error = true))
- )
- })
-})
+)
diff --git a/services/web/frontend/js/main/subscription-dashboard.js b/services/web/frontend/js/main/subscription-dashboard.js
index 3598341cd5..b52e341dbe 100644
--- a/services/web/frontend/js/main/subscription-dashboard.js
+++ b/services/web/frontend/js/main/subscription-dashboard.js
@@ -28,9 +28,9 @@ const ensureRecurlyIsSetup = _.once(() => {
return true
})
-App.controller('MetricsEmailController', function($scope, $http) {
- $scope.institutionEmailSubscription = function(institutionId) {
- var inst = _.find(window.managedInstitutions, function(institution) {
+App.controller('MetricsEmailController', function ($scope, $http) {
+ $scope.institutionEmailSubscription = function (institutionId) {
+ var inst = _.find(window.managedInstitutions, function (institution) {
return institution.v1Id === parseInt(institutionId)
})
if (inst.metricsEmail.optedOutUserIds.includes(window.user_id)) {
@@ -40,7 +40,7 @@ App.controller('MetricsEmailController', function($scope, $http) {
}
}
- $scope.changeInstitutionalEmailSubscription = function(institutionId) {
+ $scope.changeInstitutionalEmailSubscription = function (institutionId) {
$scope.subscriptionChanging = true
return $http({
method: 'POST',
@@ -49,30 +49,31 @@ App.controller('MetricsEmailController', function($scope, $http) {
'X-CSRF-Token': window.csrfToken
}
}).then(function successCallback(response) {
- window.managedInstitutions = _.map(window.managedInstitutions, function(
- institution
- ) {
- if (institution.v1Id === parseInt(institutionId)) {
- institution.metricsEmail.optedOutUserIds = response.data
+ window.managedInstitutions = _.map(
+ window.managedInstitutions,
+ function (institution) {
+ if (institution.v1Id === parseInt(institutionId)) {
+ institution.metricsEmail.optedOutUserIds = response.data
+ }
+ return institution
}
- return institution
- })
+ )
$scope.subscriptionChanging = false
})
}
})
-App.factory('RecurlyPricing', function($q, MultiCurrencyPricing) {
+App.factory('RecurlyPricing', function ($q, MultiCurrencyPricing) {
return {
- loadDisplayPriceWithTax: function(planCode, currency, taxRate) {
+ loadDisplayPriceWithTax: function (planCode, currency, taxRate) {
if (!ensureRecurlyIsSetup()) return
const currencySymbol = MultiCurrencyPricing.plans[currency].symbol
const pricing = recurly.Pricing()
- return $q(function(resolve, reject) {
+ return $q(function (resolve, reject) {
pricing
.plan(planCode, { quantity: 1 })
.currency(currency)
- .done(function(price) {
+ .done(function (price) {
const totalPriceExTax = parseFloat(price.next.total)
let taxAmmount = totalPriceExTax * taxRate
if (isNaN(taxAmmount)) {
@@ -89,79 +90,76 @@ App.factory('RecurlyPricing', function($q, MultiCurrencyPricing) {
}
})
-App.controller('ChangePlanFormController', function(
- $scope,
- $modal,
- RecurlyPricing
-) {
- if (!ensureRecurlyIsSetup()) return
+App.controller(
+ 'ChangePlanFormController',
+ function ($scope, $modal, RecurlyPricing) {
+ if (!ensureRecurlyIsSetup()) return
- $scope.changePlan = () =>
- $modal.open({
- templateUrl: 'confirmChangePlanModalTemplate',
- controller: 'ConfirmChangePlanController',
- scope: $scope
+ $scope.changePlan = () =>
+ $modal.open({
+ templateUrl: 'confirmChangePlanModalTemplate',
+ controller: 'ConfirmChangePlanController',
+ scope: $scope
+ })
+
+ $scope.$watch('plan', function (plan) {
+ if (!plan) return
+ const planCode = plan.planCode
+ const { currency, taxRate } = window.subscription.recurly
+ $scope.price = '...' // Placeholder while we talk to recurly
+ RecurlyPricing.loadDisplayPriceWithTax(planCode, currency, taxRate).then(
+ price => {
+ $scope.price = price
+ }
+ )
})
-
- $scope.$watch('plan', function(plan) {
- if (!plan) return
- const planCode = plan.planCode
- const { currency, taxRate } = window.subscription.recurly
- $scope.price = '...' // Placeholder while we talk to recurly
- RecurlyPricing.loadDisplayPriceWithTax(planCode, currency, taxRate).then(
- price => {
- $scope.price = price
- }
- )
- })
-})
-
-App.controller('ConfirmChangePlanController', function(
- $scope,
- $modalInstance,
- $http
-) {
- $scope.confirmChangePlan = function() {
- const body = {
- plan_code: $scope.plan.planCode,
- _csrf: window.csrfToken
- }
-
- $scope.inflight = true
-
- return $http
- .post(`${SUBSCRIPTION_URL}?origin=confirmChangePlan`, body)
- .then(() => location.reload())
- .catch(() => console.log('something went wrong changing plan'))
}
+)
- return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
-})
-
-App.controller('LeaveGroupModalController', function(
- $scope,
- $modalInstance,
- $http
-) {
- $scope.confirmLeaveGroup = function() {
- $scope.inflight = true
- return $http({
- url: '/subscription/group/user',
- method: 'DELETE',
- params: {
- subscriptionId: $scope.subscriptionId,
+App.controller(
+ 'ConfirmChangePlanController',
+ function ($scope, $modalInstance, $http) {
+ $scope.confirmChangePlan = function () {
+ const body = {
+ plan_code: $scope.plan.planCode,
_csrf: window.csrfToken
}
- })
- .then(() => location.reload())
- .catch(() => console.log('something went wrong changing plan'))
+
+ $scope.inflight = true
+
+ return $http
+ .post(`${SUBSCRIPTION_URL}?origin=confirmChangePlan`, body)
+ .then(() => location.reload())
+ .catch(() => console.log('something went wrong changing plan'))
+ }
+
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
}
+)
- return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
-})
+App.controller(
+ 'LeaveGroupModalController',
+ function ($scope, $modalInstance, $http) {
+ $scope.confirmLeaveGroup = function () {
+ $scope.inflight = true
+ return $http({
+ url: '/subscription/group/user',
+ method: 'DELETE',
+ params: {
+ subscriptionId: $scope.subscriptionId,
+ _csrf: window.csrfToken
+ }
+ })
+ .then(() => location.reload())
+ .catch(() => console.log('something went wrong changing plan'))
+ }
-App.controller('GroupMembershipController', function($scope, $modal) {
- $scope.removeSelfFromGroup = function(subscriptionId) {
+ return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
+ }
+)
+
+App.controller('GroupMembershipController', function ($scope, $modal) {
+ $scope.removeSelfFromGroup = function (subscriptionId) {
$scope.subscriptionId = subscriptionId
return $modal.open({
templateUrl: 'LeaveGroupModalTemplate',
@@ -171,7 +169,7 @@ App.controller('GroupMembershipController', function($scope, $modal) {
}
})
-App.controller('RecurlySubscriptionController', function($scope) {
+App.controller('RecurlySubscriptionController', function ($scope) {
const recurlyIsSetup = ensureRecurlyIsSetup()
$scope.showChangePlanButton = recurlyIsSetup && !window.subscription.groupPlan
if (
@@ -199,69 +197,68 @@ App.controller('RecurlySubscriptionController', function($scope) {
}
})
-App.controller('RecurlyCancellationController', function(
- $scope,
- RecurlyPricing,
- $http
-) {
- if (!ensureRecurlyIsSetup()) return
- const subscription = window.subscription
- const sevenDaysTime = new Date()
- sevenDaysTime.setDate(sevenDaysTime.getDate() + 7)
- const freeTrialEndDate = new Date(subscription.recurly.trial_ends_at)
- const freeTrialInFuture = freeTrialEndDate > new Date()
- const freeTrialExpiresUnderSevenDays = freeTrialEndDate < sevenDaysTime
+App.controller(
+ 'RecurlyCancellationController',
+ function ($scope, RecurlyPricing, $http) {
+ if (!ensureRecurlyIsSetup()) return
+ const subscription = window.subscription
+ const sevenDaysTime = new Date()
+ sevenDaysTime.setDate(sevenDaysTime.getDate() + 7)
+ const freeTrialEndDate = new Date(subscription.recurly.trial_ends_at)
+ const freeTrialInFuture = freeTrialEndDate > new Date()
+ const freeTrialExpiresUnderSevenDays = freeTrialEndDate < sevenDaysTime
- const isMonthlyCollab =
- subscription.plan.planCode.indexOf('collaborator') !== -1 &&
- subscription.plan.planCode.indexOf('ann') === -1 &&
- !subscription.groupPlan
- const stillInFreeTrial = freeTrialInFuture && freeTrialExpiresUnderSevenDays
+ const isMonthlyCollab =
+ subscription.plan.planCode.indexOf('collaborator') !== -1 &&
+ subscription.plan.planCode.indexOf('ann') === -1 &&
+ !subscription.groupPlan
+ const stillInFreeTrial = freeTrialInFuture && freeTrialExpiresUnderSevenDays
- if (isMonthlyCollab && stillInFreeTrial) {
- $scope.showExtendFreeTrial = true
- } else if (isMonthlyCollab && !stillInFreeTrial) {
- $scope.showDowngradeToStudent = true
- } else {
- $scope.showBasicCancel = true
- }
-
- const { currency, taxRate } = window.subscription.recurly
- $scope.studentPrice = '...' // Placeholder while we talk to recurly
- RecurlyPricing.loadDisplayPriceWithTax('student', currency, taxRate).then(
- price => {
- $scope.studentPrice = price
+ if (isMonthlyCollab && stillInFreeTrial) {
+ $scope.showExtendFreeTrial = true
+ } else if (isMonthlyCollab && !stillInFreeTrial) {
+ $scope.showDowngradeToStudent = true
+ } else {
+ $scope.showBasicCancel = true
}
- )
- $scope.downgradeToStudent = function() {
- const body = {
- plan_code: 'student',
- _csrf: window.csrfToken
+ const { currency, taxRate } = window.subscription.recurly
+ $scope.studentPrice = '...' // Placeholder while we talk to recurly
+ RecurlyPricing.loadDisplayPriceWithTax('student', currency, taxRate).then(
+ price => {
+ $scope.studentPrice = price
+ }
+ )
+
+ $scope.downgradeToStudent = function () {
+ const body = {
+ plan_code: 'student',
+ _csrf: window.csrfToken
+ }
+ $scope.inflight = true
+ return $http
+ .post(`${SUBSCRIPTION_URL}?origin=downgradeToStudent`, body)
+ .then(() => location.reload())
+ .catch(() => console.log('something went wrong changing plan'))
}
- $scope.inflight = true
- return $http
- .post(`${SUBSCRIPTION_URL}?origin=downgradeToStudent`, body)
- .then(() => location.reload())
- .catch(() => console.log('something went wrong changing plan'))
- }
- $scope.cancelSubscription = function() {
- const body = { _csrf: window.csrfToken }
+ $scope.cancelSubscription = function () {
+ const body = { _csrf: window.csrfToken }
- $scope.inflight = true
- return $http
- .post('/user/subscription/cancel', body)
- .then(() => (location.href = '/user/subscription/canceled'))
- .catch(() => console.log('something went wrong changing plan'))
- }
+ $scope.inflight = true
+ return $http
+ .post('/user/subscription/cancel', body)
+ .then(() => (location.href = '/user/subscription/canceled'))
+ .catch(() => console.log('something went wrong changing plan'))
+ }
- $scope.extendTrial = function() {
- const body = { _csrf: window.csrfToken }
- $scope.inflight = true
- return $http
- .put('/user/subscription/extend', body)
- .then(() => location.reload())
- .catch(() => console.log('something went wrong changing plan'))
+ $scope.extendTrial = function () {
+ const body = { _csrf: window.csrfToken }
+ $scope.inflight = true
+ return $http
+ .put('/user/subscription/extend', body)
+ .then(() => location.reload())
+ .catch(() => console.log('something went wrong changing plan'))
+ }
}
-})
+)
diff --git a/services/web/frontend/js/main/subscription/team-invite-controller.js b/services/web/frontend/js/main/subscription/team-invite-controller.js
index 47bc90f7ac..1e6dba5349 100644
--- a/services/web/frontend/js/main/subscription/team-invite-controller.js
+++ b/services/web/frontend/js/main/subscription/team-invite-controller.js
@@ -11,7 +11,7 @@
*/
import App from '../../base'
-export default App.controller('TeamInviteController', function($scope, $http) {
+export default App.controller('TeamInviteController', function ($scope, $http) {
$scope.inflight = false
if (window.hasIndividualRecurlySubscription) {
@@ -22,12 +22,12 @@ export default App.controller('TeamInviteController', function($scope, $http) {
$scope.keepPersonalSubscription = () => ($scope.view = 'teamInvite')
- $scope.cancelPersonalSubscription = function() {
+ $scope.cancelPersonalSubscription = function () {
$scope.inflight = true
const request = $http.post('/user/subscription/cancel', {
_csrf: window.csrfToken
})
- request.then(function() {
+ request.then(function () {
$scope.inflight = false
return ($scope.view = 'teamInvite')
})
@@ -38,12 +38,12 @@ export default App.controller('TeamInviteController', function($scope, $http) {
})
}
- return ($scope.joinTeam = function() {
+ return ($scope.joinTeam = function () {
$scope.inflight = true
const request = $http.put(`/subscription/invites/${window.inviteToken}/`, {
_csrf: window.csrfToken
})
- request.then(function(response) {
+ request.then(function (response) {
const { status } = response
$scope.inflight = false
$scope.view = 'inviteAccepted'
diff --git a/services/web/frontend/js/main/subscription/upgrade-subscription.js b/services/web/frontend/js/main/subscription/upgrade-subscription.js
index 42a0175308..660cba7b77 100644
--- a/services/web/frontend/js/main/subscription/upgrade-subscription.js
+++ b/services/web/frontend/js/main/subscription/upgrade-subscription.js
@@ -1,10 +1,10 @@
import App from '../../base'
-export default App.controller('UpgradeSubscriptionController', function(
- $scope,
- eventTracking
-) {
- $scope.upgradeSubscription = function() {
- eventTracking.send('subscription-funnel', 'subscription-page', 'upgrade')
+export default App.controller(
+ 'UpgradeSubscriptionController',
+ function ($scope, eventTracking) {
+ $scope.upgradeSubscription = function () {
+ eventTracking.send('subscription-funnel', 'subscription-page', 'upgrade')
+ }
}
-})
+)
diff --git a/services/web/frontend/js/main/system-messages.js b/services/web/frontend/js/main/system-messages.js
index a866187248..1c7d9be1d7 100644
--- a/services/web/frontend/js/main/system-messages.js
+++ b/services/web/frontend/js/main/system-messages.js
@@ -14,7 +14,7 @@ const MESSAGE_POLL_INTERVAL = 15 * 60 * 1000
// Controller for messages (array)
App.controller('SystemMessagesController', ($http, $scope) => {
$scope.messages = []
- var pollSystemMessages = function() {
+ var pollSystemMessages = function () {
// Ignore polling if tab is hidden or browser is offline
if (document.hidden || !navigator.onLine) {
return
@@ -41,19 +41,19 @@ App.controller('SystemMessagesController', ($http, $scope) => {
setInterval(pollSystemMessages, MESSAGE_POLL_INTERVAL)
})
-export default App.controller('SystemMessageController', function(
- $scope,
- $sce
-) {
- $scope.hidden = $.localStorage(`systemMessage.hide.${$scope.message._id}`)
- $scope.protected = $scope.message._id === 'protected'
- $scope.htmlContent = $scope.message.content
+export default App.controller(
+ 'SystemMessageController',
+ function ($scope, $sce) {
+ $scope.hidden = $.localStorage(`systemMessage.hide.${$scope.message._id}`)
+ $scope.protected = $scope.message._id === 'protected'
+ $scope.htmlContent = $scope.message.content
- return ($scope.hide = function() {
- if (!$scope.protected) {
- // do not allow protected messages to be hidden
- $scope.hidden = true
- return $.localStorage(`systemMessage.hide.${$scope.message._id}`, true)
- }
- })
-})
+ return ($scope.hide = function () {
+ if (!$scope.protected) {
+ // do not allow protected messages to be hidden
+ $scope.hidden = true
+ return $.localStorage(`systemMessage.hide.${$scope.message._id}`, true)
+ }
+ })
+ }
+)
diff --git a/services/web/frontend/js/main/translations.js b/services/web/frontend/js/main/translations.js
index 072c55f08d..837625ce17 100644
--- a/services/web/frontend/js/main/translations.js
+++ b/services/web/frontend/js/main/translations.js
@@ -1,33 +1,32 @@
import App from '../base'
-App.controller('TranslationsPopupController', function(
- $scope,
- ipCookie,
- localStorage
-) {
- function getStoredDismissal() {
- let localStore = localStorage('hide-i18n-notification')
+App.controller(
+ 'TranslationsPopupController',
+ function ($scope, ipCookie, localStorage) {
+ function getStoredDismissal() {
+ let localStore = localStorage('hide-i18n-notification')
- if (localStore === null) {
- // Not stored in localStorage, check cookie
- let cookieStore = ipCookie('hidei18nNotification')
+ if (localStore === null) {
+ // Not stored in localStorage, check cookie
+ let cookieStore = ipCookie('hidei18nNotification')
- // If stored in cookie, set on localStorage for forwards compat
- if (cookieStore) {
- localStorage('hide-i18n-notification', cookieStore)
- ipCookie.remove('hidei18nNotification')
+ // If stored in cookie, set on localStorage for forwards compat
+ if (cookieStore) {
+ localStorage('hide-i18n-notification', cookieStore)
+ ipCookie.remove('hidei18nNotification')
+ }
+
+ return cookieStore
}
- return cookieStore
+ return localStore
}
- return localStore
- }
+ $scope.hidei18nNotification = getStoredDismissal()
- $scope.hidei18nNotification = getStoredDismissal()
-
- $scope.dismiss = function() {
- localStorage('hide-i18n-notification', true)
- $scope.hidei18nNotification = true
+ $scope.dismiss = function () {
+ localStorage('hide-i18n-notification', true)
+ $scope.hidei18nNotification = true
+ }
}
-})
+)
diff --git a/services/web/frontend/js/main/user-membership.js b/services/web/frontend/js/main/user-membership.js
index f806ec9db5..ce46317db4 100644
--- a/services/web/frontend/js/main/user-membership.js
+++ b/services/web/frontend/js/main/user-membership.js
@@ -13,7 +13,7 @@ import _ from 'lodash'
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../base'
-App.controller('UserMembershipController', function($scope, queuedHttp) {
+App.controller('UserMembershipController', function ($scope, queuedHttp) {
$scope.users = window.users
$scope.groupSize = window.groupSize
$scope.paths = window.paths
@@ -32,7 +32,7 @@ App.controller('UserMembershipController', function($scope, queuedHttp) {
}
}
- const parseEmails = function(emailsString) {
+ const parseEmails = function (emailsString) {
const regexBySpaceOrComma = /[\s,]+/
let emails = emailsString.split(regexBySpaceOrComma)
emails = _.map(emails, email => (email = email.trim()))
@@ -40,7 +40,7 @@ App.controller('UserMembershipController', function($scope, queuedHttp) {
return emails
}
- $scope.addMembers = function() {
+ $scope.addMembers = function () {
$scope.inputs.addMembers.error = false
$scope.inputs.addMembers.errorMessage = null
$scope.inputs.addMembers.inflightCount = 0
@@ -52,7 +52,7 @@ App.controller('UserMembershipController', function($scope, queuedHttp) {
email,
_csrf: window.csrfToken
})
- .then(function(response) {
+ .then(function (response) {
$scope.inputs.addMembers.inflightCount -= 1
const { data } = response
if (data.user != null) {
@@ -60,7 +60,7 @@ App.controller('UserMembershipController', function($scope, queuedHttp) {
}
return ($scope.inputs.addMembers.content = '')
})
- .catch(function(response) {
+ .catch(function (response) {
$scope.inputs.addMembers.inflightCount -= 1
const { data } = response
$scope.inputs.addMembers.error = true
@@ -70,11 +70,11 @@ App.controller('UserMembershipController', function($scope, queuedHttp) {
})
}
- $scope.removeMembers = function() {
+ $scope.removeMembers = function () {
$scope.inputs.removeMembers.error = false
$scope.inputs.removeMembers.errorMessage = null
for (let user of Array.from($scope.selectedUsers)) {
- ;(function(user) {
+ ;(function (user) {
let url
if (window.paths.removeInvite && user.invite && user._id == null) {
url = `${window.paths.removeInvite}/${encodeURIComponent(user.email)}`
@@ -90,14 +90,14 @@ App.controller('UserMembershipController', function($scope, queuedHttp) {
'X-Csrf-Token': window.csrfToken
}
})
- .then(function() {
+ .then(function () {
const index = $scope.users.indexOf(user)
if (index === -1) {
return
}
return $scope.users.splice(index, 1)
})
- .catch(function(response) {
+ .catch(function (response) {
const { data } = response
$scope.inputs.removeMembers.error = true
return ($scope.inputs.removeMembers.errorMessage =
@@ -113,7 +113,7 @@ App.controller('UserMembershipController', function($scope, queuedHttp) {
})
export default App.controller('UserMembershipListItemController', $scope =>
- $scope.$watch('user.selected', function(value) {
+ $scope.$watch('user.selected', function (value) {
if (value != null) {
return $scope.updateSelectedUsers()
}
diff --git a/services/web/frontend/js/modules/errorCatcher.js b/services/web/frontend/js/modules/errorCatcher.js
index dae5a2e55e..ab30ba1a82 100644
--- a/services/web/frontend/js/modules/errorCatcher.js
+++ b/services/web/frontend/js/modules/errorCatcher.js
@@ -21,7 +21,7 @@ app.config([
'$log',
'$delegate',
($log, $delegate) =>
- function(exception, cause) {
+ function (exception, cause) {
if (
exception === UNHANDLED_REJECTION_ERR_MSG &&
cause === undefined
diff --git a/services/web/frontend/js/modules/recursionHelper.js b/services/web/frontend/js/modules/recursionHelper.js
index 1b569522a1..5a1814fb2d 100644
--- a/services/web/frontend/js/modules/recursionHelper.js
+++ b/services/web/frontend/js/modules/recursionHelper.js
@@ -32,7 +32,7 @@
// From: https://github.com/marklagendijk/angular-recursion
angular.module('RecursionHelper', []).factory('RecursionHelper', [
'$compile',
- function($compile) {
+ function ($compile) {
/*
Manually compiles the element, fixing the recursion loop.
@param element
@@ -62,7 +62,7 @@ angular.module('RecursionHelper', []).factory('RecursionHelper', [
}
// Re-add the compiled contents to the element
- compiledContents(scope, function(clone) {
+ compiledContents(scope, function (clone) {
element.append(clone)
})
diff --git a/services/web/frontend/js/modules/sessionStorage.js b/services/web/frontend/js/modules/sessionStorage.js
index c80e2203a0..c25d302ac7 100644
--- a/services/web/frontend/js/modules/sessionStorage.js
+++ b/services/web/frontend/js/modules/sessionStorage.js
@@ -1,13 +1,15 @@
-angular.module('sessionStorage', []).value('sessionStorage', function(...args) {
- /*
+angular
+ .module('sessionStorage', [])
+ .value('sessionStorage', function (...args) {
+ /*
sessionStorage can throw browser exceptions, for example if it is full
We don't use sessionStorage for anything critical, on in that case just
fail gracefully.
*/
- try {
- return $.sessionStorage(...args)
- } catch (e) {
- console.error('sessionStorage exception', e)
- return null
- }
-})
+ try {
+ return $.sessionStorage(...args)
+ } catch (e) {
+ console.error('sessionStorage exception', e)
+ return null
+ }
+ })
diff --git a/services/web/frontend/js/services/algolia-search.js b/services/web/frontend/js/services/algolia-search.js
index aa00acece7..1a2b6382a0 100644
--- a/services/web/frontend/js/services/algolia-search.js
+++ b/services/web/frontend/js/services/algolia-search.js
@@ -13,7 +13,7 @@
import App from '../base'
import AlgoliaSearch from 'algoliasearch'
-export default App.factory('algoliaSearch', function() {
+export default App.factory('algoliaSearch', function () {
let kbIdx, wikiIdx
if (
(window.sharelatex != null ? window.sharelatex.algolia : undefined) !=
diff --git a/services/web/frontend/js/services/queued-http.js b/services/web/frontend/js/services/queued-http.js
index dfd67f930d..b00b22744a 100644
--- a/services/web/frontend/js/services/queued-http.js
+++ b/services/web/frontend/js/services/queued-http.js
@@ -12,11 +12,11 @@
*/
import App from '../base'
-export default App.factory('queuedHttp', function($http, $q) {
+export default App.factory('queuedHttp', function ($http, $q) {
const pendingRequests = []
let inflight = false
- var processPendingRequests = function() {
+ var processPendingRequests = function () {
if (inflight) {
return
}
@@ -24,18 +24,18 @@ export default App.factory('queuedHttp', function($http, $q) {
if (doRequest != null) {
inflight = true
return doRequest()
- .then(function() {
+ .then(function () {
inflight = false
return processPendingRequests()
})
- .catch(function() {
+ .catch(function () {
inflight = false
return processPendingRequests()
})
}
}
- const queuedHttp = function(...args) {
+ const queuedHttp = function (...args) {
// We can't use Angular's $q.defer promises, because it only passes
// a single argument on error, and $http passes multiple.
const promise = {}
@@ -43,7 +43,7 @@ export default App.factory('queuedHttp', function($http, $q) {
const errorCallbacks = []
// Adhere to the $http promise conventions
- promise.then = function(callback, errCallback) {
+ promise.then = function (callback, errCallback) {
successCallbacks.push(callback)
if (errCallback != null) {
errorCallbacks.push(errCallback)
@@ -51,7 +51,7 @@ export default App.factory('queuedHttp', function($http, $q) {
return promise
}
- promise.catch = function(callback) {
+ promise.catch = function (callback) {
errorCallbacks.push(callback)
return promise
}
diff --git a/services/web/frontend/js/services/validateCaptcha.js b/services/web/frontend/js/services/validateCaptcha.js
index e7c72bf185..cb9eff84a1 100644
--- a/services/web/frontend/js/services/validateCaptcha.js
+++ b/services/web/frontend/js/services/validateCaptcha.js
@@ -11,9 +11,9 @@
*/
import App from '../base'
-export default App.factory('validateCaptcha', function() {
+export default App.factory('validateCaptcha', function () {
let _recaptchaCallbacks = []
- const onRecaptchaSubmit = function(token) {
+ const onRecaptchaSubmit = function (token) {
for (let cb of _recaptchaCallbacks) {
cb(token)
}
@@ -23,7 +23,7 @@ export default App.factory('validateCaptcha', function() {
let recaptchaId = null
const validateCaptcha = (callback, captchaDisabled) => {
if (callback == null) {
- callback = function(response) {}
+ callback = function (response) {}
}
if (
typeof grecaptcha === 'undefined' ||
diff --git a/services/web/frontend/js/services/validateCaptchaV3.js b/services/web/frontend/js/services/validateCaptchaV3.js
index a4173be3a0..8283f34076 100644
--- a/services/web/frontend/js/services/validateCaptchaV3.js
+++ b/services/web/frontend/js/services/validateCaptchaV3.js
@@ -1,6 +1,6 @@
import App from '../base'
-export default App.factory('validateCaptchaV3', function() {
+export default App.factory('validateCaptchaV3', function () {
const grecaptcha = window.grecaptcha
const ExposedSettings = window.ExposedSettings
return function validateCaptchaV3(actionName, callback = () => {}) {
@@ -10,7 +10,7 @@ export default App.factory('validateCaptchaV3', function() {
if (!ExposedSettings || !ExposedSettings.recaptchaSiteKeyV3) {
return
}
- grecaptcha.ready(function() {
+ grecaptcha.ready(function () {
grecaptcha
.execute(ExposedSettings.recaptchaSiteKeyV3, { action: actionName })
.then(callback)
diff --git a/services/web/frontend/js/services/wait-for.js b/services/web/frontend/js/services/wait-for.js
index d97e68c024..0b3b26d4e4 100644
--- a/services/web/frontend/js/services/wait-for.js
+++ b/services/web/frontend/js/services/wait-for.js
@@ -11,16 +11,16 @@
*/
import App from '../base'
-export default App.factory('waitFor', function($q) {
- const waitFor = function(testFunction, timeout, pollInterval) {
+export default App.factory('waitFor', function ($q) {
+ const waitFor = function (testFunction, timeout, pollInterval) {
if (pollInterval == null) {
pollInterval = 500
}
const iterationLimit = Math.floor(timeout / pollInterval)
let iterations = 0
- return $q(function(resolve, reject) {
+ return $q(function (resolve, reject) {
let tryIteration
- return (tryIteration = function() {
+ return (tryIteration = function () {
if (iterations > iterationLimit) {
return reject(
new Error(
diff --git a/services/web/frontend/js/shared/hooks/use-resize-observer.js b/services/web/frontend/js/shared/hooks/use-resize-observer.js
index 202fa37423..637e21b9b1 100644
--- a/services/web/frontend/js/shared/hooks/use-resize-observer.js
+++ b/services/web/frontend/js/shared/hooks/use-resize-observer.js
@@ -4,7 +4,7 @@ function useResizeObserver(observedElement, observedData, callback) {
const resizeObserver = useRef()
const observe = useCallback(() => {
- resizeObserver.current = new ResizeObserver(function(elementsObserved) {
+ resizeObserver.current = new ResizeObserver(function (elementsObserved) {
callback(elementsObserved[0])
})
}, [callback])
diff --git a/services/web/frontend/stories/file-tree.stories.js b/services/web/frontend/stories/file-tree.stories.js
index 7f3995c64f..6ac59372e1 100644
--- a/services/web/frontend/stories/file-tree.stories.js
+++ b/services/web/frontend/stories/file-tree.stories.js
@@ -41,9 +41,7 @@ function defaultSetupMocks() {
folders: [],
fileRefs: [],
docs: [],
- _id: Math.random()
- .toString(16)
- .replace(/0\./, 'random-test-id-'),
+ _id: Math.random().toString(16).replace(/0\./, 'random-test-id-'),
name: body.name
}
window._ide.socket.socketClient.emit(
diff --git a/services/web/frontend/stories/fixtures/file-tree-limit.js b/services/web/frontend/stories/fixtures/file-tree-limit.js
index 8c10e82a38..e5b507d6c4 100644
--- a/services/web/frontend/stories/fixtures/file-tree-limit.js
+++ b/services/web/frontend/stories/fixtures/file-tree-limit.js
@@ -4,9 +4,7 @@ const FOLDER_PER_FOLDER = 2
const MAX_DEPTH = 7
function fakeId() {
- return Math.random()
- .toString(16)
- .replace(/0\./, 'random-test-id-')
+ return Math.random().toString(16).replace(/0\./, 'random-test-id-')
}
function makeFileRefs(path) {
diff --git a/services/web/frontend/stylesheets/app/editor/pdf.less b/services/web/frontend/stylesheets/app/editor/pdf.less
index 01deaf021e..fd7f110d25 100644
--- a/services/web/frontend/stylesheets/app/editor/pdf.less
+++ b/services/web/frontend/stylesheets/app/editor/pdf.less
@@ -13,6 +13,7 @@
.toolbar-alt-mixin;
padding-right: 5px;
&.changes-to-autocompile {
+ // prettier-ignore
#gradient > .striped(@color: rgba(255, 255, 255, 0.1), @angle: -45deg);
background-size: @stripe-width @stripe-width;
.animation(pdf-toolbar-stripes 2s linear infinite);
@@ -86,6 +87,7 @@
border-radius: 0 @btn-border-radius-base @btn-border-radius-base 0;
background-color: @btn-primary-bg;
&.btn-recompile-group-has-changes {
+ // prettier-ignore
#gradient > .striped(@color: rgba(255, 255, 255, 0.2), @angle: -45deg);
background-size: @stripe-width @stripe-width;
.animation(pdf-toolbar-stripes 2s linear infinite);
diff --git a/services/web/frontend/stylesheets/components/carousel.less b/services/web/frontend/stylesheets/components/carousel.less
index 9fdf49e514..8ee14eaa94 100755
--- a/services/web/frontend/stylesheets/components/carousel.less
+++ b/services/web/frontend/stylesheets/components/carousel.less
@@ -80,6 +80,7 @@
// Set gradients for backgrounds
&.left {
+ // prettier-ignore
#gradient >
.horizontal(
@start-color: rgba(0, 0, 0, 0.5) ; @end-color: rgba(0, 0, 0, 0.0001)
@@ -88,6 +89,7 @@
&.right {
left: auto;
right: 0;
+ // prettier-ignore
#gradient >
.horizontal(
@start-color: rgba(0, 0, 0, 0.0001) ; @end-color: rgba(0, 0, 0, 0.5)
diff --git a/services/web/frontend/stylesheets/components/modals.less b/services/web/frontend/stylesheets/components/modals.less
index 89b22783ff..16a1a89cb5 100755
--- a/services/web/frontend/stylesheets/components/modals.less
+++ b/services/web/frontend/stylesheets/components/modals.less
@@ -123,7 +123,7 @@
background-color: @modal-footer-background-color;
border-radius: 0 0 @border-radius-large @border-radius-large;
&:extend(.clearfix
- all); // clear it in case folks use .pull-* classes on buttons
+ all); // clear it in case folks use .pull-* classes on buttons
// Properly space out buttons
.btn + .btn {
diff --git a/services/web/frontend/stylesheets/components/theme.less b/services/web/frontend/stylesheets/components/theme.less
index aaeaca72bc..28e1914e75 100755
--- a/services/web/frontend/stylesheets/components/theme.less
+++ b/services/web/frontend/stylesheets/components/theme.less
@@ -30,6 +30,7 @@
// Mixin for generating new styles
.btn-styles(@btn-color: #555) {
+ // prettier-ignore
#gradient >
.vertical(@start-color: @btn-color; @end-color: darken(@btn-color, 12%));
.reset-filter(
@@ -97,6 +98,7 @@
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
+ // prettier-ignore
#gradient >
.vertical(
@start-color: @dropdown-link-hover-bg; @end-color:
@@ -107,6 +109,7 @@
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
+ // prettier-ignore
#gradient >
.vertical(
@start-color: @dropdown-link-active-bg; @end-color:
@@ -121,6 +124,7 @@
// Default navbar
.navbar-default {
+ // prettier-ignore
#gradient >
.vertical(
@start-color: lighten(@navbar-default-bg, 10%) ; @end-color:
@@ -135,6 +139,7 @@
.box-shadow(@shadow);
.navbar-nav > .active > a {
+ // prettier-ignore
#gradient >
.vertical(
@start-color: darken(@navbar-default-bg, 5%) ; @end-color:
@@ -150,6 +155,7 @@
// Inverted navbar
.navbar-inverse {
+ // prettier-ignore
#gradient >
.vertical(
@start-color: lighten(@navbar-inverse-bg, 10%) ; @end-color:
@@ -160,6 +166,7 @@
); // Remove gradient in IE<10 to fix bug where dropdowns don't get triggered
.navbar-nav > .active > a {
+ // prettier-ignore
#gradient >
.vertical(
@start-color: @navbar-inverse-bg; @end-color:
@@ -195,6 +202,7 @@
// Mixin for generating new styles
.alert-styles(@color) {
+ // prettier-ignore
#gradient > .vertical(@start-color: @color; @end-color: darken(@color, 7.5%));
border-color: darken(@color, 15%);
}
@@ -219,12 +227,14 @@
// Give the progress background some depth
.progress {
+ // prettier-ignore
#gradient >
.vertical(@start-color: darken(@progress-bg, 4%) ; @end-color: @progress-bg);
}
// Mixin for generating new styles
.progress-bar-styles(@color) {
+ // prettier-ignore
#gradient > .vertical(@start-color: @color; @end-color: darken(@color, 10%));
}
@@ -257,6 +267,7 @@
.list-group-item.active:hover,
.list-group-item.active:focus {
text-shadow: 0 -1px 0 darken(@list-group-active-bg, 10%);
+ // prettier-ignore
#gradient >
.vertical(
@start-color: @list-group-active-bg; @end-color:
@@ -276,6 +287,7 @@
// Mixin for generating new styles
.panel-heading-styles(@color) {
+ // prettier-ignore
#gradient > .vertical(@start-color: @color; @end-color: darken(@color, 5%));
}
@@ -304,6 +316,7 @@
// --------------------------------------------------
.well {
+ // prettier-ignore
#gradient >
.vertical(@start-color: darken(@well-bg, 5%) ; @end-color: @well-bg);
border-color: darken(@well-bg, 10%);
diff --git a/services/web/frontend/stylesheets/core/type.less b/services/web/frontend/stylesheets/core/type.less
index 8496058fb7..6c9e1f3960 100755
--- a/services/web/frontend/stylesheets/core/type.less
+++ b/services/web/frontend/stylesheets/core/type.less
@@ -282,7 +282,7 @@ dd {
dd {
margin-left: @component-offset-horizontal;
&:extend(.clearfix
- all); // Clear the floated `dt` if an empty `dd` is present
+ all); // Clear the floated `dt` if an empty `dd` is present
}
}
}
diff --git a/services/web/karma.conf.js b/services/web/karma.conf.js
index 4e8040e3b0..6c7af4ce25 100644
--- a/services/web/karma.conf.js
+++ b/services/web/karma.conf.js
@@ -1,6 +1,6 @@
const webpackConfig = require('./webpack.config.test')
-module.exports = function(config) {
+module.exports = function (config) {
config.set({
customLaunchers: {
ChromeCustom: {
@@ -56,7 +56,7 @@ module.exports = function(config) {
* Handle fake images
*/
function fakeImgMiddlewareFactory() {
- return function(req, res, next) {
+ return function (req, res, next) {
if (req.originalUrl.startsWith('/fake/')) {
return res.end('fake img response')
}
diff --git a/services/web/modules/launchpad/app/src/LaunchpadController.js b/services/web/modules/launchpad/app/src/LaunchpadController.js
index d88f2a4aa5..ce3f4afecc 100644
--- a/services/web/modules/launchpad/app/src/LaunchpadController.js
+++ b/services/web/modules/launchpad/app/src/LaunchpadController.js
@@ -41,7 +41,7 @@ module.exports = LaunchpadController = {
// * how does all this work with ldap and saml?
const sessionUser = AuthenticationController.getSessionUser(req)
const authMethod = LaunchpadController._getAuthMethod()
- return LaunchpadController._atLeastOneAdminExists(function(
+ return LaunchpadController._atLeastOneAdminExists(function (
err,
adminUserExists
) {
@@ -59,35 +59,36 @@ module.exports = LaunchpadController = {
return res.redirect('/login')
}
} else {
- return UserGetter.getUser(sessionUser._id, { isAdmin: 1 }, function(
- err,
- user
- ) {
- if (err != null) {
- return next(err)
+ return UserGetter.getUser(
+ sessionUser._id,
+ { isAdmin: 1 },
+ function (err, user) {
+ if (err != null) {
+ return next(err)
+ }
+ if (user && user.isAdmin) {
+ return res.render(Path.resolve(__dirname, '../views/launchpad'), {
+ wsUrl: Settings.wsUrl,
+ adminUserExists,
+ authMethod
+ })
+ } else {
+ return res.redirect('/restricted')
+ }
}
- if (user && user.isAdmin) {
- return res.render(Path.resolve(__dirname, '../views/launchpad'), {
- wsUrl: Settings.wsUrl,
- adminUserExists,
- authMethod
- })
- } else {
- return res.redirect('/restricted')
- }
- })
+ )
}
})
},
_atLeastOneAdminExists(callback) {
if (callback == null) {
- callback = function(err, exists) {}
+ callback = function (err, exists) {}
}
return UserGetter.getUser(
{ isAdmin: true },
{ _id: 1, isAdmin: 1 },
- function(err, user) {
+ function (err, user) {
if (err != null) {
return callback(err)
}
@@ -104,7 +105,7 @@ module.exports = LaunchpadController = {
}
logger.log({ email }, 'sending test email')
const emailOptions = { to: email }
- return EmailHandler.sendEmail('testEmail', emailOptions, function(err) {
+ return EmailHandler.sendEmail('testEmail', emailOptions, function (err) {
if (err != null) {
OError.tag(err, 'error sending test email', {
email
@@ -117,7 +118,7 @@ module.exports = LaunchpadController = {
},
registerExternalAuthAdmin(authMethod) {
- return function(req, res, next) {
+ return function (req, res, next) {
if (LaunchpadController._getAuthMethod() !== authMethod) {
logger.log(
{ authMethod },
@@ -132,7 +133,7 @@ module.exports = LaunchpadController = {
}
logger.log({ email }, 'attempted register first admin user')
- return LaunchpadController._atLeastOneAdminExists(function(err, exists) {
+ return LaunchpadController._atLeastOneAdminExists(function (err, exists) {
if (err != null) {
return next(err)
}
@@ -156,42 +157,42 @@ module.exports = LaunchpadController = {
'creating admin account for specified external-auth user'
)
- return UserRegistrationHandler.registerNewUser(body, function(
- err,
- user
- ) {
- if (err != null) {
- OError.tag(err, 'error with registerNewUser', {
- email,
- authMethod
- })
- return next(err)
- }
-
- return User.updateOne(
- { _id: user._id },
- {
- $set: { isAdmin: true },
- emails: [{ email }]
- },
- function(err) {
- if (err != null) {
- OError.tag(err, 'error setting user to admin', {
- user_id: user._id
- })
- return next(err)
- }
-
- AuthenticationController.setRedirectInSession(req, '/launchpad')
- logger.log(
- { email, user_id: user._id, authMethod },
- 'created first admin account'
- )
-
- return res.json({ redir: '/launchpad', email })
+ return UserRegistrationHandler.registerNewUser(
+ body,
+ function (err, user) {
+ if (err != null) {
+ OError.tag(err, 'error with registerNewUser', {
+ email,
+ authMethod
+ })
+ return next(err)
}
- )
- })
+
+ return User.updateOne(
+ { _id: user._id },
+ {
+ $set: { isAdmin: true },
+ emails: [{ email }]
+ },
+ function (err) {
+ if (err != null) {
+ OError.tag(err, 'error setting user to admin', {
+ user_id: user._id
+ })
+ return next(err)
+ }
+
+ AuthenticationController.setRedirectInSession(req, '/launchpad')
+ logger.log(
+ { email, user_id: user._id, authMethod },
+ 'created first admin account'
+ )
+
+ return res.json({ redir: '/launchpad', email })
+ }
+ )
+ }
+ )
})
}
},
@@ -205,7 +206,7 @@ module.exports = LaunchpadController = {
}
logger.log({ email }, 'attempted register first admin user')
- return LaunchpadController._atLeastOneAdminExists(function(err, exists) {
+ return LaunchpadController._atLeastOneAdminExists(function (err, exists) {
if (err != null) {
return next(err)
}
@@ -219,44 +220,47 @@ module.exports = LaunchpadController = {
}
const body = { email, password }
- return UserRegistrationHandler.registerNewUser(body, function(err, user) {
- if (err != null) {
- return next(err)
- }
-
- logger.log({ user_id: user._id }, 'making user an admin')
- User.updateOne(
- { _id: user._id },
- {
- $set: {
- isAdmin: true,
- emails: [{ email }]
- }
- },
- function(err) {
- if (err != null) {
- OError.tag(err, 'error setting user to admin', {
- user_id: user._id
- })
- return next(err)
- }
-
- AuthenticationController.setRedirectInSession(req, '/launchpad')
- logger.log(
- { email, user_id: user._id },
- 'created first admin account'
- )
- return res.json({
- redir: '',
- id: user._id.toString(),
- first_name: user.first_name,
- last_name: user.last_name,
- email: user.email,
- created: Date.now()
- })
+ return UserRegistrationHandler.registerNewUser(
+ body,
+ function (err, user) {
+ if (err != null) {
+ return next(err)
}
- )
- })
+
+ logger.log({ user_id: user._id }, 'making user an admin')
+ User.updateOne(
+ { _id: user._id },
+ {
+ $set: {
+ isAdmin: true,
+ emails: [{ email }]
+ }
+ },
+ function (err) {
+ if (err != null) {
+ OError.tag(err, 'error setting user to admin', {
+ user_id: user._id
+ })
+ return next(err)
+ }
+
+ AuthenticationController.setRedirectInSession(req, '/launchpad')
+ logger.log(
+ { email, user_id: user._id },
+ 'created first admin account'
+ )
+ return res.json({
+ redir: '',
+ id: user._id.toString(),
+ first_name: user.first_name,
+ last_name: user.last_name,
+ email: user.email,
+ created: Date.now()
+ })
+ }
+ )
+ }
+ )
})
}
}
diff --git a/services/web/modules/launchpad/frontend/js/main/controllers/LaunchpadController.js b/services/web/modules/launchpad/frontend/js/main/controllers/LaunchpadController.js
index 22615064c1..ca78bd12ac 100644
--- a/services/web/modules/launchpad/frontend/js/main/controllers/LaunchpadController.js
+++ b/services/web/modules/launchpad/frontend/js/main/controllers/LaunchpadController.js
@@ -14,145 +14,144 @@
*/
import App from '../../../../../../frontend/js/base'
-export default App.controller('LaunchpadController', function(
- $scope,
- $http,
- $timeout
-) {
- $scope.adminUserExists = window.data.adminUserExists
- $scope.ideJsPath = window.data.ideJsPath
- $scope.authMethod = window.data.authMethod
+export default App.controller(
+ 'LaunchpadController',
+ function ($scope, $http, $timeout) {
+ $scope.adminUserExists = window.data.adminUserExists
+ $scope.ideJsPath = window.data.ideJsPath
+ $scope.authMethod = window.data.authMethod
- $scope.createAdminSuccess = null
- $scope.createAdminError = null
+ $scope.createAdminSuccess = null
+ $scope.createAdminError = null
- $scope.statusChecks = {
- ideJs: { status: 'inflight', error: null },
- websocket: { status: 'inflight', error: null },
- healthCheck: { status: 'inflight', error: null }
- }
+ $scope.statusChecks = {
+ ideJs: { status: 'inflight', error: null },
+ websocket: { status: 'inflight', error: null },
+ healthCheck: { status: 'inflight', error: null }
+ }
- $scope.testEmail = {
- emailAddress: '',
- inflight: false,
- status: null // | 'ok' | 'success'
- }
+ $scope.testEmail = {
+ emailAddress: '',
+ inflight: false,
+ status: null // | 'ok' | 'success'
+ }
- $scope.shouldShowAdminForm = () => !$scope.adminUserExists
+ $scope.shouldShowAdminForm = () => !$scope.adminUserExists
- $scope.onCreateAdminSuccess = function(response) {
- const { status } = response
- if (status >= 200 && status < 300) {
- return ($scope.createAdminSuccess = true)
+ $scope.onCreateAdminSuccess = function (response) {
+ const { status } = response
+ if (status >= 200 && status < 300) {
+ return ($scope.createAdminSuccess = true)
+ }
+ }
+
+ $scope.onCreateAdminError = () => ($scope.createAdminError = true)
+
+ $scope.sendTestEmail = function () {
+ $scope.testEmail.inflight = true
+ $scope.testEmail.status = null
+ return $http
+ .post('/launchpad/send_test_email', {
+ email: $scope.testEmail.emailAddress,
+ _csrf: window.csrfToken
+ })
+ .then(function (response) {
+ const { status } = response
+ $scope.testEmail.inflight = false
+ if (status >= 200 && status < 300) {
+ return ($scope.testEmail.status = 'ok')
+ }
+ })
+ .catch(function () {
+ $scope.testEmail.inflight = false
+ return ($scope.testEmail.status = 'error')
+ })
+ }
+
+ $scope.tryFetchIdeJs = function () {
+ $scope.statusChecks.ideJs.status = 'inflight'
+ return $timeout(
+ () =>
+ $http
+ .get($scope.ideJsPath)
+ .then(function (response) {
+ const { status } = response
+ if (status >= 200 && status < 300) {
+ return ($scope.statusChecks.ideJs.status = 'ok')
+ }
+ })
+ .catch(function (response) {
+ const { status } = response
+ $scope.statusChecks.ideJs.status = 'error'
+ return ($scope.statusChecks.ideJs.error = new Error(
+ `Http status: ${status}`
+ ))
+ }),
+
+ 1000
+ )
+ }
+
+ $scope.tryOpenWebSocket = function () {
+ $scope.statusChecks.websocket.status = 'inflight'
+ return $timeout(function () {
+ if (typeof io === 'undefined' || io === null) {
+ $scope.statusChecks.websocket.status = 'error'
+ $scope.statusChecks.websocket.error = 'socket.io not loaded'
+ return
+ }
+ const socket = io.connect(null, {
+ reconnect: false,
+ 'connect timeout': 30 * 1000,
+ 'force new connection': true
+ })
+
+ socket.on('connectionAccepted', function () {
+ $scope.statusChecks.websocket.status = 'ok'
+ return $scope.$apply(function () {})
+ })
+
+ socket.on('connectionRejected', function (err) {
+ $scope.statusChecks.websocket.status = 'error'
+ $scope.statusChecks.websocket.error = err
+ return $scope.$apply(function () {})
+ })
+
+ return socket.on('connect_failed', function (err) {
+ $scope.statusChecks.websocket.status = 'error'
+ $scope.statusChecks.websocket.error = err
+ return $scope.$apply(function () {})
+ })
+ }, 1000)
+ }
+
+ $scope.tryHealthCheck = function () {
+ $scope.statusChecks.healthCheck.status = 'inflight'
+ return $http
+ .get('/health_check')
+ .then(function (response) {
+ const { status } = response
+ if (status >= 200 && status < 300) {
+ return ($scope.statusChecks.healthCheck.status = 'ok')
+ }
+ })
+ .catch(function (response) {
+ const { status } = response
+ $scope.statusChecks.healthCheck.status = 'error'
+ return ($scope.statusChecks.healthCheck.error = new Error(
+ `Http status: ${status}`
+ ))
+ })
+ }
+
+ $scope.runStatusChecks = function () {
+ $timeout(() => $scope.tryFetchIdeJs(), 1000)
+ return $timeout(() => $scope.tryOpenWebSocket(), 2000)
+ }
+
+ // kick off the status checks on load
+ if ($scope.adminUserExists) {
+ return $scope.runStatusChecks()
}
}
-
- $scope.onCreateAdminError = () => ($scope.createAdminError = true)
-
- $scope.sendTestEmail = function() {
- $scope.testEmail.inflight = true
- $scope.testEmail.status = null
- return $http
- .post('/launchpad/send_test_email', {
- email: $scope.testEmail.emailAddress,
- _csrf: window.csrfToken
- })
- .then(function(response) {
- const { status } = response
- $scope.testEmail.inflight = false
- if (status >= 200 && status < 300) {
- return ($scope.testEmail.status = 'ok')
- }
- })
- .catch(function() {
- $scope.testEmail.inflight = false
- return ($scope.testEmail.status = 'error')
- })
- }
-
- $scope.tryFetchIdeJs = function() {
- $scope.statusChecks.ideJs.status = 'inflight'
- return $timeout(
- () =>
- $http
- .get($scope.ideJsPath)
- .then(function(response) {
- const { status } = response
- if (status >= 200 && status < 300) {
- return ($scope.statusChecks.ideJs.status = 'ok')
- }
- })
- .catch(function(response) {
- const { status } = response
- $scope.statusChecks.ideJs.status = 'error'
- return ($scope.statusChecks.ideJs.error = new Error(
- `Http status: ${status}`
- ))
- }),
-
- 1000
- )
- }
-
- $scope.tryOpenWebSocket = function() {
- $scope.statusChecks.websocket.status = 'inflight'
- return $timeout(function() {
- if (typeof io === 'undefined' || io === null) {
- $scope.statusChecks.websocket.status = 'error'
- $scope.statusChecks.websocket.error = 'socket.io not loaded'
- return
- }
- const socket = io.connect(null, {
- reconnect: false,
- 'connect timeout': 30 * 1000,
- 'force new connection': true
- })
-
- socket.on('connectionAccepted', function() {
- $scope.statusChecks.websocket.status = 'ok'
- return $scope.$apply(function() {})
- })
-
- socket.on('connectionRejected', function(err) {
- $scope.statusChecks.websocket.status = 'error'
- $scope.statusChecks.websocket.error = err
- return $scope.$apply(function() {})
- })
-
- return socket.on('connect_failed', function(err) {
- $scope.statusChecks.websocket.status = 'error'
- $scope.statusChecks.websocket.error = err
- return $scope.$apply(function() {})
- })
- }, 1000)
- }
-
- $scope.tryHealthCheck = function() {
- $scope.statusChecks.healthCheck.status = 'inflight'
- return $http
- .get('/health_check')
- .then(function(response) {
- const { status } = response
- if (status >= 200 && status < 300) {
- return ($scope.statusChecks.healthCheck.status = 'ok')
- }
- })
- .catch(function(response) {
- const { status } = response
- $scope.statusChecks.healthCheck.status = 'error'
- return ($scope.statusChecks.healthCheck.error = new Error(
- `Http status: ${status}`
- ))
- })
- }
-
- $scope.runStatusChecks = function() {
- $timeout(() => $scope.tryFetchIdeJs(), 1000)
- return $timeout(() => $scope.tryOpenWebSocket(), 2000)
- }
-
- // kick off the status checks on load
- if ($scope.adminUserExists) {
- return $scope.runStatusChecks()
- }
-})
+)
diff --git a/services/web/modules/launchpad/test/unit/src/LaunchpadControllerTests.js b/services/web/modules/launchpad/test/unit/src/LaunchpadControllerTests.js
index 7ca3559f30..654dc0d464 100644
--- a/services/web/modules/launchpad/test/unit/src/LaunchpadControllerTests.js
+++ b/services/web/modules/launchpad/test/unit/src/LaunchpadControllerTests.js
@@ -19,8 +19,8 @@ const modulePath = require('path').join(
'../../../app/src/LaunchpadController.js'
)
-describe('LaunchpadController', function() {
- beforeEach(function() {
+describe('LaunchpadController', function () {
+ beforeEach(function () {
this.user = {
_id: '323123',
first_name: 'fn',
@@ -59,8 +59,8 @@ describe('LaunchpadController', function() {
return (this.next = sinon.stub())
})
- describe('launchpadPage', function() {
- beforeEach(function() {
+ describe('launchpadPage', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists = sinon.stub(
this.LaunchpadController,
'_atLeastOneAdminExists'
@@ -68,20 +68,20 @@ describe('LaunchpadController', function() {
return (this.AuthenticationController.setRedirectInSession = sinon.stub())
})
- afterEach(function() {
+ afterEach(function () {
return this._atLeastOneAdminExists.restore()
})
- describe('when the user is not logged in', function() {
- beforeEach(function() {
+ describe('when the user is not logged in', function () {
+ beforeEach(function () {
this.AuthenticationController.getSessionUser = sinon
.stub()
.returns(null)
return (this.res.render = sinon.stub())
})
- describe('when there are no admins', function() {
- beforeEach(function() {
+ describe('when there are no admins', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
return this.LaunchpadController.launchpadPage(
this.req,
@@ -90,7 +90,7 @@ describe('LaunchpadController', function() {
)
})
- it('should render the launchpad page', function() {
+ it('should render the launchpad page', function () {
const viewPath = require('path').join(
__dirname,
'../../../app/views/launchpad'
@@ -105,8 +105,8 @@ describe('LaunchpadController', function() {
})
})
- describe('when there is at least one admin', function() {
- beforeEach(function() {
+ describe('when there is at least one admin', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, true)
return this.LaunchpadController.launchpadPage(
this.req,
@@ -115,21 +115,21 @@ describe('LaunchpadController', function() {
)
})
- it('should redirect to login page', function() {
+ it('should redirect to login page', function () {
this.AuthenticationController.setRedirectInSession.callCount.should.equal(
1
)
this.res.redirect.calledWith('/login').should.equal(true)
})
- it('should not render the launchpad page', function() {
+ it('should not render the launchpad page', function () {
return this.res.render.callCount.should.equal(0)
})
})
})
- describe('when the user is logged in', function() {
- beforeEach(function() {
+ describe('when the user is logged in', function () {
+ beforeEach(function () {
this.user = {
_id: 'abcd',
email: 'abcd@example.com'
@@ -142,8 +142,8 @@ describe('LaunchpadController', function() {
return (this.res.redirect = sinon.stub())
})
- describe('when the user is an admin', function() {
- beforeEach(function() {
+ describe('when the user is an admin', function () {
+ beforeEach(function () {
this.UserGetter.getUser = sinon
.stub()
.callsArgWith(2, null, { isAdmin: true })
@@ -154,7 +154,7 @@ describe('LaunchpadController', function() {
)
})
- it('should render the launchpad page', function() {
+ it('should render the launchpad page', function () {
const viewPath = require('path').join(
__dirname,
'../../../app/views/launchpad'
@@ -170,8 +170,8 @@ describe('LaunchpadController', function() {
})
})
- describe('when the user is not an admin', function() {
- beforeEach(function() {
+ describe('when the user is not an admin', function () {
+ beforeEach(function () {
this.UserGetter.getUser = sinon
.stub()
.callsArgWith(2, null, { isAdmin: false })
@@ -182,7 +182,7 @@ describe('LaunchpadController', function() {
)
})
- it('should redirect to restricted page', function() {
+ it('should redirect to restricted page', function () {
this.res.redirect.callCount.should.equal(1)
return this.res.redirect.calledWith('/restricted').should.equal(true)
})
@@ -190,15 +190,15 @@ describe('LaunchpadController', function() {
})
})
- describe('_atLeastOneAdminExists', function() {
- describe('when there are no admins', function() {
- beforeEach(function() {
+ describe('_atLeastOneAdminExists', function () {
+ describe('when there are no admins', function () {
+ beforeEach(function () {
return (this.UserGetter.getUser = sinon
.stub()
.callsArgWith(2, null, null))
})
- it('should callback with false', function(done) {
+ it('should callback with false', function (done) {
return this.LaunchpadController._atLeastOneAdminExists(
(err, exists) => {
expect(err).to.equal(null)
@@ -209,14 +209,14 @@ describe('LaunchpadController', function() {
})
})
- describe('when there are some admins', function() {
- beforeEach(function() {
+ describe('when there are some admins', function () {
+ beforeEach(function () {
return (this.UserGetter.getUser = sinon
.stub()
.callsArgWith(2, null, { _id: 'abcd' }))
})
- it('should callback with true', function(done) {
+ it('should callback with true', function (done) {
return this.LaunchpadController._atLeastOneAdminExists(
(err, exists) => {
expect(err).to.equal(null)
@@ -227,14 +227,14 @@ describe('LaunchpadController', function() {
})
})
- describe('when getUser produces an error', function() {
- beforeEach(function() {
+ describe('when getUser produces an error', function () {
+ beforeEach(function () {
return (this.UserGetter.getUser = sinon
.stub()
.callsArgWith(2, new Error('woops')))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.LaunchpadController._atLeastOneAdminExists(
(err, exists) => {
expect(err).to.not.equal(null)
@@ -247,26 +247,26 @@ describe('LaunchpadController', function() {
})
})
- describe('sendTestEmail', function() {
- beforeEach(function() {
+ describe('sendTestEmail', function () {
+ beforeEach(function () {
this.EmailHandler.sendEmail = sinon.stub().callsArgWith(2, null)
this.req.body.email = 'someone@example.com'
this.res.sendStatus = sinon.stub()
return (this.next = sinon.stub())
})
- it('should produce a 201 response', function() {
+ it('should produce a 201 response', function () {
this.LaunchpadController.sendTestEmail(this.req, this.res, this.next)
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(201).should.equal(true)
})
- it('should not call next with an error', function() {
+ it('should not call next with an error', function () {
this.LaunchpadController.sendTestEmail(this.req, this.res, this.next)
return this.next.callCount.should.equal(0)
})
- it('should have called sendEmail', function() {
+ it('should have called sendEmail', function () {
this.LaunchpadController.sendTestEmail(this.req, this.res, this.next)
this.EmailHandler.sendEmail.callCount.should.equal(1)
return this.EmailHandler.sendEmail
@@ -274,26 +274,26 @@ describe('LaunchpadController', function() {
.should.equal(true)
})
- describe('when sendEmail produces an error', function() {
- beforeEach(function() {
+ describe('when sendEmail produces an error', function () {
+ beforeEach(function () {
return (this.EmailHandler.sendEmail = sinon
.stub()
.callsArgWith(2, new Error('woops')))
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.LaunchpadController.sendTestEmail(this.req, this.res, this.next)
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
})
- describe('when no email address is supplied', function() {
- beforeEach(function() {
+ describe('when no email address is supplied', function () {
+ beforeEach(function () {
return (this.req.body.email = undefined)
})
- it('should produce a 400 response', function() {
+ it('should produce a 400 response', function () {
this.LaunchpadController.sendTestEmail(this.req, this.res, this.next)
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(400).should.equal(true)
@@ -301,20 +301,20 @@ describe('LaunchpadController', function() {
})
})
- describe('registerAdmin', function() {
- beforeEach(function() {
+ describe('registerAdmin', function () {
+ beforeEach(function () {
return (this._atLeastOneAdminExists = sinon.stub(
this.LaunchpadController,
'_atLeastOneAdminExists'
))
})
- afterEach(function() {
+ afterEach(function () {
return this._atLeastOneAdminExists.restore()
})
- describe('when all goes well', function() {
- beforeEach(function() {
+ describe('when all goes well', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
this.email = 'someone@example.com'
this.password = 'a_really_bad_password'
@@ -338,23 +338,23 @@ describe('LaunchpadController', function() {
)
})
- it('should send back a json response', function() {
+ it('should send back a json response', function () {
this.res.json.callCount.should.equal(1)
return expect(this.res.json.lastCall.args[0].email).to.equal(this.email)
})
- it('should have checked for existing admins', function() {
+ it('should have checked for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(1)
})
- it('should have called registerNewUser', function() {
+ it('should have called registerNewUser', function () {
this.UserRegistrationHandler.registerNewUser.callCount.should.equal(1)
return this.UserRegistrationHandler.registerNewUser
.calledWith({ email: this.email, password: this.password })
.should.equal(true)
})
- it('should have updated the user to make them an admin', function() {
+ it('should have updated the user to make them an admin', function () {
this.User.updateOne.callCount.should.equal(1)
return this.User.updateOne
.calledWithMatch(
@@ -369,7 +369,7 @@ describe('LaunchpadController', function() {
.should.equal(true)
})
- it('should have set a redirect in session', function() {
+ it('should have set a redirect in session', function () {
this.AuthenticationController.setRedirectInSession.callCount.should.equal(
1
)
@@ -379,8 +379,8 @@ describe('LaunchpadController', function() {
})
})
- describe('when no email is supplied', function() {
- beforeEach(function() {
+ describe('when no email is supplied', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
this.email = undefined
this.password = 'a_really_bad_password'
@@ -402,24 +402,24 @@ describe('LaunchpadController', function() {
)
})
- it('should send a 400 response', function() {
+ it('should send a 400 response', function () {
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(400).should.equal(true)
})
- it('should not check for existing admins', function() {
+ it('should not check for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(0)
})
- it('should not call registerNewUser', function() {
+ it('should not call registerNewUser', function () {
return this.UserRegistrationHandler.registerNewUser.callCount.should.equal(
0
)
})
})
- describe('when no password is supplied', function() {
- beforeEach(function() {
+ describe('when no password is supplied', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
this.email = 'someone@example.com'
this.password = undefined
@@ -441,24 +441,24 @@ describe('LaunchpadController', function() {
)
})
- it('should send a 400 response', function() {
+ it('should send a 400 response', function () {
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(400).should.equal(true)
})
- it('should not check for existing admins', function() {
+ it('should not check for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(0)
})
- it('should not call registerNewUser', function() {
+ it('should not call registerNewUser', function () {
return this.UserRegistrationHandler.registerNewUser.callCount.should.equal(
0
)
})
})
- describe('when there are already existing admins', function() {
- beforeEach(function() {
+ describe('when there are already existing admins', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, true)
this.email = 'someone@example.com'
this.password = 'a_really_bad_password'
@@ -480,20 +480,20 @@ describe('LaunchpadController', function() {
)
})
- it('should send a 403 response', function() {
+ it('should send a 403 response', function () {
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(403).should.equal(true)
})
- it('should not call registerNewUser', function() {
+ it('should not call registerNewUser', function () {
return this.UserRegistrationHandler.registerNewUser.callCount.should.equal(
0
)
})
})
- describe('when checking admins produces an error', function() {
- beforeEach(function() {
+ describe('when checking admins produces an error', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, new Error('woops'))
this.email = 'someone@example.com'
this.password = 'a_really_bad_password'
@@ -515,24 +515,24 @@ describe('LaunchpadController', function() {
)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
- it('should have checked for existing admins', function() {
+ it('should have checked for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(1)
})
- it('should not call registerNewUser', function() {
+ it('should not call registerNewUser', function () {
return this.UserRegistrationHandler.registerNewUser.callCount.should.equal(
0
)
})
})
- describe('when registerNewUser produces an error', function() {
- beforeEach(function() {
+ describe('when registerNewUser produces an error', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
this.email = 'someone@example.com'
this.password = 'a_really_bad_password'
@@ -556,29 +556,29 @@ describe('LaunchpadController', function() {
)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
- it('should have checked for existing admins', function() {
+ it('should have checked for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(1)
})
- it('should have called registerNewUser', function() {
+ it('should have called registerNewUser', function () {
this.UserRegistrationHandler.registerNewUser.callCount.should.equal(1)
return this.UserRegistrationHandler.registerNewUser
.calledWith({ email: this.email, password: this.password })
.should.equal(true)
})
- it('should not call update', function() {
+ it('should not call update', function () {
return this.User.updateOne.callCount.should.equal(0)
})
})
- describe('when user update produces an error', function() {
- beforeEach(function() {
+ describe('when user update produces an error', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
this.email = 'someone@example.com'
this.password = 'a_really_bad_password'
@@ -602,16 +602,16 @@ describe('LaunchpadController', function() {
)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
- it('should have checked for existing admins', function() {
+ it('should have checked for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(1)
})
- it('should have called registerNewUser', function() {
+ it('should have called registerNewUser', function () {
this.UserRegistrationHandler.registerNewUser.callCount.should.equal(1)
return this.UserRegistrationHandler.registerNewUser
.calledWith({ email: this.email, password: this.password })
@@ -619,8 +619,8 @@ describe('LaunchpadController', function() {
})
})
- describe('when overleaf', function() {
- beforeEach(function() {
+ describe('when overleaf', function () {
+ beforeEach(function () {
this.Settings.overleaf = { one: 1 }
this.Settings.createV1AccountOnLogin = true
this._atLeastOneAdminExists.callsArgWith(0, null, false)
@@ -649,23 +649,23 @@ describe('LaunchpadController', function() {
)
})
- it('should send back a json response', function() {
+ it('should send back a json response', function () {
this.res.json.callCount.should.equal(1)
return expect(this.res.json.lastCall.args[0].email).to.equal(this.email)
})
- it('should have checked for existing admins', function() {
+ it('should have checked for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(1)
})
- it('should have called registerNewUser', function() {
+ it('should have called registerNewUser', function () {
this.UserRegistrationHandler.registerNewUser.callCount.should.equal(1)
return this.UserRegistrationHandler.registerNewUser
.calledWith({ email: this.email, password: this.password })
.should.equal(true)
})
- it('should have updated the user to make them an admin', function() {
+ it('should have updated the user to make them an admin', function () {
return this.User.updateOne
.calledWith(
{ _id: this.user._id },
@@ -679,7 +679,7 @@ describe('LaunchpadController', function() {
.should.equal(true)
})
- it('should have set a redirect in session', function() {
+ it('should have set a redirect in session', function () {
this.AuthenticationController.setRedirectInSession.callCount.should.equal(
1
)
@@ -690,8 +690,8 @@ describe('LaunchpadController', function() {
})
})
- describe('registerExternalAuthAdmin', function() {
- beforeEach(function() {
+ describe('registerExternalAuthAdmin', function () {
+ beforeEach(function () {
this.Settings.ldap = { one: 1 }
return (this._atLeastOneAdminExists = sinon.stub(
this.LaunchpadController,
@@ -699,12 +699,12 @@ describe('LaunchpadController', function() {
))
})
- afterEach(function() {
+ afterEach(function () {
return this._atLeastOneAdminExists.restore()
})
- describe('when all goes well', function() {
- beforeEach(function() {
+ describe('when all goes well', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
this.email = 'someone@example.com'
this.req.body.email = this.email
@@ -726,16 +726,16 @@ describe('LaunchpadController', function() {
)
})
- it('should send back a json response', function() {
+ it('should send back a json response', function () {
this.res.json.callCount.should.equal(1)
return expect(this.res.json.lastCall.args[0].email).to.equal(this.email)
})
- it('should have checked for existing admins', function() {
+ it('should have checked for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(1)
})
- it('should have called registerNewUser', function() {
+ it('should have called registerNewUser', function () {
this.UserRegistrationHandler.registerNewUser.callCount.should.equal(1)
return this.UserRegistrationHandler.registerNewUser
.calledWith({
@@ -747,7 +747,7 @@ describe('LaunchpadController', function() {
.should.equal(true)
})
- it('should have updated the user to make them an admin', function() {
+ it('should have updated the user to make them an admin', function () {
this.User.updateOne.callCount.should.equal(1)
return this.User.updateOne
.calledWith(
@@ -760,7 +760,7 @@ describe('LaunchpadController', function() {
.should.equal(true)
})
- it('should have set a redirect in session', function() {
+ it('should have set a redirect in session', function () {
this.AuthenticationController.setRedirectInSession.callCount.should.equal(
1
)
@@ -770,8 +770,8 @@ describe('LaunchpadController', function() {
})
})
- describe('when the authMethod is invalid', function() {
- beforeEach(function() {
+ describe('when the authMethod is invalid', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
this.email = undefined
this.req.body.email = this.email
@@ -789,24 +789,24 @@ describe('LaunchpadController', function() {
)(this.req, this.res, this.next)
})
- it('should send a 403 response', function() {
+ it('should send a 403 response', function () {
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(403).should.equal(true)
})
- it('should not check for existing admins', function() {
+ it('should not check for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(0)
})
- it('should not call registerNewUser', function() {
+ it('should not call registerNewUser', function () {
return this.UserRegistrationHandler.registerNewUser.callCount.should.equal(
0
)
})
})
- describe('when no email is supplied', function() {
- beforeEach(function() {
+ describe('when no email is supplied', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
this.email = undefined
this.req.body.email = this.email
@@ -826,24 +826,24 @@ describe('LaunchpadController', function() {
)
})
- it('should send a 400 response', function() {
+ it('should send a 400 response', function () {
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(400).should.equal(true)
})
- it('should not check for existing admins', function() {
+ it('should not check for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(0)
})
- it('should not call registerNewUser', function() {
+ it('should not call registerNewUser', function () {
return this.UserRegistrationHandler.registerNewUser.callCount.should.equal(
0
)
})
})
- describe('when there are already existing admins', function() {
- beforeEach(function() {
+ describe('when there are already existing admins', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, true)
this.email = 'someone@example.com'
this.req.body.email = this.email
@@ -863,20 +863,20 @@ describe('LaunchpadController', function() {
)
})
- it('should send a 403 response', function() {
+ it('should send a 403 response', function () {
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(403).should.equal(true)
})
- it('should not call registerNewUser', function() {
+ it('should not call registerNewUser', function () {
return this.UserRegistrationHandler.registerNewUser.callCount.should.equal(
0
)
})
})
- describe('when checking admins produces an error', function() {
- beforeEach(function() {
+ describe('when checking admins produces an error', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, new Error('woops'))
this.email = 'someone@example.com'
this.req.body.email = this.email
@@ -896,24 +896,24 @@ describe('LaunchpadController', function() {
)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
- it('should have checked for existing admins', function() {
+ it('should have checked for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(1)
})
- it('should not call registerNewUser', function() {
+ it('should not call registerNewUser', function () {
return this.UserRegistrationHandler.registerNewUser.callCount.should.equal(
0
)
})
})
- describe('when registerNewUser produces an error', function() {
- beforeEach(function() {
+ describe('when registerNewUser produces an error', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
this.email = 'someone@example.com'
this.req.body.email = this.email
@@ -935,16 +935,16 @@ describe('LaunchpadController', function() {
)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
- it('should have checked for existing admins', function() {
+ it('should have checked for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(1)
})
- it('should have called registerNewUser', function() {
+ it('should have called registerNewUser', function () {
this.UserRegistrationHandler.registerNewUser.callCount.should.equal(1)
return this.UserRegistrationHandler.registerNewUser
.calledWith({
@@ -956,13 +956,13 @@ describe('LaunchpadController', function() {
.should.equal(true)
})
- it('should not call update', function() {
+ it('should not call update', function () {
return this.User.updateOne.callCount.should.equal(0)
})
})
- describe('when user update produces an error', function() {
- beforeEach(function() {
+ describe('when user update produces an error', function () {
+ beforeEach(function () {
this._atLeastOneAdminExists.callsArgWith(0, null, false)
this.email = 'someone@example.com'
this.req.body.email = this.email
@@ -984,16 +984,16 @@ describe('LaunchpadController', function() {
)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
- it('should have checked for existing admins', function() {
+ it('should have checked for existing admins', function () {
return this._atLeastOneAdminExists.callCount.should.equal(1)
})
- it('should have called registerNewUser', function() {
+ it('should have called registerNewUser', function () {
this.UserRegistrationHandler.registerNewUser.callCount.should.equal(1)
return this.UserRegistrationHandler.registerNewUser
.calledWith({
diff --git a/services/web/modules/modules-ide.js b/services/web/modules/modules-ide.js
index 94c758d9fb..537f27829c 100644
--- a/services/web/modules/modules-ide.js
+++ b/services/web/modules/modules-ide.js
@@ -18,7 +18,7 @@ if (fs.existsSync(MODULES_PATH)) {
}, entryPoints)
}
-module.exports = function() {
+module.exports = function () {
return {
code: entryPoints.map(entryPoint => `import '${entryPoint}'`).join('\n')
}
diff --git a/services/web/modules/modules-main.js b/services/web/modules/modules-main.js
index d30aa39b58..e565f82bc2 100644
--- a/services/web/modules/modules-main.js
+++ b/services/web/modules/modules-main.js
@@ -18,7 +18,7 @@ if (fs.existsSync(MODULES_PATH)) {
}, entryPoints)
}
-module.exports = function() {
+module.exports = function () {
return {
code: entryPoints.map(entryPoint => `import '${entryPoint}'`).join('\n')
}
diff --git a/services/web/modules/user-activate/test/unit/src/UserActivateControllerTests.js b/services/web/modules/user-activate/test/unit/src/UserActivateControllerTests.js
index 59ed17ea9a..dc5ba4d322 100644
--- a/services/web/modules/user-activate/test/unit/src/UserActivateControllerTests.js
+++ b/services/web/modules/user-activate/test/unit/src/UserActivateControllerTests.js
@@ -8,8 +8,8 @@ const MODULE_PATH = Path.join(
)
const VIEW_PATH = Path.join(__dirname, '../../../app/views/user/activate')
-describe('UserActivateController', function() {
- beforeEach(function() {
+describe('UserActivateController', function () {
+ beforeEach(function () {
this.user = {
_id: (this.user_id = 'kwjewkl'),
features: {},
@@ -34,38 +34,38 @@ describe('UserActivateController', function() {
this.res = {}
})
- describe('activateAccountPage', function() {
- beforeEach(function() {
+ describe('activateAccountPage', function () {
+ beforeEach(function () {
this.UserGetter.getUser = sinon.stub().callsArgWith(2, null, this.user)
this.req.query.user_id = this.user_id
this.req.query.token = this.token = 'mock-token-123'
})
- it('should 404 without a user_id', function(done) {
+ it('should 404 without a user_id', function (done) {
delete this.req.query.user_id
this.ErrorController.notFound = () => done()
this.UserActivateController.activateAccountPage(this.req, this.res)
})
- it('should 404 without a token', function(done) {
+ it('should 404 without a token', function (done) {
delete this.req.query.token
this.ErrorController.notFound = () => done()
this.UserActivateController.activateAccountPage(this.req, this.res)
})
- it('should 404 without a valid user_id', function(done) {
+ it('should 404 without a valid user_id', function (done) {
this.UserGetter.getUser = sinon.stub().callsArgWith(2, null, null)
this.ErrorController.notFound = () => done()
this.UserActivateController.activateAccountPage(this.req, this.res)
})
- it('should 403 for complex user_id', function(done) {
+ it('should 403 for complex user_id', function (done) {
this.ErrorController.forbidden = () => done()
this.req.query.user_id = { first_name: 'X' }
this.UserActivateController.activateAccountPage(this.req, this.res)
})
- it('should redirect activated users to login', function(done) {
+ it('should redirect activated users to login', function (done) {
this.user.loginCount = 1
this.res.redirect = url => {
this.UserGetter.getUser.calledWith(this.user_id).should.equal(true)
@@ -75,7 +75,7 @@ describe('UserActivateController', function() {
this.UserActivateController.activateAccountPage(this.req, this.res)
})
- it('render the activation page if the user has not logged in before', function(done) {
+ it('render the activation page if the user has not logged in before', function (done) {
this.user.loginCount = 0
this.res.render = (page, opts) => {
page.should.equal(VIEW_PATH)
diff --git a/services/web/package-lock.json b/services/web/package-lock.json
index 18d4e76466..633ad494db 100644
--- a/services/web/package-lock.json
+++ b/services/web/package-lock.json
@@ -24395,9 +24395,9 @@
"dev": true
},
"prettier": {
- "version": "1.19.1",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz",
- "integrity": "sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==",
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.2.1.tgz",
+ "integrity": "sha512-PqyhM2yCjg/oKkFPtTGUojv7gnZAoG80ttl45O6x2Ug/rMJw4wcc9k6aaf2hibP7BGVCCM33gZoGjyvt9mm16Q==",
"dev": true
},
"pretty-error": {
diff --git a/services/web/package.json b/services/web/package.json
index 2e8734afc4..fecab3cb6c 100644
--- a/services/web/package.json
+++ b/services/web/package.json
@@ -230,7 +230,7 @@
"optimize-css-assets-webpack-plugin": "^5.0.3",
"pirates": "^4.0.1",
"postcss-loader": "^3.0.0",
- "prettier": "^1.19.1",
+ "prettier": "^2.2.1",
"requirejs": "^2.3.6",
"samlp": "^3.4.1",
"sandboxed-module": "^2.0.4",
diff --git a/services/web/scripts/check_institution_users.js b/services/web/scripts/check_institution_users.js
index 1e31fd8133..4a56fbd60a 100644
--- a/services/web/scripts/check_institution_users.js
+++ b/services/web/scripts/check_institution_users.js
@@ -13,15 +13,15 @@ waitForDb()
})
function main() {
- InstitutionsManager.checkInstitutionUsers(institutionId, function(
- error,
- usersSummary
- ) {
- if (error) {
- console.log(error)
- } else {
- console.log(usersSummary)
+ InstitutionsManager.checkInstitutionUsers(
+ institutionId,
+ function (error, usersSummary) {
+ if (error) {
+ console.log(error)
+ } else {
+ console.log(usersSummary)
+ }
+ process.exit()
}
- process.exit()
- })
+ )
}
diff --git a/services/web/scripts/recurly/get_paypal_accounts_csv.js b/services/web/scripts/recurly/get_paypal_accounts_csv.js
index cb295213b0..2012cc4a08 100644
--- a/services/web/scripts/recurly/get_paypal_accounts_csv.js
+++ b/services/web/scripts/recurly/get_paypal_accounts_csv.js
@@ -57,8 +57,9 @@ const printAccountCSV = (account, callback) => {
hosted_login_token: account.hosted_login_token,
billing_info_url: `https://sharelatex.recurly.com/account/billing_info/edit?ht=${account.hosted_login_token}`,
account_management_url: `https://sharelatex.recurly.com/account/${account.hosted_login_token}`,
- current_period_ends_at: `${endAt.getFullYear()}-${endAt.getMonth() +
- 1}-${endAt.getDate()}`,
+ current_period_ends_at: `${endAt.getFullYear()}-${
+ endAt.getMonth() + 1
+ }-${endAt.getDate()}`,
current_period_ends_at_segment: parseInt(
((endAt - NOW) / 1000 / 3600 / 24 / 365) * 7
)
diff --git a/services/web/scripts/refresh_institution_users.js b/services/web/scripts/refresh_institution_users.js
index 17020ae7ac..9e45bd5f3f 100644
--- a/services/web/scripts/refresh_institution_users.js
+++ b/services/web/scripts/refresh_institution_users.js
@@ -24,14 +24,16 @@ function main() {
const notify = argv.notify[0] === 't'
console.log('Running with notify =', notify)
- InstitutionsManager.refreshInstitutionUsers(institutionId, notify, function(
- error
- ) {
- if (error) {
- console.log(error)
- } else {
- console.log('DONE 👌')
+ InstitutionsManager.refreshInstitutionUsers(
+ institutionId,
+ notify,
+ function (error) {
+ if (error) {
+ console.log(error)
+ } else {
+ console.log('DONE 👌')
+ }
+ process.exit()
}
- process.exit()
- })
+ )
}
diff --git a/services/web/test/acceptance/src/AdminEmailTests.js b/services/web/test/acceptance/src/AdminEmailTests.js
index 1cfcc13c95..16838daa97 100644
--- a/services/web/test/acceptance/src/AdminEmailTests.js
+++ b/services/web/test/acceptance/src/AdminEmailTests.js
@@ -2,14 +2,14 @@ const { expect } = require('chai')
const async = require('async')
const User = require('./helpers/User')
-describe('AdminEmails', function() {
- beforeEach(function(done) {
+describe('AdminEmails', function () {
+ beforeEach(function (done) {
this.timeout(5000)
done()
})
- describe('an admin with an invalid email address', function() {
- before(function(done) {
+ describe('an admin with an invalid email address', function () {
+ before(function (done) {
this.badUser = new User({ email: 'alice@evil.com' })
async.series(
[
@@ -20,7 +20,7 @@ describe('AdminEmails', function() {
)
})
- it('should block the user', function(done) {
+ it('should block the user', function (done) {
this.badUser.login(err => {
expect(err).to.not.exist
this.badUser.getProjectListPage((err, statusCode) => {
@@ -31,8 +31,8 @@ describe('AdminEmails', function() {
})
})
- describe('an admin with a valid email address', function() {
- before(function(done) {
+ describe('an admin with a valid email address', function () {
+ before(function (done) {
this.goodUser = new User({ email: 'alice@example.com' })
async.series(
[
@@ -43,7 +43,7 @@ describe('AdminEmails', function() {
)
})
- it('should not block the user', function(done) {
+ it('should not block the user', function (done) {
this.goodUser.login(err => {
expect(err).to.not.exist
this.goodUser.getProjectListPage((err, statusCode) => {
diff --git a/services/web/test/acceptance/src/ApiClsiTests.js b/services/web/test/acceptance/src/ApiClsiTests.js
index eac79ed7a2..599c62104a 100644
--- a/services/web/test/acceptance/src/ApiClsiTests.js
+++ b/services/web/test/acceptance/src/ApiClsiTests.js
@@ -23,9 +23,9 @@ const authed_request = request.defaults({
}
})
-describe('ApiClsiTests', function() {
- describe('compile', function() {
- beforeEach(function(done) {
+describe('ApiClsiTests', function () {
+ describe('compile', function () {
+ beforeEach(function (done) {
this.compileSpec = {
compile: {
options: {
@@ -50,8 +50,8 @@ describe('ApiClsiTests', function() {
return done()
})
- describe('valid request', function() {
- it('returns success and a list of output files', function(done) {
+ describe('valid request', function () {
+ it('returns success and a list of output files', function (done) {
return authed_request.post(
{
uri: '/api/clsi/compile/abcd',
@@ -85,8 +85,8 @@ describe('ApiClsiTests', function() {
})
})
- describe('unauthorized', function() {
- it('returns 401', function(done) {
+ describe('unauthorized', function () {
+ it('returns 401', function (done) {
return request.post(
{
uri: '/api/clsi/compile/abcd',
@@ -105,9 +105,9 @@ describe('ApiClsiTests', function() {
})
})
- describe('get output', function() {
- describe('valid file', function() {
- it('returns the file', function(done) {
+ describe('get output', function () {
+ describe('valid file', function () {
+ it('returns the file', function (done) {
return authed_request.get(
'/api/clsi/compile/abcd/build/1234/output/project.pdf',
(error, response, body) => {
@@ -122,8 +122,8 @@ describe('ApiClsiTests', function() {
})
})
- describe('invalid file', function() {
- it('returns 404', function(done) {
+ describe('invalid file', function () {
+ it('returns 404', function (done) {
return authed_request.get(
'/api/clsi/compile/abcd/build/1234/output/project.aux',
(error, response, body) => {
@@ -138,8 +138,8 @@ describe('ApiClsiTests', function() {
})
})
- describe('unauthorized', function() {
- it('returns 401', function(done) {
+ describe('unauthorized', function () {
+ it('returns 401', function (done) {
return request.get(
'/api/clsi/compile/abcd/build/1234/output/project.pdf',
(error, response, body) => {
diff --git a/services/web/test/acceptance/src/AuthenticationTests.js b/services/web/test/acceptance/src/AuthenticationTests.js
index 445813b813..523701561b 100644
--- a/services/web/test/acceptance/src/AuthenticationTests.js
+++ b/services/web/test/acceptance/src/AuthenticationTests.js
@@ -2,14 +2,14 @@ const { expect } = require('chai')
const { ObjectId } = require('mongodb')
const User = require('./helpers/User').promises
-describe('Authentication', function() {
+describe('Authentication', function () {
let user
- beforeEach('init vars', function() {
+ beforeEach('init vars', function () {
user = new User()
})
- describe('CSRF regeneration on login', function() {
- it('should prevent use of csrf token from before login', function(done) {
+ describe('CSRF regeneration on login', function () {
+ it('should prevent use of csrf token from before login', function (done) {
user.logout(err => {
if (err) {
return done(err)
@@ -45,19 +45,19 @@ describe('Authentication', function() {
})
})
- describe('login', function() {
- beforeEach('doLogin', async function() {
+ describe('login', function () {
+ beforeEach('doLogin', async function () {
await user.login()
})
- it('should log the user in', async function() {
+ it('should log the user in', async function () {
const {
response: { statusCode }
} = await user.doRequest('GET', '/project')
expect(statusCode).to.equal(200)
})
- it('should emit an user auditLog entry for the login', async function() {
+ it('should emit an user auditLog entry for the login', async function () {
const {
auditLog: [auditLogEntry]
} = await user.get()
diff --git a/services/web/test/acceptance/src/AuthorizationTests.js b/services/web/test/acceptance/src/AuthorizationTests.js
index 4a8137a08d..ab7f8ee37d 100644
--- a/services/web/test/acceptance/src/AuthorizationTests.js
+++ b/services/web/test/acceptance/src/AuthorizationTests.js
@@ -275,8 +275,8 @@ function expectNoChatAccess(user, projectId, callback) {
)
}
-describe('Authorization', function() {
- beforeEach(function(done) {
+describe('Authorization', function () {
+ beforeEach(function (done) {
this.timeout(90000)
this.owner = new User()
this.other1 = new User()
@@ -302,8 +302,8 @@ describe('Authorization', function() {
)
})
- describe('private project', function() {
- beforeEach(function(done) {
+ describe('private project', function () {
+ beforeEach(function (done) {
this.owner.createProject('private-project', (error, projectId) => {
if (error != null) {
return done(error)
@@ -313,27 +313,27 @@ describe('Authorization', function() {
})
})
- it('should allow the owner read access to it', function(done) {
+ it('should allow the owner read access to it', function (done) {
expectReadAccess(this.owner, this.projectId, done)
})
- it('should allow the owner write access to its content', function(done) {
+ it('should allow the owner write access to its content', function (done) {
expectContentWriteAccess(this.owner, this.projectId, done)
})
- it('should allow the owner write access to its settings', function(done) {
+ it('should allow the owner write access to its settings', function (done) {
expectSettingsWriteAccess(this.owner, this.projectId, done)
})
- it('should allow the owner admin access to it', function(done) {
+ it('should allow the owner admin access to it', function (done) {
expectAdminAccess(this.owner, this.projectId, done)
})
- it('should allow the owner user chat messages access', function(done) {
+ it('should allow the owner user chat messages access', function (done) {
expectChatAccess(this.owner, this.projectId, done)
})
- it('should not allow another user read access to the project', function(done) {
+ it('should not allow another user read access to the project', function (done) {
expectNoReadAccess(
this.other1,
this.projectId,
@@ -342,11 +342,11 @@ describe('Authorization', function() {
)
})
- it('should not allow another user write access to its content', function(done) {
+ it('should not allow another user write access to its content', function (done) {
expectNoContentWriteAccess(this.other1, this.projectId, done)
})
- it('should not allow another user write access to its settings', function(done) {
+ it('should not allow another user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.other1,
this.projectId,
@@ -355,15 +355,15 @@ describe('Authorization', function() {
)
})
- it('should not allow another user admin access to it', function(done) {
+ it('should not allow another user admin access to it', function (done) {
expectNoAdminAccess(this.other1, this.projectId, done)
})
- it('should not allow another user chat messages access', function(done) {
+ it('should not allow another user chat messages access', function (done) {
expectNoChatAccess(this.other1, this.projectId, done)
})
- it('should not allow anonymous user read access to it', function(done) {
+ it('should not allow anonymous user read access to it', function (done) {
expectNoReadAccess(
this.anon,
this.projectId,
@@ -372,11 +372,11 @@ describe('Authorization', function() {
)
})
- it('should not allow anonymous user write access to its content', function(done) {
+ it('should not allow anonymous user write access to its content', function (done) {
expectNoContentWriteAccess(this.anon, this.projectId, done)
})
- it('should not allow anonymous user write access to its settings', function(done) {
+ it('should not allow anonymous user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.anon,
this.projectId,
@@ -385,33 +385,33 @@ describe('Authorization', function() {
)
})
- it('should not allow anonymous user admin access to it', function(done) {
+ it('should not allow anonymous user admin access to it', function (done) {
expectNoAnonymousAdminAccess(this.anon, this.projectId, done)
})
- it('should not allow anonymous user chat messages access', function(done) {
+ it('should not allow anonymous user chat messages access', function (done) {
expectNoChatAccess(this.anon, this.projectId, done)
})
- it('should allow site admin users read access to it', function(done) {
+ it('should allow site admin users read access to it', function (done) {
expectReadAccess(this.site_admin, this.projectId, done)
})
- it('should allow site admin users write access to its content', function(done) {
+ it('should allow site admin users write access to its content', function (done) {
expectContentWriteAccess(this.site_admin, this.projectId, done)
})
- it('should allow site admin users write access to its settings', function(done) {
+ it('should allow site admin users write access to its settings', function (done) {
expectSettingsWriteAccess(this.site_admin, this.projectId, done)
})
- it('should allow site admin users admin access to it', function(done) {
+ it('should allow site admin users admin access to it', function (done) {
expectAdminAccess(this.site_admin, this.projectId, done)
})
})
- describe('shared project', function() {
- beforeEach(function(done) {
+ describe('shared project', function () {
+ beforeEach(function (done) {
this.rw_user = this.other1
this.ro_user = this.other2
this.owner.createProject('private-project', (error, projectId) => {
@@ -443,19 +443,19 @@ describe('Authorization', function() {
})
})
- it('should allow the read-only user read access to it', function(done) {
+ it('should allow the read-only user read access to it', function (done) {
expectReadAccess(this.ro_user, this.projectId, done)
})
- it('should allow the read-only user chat messages access', function(done) {
+ it('should allow the read-only user chat messages access', function (done) {
expectChatAccess(this.ro_user, this.projectId, done)
})
- it('should not allow the read-only user write access to its content', function(done) {
+ it('should not allow the read-only user write access to its content', function (done) {
expectNoContentWriteAccess(this.ro_user, this.projectId, done)
})
- it('should not allow the read-only user write access to its settings', function(done) {
+ it('should not allow the read-only user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.ro_user,
this.projectId,
@@ -464,33 +464,33 @@ describe('Authorization', function() {
)
})
- it('should not allow the read-only user admin access to it', function(done) {
+ it('should not allow the read-only user admin access to it', function (done) {
expectNoAdminAccess(this.ro_user, this.projectId, done)
})
- it('should allow the read-write user read access to it', function(done) {
+ it('should allow the read-write user read access to it', function (done) {
expectReadAccess(this.rw_user, this.projectId, done)
})
- it('should allow the read-write user write access to its content', function(done) {
+ it('should allow the read-write user write access to its content', function (done) {
expectContentWriteAccess(this.rw_user, this.projectId, done)
})
- it('should allow the read-write user write access to its settings', function(done) {
+ it('should allow the read-write user write access to its settings', function (done) {
expectSettingsWriteAccess(this.rw_user, this.projectId, done)
})
- it('should not allow the read-write user admin access to it', function(done) {
+ it('should not allow the read-write user admin access to it', function (done) {
expectNoAdminAccess(this.rw_user, this.projectId, done)
})
- it('should allow the read-write user chat messages access', function(done) {
+ it('should allow the read-write user chat messages access', function (done) {
expectChatAccess(this.rw_user, this.projectId, done)
})
})
- describe('public read-write project', function() {
- beforeEach(function(done) {
+ describe('public read-write project', function () {
+ beforeEach(function (done) {
this.owner.createProject('public-rw-project', (error, projectId) => {
if (error != null) {
return done(error)
@@ -500,19 +500,19 @@ describe('Authorization', function() {
})
})
- it('should allow a user read access to it', function(done) {
+ it('should allow a user read access to it', function (done) {
expectReadAccess(this.other1, this.projectId, done)
})
- it('should allow a user write access to its content', function(done) {
+ it('should allow a user write access to its content', function (done) {
expectContentWriteAccess(this.other1, this.projectId, done)
})
- it('should allow a user chat messages access', function(done) {
+ it('should allow a user chat messages access', function (done) {
expectChatAccess(this.other1, this.projectId, done)
})
- it('should not allow a user write access to its settings', function(done) {
+ it('should not allow a user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.other1,
this.projectId,
@@ -521,23 +521,23 @@ describe('Authorization', function() {
)
})
- it('should not allow a user admin access to it', function(done) {
+ it('should not allow a user admin access to it', function (done) {
expectNoAdminAccess(this.other1, this.projectId, done)
})
- it('should allow an anonymous user read access to it', function(done) {
+ it('should allow an anonymous user read access to it', function (done) {
expectReadAccess(this.anon, this.projectId, done)
})
- it('should allow an anonymous user write access to its content', function(done) {
+ it('should allow an anonymous user write access to its content', function (done) {
expectContentWriteAccess(this.anon, this.projectId, done)
})
- it('should allow an anonymous user chat messages access', function(done) {
+ it('should allow an anonymous user chat messages access', function (done) {
expectChatAccess(this.anon, this.projectId, done)
})
- it('should not allow an anonymous user write access to its settings', function(done) {
+ it('should not allow an anonymous user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.anon,
this.projectId,
@@ -546,13 +546,13 @@ describe('Authorization', function() {
)
})
- it('should not allow an anonymous user admin access to it', function(done) {
+ it('should not allow an anonymous user admin access to it', function (done) {
expectNoAnonymousAdminAccess(this.anon, this.projectId, done)
})
})
- describe('public read-only project', function() {
- beforeEach(function(done) {
+ describe('public read-only project', function () {
+ beforeEach(function (done) {
this.owner.createProject('public-ro-project', (error, projectId) => {
if (error != null) {
return done(error)
@@ -562,15 +562,15 @@ describe('Authorization', function() {
})
})
- it('should allow a user read access to it', function(done) {
+ it('should allow a user read access to it', function (done) {
expectReadAccess(this.other1, this.projectId, done)
})
- it('should not allow a user write access to its content', function(done) {
+ it('should not allow a user write access to its content', function (done) {
expectNoContentWriteAccess(this.other1, this.projectId, done)
})
- it('should not allow a user write access to its settings', function(done) {
+ it('should not allow a user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.other1,
this.projectId,
@@ -579,24 +579,24 @@ describe('Authorization', function() {
)
})
- it('should not allow a user admin access to it', function(done) {
+ it('should not allow a user admin access to it', function (done) {
expectNoAdminAccess(this.other1, this.projectId, done)
})
// NOTE: legacy readOnly access does not count as 'restricted' in the new model
- it('should allow a user chat messages access', function(done) {
+ it('should allow a user chat messages access', function (done) {
expectChatAccess(this.other1, this.projectId, done)
})
- it('should allow an anonymous user read access to it', function(done) {
+ it('should allow an anonymous user read access to it', function (done) {
expectReadAccess(this.anon, this.projectId, done)
})
- it('should not allow an anonymous user write access to its content', function(done) {
+ it('should not allow an anonymous user write access to its content', function (done) {
expectNoContentWriteAccess(this.anon, this.projectId, done)
})
- it('should not allow an anonymous user write access to its settings', function(done) {
+ it('should not allow an anonymous user write access to its settings', function (done) {
expectNoSettingsWriteAccess(
this.anon,
this.projectId,
@@ -605,11 +605,11 @@ describe('Authorization', function() {
)
})
- it('should not allow an anonymous user admin access to it', function(done) {
+ it('should not allow an anonymous user admin access to it', function (done) {
expectNoAnonymousAdminAccess(this.anon, this.projectId, done)
})
- it('should not allow an anonymous user chat messages access', function(done) {
+ it('should not allow an anonymous user chat messages access', function (done) {
expectNoChatAccess(this.anon, this.projectId, done)
})
})
diff --git a/services/web/test/acceptance/src/BackFillDeletedFilesTests.js b/services/web/test/acceptance/src/BackFillDeletedFilesTests.js
index afd57d81bb..21bd950476 100644
--- a/services/web/test/acceptance/src/BackFillDeletedFilesTests.js
+++ b/services/web/test/acceptance/src/BackFillDeletedFilesTests.js
@@ -20,10 +20,10 @@ async function unsetDeletedFiles(projectId) {
)
}
-describe('BackFillDeletedFiles', function() {
+describe('BackFillDeletedFiles', function () {
let user, projectId1, projectId2, projectId3, projectId4, projectId5
- beforeEach('create projects', async function() {
+ beforeEach('create projects', async function () {
user = new User()
await user.login()
@@ -35,7 +35,7 @@ describe('BackFillDeletedFiles', function() {
})
let fileId1, fileId2, fileId3, fileId4
- beforeEach('create files', function() {
+ beforeEach('create files', function () {
// take a short cut and just allocate file ids
fileId1 = ObjectId()
fileId2 = ObjectId()
@@ -50,7 +50,7 @@ describe('BackFillDeletedFiles', function() {
__v: 0
}
let deletedFiles1, deletedFiles2, deletedFiles3
- beforeEach('set deletedFiles details', async function() {
+ beforeEach('set deletedFiles details', async function () {
deletedFiles1 = [
{ _id: fileId1, ...otherFileDetails },
{ _id: fileId2, ...otherFileDetails }
@@ -93,7 +93,7 @@ describe('BackFillDeletedFiles', function() {
}
function checkAreFilesBackFilled() {
- it('should back fill file and set projectId', async function() {
+ it('should back fill file and set projectId', async function () {
const docs = await db.deletedFiles
.find({}, { sort: { _id: 1 } })
.toArray()
@@ -106,54 +106,54 @@ describe('BackFillDeletedFiles', function() {
})
}
- describe('back fill only', function() {
+ describe('back fill only', function () {
beforeEach('run script', runScript)
checkAreFilesBackFilled()
- it('should leave the deletedFiles as is', async function() {
+ it('should leave the deletedFiles as is', async function () {
expect(await getDeletedFiles(projectId1)).to.deep.equal(deletedFiles1)
expect(await getDeletedFiles(projectId2)).to.deep.equal(deletedFiles2)
expect(await getDeletedFiles(projectId5)).to.deep.equal(deletedFiles3)
})
})
- describe('back fill and cleanup', function() {
- beforeEach('run script with cleanup flag', async function() {
+ describe('back fill and cleanup', function () {
+ beforeEach('run script with cleanup flag', async function () {
await runScript(['--perform-cleanup'])
})
checkAreFilesBackFilled()
- it('should cleanup the deletedFiles', async function() {
+ it('should cleanup the deletedFiles', async function () {
expect(await getDeletedFiles(projectId1)).to.deep.equal([])
expect(await getDeletedFiles(projectId2)).to.deep.equal([])
expect(await getDeletedFiles(projectId5)).to.deep.equal([])
})
})
- describe('fix partial inserts and cleanup', function() {
- beforeEach('simulate one missing insert', async function() {
+ describe('fix partial inserts and cleanup', function () {
+ beforeEach('simulate one missing insert', async function () {
await setDeletedFiles(projectId1, [deletedFiles1[0]])
})
- beforeEach('run script with cleanup flag', async function() {
+ beforeEach('run script with cleanup flag', async function () {
await runScript(['--perform-cleanup'])
})
- beforeEach('add case for one missing file', async function() {
+ beforeEach('add case for one missing file', async function () {
await setDeletedFiles(projectId1, deletedFiles1)
})
- beforeEach('add cases for no more files to insert', async function() {
+ beforeEach('add cases for no more files to insert', async function () {
await setDeletedFiles(projectId2, deletedFiles2)
await setDeletedFiles(projectId5, deletedFiles3)
})
- beforeEach('fixing partial insert and cleanup', async function() {
+ beforeEach('fixing partial insert and cleanup', async function () {
await runScript(['--fix-partial-inserts', '--perform-cleanup'])
})
checkAreFilesBackFilled()
- it('should cleanup the deletedFiles', async function() {
+ it('should cleanup the deletedFiles', async function () {
expect(await getDeletedFiles(projectId1)).to.deep.equal([])
expect(await getDeletedFiles(projectId2)).to.deep.equal([])
expect(await getDeletedFiles(projectId5)).to.deep.equal([])
diff --git a/services/web/test/acceptance/src/BackFillDocNameForDeletedDocsTests.js b/services/web/test/acceptance/src/BackFillDocNameForDeletedDocsTests.js
index 53a0bee31c..3fafb3e6a3 100644
--- a/services/web/test/acceptance/src/BackFillDocNameForDeletedDocsTests.js
+++ b/services/web/test/acceptance/src/BackFillDocNameForDeletedDocsTests.js
@@ -13,16 +13,16 @@ async function setDeletedDocs(projectId, deletedDocs) {
await db.projects.updateOne({ _id: projectId }, { $set: { deletedDocs } })
}
-describe('BackFillDocNameForDeletedDocs', function() {
+describe('BackFillDocNameForDeletedDocs', function () {
let user, projectId1, projectId2, docId1, docId2, docId3
- beforeEach('create projects', async function() {
+ beforeEach('create projects', async function () {
user = new User()
await user.login()
projectId1 = ObjectId(await user.createProject('project1'))
projectId2 = ObjectId(await user.createProject('project2'))
})
- beforeEach('create docs', async function() {
+ beforeEach('create docs', async function () {
docId1 = ObjectId(
await user.createDocInProject(projectId1, null, 'doc1.tex')
)
@@ -33,12 +33,12 @@ describe('BackFillDocNameForDeletedDocs', function() {
await user.createDocInProject(projectId2, null, 'doc3.tex')
)
})
- beforeEach('deleted docs', async function() {
+ beforeEach('deleted docs', async function () {
await user.deleteItemInProject(projectId1, 'doc', docId1)
await user.deleteItemInProject(projectId1, 'doc', docId2)
await user.deleteItemInProject(projectId2, 'doc', docId3)
})
- beforeEach('insert doc stubs into docs collection', async function() {
+ beforeEach('insert doc stubs into docs collection', async function () {
await db.docs.insertMany([
{ _id: docId1, deleted: true },
{ _id: docId2, deleted: true },
@@ -47,7 +47,7 @@ describe('BackFillDocNameForDeletedDocs', function() {
})
let deletedDocs1, deletedDocs2
let deletedAt1, deletedAt2, deletedAt3
- beforeEach('set deletedDocs details', async function() {
+ beforeEach('set deletedDocs details', async function () {
deletedAt1 = new Date()
deletedAt2 = new Date()
deletedAt3 = new Date()
@@ -82,7 +82,7 @@ describe('BackFillDocNameForDeletedDocs', function() {
}
function checkDocsBackFilled() {
- it('should back fill names and deletedAt dates into docs', async function() {
+ it('should back fill names and deletedAt dates into docs', async function () {
const docs = await db.docs.find({}).toArray()
expect(docs).to.deep.equal([
{ _id: docId1, deleted: true, name: 'doc1.tex', deletedAt: deletedAt1 },
@@ -92,25 +92,25 @@ describe('BackFillDocNameForDeletedDocs', function() {
})
}
- describe('back fill only', function() {
+ describe('back fill only', function () {
beforeEach('run script', runScript)
checkDocsBackFilled()
- it('should leave the deletedDocs as is', async function() {
+ it('should leave the deletedDocs as is', async function () {
expect(await getDeletedDocs(projectId1)).to.deep.equal(deletedDocs1)
expect(await getDeletedDocs(projectId2)).to.deep.equal(deletedDocs2)
})
})
- describe('back fill and cleanup', function() {
- beforeEach('run script with cleanup flag', async function() {
+ describe('back fill and cleanup', function () {
+ beforeEach('run script with cleanup flag', async function () {
await runScript(['--perform-cleanup'])
})
checkDocsBackFilled()
- it('should cleanup the deletedDocs', async function() {
+ it('should cleanup the deletedDocs', async function () {
expect(await getDeletedDocs(projectId1)).to.deep.equal([])
expect(await getDeletedDocs(projectId2)).to.deep.equal([])
})
diff --git a/services/web/test/acceptance/src/BetaProgramTests.js b/services/web/test/acceptance/src/BetaProgramTests.js
index dd3e070247..df28a4c23d 100644
--- a/services/web/test/acceptance/src/BetaProgramTests.js
+++ b/services/web/test/acceptance/src/BetaProgramTests.js
@@ -1,9 +1,9 @@
const { expect } = require('chai')
const UserHelper = require('../src/helpers/UserHelper')
-describe('BetaProgram', function() {
+describe('BetaProgram', function () {
let email, userHelper
- beforeEach(async function() {
+ beforeEach(async function () {
userHelper = new UserHelper()
email = userHelper.getDefaultEmail()
userHelper = await UserHelper.createUser({ email })
@@ -12,7 +12,7 @@ describe('BetaProgram', function() {
password: userHelper.getDefaultPassword()
})
})
- it('should opt in', async function() {
+ it('should opt in', async function () {
const response = await userHelper.request.post('/beta/opt-in', {
simple: false
})
@@ -26,7 +26,7 @@ describe('BetaProgram', function() {
).user
expect(user.betaProgram).to.equal(true)
})
- it('should opt out', async function() {
+ it('should opt out', async function () {
const response = await userHelper.request.post('/beta/opt-out', {
simple: false
})
diff --git a/services/web/test/acceptance/src/BodyParserErrorsTest.js b/services/web/test/acceptance/src/BodyParserErrorsTest.js
index 71f915e126..42aec8a61c 100644
--- a/services/web/test/acceptance/src/BodyParserErrorsTest.js
+++ b/services/web/test/acceptance/src/BodyParserErrorsTest.js
@@ -4,10 +4,10 @@ const request = require('./helpers/request')
// create a string that is longer than the max allowed (as defined in Server.js)
const wayTooLongString = 'a'.repeat(Settings.max_json_request_size + 1)
-describe('BodyParserErrors', function() {
- describe('when request is too large', function() {
- describe('json', function() {
- it('return 413', function(done) {
+describe('BodyParserErrors', function () {
+ describe('when request is too large', function () {
+ describe('json', function () {
+ it('return 413', function (done) {
request.post(
{
url: '/login',
@@ -26,8 +26,8 @@ describe('BodyParserErrors', function() {
})
})
- describe('urlencoded', function() {
- it('return 413', function(done) {
+ describe('urlencoded', function () {
+ it('return 413', function (done) {
request.post(
{
url: '/login',
@@ -46,9 +46,9 @@ describe('BodyParserErrors', function() {
})
})
- describe('when request is not too large', function() {
- describe('json', function() {
- it('return normal status code', function(done) {
+ describe('when request is not too large', function () {
+ describe('json', function () {
+ it('return normal status code', function (done) {
request.post(
{
url: '/login',
@@ -66,8 +66,8 @@ describe('BodyParserErrors', function() {
})
})
- describe('urlencoded', function() {
- it('return normal status code', function(done) {
+ describe('urlencoded', function () {
+ it('return normal status code', function (done) {
request.post(
{
url: '/login',
diff --git a/services/web/test/acceptance/src/BonusTests.js b/services/web/test/acceptance/src/BonusTests.js
index c1a821238c..dd51cadb0e 100644
--- a/services/web/test/acceptance/src/BonusTests.js
+++ b/services/web/test/acceptance/src/BonusTests.js
@@ -2,9 +2,9 @@ const { expect } = require('chai')
const cheerio = require('cheerio')
const UserHelper = require('../src/helpers/UserHelper')
-describe('Bonus', function() {
+describe('Bonus', function () {
let userHelper
- beforeEach(async function() {
+ beforeEach(async function () {
userHelper = new UserHelper()
const email = userHelper.getDefaultEmail()
userHelper = await UserHelper.createUser({ email })
@@ -14,7 +14,7 @@ describe('Bonus', function() {
})
})
- it('should use the count rather than refered_users', async function() {
+ it('should use the count rather than refered_users', async function () {
await UserHelper.updateUser(userHelper.user._id, {
$set: { refered_user_count: 1, refered_users: [] }
})
diff --git a/services/web/test/acceptance/src/CloseSiteTests.js b/services/web/test/acceptance/src/CloseSiteTests.js
index 78268b6dd4..4235ef3103 100644
--- a/services/web/test/acceptance/src/CloseSiteTests.js
+++ b/services/web/test/acceptance/src/CloseSiteTests.js
@@ -13,9 +13,9 @@
const Settings = require('settings-sharelatex')
const request = require('./helpers/request')
-describe('siteIsOpen', function() {
- describe('when siteIsOpen is default (true)', function() {
- it('should get page', function(done) {
+describe('siteIsOpen', function () {
+ describe('when siteIsOpen is default (true)', function () {
+ it('should get page', function (done) {
return request.get('/login', (error, response, body) => {
response.statusCode.should.equal(200)
return done()
@@ -23,16 +23,16 @@ describe('siteIsOpen', function() {
})
})
- describe('when siteIsOpen is false', function() {
- beforeEach(function() {
+ describe('when siteIsOpen is false', function () {
+ beforeEach(function () {
return (Settings.siteIsOpen = false)
})
- afterEach(function() {
+ afterEach(function () {
return (Settings.siteIsOpen = true)
})
- it('should return maintenance page', function(done) {
+ it('should return maintenance page', function (done) {
request.get('/login', (error, response, body) => {
response.statusCode.should.equal(503)
body.should.match(/is currently down for maintenance/)
@@ -40,7 +40,7 @@ describe('siteIsOpen', function() {
})
})
- it('should return a plain text message for a json request', function(done) {
+ it('should return a plain text message for a json request', function (done) {
request.get('/some/route', { json: true }, (error, response, body) => {
response.statusCode.should.equal(503)
body.message.should.match(/maintenance/)
@@ -49,14 +49,14 @@ describe('siteIsOpen', function() {
})
})
- it('should return a 200 on / for load balancer health checks', function(done) {
+ it('should return a 200 on / for load balancer health checks', function (done) {
request.get('/', (error, response, body) => {
response.statusCode.should.equal(200)
done()
})
})
- it('should return a 200 on /status for readiness checks', function(done) {
+ it('should return a 200 on /status for readiness checks', function (done) {
request.get('/status', (error, response, body) => {
response.statusCode.should.equal(200)
done()
diff --git a/services/web/test/acceptance/src/ConvertArchivedState.js b/services/web/test/acceptance/src/ConvertArchivedState.js
index 4507084e8c..44e7058d8b 100644
--- a/services/web/test/acceptance/src/ConvertArchivedState.js
+++ b/services/web/test/acceptance/src/ConvertArchivedState.js
@@ -4,14 +4,14 @@ const { ObjectId } = require('mongodb')
const User = require('./helpers/User').promises
-describe('ConvertArchivedState', function() {
+describe('ConvertArchivedState', function () {
let userOne, userTwo, userThree, userFour
let projectOne, projectOneId
let projectTwo, projectTwoId
let projectThree, projectThreeId
let projectFour, projectFourId
- beforeEach(async function() {
+ beforeEach(async function () {
userOne = new User()
userTwo = new User()
userThree = new User()
@@ -66,7 +66,7 @@ describe('ConvertArchivedState', function() {
await userOne.saveProject(projectFour)
})
- beforeEach(function(done) {
+ beforeEach(function (done) {
exec(
'CONNECT_DELAY=1 node scripts/convert_archived_state.js FIRST,SECOND',
(error, stdout, stderr) => {
@@ -80,8 +80,8 @@ describe('ConvertArchivedState', function() {
)
})
- describe('main method', function() {
- it('should change a project archived boolean to an array', async function() {
+ describe('main method', function () {
+ it('should change a project archived boolean to an array', async function () {
projectOne = await userOne.getProject(projectOneId)
projectTwo = await userOne.getProject(projectTwoId)
expect(convertObjectIdsToStrings(projectOne.archived)).to.deep.equal([
@@ -97,7 +97,7 @@ describe('ConvertArchivedState', function() {
])
})
- it('should not change the value of a project already archived with an array', async function() {
+ it('should not change the value of a project already archived with an array', async function () {
projectThree = await userOne.getProject(projectThreeId)
expect(convertObjectIdsToStrings(projectThree.archived)).to.deep.equal([
userOne._id,
@@ -106,7 +106,7 @@ describe('ConvertArchivedState', function() {
])
})
- it('should change a none-archived project with a boolean value to an array', async function() {
+ it('should change a none-archived project with a boolean value to an array', async function () {
projectFour = await userOne.getProject(projectFourId)
expect(convertObjectIdsToStrings(projectFour.archived)).to.deep.equal([])
})
diff --git a/services/web/test/acceptance/src/DeletionTests.js b/services/web/test/acceptance/src/DeletionTests.js
index e1d7728242..6b6416e561 100644
--- a/services/web/test/acceptance/src/DeletionTests.js
+++ b/services/web/test/acceptance/src/DeletionTests.js
@@ -11,13 +11,13 @@ const MockFilestoreApiClass = require('./mocks/MockFilestoreApi')
let MockDocstoreApi, MockFilestoreApi
-before(function() {
+before(function () {
MockDocstoreApi = MockDocstoreApiClass.instance()
MockFilestoreApi = MockFilestoreApiClass.instance()
})
-describe('Deleting a user', function() {
- beforeEach(function(done) {
+describe('Deleting a user', function () {
+ beforeEach(function (done) {
this.user = new User()
async.series(
[
@@ -28,7 +28,7 @@ describe('Deleting a user', function() {
)
})
- it('Should remove the user from active users', function(done) {
+ it('Should remove the user from active users', function (done) {
this.user.get((error, user) => {
expect(error).not.to.exist
expect(user).to.exist
@@ -43,7 +43,7 @@ describe('Deleting a user', function() {
})
})
- it('Should create a soft-deleted user', function(done) {
+ it('Should create a soft-deleted user', function (done) {
this.user.get((error, user) => {
expect(error).not.to.exist
this.user.deleteUser(error => {
@@ -75,7 +75,7 @@ describe('Deleting a user', function() {
})
})
- it('Should fail if the user has a subscription', function(done) {
+ it('Should fail if the user has a subscription', function (done) {
Subscription.create(
{
admin_id: this.user._id,
@@ -98,7 +98,7 @@ describe('Deleting a user', function() {
)
})
- it("Should delete the user's projects", function(done) {
+ it("Should delete the user's projects", function (done) {
this.user.createProject('wombat', (error, projectId) => {
expect(error).not.to.exist
this.user.getProject(projectId, (error, project) => {
@@ -117,8 +117,8 @@ describe('Deleting a user', function() {
})
})
- describe('when scrubbing the user', function() {
- beforeEach(function(done) {
+ describe('when scrubbing the user', function () {
+ beforeEach(function (done) {
this.user.get((error, user) => {
if (error) {
throw error
@@ -128,7 +128,7 @@ describe('Deleting a user', function() {
})
})
- it('Should remove the user data from mongo', function(done) {
+ it('Should remove the user data from mongo', function (done) {
db.deletedUsers.findOne(
{ 'deleterData.deletedUserId': this.userId },
(error, deletedUser) => {
@@ -168,8 +168,8 @@ describe('Deleting a user', function() {
})
})
-describe('Deleting a project', function() {
- beforeEach(function(done) {
+describe('Deleting a project', function () {
+ beforeEach(function (done) {
this.user = new User()
this.projectName = 'wombat'
this.user.ensureUserExists(() => {
@@ -182,7 +182,7 @@ describe('Deleting a project', function() {
})
})
- it('Should remove the project from active projects', function(done) {
+ it('Should remove the project from active projects', function (done) {
this.user.getProject(this.projectId, (error, project) => {
expect(error).not.to.exist
expect(project).to.exist
@@ -199,7 +199,7 @@ describe('Deleting a project', function() {
})
})
- it('Should create a soft-deleted project', function(done) {
+ it('Should create a soft-deleted project', function (done) {
this.user.getProject(this.projectId, (error, project) => {
expect(error).not.to.exist
@@ -239,8 +239,8 @@ describe('Deleting a project', function() {
})
})
- describe('when the project has deleted files', function() {
- beforeEach('get rootFolder id', function(done) {
+ describe('when the project has deleted files', function () {
+ beforeEach('get rootFolder id', function (done) {
this.user.getProject(this.projectId, (error, project) => {
if (error) return done(error)
this.rootFolder = project.rootFolder[0]._id
@@ -249,12 +249,12 @@ describe('Deleting a project', function() {
})
let allFileIds
- beforeEach('reset allFileIds', function() {
+ beforeEach('reset allFileIds', function () {
allFileIds = []
})
function createAndDeleteFile(name) {
let fileId
- beforeEach(`create file ${name}`, function(done) {
+ beforeEach(`create file ${name}`, function (done) {
this.user.uploadExampleFileInProject(
this.projectId,
this.rootFolder,
@@ -266,7 +266,7 @@ describe('Deleting a project', function() {
}
)
})
- beforeEach(`delete file ${name}`, function(done) {
+ beforeEach(`delete file ${name}`, function (done) {
this.user.deleteItemInProject(this.projectId, 'file', fileId, done)
})
}
@@ -274,7 +274,7 @@ describe('Deleting a project', function() {
createAndDeleteFile(name)
}
- it('should have two deleteFiles entries', async function() {
+ it('should have two deleteFiles entries', async function () {
const files = await db.deletedFiles
.find({}, { sort: { _id: 1 } })
.toArray()
@@ -282,11 +282,11 @@ describe('Deleting a project', function() {
expect(files.map(file => file._id.toString())).to.deep.equal(allFileIds)
})
- describe('When the deleted project is expired', function() {
- beforeEach('soft delete the project', function(done) {
+ describe('When the deleted project is expired', function () {
+ beforeEach('soft delete the project', function (done) {
this.user.deleteProject(this.projectId, done)
})
- beforeEach('hard delete the project', function(done) {
+ beforeEach('hard delete the project', function (done) {
request.post(
`/internal/project/${this.projectId}/expire-deleted-project`,
{
@@ -305,7 +305,7 @@ describe('Deleting a project', function() {
)
})
- it('should cleanup the deleteFiles', async function() {
+ it('should cleanup the deleteFiles', async function () {
const files = await db.deletedFiles
.find({}, { sort: { _id: 1 } })
.toArray()
@@ -314,8 +314,8 @@ describe('Deleting a project', function() {
})
})
- describe('When the project has docs', function() {
- beforeEach(function(done) {
+ describe('When the project has docs', function () {
+ beforeEach(function (done) {
this.user.getProject(this.projectId, (error, project) => {
if (error) {
throw error
@@ -338,8 +338,8 @@ describe('Deleting a project', function() {
})
})
- describe('When the deleted project is expired', function() {
- beforeEach(function(done) {
+ describe('When the deleted project is expired', function () {
+ beforeEach(function (done) {
this.user.deleteProject(this.projectId, error => {
if (error) {
throw error
@@ -348,7 +348,7 @@ describe('Deleting a project', function() {
})
})
- it('Should destroy the docs', function(done) {
+ it('Should destroy the docs', function (done) {
expect(
MockDocstoreApi.docs[this.projectId.toString()][this.docId.toString()]
).to.exist
@@ -372,7 +372,7 @@ describe('Deleting a project', function() {
)
})
- it('Should destroy the files', function(done) {
+ it('Should destroy the files', function (done) {
expect(MockFilestoreApi.files[this.projectId.toString()]).to.exist
request.post(
@@ -395,7 +395,7 @@ describe('Deleting a project', function() {
)
})
- it('Should remove the project data from mongo', function(done) {
+ it('Should remove the project data from mongo', function (done) {
db.deletedProjects.findOne(
{ 'deleterData.deletedProjectId': ObjectId(this.projectId) },
(error, deletedProject) => {
@@ -438,12 +438,12 @@ describe('Deleting a project', function() {
})
})
- describe('when the deleted project has deletedFiles', function() {
- beforeEach('delete project', function(done) {
+ describe('when the deleted project has deletedFiles', function () {
+ beforeEach('delete project', function (done) {
this.user.deleteProject(this.projectId, done)
})
let fileId1, fileId2
- beforeEach('create files', function() {
+ beforeEach('create files', function () {
// take a short cut and just allocate file ids
fileId1 = ObjectId()
fileId2 = ObjectId()
@@ -454,7 +454,7 @@ describe('Deleting a project', function() {
hash: 'ed19e7d6779b47d8c63f6fa5a21954dcfb6cac00',
deletedAt: new Date()
}
- beforeEach('insert deletedFiles', async function() {
+ beforeEach('insert deletedFiles', async function () {
const deletedFiles = [
{ _id: fileId1, ...otherFileDetails },
{ _id: fileId2, ...otherFileDetails },
@@ -466,9 +466,9 @@ describe('Deleting a project', function() {
{ $set: { 'project.deletedFiles': deletedFiles } }
)
})
- describe('when undelete the project', function() {
+ describe('when undelete the project', function () {
let admin
- beforeEach('create admin', function(done) {
+ beforeEach('create admin', function (done) {
admin = new User()
async.series(
[
@@ -479,11 +479,11 @@ describe('Deleting a project', function() {
done
)
})
- beforeEach('undelete project', function(done) {
+ beforeEach('undelete project', function (done) {
admin.undeleteProject(this.projectId, done)
})
- it('should not insert deletedFiles into the projects collection', function(done) {
+ it('should not insert deletedFiles into the projects collection', function (done) {
this.user.getProject(this.projectId, (error, project) => {
if (error) return done(error)
expect(project.deletedFiles).to.deep.equal([])
@@ -491,7 +491,7 @@ describe('Deleting a project', function() {
})
})
- it('should insert unique entries into the deletedFiles collection', async function() {
+ it('should insert unique entries into the deletedFiles collection', async function () {
const docs = await db.deletedFiles
.find({}, { sort: { _id: 1 } })
.toArray()
@@ -503,13 +503,13 @@ describe('Deleting a project', function() {
})
})
- describe('when the deleted project has deletedDocs', function() {
- beforeEach('delete project', function(done) {
+ describe('when the deleted project has deletedDocs', function () {
+ beforeEach('delete project', function (done) {
this.user.deleteProject(this.projectId, done)
})
let deletedDocs
- beforeEach('set deletedDocs', function() {
+ beforeEach('set deletedDocs', function () {
deletedDocs = [
{ _id: ObjectId(), name: 'foo.tex', deletedAt: new Date() },
{ _id: ObjectId(), name: 'bar.tex', deletedAt: new Date() }
@@ -522,14 +522,14 @@ describe('Deleting a project', function() {
})
})
- beforeEach('insert deletedDocs', async function() {
+ beforeEach('insert deletedDocs', async function () {
await db.deletedProjects.updateOne(
{ 'deleterData.deletedProjectId': ObjectId(this.projectId) },
{ $set: { 'project.deletedDocs': deletedDocs } }
)
})
- it('should not see any doc names before', async function() {
+ it('should not see any doc names before', async function () {
const docs = MockDocstoreApi.getDeletedDocs(this.projectId)
expect(docs).to.deep.equal(
deletedDocs.map(doc => {
@@ -539,9 +539,9 @@ describe('Deleting a project', function() {
)
})
- describe('when undeleting the project', function() {
+ describe('when undeleting the project', function () {
let admin
- beforeEach('create admin', function(done) {
+ beforeEach('create admin', function (done) {
admin = new User()
async.series(
[
@@ -552,11 +552,11 @@ describe('Deleting a project', function() {
done
)
})
- beforeEach('undelete project', function(done) {
+ beforeEach('undelete project', function (done) {
admin.undeleteProject(this.projectId, done)
})
- it('should not insert deletedDocs into the projects collection', function(done) {
+ it('should not insert deletedDocs into the projects collection', function (done) {
this.user.getProject(this.projectId, (error, project) => {
if (error) return done(error)
expect(project.deletedDocs).to.deep.equal([])
@@ -564,7 +564,7 @@ describe('Deleting a project', function() {
})
})
- it('should back fill deleted docs context', async function() {
+ it('should back fill deleted docs context', async function () {
const docs = MockDocstoreApi.getDeletedDocs(this.projectId)
expect(docs).to.deep.equal(
deletedDocs.map(doc => {
diff --git a/services/web/test/acceptance/src/DocUpdateTests.js b/services/web/test/acceptance/src/DocUpdateTests.js
index 6ebc137ae5..e57ec6e2d4 100644
--- a/services/web/test/acceptance/src/DocUpdateTests.js
+++ b/services/web/test/acceptance/src/DocUpdateTests.js
@@ -4,8 +4,8 @@ const { expect } = require('chai')
const settings = require('settings-sharelatex')
const { ObjectId } = require('mongodb')
-describe('DocUpdate', function() {
- beforeEach(function(done) {
+describe('DocUpdate', function () {
+ beforeEach(function (done) {
this.user = new User()
this.projectName = 'wombat'
this.user.ensureUserExists(() => {
@@ -77,7 +77,7 @@ describe('DocUpdate', function() {
}
let writeOptions
- beforeEach(function() {
+ beforeEach(function () {
writeOptions = {
projectId: this.projectId,
docId: this.docId,
@@ -90,21 +90,21 @@ describe('DocUpdate', function() {
})
function shouldAcceptChanges() {
- it('should accept writes', function(done) {
+ it('should accept writes', function (done) {
writeContent(writeOptions, done)
})
- it('should accept updates', function(done) {
+ it('should accept updates', function (done) {
updateContent(writeOptions, done)
})
- it('should accept same write twice', function(done) {
+ it('should accept same write twice', function (done) {
writeContentTwice(writeOptions, done)
})
}
function shouldBlockChanges() {
- it('should block writes', function(done) {
+ it('should block writes', function (done) {
writeContent(writeOptions, err => {
expect(err).to.exist
expect(err.message).to.equal('non-success statusCode: 404')
@@ -112,7 +112,7 @@ describe('DocUpdate', function() {
})
})
- it('should block updates', function(done) {
+ it('should block updates', function (done) {
updateContent(writeOptions, err => {
expect(err).to.exist
expect(err.message).to.equal('non-success statusCode: 404')
@@ -121,28 +121,28 @@ describe('DocUpdate', function() {
})
}
- describe('a regular doc', function() {
+ describe('a regular doc', function () {
shouldAcceptChanges()
})
- describe('after deleting the doc', function() {
- beforeEach(function(done) {
+ describe('after deleting the doc', function () {
+ beforeEach(function (done) {
this.user.deleteItemInProject(this.projectId, 'doc', this.docId, done)
})
shouldAcceptChanges()
})
- describe('unknown doc', function() {
- beforeEach(function() {
+ describe('unknown doc', function () {
+ beforeEach(function () {
writeOptions.docId = ObjectId()
})
shouldBlockChanges()
})
- describe('doc in another project', function() {
- beforeEach(function(done) {
+ describe('doc in another project', function () {
+ beforeEach(function (done) {
this.user.createProject('foo', (error, projectId) => {
if (error) return done(error)
writeOptions.projectId = projectId
diff --git a/services/web/test/acceptance/src/EditorHttpControllerTests.js b/services/web/test/acceptance/src/EditorHttpControllerTests.js
index 52bb64a75f..8a7feeedcd 100644
--- a/services/web/test/acceptance/src/EditorHttpControllerTests.js
+++ b/services/web/test/acceptance/src/EditorHttpControllerTests.js
@@ -1,12 +1,12 @@
const User = require('./helpers/User')
const { expect } = require('chai')
-describe('EditorHttpController', function() {
- beforeEach('login', function(done) {
+describe('EditorHttpController', function () {
+ beforeEach('login', function (done) {
this.user = new User()
this.user.login(done)
})
- beforeEach('create project', function(done) {
+ beforeEach('create project', function (done) {
this.projectName = 'wombat'
this.user.createProject(this.projectName, (error, projectId) => {
if (error) return done(error)
@@ -14,7 +14,7 @@ describe('EditorHttpController', function() {
done()
})
})
- beforeEach('create doc', function(done) {
+ beforeEach('create doc', function (done) {
this.user.createDocInProject(
this.projectId,
null,
@@ -26,8 +26,8 @@ describe('EditorHttpController', function() {
)
})
- describe('joinProject', function() {
- it('should emit an empty deletedDocs array', function(done) {
+ describe('joinProject', function () {
+ it('should emit an empty deletedDocs array', function (done) {
this.user.joinProject(this.projectId, (error, details) => {
if (error) return done(error)
@@ -36,12 +36,12 @@ describe('EditorHttpController', function() {
})
})
- describe('after deleting a doc', function() {
- beforeEach(function(done) {
+ describe('after deleting a doc', function () {
+ beforeEach(function (done) {
this.user.deleteItemInProject(this.projectId, 'doc', this.docId, done)
})
- it('should include the deleted doc in the deletedDocs array', function(done) {
+ it('should include the deleted doc in the deletedDocs array', function (done) {
this.user.joinProject(this.projectId, (error, details) => {
if (error) return done(error)
diff --git a/services/web/test/acceptance/src/ExportsTests.js b/services/web/test/acceptance/src/ExportsTests.js
index 83fa01f94d..bf8e567588 100644
--- a/services/web/test/acceptance/src/ExportsTests.js
+++ b/services/web/test/acceptance/src/ExportsTests.js
@@ -24,13 +24,13 @@ const MockV1ApiClass = require('./mocks/MockV1Api')
let MockProjectHistoryApi, MockV1Api
-before(function() {
+before(function () {
MockV1Api = MockV1ApiClass.instance()
MockProjectHistoryApi = MockProjectHistoryApiClass.instance()
})
-describe('Exports', function() {
- beforeEach(function(done) {
+describe('Exports', function () {
+ beforeEach(function (done) {
this.brand_variation_id = '18'
this.owner = new User()
return this.owner.login(error => {
@@ -51,8 +51,8 @@ describe('Exports', function() {
})
})
- describe('exporting a project', function() {
- beforeEach(function(done) {
+ describe('exporting a project', function () {
+ beforeEach(function (done) {
this.version = Math.floor(Math.random() * 10000)
MockProjectHistoryApi.setProjectVersion(this.project_id, this.version)
this.export_id = Math.floor(Math.random() * 10000)
@@ -81,7 +81,7 @@ describe('Exports', function() {
)
})
- it('should have sent correct data to v1', function(done) {
+ it('should have sent correct data to v1', function (done) {
const {
project,
user,
@@ -107,7 +107,7 @@ describe('Exports', function() {
return done()
})
- it('should have returned the export ID provided by v1', function(done) {
+ it('should have returned the export ID provided by v1', function (done) {
expect(this.exportResponseBody.export_v1_id).to.equal(this.export_id)
return done()
})
diff --git a/services/web/test/acceptance/src/FeatureUpdaterTests.js b/services/web/test/acceptance/src/FeatureUpdaterTests.js
index 33bdc5cc88..9efe5fff83 100644
--- a/services/web/test/acceptance/src/FeatureUpdaterTests.js
+++ b/services/web/test/acceptance/src/FeatureUpdaterTests.js
@@ -12,11 +12,11 @@ logger.logger.level('error')
let MockV1Api
-before(function() {
+before(function () {
MockV1Api = MockV1ApiClass.instance()
})
-const syncUserAndGetFeatures = function(user, callback) {
+const syncUserAndGetFeatures = function (user, callback) {
FeaturesUpdater.refreshFeatures(user._id, error => {
if (error) {
return callback(error)
@@ -32,15 +32,15 @@ const syncUserAndGetFeatures = function(user, callback) {
})
}
-describe('FeatureUpdater.refreshFeatures', function() {
+describe('FeatureUpdater.refreshFeatures', function () {
let userHelper, user
- beforeEach(async function() {
+ beforeEach(async function () {
userHelper = await UserHelper.createUser()
user = userHelper.user
})
- describe('when user has no subscriptions', function() {
- it('should set their features to the basic set', function(done) {
+ describe('when user has no subscriptions', function () {
+ it('should set their features to the basic set', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
if (error) {
throw error
@@ -51,8 +51,8 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
})
- describe('when the user has an individual subscription', function() {
- beforeEach(function() {
+ describe('when the user has an individual subscription', function () {
+ beforeEach(function () {
Subscription.create({
admin_id: user._id,
manager_ids: [user._id],
@@ -61,7 +61,7 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
}) // returns a promise
- it('should set their features to the upgraded set', function(done) {
+ it('should set their features to the upgraded set', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
if (error) {
throw error
@@ -75,8 +75,8 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
})
- describe('when the user is in a group subscription', function() {
- beforeEach(function() {
+ describe('when the user is in a group subscription', function () {
+ beforeEach(function () {
const groupAdminId = ObjectId()
Subscription.create({
admin_id: groupAdminId,
@@ -88,7 +88,7 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
}) // returns a promise
- it('should set their features to the upgraded set', function(done) {
+ it('should set their features to the upgraded set', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
if (error) {
throw error
@@ -102,8 +102,8 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
})
- describe('when the user has bonus features', function() {
- beforeEach(function() {
+ describe('when the user has bonus features', function () {
+ beforeEach(function () {
return User.updateOne(
{
_id: user._id
@@ -114,7 +114,7 @@ describe('FeatureUpdater.refreshFeatures', function() {
)
}) // returns a promise
- it('should set their features to the bonus set', function(done) {
+ it('should set their features to the bonus set', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
if (error) {
throw error
@@ -131,9 +131,9 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
})
- describe('when the user has affiliations', function() {
+ describe('when the user has affiliations', function () {
let email2, institutionId, hostname
- beforeEach(async function() {
+ beforeEach(async function () {
institutionId = MockV1Api.createInstitution({ commonsAccount: true })
hostname = 'institution.edu'
MockV1Api.addInstitutionDomain(institutionId, hostname, {
@@ -149,32 +149,32 @@ describe('FeatureUpdater.refreshFeatures', function() {
)
})
- it('should not set their features if email is not confirmed', function(done) {
+ it('should not set their features if email is not confirmed', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
expect(features).to.deep.equal(settings.defaultFeatures)
done()
})
})
- describe('when email is confirmed', function() {
- beforeEach(async function() {
+ describe('when email is confirmed', function () {
+ beforeEach(async function () {
await userHelper.confirmEmail(user._id, email2)
})
- it('should set their features', function(done) {
+ it('should set their features', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
expect(features).to.deep.equal(this.institutionPlan.features)
done()
})
})
- describe('when domain is not confirmed as part of institution', function() {
- beforeEach(function() {
+ describe('when domain is not confirmed as part of institution', function () {
+ beforeEach(function () {
MockV1Api.updateInstitutionDomain(institutionId, hostname, {
confirmed: false
})
})
- it('should not set their features', function(done) {
+ it('should not set their features', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
expect(features).to.deep.equal(settings.defaultFeatures)
done()
@@ -184,8 +184,8 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
})
- describe('when the user is due bonus features and has extra features that no longer apply', function() {
- beforeEach(function() {
+ describe('when the user is due bonus features and has extra features that no longer apply', function () {
+ beforeEach(function () {
return User.updateOne(
{
_id: user._id
@@ -197,7 +197,7 @@ describe('FeatureUpdater.refreshFeatures', function() {
)
}) // returns a promise
- it('should set their features to the bonus set and downgrade the extras', function(done) {
+ it('should set their features to the bonus set and downgrade the extras', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
if (error) {
throw error
@@ -214,8 +214,8 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
})
- describe('when the user has a v1 plan', function() {
- beforeEach(function() {
+ describe('when the user has a v1 plan', function () {
+ beforeEach(function () {
MockV1Api.setUser(42, { plan_name: 'free' })
return User.updateOne(
{
@@ -229,7 +229,7 @@ describe('FeatureUpdater.refreshFeatures', function() {
)
}) // returns a promise
- it('should set their features to the v1 plan', function(done) {
+ it('should set their features to the v1 plan', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
if (error) {
throw error
@@ -241,8 +241,8 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
})
- describe('when the user has a v1 plan and bonus features', function() {
- beforeEach(function() {
+ describe('when the user has a v1 plan and bonus features', function () {
+ beforeEach(function () {
MockV1Api.setUser(42, { plan_name: 'free' })
return User.updateOne(
{
@@ -257,7 +257,7 @@ describe('FeatureUpdater.refreshFeatures', function() {
)
}) // returns a promise
- it('should set their features to the best of the v1 plan and bonus features', function(done) {
+ it('should set their features to the best of the v1 plan and bonus features', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
if (error) {
throw error
@@ -274,8 +274,8 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
})
- describe('when the user has a group and personal subscription', function() {
- beforeEach(function(done) {
+ describe('when the user has a group and personal subscription', function () {
+ beforeEach(function (done) {
const groupAdminId = ObjectId()
Subscription.create(
@@ -304,7 +304,7 @@ describe('FeatureUpdater.refreshFeatures', function() {
)
})
- it('should set their features to the best set', function(done) {
+ it('should set their features to the best set', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
if (error) {
throw error
@@ -318,8 +318,8 @@ describe('FeatureUpdater.refreshFeatures', function() {
})
})
- describe('when the notifyV1Flag is passed', function() {
- beforeEach(function() {
+ describe('when the notifyV1Flag is passed', function () {
+ beforeEach(function () {
User.updateOne(
{
_id: user._id
@@ -333,8 +333,8 @@ describe('FeatureUpdater.refreshFeatures', function() {
}) // returns a promise
})
- describe('when the user has features overrides', function() {
- beforeEach(function() {
+ describe('when the user has features overrides', function () {
+ beforeEach(function () {
const futureDate = new Date()
futureDate.setDate(futureDate.getDate() + 1)
return User.updateOne(
@@ -365,7 +365,7 @@ describe('FeatureUpdater.refreshFeatures', function() {
)
}) // returns a promise
- it('should set their features to the overridden set', function(done) {
+ it('should set their features to the overridden set', function (done) {
syncUserAndGetFeatures(user, (error, features) => {
if (error) {
throw error
diff --git a/services/web/test/acceptance/src/HealthCheckControllerTests.js b/services/web/test/acceptance/src/HealthCheckControllerTests.js
index cc45e95e11..7498a93869 100644
--- a/services/web/test/acceptance/src/HealthCheckControllerTests.js
+++ b/services/web/test/acceptance/src/HealthCheckControllerTests.js
@@ -2,11 +2,11 @@ const { expect } = require('chai')
const Settings = require('settings-sharelatex')
const User = require('./helpers/User').promises
-describe('HealthCheckController', function() {
- describe('SmokeTests', function() {
+describe('HealthCheckController', function () {
+ describe('SmokeTests', function () {
let user, projectId
- beforeEach(async function() {
+ beforeEach(async function () {
user = new User()
await user.login()
projectId = await user.createProject('SmokeTest')
@@ -36,8 +36,8 @@ describe('HealthCheckController', function() {
return { response, body }
}
- describe('happy path', function() {
- it('should respond with a 200 and stats', async function() {
+ describe('happy path', function () {
+ it('should respond with a 200 and stats', async function () {
const { response, body } = await performSmokeTestRequest()
expect(body.error).to.not.exist
@@ -45,8 +45,8 @@ describe('HealthCheckController', function() {
})
})
- describe('when the request is aborted', function() {
- it('should not crash', async function() {
+ describe('when the request is aborted', function () {
+ it('should not crash', async function () {
try {
await user.doRequest('GET', {
timeout: 1,
@@ -61,11 +61,11 @@ describe('HealthCheckController', function() {
})
})
- describe('when the project does not exist', function() {
- beforeEach(function() {
+ describe('when the project does not exist', function () {
+ beforeEach(function () {
Settings.smokeTest.projectId = '404'
})
- it('should respond with a 500 ', async function() {
+ it('should respond with a 500 ', async function () {
const { response, body } = await performSmokeTestRequest()
expect(body.error).to.equal('run.101_loadEditor failed')
@@ -73,11 +73,11 @@ describe('HealthCheckController', function() {
})
})
- describe('when the password mismatches', function() {
- beforeEach(function() {
+ describe('when the password mismatches', function () {
+ beforeEach(function () {
Settings.smokeTest.password = 'foo-bar'
})
- it('should respond with a 500 with mismatching password', async function() {
+ it('should respond with a 500 with mismatching password', async function () {
const { response, body } = await performSmokeTestRequest()
expect(body.error).to.equal('run.002_login failed')
diff --git a/services/web/test/acceptance/src/HistoryTests.js b/services/web/test/acceptance/src/HistoryTests.js
index 036dddd06f..a1ba614286 100644
--- a/services/web/test/acceptance/src/HistoryTests.js
+++ b/services/web/test/acceptance/src/HistoryTests.js
@@ -19,18 +19,18 @@ const MockV1HistoryApiClass = require('./mocks/MockV1HistoryApi')
let MockV1HistoryApi
-before(function() {
+before(function () {
MockV1HistoryApi = MockV1HistoryApiClass.instance()
})
-describe('History', function() {
- beforeEach(function(done) {
+describe('History', function () {
+ beforeEach(function (done) {
this.owner = new User()
return this.owner.login(done)
})
- describe('zip download of version', function() {
- it('should stream the zip file of a version', function(done) {
+ describe('zip download of version', function () {
+ it('should stream the zip file of a version', function (done) {
return this.owner.createProject(
'example-project',
(error, project_id) => {
@@ -77,7 +77,7 @@ describe('History', function() {
)
})
- describe('request abort', function() {
+ describe('request abort', function () {
// Optional manual verification: add unique logging statements into
// HistoryController._pipeHistoryZipToResponse
// in each of the `req.aborted` branches and confirm that each branch
@@ -101,7 +101,7 @@ describe('History', function() {
})
})
- it('should abort the upstream request', function(done) {
+ it('should abort the upstream request', function (done) {
const request = this.owner.request(
`/project/${this.project_id}/version/100/zip`
)
@@ -141,7 +141,7 @@ describe('History', function() {
})
})
- it('should skip the v1-history request', function(done) {
+ it('should skip the v1-history request', function (done) {
const request = this.owner.request(
`/project/${this.project_id}/version/100/zip`
)
@@ -159,7 +159,7 @@ describe('History', function() {
}, 500)
})
- it('should skip the async-polling', function(done) {
+ it('should skip the async-polling', function (done) {
const request = this.owner.request(
`/project/${this.project_id}/version/100/zip`
)
@@ -173,7 +173,7 @@ describe('History', function() {
}, 3000) // initial polling delay is 2s
})
- it('should skip the upstream request', function(done) {
+ it('should skip the upstream request', function (done) {
const request = this.owner.request(
`/project/${this.project_id}/version/100/zip`
)
@@ -190,7 +190,7 @@ describe('History', function() {
})
})
- it('should return 402 for non-v2-history project', function(done) {
+ it('should return 402 for non-v2-history project', function (done) {
return this.owner.createProject('non-v2-project', (error, project_id) => {
this.project_id = project_id
if (error != null) {
diff --git a/services/web/test/acceptance/src/LabelsTests.js b/services/web/test/acceptance/src/LabelsTests.js
index 4d1cffd09d..d38cee1219 100644
--- a/services/web/test/acceptance/src/LabelsTests.js
+++ b/services/web/test/acceptance/src/LabelsTests.js
@@ -21,12 +21,12 @@ const MockProjectHistoryApiClass = require('./mocks/MockProjectHistoryApi')
let MockProjectHistoryApi
-before(function() {
+before(function () {
MockProjectHistoryApi = MockProjectHistoryApiClass.instance()
})
-describe('Labels', function() {
- beforeEach(function(done) {
+describe('Labels', function () {
+ beforeEach(function (done) {
this.owner = new User()
return this.owner.login(error => {
if (error != null) {
@@ -46,7 +46,7 @@ describe('Labels', function() {
})
})
- it('getting labels', function(done) {
+ it('getting labels', function (done) {
const label_id = new ObjectId().toString()
const comment = 'a label comment'
const version = 3
@@ -73,7 +73,7 @@ describe('Labels', function() {
)
})
- it('creating a label', function(done) {
+ it('creating a label', function (done) {
const comment = 'a label comment'
const version = 3
@@ -97,7 +97,7 @@ describe('Labels', function() {
)
})
- it('deleting a label', function(done) {
+ it('deleting a label', function (done) {
const label_id = new ObjectId().toString()
const comment = 'a label comment'
const version = 3
diff --git a/services/web/test/acceptance/src/LinkedFilesTests.js b/services/web/test/acceptance/src/LinkedFilesTests.js
index b7106abc27..727352f676 100644
--- a/services/web/test/acceptance/src/LinkedFilesTests.js
+++ b/services/web/test/acceptance/src/LinkedFilesTests.js
@@ -18,24 +18,24 @@ LinkedUrlProxy.get('/', (req, res, next) => {
}
})
-describe('LinkedFiles', function() {
+describe('LinkedFiles', function () {
let projectOne, projectOneId, projectOneRootFolderId
let projectTwo, projectTwoId, projectTwoRootFolderId
let sourceDocName = 'test.txt'
let owner
- before(function(done) {
+ before(function (done) {
LinkedUrlProxy.listen(6543, done)
})
- beforeEach(async function() {
+ beforeEach(async function () {
owner = new User()
await owner.login()
await promisify(mkdirp)(Settings.path.dumpFolder)
})
- describe('creating a project linked file', function() {
- beforeEach(async function() {
+ describe('creating a project linked file', function () {
+ beforeEach(async function () {
projectOneId = await owner.createProject('plf-test-one', {
template: 'blank'
})
@@ -60,7 +60,7 @@ describe('LinkedFiles', function() {
)
})
- it('should produce a list of the users projects and their entities', async function() {
+ it('should produce a list of the users projects and their entities', async function () {
let { body } = await owner.doRequest('get', {
url: '/user/projects',
json: true
@@ -94,7 +94,7 @@ describe('LinkedFiles', function() {
})
})
- it('should import a file and refresh it if there is no v1 id', async function() {
+ it('should import a file and refresh it if there is no v1 id', async function () {
// import the file from the source project
let { response, body } = await owner.doRequest('post', {
url: `/project/${projectOneId}/linked_file`,
@@ -156,8 +156,8 @@ describe('LinkedFiles', function() {
})
})
- describe('with a linked project_file from a v1 project that has not been imported', function() {
- beforeEach(async function() {
+ describe('with a linked project_file from a v1 project that has not been imported', function () {
+ beforeEach(async function () {
projectOneId = await owner.createProject('plf-v1-test-one', {
template: 'blank'
})
@@ -177,7 +177,7 @@ describe('LinkedFiles', function() {
await owner.saveProject(projectOne)
})
- it('should refuse to refresh', async function() {
+ it('should refuse to refresh', async function () {
const { response, body } = await owner.doRequest('post', {
url: `/project/${projectOneId}/linked_file/abcd/refresh`,
json: true
@@ -189,8 +189,8 @@ describe('LinkedFiles', function() {
})
})
- describe('creating a URL based linked file', function() {
- beforeEach(async function() {
+ describe('creating a URL based linked file', function () {
+ beforeEach(async function () {
projectOneId = await owner.createProject('url-linked-files-project', {
template: 'blank'
})
@@ -198,7 +198,7 @@ describe('LinkedFiles', function() {
projectOneRootFolderId = projectOne.rootFolder[0]._id.toString()
})
- it('should download, create and replace a file', async function() {
+ it('should download, create and replace a file', async function () {
// downloading the initial file
let { response, body } = await owner.doRequest('post', {
url: `/project/${projectOneId}/linked_file`,
@@ -266,7 +266,7 @@ describe('LinkedFiles', function() {
expect(body).to.equal('bar bar bar')
})
- it("should return an error if the file can't be downloaded", async function() {
+ it("should return an error if the file can't be downloaded", async function () {
// download does not succeed
let { response, body } = await owner.doRequest('post', {
url: `/project/${projectOneId}/linked_file`,
@@ -319,7 +319,7 @@ describe('LinkedFiles', function() {
)
})
- it('should accept a URL withuot a leading http://, and add it', async function() {
+ it('should accept a URL withuot a leading http://, and add it', async function () {
let { response, body } = await owner.doRequest('post', {
url: `/project/${projectOneId}/linked_file`,
json: {
@@ -355,8 +355,8 @@ describe('LinkedFiles', function() {
// TODO: Add test for asking for host that return ENOTFOUND
// (This will probably end up handled by the proxy)
- describe('creating a linked output file', function() {
- beforeEach(async function() {
+ describe('creating a linked output file', function () {
+ beforeEach(async function () {
projectOneId = await owner.createProject('output-test-one', {
template: 'blank'
})
@@ -370,7 +370,7 @@ describe('LinkedFiles', function() {
projectTwoRootFolderId = projectTwo.rootFolder[0]._id.toString()
})
- it('should import the project.pdf file from the source project and refresh it', async function() {
+ it('should import the project.pdf file from the source project and refresh it', async function () {
// import the file
let { response, body } = await owner.doRequest('post', {
url: `/project/${projectOneId}/linked_file`,
@@ -417,8 +417,8 @@ describe('LinkedFiles', function() {
})
})
- describe('with a linked project_output_file from a v1 project that has not been imported', function() {
- beforeEach(async function() {
+ describe('with a linked project_output_file from a v1 project that has not been imported', function () {
+ beforeEach(async function () {
projectOneId = await owner.createProject('output-v1-test-one', {
template: 'blank'
})
@@ -439,7 +439,7 @@ describe('LinkedFiles', function() {
await owner.saveProject(projectOne)
})
- it('should refuse to refresh', async function() {
+ it('should refuse to refresh', async function () {
const { response, body } = await owner.doRequest('post', {
url: `/project/${projectOneId}/linked_file/abcdef/refresh`,
json: true
diff --git a/services/web/test/acceptance/src/ModelTests.js b/services/web/test/acceptance/src/ModelTests.js
index 643ae52d49..f90bf47657 100644
--- a/services/web/test/acceptance/src/ModelTests.js
+++ b/services/web/test/acceptance/src/ModelTests.js
@@ -3,30 +3,30 @@ const { expect } = require('chai')
const { User } = require('../../../app/src/models/User')
const { Subscription } = require('../../../app/src/models/Subscription')
-describe('mongoose', function() {
- describe('User', function() {
+describe('mongoose', function () {
+ describe('User', function () {
const email = 'wombat@potato.net'
- it('allows the creation of a user', async function() {
+ it('allows the creation of a user', async function () {
await expect(User.create({ email: email })).to.be.fulfilled
await expect(User.findOne({ email: email })).to.eventually.exist
})
- it('does not allow the creation of multiple users with the same email', async function() {
+ it('does not allow the creation of multiple users with the same email', async function () {
await expect(User.create({ email: email })).to.be.fulfilled
await expect(User.create({ email: email })).to.be.rejected
await expect(User.countDocuments({ email: email })).to.eventually.equal(1)
})
})
- describe('Subsription', function() {
+ describe('Subsription', function () {
let user
- beforeEach(async function() {
+ beforeEach(async function () {
user = await User.create({ email: 'wombat@potato.net' })
})
- it('allows the creation of a subscription', async function() {
+ it('allows the creation of a subscription', async function () {
await expect(
Subscription.create({ admin_id: user._id, manager_ids: [user._id] })
).to.be.fulfilled
@@ -34,7 +34,7 @@ describe('mongoose', function() {
.exist
})
- it('does not allow the creation of a subscription without a manager', async function() {
+ it('does not allow the creation of a subscription without a manager', async function () {
await expect(Subscription.create({ admin_id: user._id })).to.be.rejected
})
})
diff --git a/services/web/test/acceptance/src/MongoHelper.js b/services/web/test/acceptance/src/MongoHelper.js
index 0491d3befd..6eb7acec4c 100644
--- a/services/web/test/acceptance/src/MongoHelper.js
+++ b/services/web/test/acceptance/src/MongoHelper.js
@@ -12,7 +12,7 @@ const {
const User = require('./helpers/User').promises
-describe('MongoTests', function() {
+describe('MongoTests', function () {
let userIdAsString, userEmail, userIds
beforeEach(async function setUpUsers() {
// the first user in the db should not match the target user
@@ -31,7 +31,7 @@ describe('MongoTests', function() {
userIds = [otherUser.id, user.id, yetAnotherUser.id]
})
- describe('normalizeQuery', function() {
+ describe('normalizeQuery', function () {
async function expectToWork(blob) {
const query = normalizeQuery(blob)
@@ -44,21 +44,21 @@ describe('MongoTests', function() {
expect(user.email).to.equal(userEmail)
}
- it('should work with the user id as string', async function() {
+ it('should work with the user id as string', async function () {
await expectToWork(userIdAsString)
})
- it('should work with the user id in an object', async function() {
+ it('should work with the user id in an object', async function () {
await expectToWork({ _id: userIdAsString })
})
- it('should pass back the object with id', function() {
+ it('should pass back the object with id', function () {
const inputQuery = { _id: userIdAsString, other: 1 }
const query = normalizeMultiQuery(inputQuery)
expect(inputQuery).to.equal(query)
})
- describe('with an ObjectId from mongoose', function() {
+ describe('with an ObjectId from mongoose', function () {
let user
beforeEach(async function getUser() {
user = await UserModel.findById(userIdAsString).exec()
@@ -67,16 +67,16 @@ describe('MongoTests', function() {
expect(user.email).to.equal(userEmail)
})
- it('should have a mongoose ObjectId', function() {
+ it('should have a mongoose ObjectId', function () {
expect(user._id).to.be.instanceof(MongooseObjectId)
})
- it('should work with the users _id field', async function() {
+ it('should work with the users _id field', async function () {
await expectToWork(user._id)
})
})
- describe('with an ObjectId from the native driver', function() {
+ describe('with an ObjectId from the native driver', function () {
let user
beforeEach(async function getUser() {
user = await db.users.findOne({ _id: NativeObjectId(userIdAsString) })
@@ -85,17 +85,17 @@ describe('MongoTests', function() {
expect(user.email).to.equal(userEmail)
})
- it('should have a native ObjectId', function() {
+ it('should have a native ObjectId', function () {
expect(user._id).to.be.instanceof(NativeObjectId)
})
- it('should work with the users _id field', async function() {
+ it('should work with the users _id field', async function () {
await expectToWork(user._id)
})
})
})
- describe('normalizeMultiQuery', function() {
+ describe('normalizeMultiQuery', function () {
let ghost
beforeEach(async function addGhost() {
// add a user which is not part of the initial three users
@@ -113,7 +113,7 @@ describe('MongoTests', function() {
)
}
- describe('with an array as query', function() {
+ describe('with an array as query', function () {
function expectInQueryWithNativeObjectIds(query) {
expect(query).to.exist
expect(query._id).to.exist
@@ -123,47 +123,47 @@ describe('MongoTests', function() {
).to.deep.equal([true, true, true])
}
- it('should transform all strings to native ObjectIds', function() {
+ it('should transform all strings to native ObjectIds', function () {
const query = normalizeMultiQuery(userIds)
expectInQueryWithNativeObjectIds(query)
})
- it('should transform all Mongoose ObjectIds to native ObjectIds', function() {
+ it('should transform all Mongoose ObjectIds to native ObjectIds', function () {
const query = normalizeMultiQuery(userIds.map(MongooseObjectId))
expectInQueryWithNativeObjectIds(query)
})
- it('should leave all native Objects as native ObjectIds', function() {
+ it('should leave all native Objects as native ObjectIds', function () {
const query = normalizeMultiQuery(userIds.map(NativeObjectId))
expectInQueryWithNativeObjectIds(query)
})
- it('should find the three users from string ids', async function() {
+ it('should find the three users from string ids', async function () {
const query = normalizeMultiQuery(userIds)
await expectToFindTheThreeUsers(query)
})
- it('should find the three users from Mongoose ObjectIds', async function() {
+ it('should find the three users from Mongoose ObjectIds', async function () {
const query = normalizeMultiQuery(userIds.map(MongooseObjectId))
await expectToFindTheThreeUsers(query)
})
- it('should find the three users from native ObjectIds', async function() {
+ it('should find the three users from native ObjectIds', async function () {
const query = normalizeMultiQuery(userIds.map(NativeObjectId))
await expectToFindTheThreeUsers(query)
})
})
- describe('with an object as query', function() {
+ describe('with an object as query', function () {
beforeEach(async function addHiddenFlag() {
// add a mongo field that does not exist on the other users
await ghost.mongoUpdate({ $set: { hidden: 1 } })
})
- it('should pass through the query', function() {
+ it('should pass through the query', function () {
const inputQuery = { complex: 1 }
const query = normalizeMultiQuery(inputQuery)
expect(inputQuery).to.equal(query)
})
- describe('when searching for hidden users', function() {
- it('should match the ghost only', async function() {
+ describe('when searching for hidden users', function () {
+ it('should match the ghost only', async function () {
const query = normalizeMultiQuery({ hidden: 1 })
const users = await db.users.find(query).toArray()
@@ -172,8 +172,8 @@ describe('MongoTests', function() {
})
})
- describe('when searching for non hidden users', function() {
- it('should find the three users', async function() {
+ describe('when searching for non hidden users', function () {
+ it('should find the three users', async function () {
const query = normalizeMultiQuery({ hidden: { $exists: false } })
await expectToFindTheThreeUsers(query)
diff --git a/services/web/test/acceptance/src/PasswordResetTests.js b/services/web/test/acceptance/src/PasswordResetTests.js
index 66d48fdaad..164eb5db77 100644
--- a/services/web/test/acceptance/src/PasswordResetTests.js
+++ b/services/web/test/acceptance/src/PasswordResetTests.js
@@ -3,15 +3,15 @@ const RateLimiter = require('../../../app/src/infrastructure/RateLimiter')
const UserHelper = require('./helpers/UserHelper')
const { db } = require('../../../app/src/infrastructure/mongodb')
-describe('PasswordReset', function() {
+describe('PasswordReset', function () {
let email, response, user, userHelper, token, emailQuery
- afterEach(async function() {
+ afterEach(async function () {
await RateLimiter.promises.clearRateLimit(
'password_reset_rate_limit',
'127.0.0.1'
)
})
- beforeEach(async function() {
+ beforeEach(async function () {
userHelper = new UserHelper()
email = userHelper.getDefaultEmail()
emailQuery = `?email=${encodeURIComponent(email)}`
@@ -32,9 +32,9 @@ describe('PasswordReset', function() {
})
).token
})
- describe('with a valid token', function() {
- describe('when logged in', function() {
- beforeEach(async function() {
+ describe('with a valid token', function () {
+ describe('when logged in', function () {
+ beforeEach(async function () {
userHelper = await UserHelper.loginUser({
email,
password: userHelper.getDefaultPassword()
@@ -57,11 +57,11 @@ describe('PasswordReset', function() {
userHelper = await UserHelper.getUser({ email })
user = userHelper.user
})
- it('update the password', async function() {
+ it('update the password', async function () {
expect(user.hashedPassword).to.exist
expect(user.password).to.not.exist
})
- it('log the change with initiatorId', async function() {
+ it('log the change with initiatorId', async function () {
const auditLog = userHelper.getAuditLogWithoutNoise()
expect(auditLog).to.exist
expect(auditLog[0]).to.exist
@@ -72,9 +72,9 @@ describe('PasswordReset', function() {
expect(auditLog[0].timestamp).to.exist
})
})
- describe('when logged in as another user', function() {
+ describe('when logged in as another user', function () {
let otherUser, otherUserEmail
- beforeEach(async function() {
+ beforeEach(async function () {
otherUserEmail = userHelper.getDefaultEmail()
userHelper = await UserHelper.createUser({ email: otherUserEmail })
otherUser = userHelper.user
@@ -100,11 +100,11 @@ describe('PasswordReset', function() {
userHelper = await UserHelper.getUser({ email })
user = userHelper.user
})
- it('update the password', async function() {
+ it('update the password', async function () {
expect(user.hashedPassword).to.exist
expect(user.password).to.not.exist
})
- it('log the change with the logged in user as the initiatorId', async function() {
+ it('log the change with the logged in user as the initiatorId', async function () {
const auditLog = userHelper.getAuditLogWithoutNoise()
expect(auditLog).to.exist
expect(auditLog[0]).to.exist
@@ -115,8 +115,8 @@ describe('PasswordReset', function() {
expect(auditLog[0].timestamp).to.exist
})
})
- describe('when not logged in', function() {
- beforeEach(async function() {
+ describe('when not logged in', function () {
+ beforeEach(async function () {
response = await userHelper.request.get(
`/user/password/set?passwordResetToken=${token}&email=${email}`,
{ simple: false }
@@ -135,11 +135,11 @@ describe('PasswordReset', function() {
userHelper = await UserHelper.getUser({ email })
user = userHelper.user
})
- it('updates the password', function() {
+ it('updates the password', function () {
expect(user.hashedPassword).to.exist
expect(user.password).to.not.exist
})
- it('log the change', async function() {
+ it('log the change', async function () {
const auditLog = userHelper.getAuditLogWithoutNoise()
expect(auditLog).to.exist
expect(auditLog[0]).to.exist
@@ -149,8 +149,8 @@ describe('PasswordReset', function() {
expect(auditLog[0].timestamp).to.exist
})
})
- describe('password checks', function() {
- beforeEach(async function() {
+ describe('password checks', function () {
+ beforeEach(async function () {
response = await userHelper.request.get(
`/user/password/set?passwordResetToken=${token}&email=${email}`,
{ simple: false }
@@ -160,7 +160,7 @@ describe('PasswordReset', function() {
`/user/password/set${emailQuery}`
)
})
- it('without a password should return 400 and not log the change', async function() {
+ it('without a password should return 400 and not log the change', async function () {
// send reset request
response = await userHelper.request.post('/user/password/set', {
form: {
@@ -175,7 +175,7 @@ describe('PasswordReset', function() {
expect(auditLog).to.deep.equal([])
})
- it('without a valid password should return 400 and not log the change', async function() {
+ it('without a valid password should return 400 and not log the change', async function () {
// send reset request
response = await userHelper.request.post('/user/password/set', {
form: {
@@ -192,8 +192,8 @@ describe('PasswordReset', function() {
})
})
})
- describe('without a valid token', function() {
- it('no token should redirect to page to re-request reset token', async function() {
+ describe('without a valid token', function () {
+ it('no token should redirect to page to re-request reset token', async function () {
response = await userHelper.request.get(
`/user/password/set?&email=${email}`,
{ simple: false }
@@ -201,7 +201,7 @@ describe('PasswordReset', function() {
expect(response.statusCode).to.equal(302)
expect(response.headers.location).to.equal('/user/password/reset')
})
- it('should return 404 for invalid tokens', async function() {
+ it('should return 404 for invalid tokens', async function () {
const invalidToken = 'not-real-token'
response = await userHelper.request.get(
`/user/password/set?&passwordResetToken=${invalidToken}&email=${email}`,
@@ -222,8 +222,8 @@ describe('PasswordReset', function() {
expect(response.statusCode).to.equal(404)
})
})
- describe('password reset', function() {
- it('should return 200 if email field is valid', async function() {
+ describe('password reset', function () {
+ it('should return 200 if email field is valid', async function () {
response = await userHelper.request.post(`/user/password/reset`, {
form: {
email
@@ -232,7 +232,7 @@ describe('PasswordReset', function() {
expect(response.statusCode).to.equal(200)
})
- it('should return 400 if email field is missing', async function() {
+ it('should return 400 if email field is missing', async function () {
response = await userHelper.request.post(`/user/password/reset`, {
form: {
mail: email
@@ -242,8 +242,8 @@ describe('PasswordReset', function() {
expect(response.statusCode).to.equal(400)
})
})
- describe('password set', function() {
- it('should return 200 if password and passwordResetToken fields are valid', async function() {
+ describe('password set', function () {
+ it('should return 200 if password and passwordResetToken fields are valid', async function () {
response = await userHelper.request.post(`/user/password/set`, {
form: {
password: 'new-password',
@@ -253,7 +253,7 @@ describe('PasswordReset', function() {
expect(response.statusCode).to.equal(200)
})
- it('should return 400 if password field is missing', async function() {
+ it('should return 400 if password field is missing', async function () {
response = await userHelper.request.post(`/user/password/set`, {
form: {
passwordResetToken: token
@@ -263,7 +263,7 @@ describe('PasswordReset', function() {
expect(response.statusCode).to.equal(400)
})
- it('should return 400 if passwordResetToken field is missing', async function() {
+ it('should return 400 if passwordResetToken field is missing', async function () {
response = await userHelper.request.post(`/user/password/set`, {
form: {
password: 'new-password'
diff --git a/services/web/test/acceptance/src/PasswordUpdateTests.js b/services/web/test/acceptance/src/PasswordUpdateTests.js
index 20c3ea9f87..137a1f90fe 100644
--- a/services/web/test/acceptance/src/PasswordUpdateTests.js
+++ b/services/web/test/acceptance/src/PasswordUpdateTests.js
@@ -2,15 +2,15 @@ const { expect } = require('chai')
const RateLimiter = require('../../../app/src/infrastructure/RateLimiter')
const UserHelper = require('./helpers/UserHelper')
-describe('PasswordUpdate', function() {
+describe('PasswordUpdate', function () {
let email, password, response, user, userHelper
- afterEach(async function() {
+ afterEach(async function () {
await RateLimiter.promises.clearRateLimit(
'password_reset_rate_limit',
'127.0.0.1'
)
})
- beforeEach(async function() {
+ beforeEach(async function () {
userHelper = new UserHelper()
email = userHelper.getDefaultEmail()
password = 'old-password'
@@ -21,8 +21,8 @@ describe('PasswordUpdate', function() {
})
await userHelper.getCsrfToken()
})
- describe('success', function() {
- beforeEach(async function() {
+ describe('success', function () {
+ beforeEach(async function () {
response = await userHelper.request.post('/user/password/update', {
form: {
currentPassword: password,
@@ -34,10 +34,10 @@ describe('PasswordUpdate', function() {
userHelper = await UserHelper.getUser({ email })
user = userHelper.user
})
- it('should return 200', async function() {
+ it('should return 200', async function () {
expect(response.statusCode).to.equal(200)
})
- it('should update the audit log', function() {
+ it('should update the audit log', function () {
const auditLog = userHelper.getAuditLogWithoutNoise()
expect(auditLog[0]).to.exist
expect(typeof auditLog[0].initiatorId).to.equal('object')
@@ -47,9 +47,9 @@ describe('PasswordUpdate', function() {
expect(auditLog[0].timestamp).to.exist
})
})
- describe('errors', function() {
- describe('missing current password', function() {
- beforeEach(async function() {
+ describe('errors', function () {
+ describe('missing current password', function () {
+ beforeEach(async function () {
response = await userHelper.request.post('/user/password/update', {
form: {
newPassword1: 'new-password',
@@ -59,16 +59,16 @@ describe('PasswordUpdate', function() {
})
userHelper = await UserHelper.getUser({ email })
})
- it('should return 500', async function() {
+ it('should return 500', async function () {
expect(response.statusCode).to.equal(500)
})
- it('should not update audit log', async function() {
+ it('should not update audit log', async function () {
const auditLog = userHelper.getAuditLogWithoutNoise()
expect(auditLog).to.deep.equal([])
})
})
- describe('wrong current password', function() {
- beforeEach(async function() {
+ describe('wrong current password', function () {
+ beforeEach(async function () {
response = await userHelper.request.post('/user/password/update', {
form: {
currentPassword: 'wrong-password',
@@ -79,16 +79,16 @@ describe('PasswordUpdate', function() {
})
userHelper = await UserHelper.getUser({ email })
})
- it('should return 400', async function() {
+ it('should return 400', async function () {
expect(response.statusCode).to.equal(400)
})
- it('should not update audit log', async function() {
+ it('should not update audit log', async function () {
const auditLog = userHelper.getAuditLogWithoutNoise()
expect(auditLog).to.deep.equal([])
})
})
- describe('newPassword1 does not match newPassword2', function() {
- beforeEach(async function() {
+ describe('newPassword1 does not match newPassword2', function () {
+ beforeEach(async function () {
response = await userHelper.request.post('/user/password/update', {
form: {
currentPassword: password,
@@ -100,19 +100,19 @@ describe('PasswordUpdate', function() {
})
userHelper = await UserHelper.getUser({ email })
})
- it('should return 400', async function() {
+ it('should return 400', async function () {
expect(response.statusCode).to.equal(400)
})
- it('should return error message', async function() {
+ it('should return error message', async function () {
expect(response.body.message).to.equal('Passwords do not match')
})
- it('should not update audit log', async function() {
+ it('should not update audit log', async function () {
const auditLog = userHelper.getAuditLogWithoutNoise()
expect(auditLog).to.deep.equal([])
})
})
- describe('new password is not valid', function() {
- beforeEach(async function() {
+ describe('new password is not valid', function () {
+ beforeEach(async function () {
response = await userHelper.request.post('/user/password/update', {
form: {
currentPassword: password,
@@ -124,13 +124,13 @@ describe('PasswordUpdate', function() {
})
userHelper = await UserHelper.getUser({ email })
})
- it('should return 400', async function() {
+ it('should return 400', async function () {
expect(response.statusCode).to.equal(400)
})
- it('should return error message', async function() {
+ it('should return error message', async function () {
expect(response.body.message).to.equal('password is too short')
})
- it('should not update audit log', async function() {
+ it('should not update audit log', async function () {
const auditLog = userHelper.getAuditLogWithoutNoise()
expect(auditLog).to.deep.equal([])
})
diff --git a/services/web/test/acceptance/src/ProjectCRUDTests.js b/services/web/test/acceptance/src/ProjectCRUDTests.js
index 38f4efc093..a8de99521e 100644
--- a/services/web/test/acceptance/src/ProjectCRUDTests.js
+++ b/services/web/test/acceptance/src/ProjectCRUDTests.js
@@ -3,16 +3,16 @@ const User = require('./helpers/User').promises
const { Project } = require('../../../app/src/models/Project')
const { ObjectId } = require('mongodb')
-describe('Project CRUD', function() {
- beforeEach(async function() {
+describe('Project CRUD', function () {
+ beforeEach(async function () {
this.user = new User()
await this.user.login()
this.projectId = await this.user.createProject('example-project')
})
- describe("when project doesn't exist", function() {
- it('should return 404', async function() {
+ describe("when project doesn't exist", function () {
+ it('should return 404', async function () {
const { response } = await this.user.doRequest(
'GET',
'/project/aaaaaaaaaaaaaaaaaaaaaaaa'
@@ -21,15 +21,15 @@ describe('Project CRUD', function() {
})
})
- describe('when project has malformed id', function() {
- it('should return 404', async function() {
+ describe('when project has malformed id', function () {
+ it('should return 404', async function () {
const { response } = await this.user.doRequest('GET', '/project/blah')
expect(response.statusCode).to.equal(404)
})
})
- describe('when trashing a project', function() {
- it('should mark the project as trashed for the user', async function() {
+ describe('when trashing a project', function () {
+ it('should mark the project as trashed for the user', async function () {
const { response } = await this.user.doRequest(
'POST',
`/project/${this.projectId}/trash`
@@ -40,7 +40,7 @@ describe('Project CRUD', function() {
expectObjectIdArrayEqual(trashedProject.trashed, [this.user._id])
})
- it('does nothing if the user has already trashed the project', async function() {
+ it('does nothing if the user has already trashed the project', async function () {
// Mark as trashed the first time
await this.user.doRequest('POST', `/project/${this.projectId}/trash`)
@@ -51,8 +51,8 @@ describe('Project CRUD', function() {
expectObjectIdArrayEqual(trashedProject.trashed, [this.user._id])
})
- describe('with an array archived state', function() {
- it('should mark the project as not archived for the user', async function() {
+ describe('with an array archived state', function () {
+ it('should mark the project as not archived for the user', async function () {
await Project.updateOne(
{ _id: this.projectId },
{ $set: { archived: [ObjectId(this.user._id)] } }
@@ -70,8 +70,8 @@ describe('Project CRUD', function() {
})
})
- describe('with a legacy boolean state', function() {
- it('should mark the project as not archived for the user', async function() {
+ describe('with a legacy boolean state', function () {
+ it('should mark the project as not archived for the user', async function () {
await Project.updateOne(
{ _id: this.projectId },
{ $set: { archived: true } }
@@ -90,8 +90,8 @@ describe('Project CRUD', function() {
})
})
- describe('when untrashing a project', function() {
- it('should mark the project as untrashed for the user', async function() {
+ describe('when untrashing a project', function () {
+ it('should mark the project as untrashed for the user', async function () {
await Project.updateOne(
{ _id: this.projectId },
{ trashed: [ObjectId(this.user._id)] }
@@ -106,7 +106,7 @@ describe('Project CRUD', function() {
expectObjectIdArrayEqual(trashedProject.trashed, [])
})
- it('does nothing if the user has already untrashed the project', async function() {
+ it('does nothing if the user has already untrashed the project', async function () {
await Project.updateOne(
{ _id: this.projectId },
{ trashed: [ObjectId(this.user._id)] }
@@ -121,7 +121,7 @@ describe('Project CRUD', function() {
expectObjectIdArrayEqual(trashedProject.trashed, [])
})
- it('sets trashed to an empty array if not set', async function() {
+ it('sets trashed to an empty array if not set', async function () {
await this.user.doRequest('DELETE', `/project/${this.projectId}/trash`)
const trashedProject = await Project.findById(this.projectId).exec()
diff --git a/services/web/test/acceptance/src/ProjectDuplicateNameTests.js b/services/web/test/acceptance/src/ProjectDuplicateNameTests.js
index 0bdc60b8d6..d0e0966863 100644
--- a/services/web/test/acceptance/src/ProjectDuplicateNameTests.js
+++ b/services/web/test/acceptance/src/ProjectDuplicateNameTests.js
@@ -34,21 +34,21 @@ const MockFilestoreApiClass = require('./mocks/MockFilestoreApi')
let MockDocstoreApi, MockFilestoreApi
-before(function() {
+before(function () {
MockDocstoreApi = MockDocstoreApiClass.instance()
MockFilestoreApi = MockFilestoreApiClass.instance()
})
-describe('ProjectDuplicateNames', function() {
- beforeEach(function(done) {
+describe('ProjectDuplicateNames', function () {
+ beforeEach(function (done) {
this.owner = new User()
this.owner.login(done)
this.project = {}
return (this.callback = sinon.stub())
})
- describe('creating a project from the example template', function() {
- beforeEach(function(done) {
+ describe('creating a project from the example template', function () {
+ beforeEach(function (done) {
return this.owner.createProject(
'example-project',
{ template: 'example' },
@@ -91,24 +91,24 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should create a project', function() {
+ it('should create a project', function () {
expect(this.project.rootFolder[0].docs.length).to.equal(2)
return expect(this.project.rootFolder[0].fileRefs.length).to.equal(1)
})
- it('should create two docs in the docstore', function() {
+ it('should create two docs in the docstore', function () {
const docs = MockDocstoreApi.docs[this.example_project_id]
return expect(Object.keys(docs).length).to.equal(2)
})
- it('should create one file in the filestore', function() {
+ it('should create one file in the filestore', function () {
const files = MockFilestoreApi.files[this.example_project_id]
return expect(Object.keys(files).length).to.equal(1)
})
- describe('for an existing doc', function() {
- describe('trying to add a doc with the same name', function() {
- beforeEach(function(done) {
+ describe('for an existing doc', function () {
+ describe('trying to add a doc with the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc`,
@@ -124,13 +124,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to add a folder with the same name', function() {
- beforeEach(function(done) {
+ describe('trying to add a folder with the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
@@ -146,13 +146,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to add a folder with the same name', function() {
- beforeEach(function(done) {
+ describe('trying to add a folder with the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
@@ -168,15 +168,15 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
})
- describe('for an existing file', function() {
- describe('trying to add a doc with the same name', function() {
- beforeEach(function(done) {
+ describe('for an existing file', function () {
+ describe('trying to add a doc with the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc`,
@@ -192,13 +192,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to add a folder with the same name', function() {
- beforeEach(function(done) {
+ describe('trying to add a folder with the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
@@ -214,13 +214,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to upload a file with the same name', function() {
- beforeEach(function(done) {
+ describe('trying to upload a file with the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/upload`,
@@ -250,16 +250,16 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should succeed (overwriting the file)', function() {
+ it('should succeed (overwriting the file)', function () {
return expect(this.body.success).to.equal(true)
})
})
})
// at this point the @imageFile._id has changed
- describe('for an existing folder', function() {
- describe('trying to add a doc with the same name', function() {
- beforeEach(function(done) {
+ describe('for an existing folder', function () {
+ describe('trying to add a doc with the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc`,
@@ -275,13 +275,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to add a folder with the same name', function() {
- beforeEach(function(done) {
+ describe('trying to add a folder with the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
@@ -297,13 +297,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to upload a file with the same name', function() {
- beforeEach(function(done) {
+ describe('trying to upload a file with the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/upload`,
@@ -331,15 +331,15 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with failure status', function() {
+ it('should respond with failure status', function () {
return expect(this.body.success).to.equal(false)
})
})
})
- describe('for an existing doc', function() {
- describe('trying to rename a doc to the same name', function() {
- beforeEach(function(done) {
+ describe('for an existing doc', function () {
+ describe('trying to rename a doc to the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc/${this.refBibDoc._id}/rename`,
@@ -354,13 +354,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to rename a folder to the same name', function() {
- beforeEach(function(done) {
+ describe('trying to rename a folder to the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder/${this.testFolderId}/rename`,
@@ -375,13 +375,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to rename a file to the same name', function() {
- beforeEach(function(done) {
+ describe('trying to rename a file to the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/file/${this.imageFile._id}/rename`,
@@ -396,15 +396,15 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with failure status', function() {
+ it('should respond with failure status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
})
- describe('for an existing file', function() {
- describe('trying to rename a doc to the same name', function() {
- beforeEach(function(done) {
+ describe('for an existing file', function () {
+ describe('trying to rename a doc to the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc/${this.refBibDoc._id}/rename`,
@@ -419,13 +419,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to rename a folder to the same name', function() {
- beforeEach(function(done) {
+ describe('trying to rename a folder to the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder/${this.testFolderId}/rename`,
@@ -440,13 +440,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to rename a file to the same name', function() {
- beforeEach(function(done) {
+ describe('trying to rename a file to the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/file/${this.imageFile._id}/rename`,
@@ -461,15 +461,15 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with failure status', function() {
+ it('should respond with failure status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
})
- describe('for an existing folder', function() {
- describe('trying to rename a doc to the same name', function() {
- beforeEach(function(done) {
+ describe('for an existing folder', function () {
+ describe('trying to rename a doc to the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc/${this.refBibDoc._id}/rename`,
@@ -484,13 +484,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to rename a folder to the same name', function() {
- beforeEach(function(done) {
+ describe('trying to rename a folder to the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder/${this.testFolderId}/rename`,
@@ -505,13 +505,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to rename a file to the same name', function() {
- beforeEach(function(done) {
+ describe('trying to rename a file to the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/file/${this.imageFile._id}/rename`,
@@ -526,14 +526,14 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with failure status', function() {
+ it('should respond with failure status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
})
- describe('for an existing folder with a file with the same name', function() {
- beforeEach(function(done) {
+ describe('for an existing folder with a file with the same name', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc`,
@@ -583,8 +583,8 @@ describe('ProjectDuplicateNames', function() {
)
})
- describe('trying to move a doc into the folder', function() {
- beforeEach(function(done) {
+ describe('trying to move a doc into the folder', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc/${this.mainTexDoc._id}/move`,
@@ -599,13 +599,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to move a file into the folder', function() {
- beforeEach(function(done) {
+ describe('trying to move a file into the folder', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/file/${this.imageFile._id}/move`,
@@ -620,13 +620,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to move a folder into the folder', function() {
- beforeEach(function(done) {
+ describe('trying to move a folder into the folder', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder/${this.otherFolderId}/move`,
@@ -641,13 +641,13 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
- describe('trying to move a folder into a subfolder of itself', function() {
- beforeEach(function(done) {
+ describe('trying to move a folder into a subfolder of itself', function () {
+ beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder/${this.testFolderId}/move`,
@@ -662,7 +662,7 @@ describe('ProjectDuplicateNames', function() {
)
})
- it('should respond with 400 error status', function() {
+ it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
diff --git a/services/web/test/acceptance/src/ProjectFeaturesTests.js b/services/web/test/acceptance/src/ProjectFeaturesTests.js
index 5c51e36d4c..6086e67657 100644
--- a/services/web/test/acceptance/src/ProjectFeaturesTests.js
+++ b/services/web/test/acceptance/src/ProjectFeaturesTests.js
@@ -33,15 +33,15 @@ const joinProject = (user_id, project_id, callback) =>
callback
)
-describe('ProjectFeatures', function() {
- beforeEach(function(done) {
+describe('ProjectFeatures', function () {
+ beforeEach(function (done) {
this.timeout(90000)
this.owner = new User()
return async.series([cb => this.owner.login(cb)], done)
})
- describe('with private project', function() {
- beforeEach(function(done) {
+ describe('with private project', function () {
+ beforeEach(function (done) {
return this.owner.createProject(
'private-project',
(error, project_id) => {
@@ -54,15 +54,15 @@ describe('ProjectFeatures', function() {
)
})
- describe('with an upgraded account', function() {
- beforeEach(function(done) {
+ describe('with an upgraded account', function () {
+ beforeEach(function (done) {
return this.owner.upgradeFeatures(done)
})
- after(function(done) {
+ after(function (done) {
return this.owner.defaultFeatures(done)
})
- it('should have premium features', function(done) {
+ it('should have premium features', function (done) {
return joinProject(
this.owner._id,
this.project_id,
@@ -77,15 +77,15 @@ describe('ProjectFeatures', function() {
})
})
- describe('with an basic account', function() {
- beforeEach(function(done) {
+ describe('with an basic account', function () {
+ beforeEach(function (done) {
return this.owner.downgradeFeatures(done)
})
- after(function(done) {
+ after(function (done) {
return this.owner.defaultFeatures(done)
})
- it('should have basic features', function(done) {
+ it('should have basic features', function (done) {
return joinProject(
this.owner._id,
this.project_id,
diff --git a/services/web/test/acceptance/src/ProjectInviteTests.js b/services/web/test/acceptance/src/ProjectInviteTests.js
index 87c3d2e7d6..d4a90944fe 100644
--- a/services/web/test/acceptance/src/ProjectInviteTests.js
+++ b/services/web/test/acceptance/src/ProjectInviteTests.js
@@ -299,8 +299,8 @@ const expectInvitesInJoinProjectCount = (user, projectId, count, callback) => {
})
}
-describe('ProjectInviteTests', function() {
- beforeEach(function(done) {
+describe('ProjectInviteTests', function () {
+ beforeEach(function (done) {
this.sendingUser = new User()
this.user = new User()
this.site_admin = new User({ email: 'admin@example.com' })
@@ -316,13 +316,13 @@ describe('ProjectInviteTests', function() {
)
})
- describe('creating invites', function() {
- beforeEach(function() {
+ describe('creating invites', function () {
+ beforeEach(function () {
this.projectName = 'wat'
})
- describe('creating two invites', function() {
- beforeEach(function(done) {
+ describe('creating two invites', function () {
+ beforeEach(function (done) {
createProject(
this.sendingUser,
this.projectName,
@@ -335,7 +335,7 @@ describe('ProjectInviteTests', function() {
)
})
- it('should allow the project owner to create and remove invites', function(done) {
+ it('should allow the project owner to create and remove invites', function (done) {
Async.series(
[
cb => expectProjectAccess(this.sendingUser, this.projectId, cb),
@@ -414,7 +414,7 @@ describe('ProjectInviteTests', function() {
)
})
- it('should allow the project owner to create many invites at once', function(done) {
+ it('should allow the project owner to create many invites at once', function (done) {
Async.series(
[
cb => expectProjectAccess(this.sendingUser, this.projectId, cb),
@@ -488,8 +488,8 @@ describe('ProjectInviteTests', function() {
})
})
- describe('clicking the invite link', function() {
- beforeEach(function(done) {
+ describe('clicking the invite link', function () {
+ beforeEach(function (done) {
createProjectAndInvite(
this.sendingUser,
this.projectName,
@@ -505,13 +505,13 @@ describe('ProjectInviteTests', function() {
)
})
- describe('user is logged in already', function() {
- beforeEach(function(done) {
+ describe('user is logged in already', function () {
+ beforeEach(function (done) {
this.user.login(done)
})
- describe('user is already a member of the project', function() {
- beforeEach(function(done) {
+ describe('user is already a member of the project', function () {
+ beforeEach(function (done) {
Async.series(
[
cb => expectInvitePage(this.user, this.link, cb),
@@ -522,8 +522,8 @@ describe('ProjectInviteTests', function() {
)
})
- describe('when user clicks on the invite a second time', function() {
- it('should just redirect to the project page', function(done) {
+ describe('when user clicks on the invite a second time', function () {
+ it('should just redirect to the project page', function (done) {
Async.series(
[
cb => expectProjectAccess(this.user, this.invite.projectId, cb),
@@ -540,8 +540,8 @@ describe('ProjectInviteTests', function() {
)
})
- describe('when the user recieves another invite to the same project', function() {
- it('should redirect to the project page', function(done) {
+ describe('when the user recieves another invite to the same project', function () {
+ it('should redirect to the project page', function (done) {
Async.series(
[
cb => {
@@ -586,8 +586,8 @@ describe('ProjectInviteTests', function() {
})
})
- describe('user is not a member of the project', function() {
- it('should not grant access if the user does not accept the invite', function(done) {
+ describe('user is not a member of the project', function () {
+ it('should not grant access if the user does not accept the invite', function (done) {
Async.series(
[
cb => expectInvitePage(this.user, this.link, cb),
@@ -597,7 +597,7 @@ describe('ProjectInviteTests', function() {
)
})
- it('should render the invalid-invite page if the token is invalid', function(done) {
+ it('should render the invalid-invite page if the token is invalid', function (done) {
Async.series(
[
cb => {
@@ -614,7 +614,7 @@ describe('ProjectInviteTests', function() {
)
})
- it('should allow the user to accept the invite and access the project', function(done) {
+ it('should allow the user to accept the invite and access the project', function (done) {
Async.series(
[
cb => expectInvitePage(this.user, this.link, cb),
@@ -627,19 +627,19 @@ describe('ProjectInviteTests', function() {
})
})
- describe('user is not logged in initially', function() {
- describe('registration prompt workflow with valid token', function() {
- before(function() {
+ describe('user is not logged in initially', function () {
+ describe('registration prompt workflow with valid token', function () {
+ before(function () {
if (!Features.hasFeature('public-registration')) {
this.skip()
}
})
- it('should redirect to the register page', function(done) {
+ it('should redirect to the register page', function (done) {
expectInviteRedirectToRegister(this.user, this.link, done)
})
- it('should allow user to accept the invite if the user registers a new account', function(done) {
+ it('should allow user to accept the invite if the user registers a new account', function (done) {
Async.series(
[
cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@@ -659,14 +659,14 @@ describe('ProjectInviteTests', function() {
})
})
- describe('registration prompt workflow with non-valid token', function() {
- before(function() {
+ describe('registration prompt workflow with non-valid token', function () {
+ before(function () {
if (!Features.hasFeature('public-registration')) {
this.skip()
}
})
- it('should redirect to the register page', function(done) {
+ it('should redirect to the register page', function (done) {
Async.series(
[
cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@@ -676,7 +676,7 @@ describe('ProjectInviteTests', function() {
)
})
- it('should display invalid-invite if the user registers a new account', function(done) {
+ it('should display invalid-invite if the user registers a new account', function (done) {
const badLink = this.link.replace(
this.invite.token,
'not_a_real_token'
@@ -699,8 +699,8 @@ describe('ProjectInviteTests', function() {
})
})
- describe('login workflow with valid token', function() {
- it('should redirect to the register page', function(done) {
+ describe('login workflow with valid token', function () {
+ it('should redirect to the register page', function (done) {
Async.series(
[
cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@@ -710,7 +710,7 @@ describe('ProjectInviteTests', function() {
)
})
- it('should allow the user to login to view the invite', function(done) {
+ it('should allow the user to login to view the invite', function (done) {
Async.series(
[
cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@@ -723,7 +723,7 @@ describe('ProjectInviteTests', function() {
)
})
- it('should allow user to accept the invite if the user logs in', function(done) {
+ it('should allow user to accept the invite if the user logs in', function (done) {
Async.series(
[
cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@@ -738,8 +738,8 @@ describe('ProjectInviteTests', function() {
})
})
- describe('login workflow with non-valid token', function() {
- it('should redirect to the register page', function(done) {
+ describe('login workflow with non-valid token', function () {
+ it('should redirect to the register page', function (done) {
Async.series(
[
cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@@ -749,7 +749,7 @@ describe('ProjectInviteTests', function() {
)
})
- it('should show the invalid-invite page once the user has logged in', function(done) {
+ it('should show the invalid-invite page once the user has logged in', function (done) {
const badLink = this.link.replace(
this.invite.token,
'not_a_real_token'
diff --git a/services/web/test/acceptance/src/ProjectOwnershipTransferTests.js b/services/web/test/acceptance/src/ProjectOwnershipTransferTests.js
index bbf30d23b8..739f1f71e1 100644
--- a/services/web/test/acceptance/src/ProjectOwnershipTransferTests.js
+++ b/services/web/test/acceptance/src/ProjectOwnershipTransferTests.js
@@ -1,8 +1,8 @@
const { expect } = require('chai')
const User = require('./helpers/User').promises
-describe('Project ownership transfer', function() {
- beforeEach(async function() {
+describe('Project ownership transfer', function () {
+ beforeEach(async function () {
this.ownerSession = new User()
this.collaboratorSession = new User()
this.strangerSession = new User()
@@ -25,39 +25,39 @@ describe('Project ownership transfer', function() {
)
})
- describe('happy path', function() {
- beforeEach(async function() {
+ describe('happy path', function () {
+ beforeEach(async function () {
await this.ownerSession.transferProjectOwnership(
this.projectId,
this.collaborator._id
)
})
- it('changes the project owner', async function() {
+ it('changes the project owner', async function () {
const project = await this.collaboratorSession.getProject(this.projectId)
expect(project.owner_ref.toString()).to.equal(
this.collaborator._id.toString()
)
})
- it('adds the previous owner as a read/write collaborator', async function() {
+ it('adds the previous owner as a read/write collaborator', async function () {
const project = await this.collaboratorSession.getProject(this.projectId)
expect(project.collaberator_refs.map(x => x.toString())).to.have.members([
this.owner._id.toString()
])
})
- it('lets the new owner open the project', async function() {
+ it('lets the new owner open the project', async function () {
await this.collaboratorSession.openProject(this.projectId)
})
- it('lets the previous owner open the project', async function() {
+ it('lets the previous owner open the project', async function () {
await this.ownerSession.openProject(this.projectId)
})
})
- describe('validation', function() {
- it('lets only the project owner transfer ownership', async function() {
+ describe('validation', function () {
+ it('lets only the project owner transfer ownership', async function () {
await expect(
this.collaboratorSession.transferProjectOwnership(
this.projectId,
@@ -66,7 +66,7 @@ describe('Project ownership transfer', function() {
).to.be.rejectedWith('Unexpected status code: 403')
})
- it('prevents transfers to a non-collaborator', async function() {
+ it('prevents transfers to a non-collaborator', async function () {
await expect(
this.ownerSession.transferProjectOwnership(
this.projectId,
@@ -75,7 +75,7 @@ describe('Project ownership transfer', function() {
).to.be.rejectedWith('Unexpected status code: 403')
})
- it('allows an admin to transfer to any project to a non-collaborator', async function() {
+ it('allows an admin to transfer to any project to a non-collaborator', async function () {
await expect(
this.adminSession.transferProjectOwnership(
this.projectId,
diff --git a/services/web/test/acceptance/src/ProjectStructureMongoLockTest.js b/services/web/test/acceptance/src/ProjectStructureMongoLockTest.js
index 6804398d82..7e3008b9ae 100644
--- a/services/web/test/acceptance/src/ProjectStructureMongoLockTest.js
+++ b/services/web/test/acceptance/src/ProjectStructureMongoLockTest.js
@@ -30,17 +30,17 @@ const _ = require('lodash')
// It is tested that these methods DO work when the lock has not been taken in
// other acceptance tests.
-describe('ProjectStructureMongoLock', function() {
- describe('whilst a project lock is taken', function() {
+describe('ProjectStructureMongoLock', function () {
+ describe('whilst a project lock is taken', function () {
let oldMaxLockWaitTime
- before(function() {
+ before(function () {
oldMaxLockWaitTime = LockManager.MAX_LOCK_WAIT_TIME
})
- after(function() {
+ after(function () {
LockManager.MAX_LOCK_WAIT_TIME = oldMaxLockWaitTime
})
- beforeEach(function(done) {
+ beforeEach(function (done) {
// We want to instantly fail if the lock is taken
LockManager.MAX_LOCK_WAIT_TIME = 1
this.lockValue = 'lock-value'
@@ -76,11 +76,11 @@ describe('ProjectStructureMongoLock', function() {
})
})
- after(function(done) {
+ after(function (done) {
return LockManager._releaseLock(this.lock_key, this.lockValue, done)
})
- describe('interacting with the locked project', function() {
+ describe('interacting with the locked project', function () {
const LOCKING_UPDATE_METHODS = [
'addDoc',
'addFile',
@@ -90,7 +90,7 @@ describe('ProjectStructureMongoLock', function() {
'addFolder'
]
for (var methodName of Array.from(LOCKING_UPDATE_METHODS)) {
- it(`cannot call ProjectEntityMongoUpdateHandler.${methodName}`, function(done) {
+ it(`cannot call ProjectEntityMongoUpdateHandler.${methodName}`, function (done) {
const method = ProjectEntityMongoUpdateHandler[methodName]
const args = _.times(method.length - 2, _.constant(null))
return method(this.locked_project._id, args, err => {
@@ -101,7 +101,7 @@ describe('ProjectStructureMongoLock', function() {
})
}
- it('cannot get the project without a projection', function(done) {
+ it('cannot get the project without a projection', function (done) {
return ProjectGetter.getProject(this.locked_project._id, err => {
expect(err).to.be.instanceOf(Error)
expect(err).to.have.property('message', 'Timeout')
@@ -109,7 +109,7 @@ describe('ProjectStructureMongoLock', function() {
})
})
- it('cannot get the project if rootFolder is in the projection', function(done) {
+ it('cannot get the project if rootFolder is in the projection', function (done) {
return ProjectGetter.getProject(
this.locked_project._id,
{ rootFolder: true },
@@ -121,7 +121,7 @@ describe('ProjectStructureMongoLock', function() {
)
})
- it('can get the project if rootFolder is not in the projection', function(done) {
+ it('can get the project if rootFolder is not in the projection', function (done) {
return ProjectGetter.getProject(
this.locked_project._id,
{ _id: true },
@@ -134,8 +134,8 @@ describe('ProjectStructureMongoLock', function() {
})
})
- describe('interacting with other projects', function() {
- beforeEach(function(done) {
+ describe('interacting with other projects', function () {
+ beforeEach(function (done) {
return ProjectCreationHandler.createBlankProject(
this.user._id,
'unlocked-project',
@@ -149,7 +149,7 @@ describe('ProjectStructureMongoLock', function() {
)
})
- it('can add folders to other projects', function(done) {
+ it('can add folders to other projects', function (done) {
return ProjectEntityMongoUpdateHandler.addFolder(
this.unlocked_project._id,
this.unlocked_project.rootFolder[0]._id,
@@ -162,7 +162,7 @@ describe('ProjectStructureMongoLock', function() {
)
})
- it('can get other projects without a projection', function(done) {
+ it('can get other projects without a projection', function (done) {
return ProjectGetter.getProject(
this.unlocked_project._id,
(err, project) => {
diff --git a/services/web/test/acceptance/src/ProjectStructureTests.js b/services/web/test/acceptance/src/ProjectStructureTests.js
index 8c3e566324..48def3e9aa 100644
--- a/services/web/test/acceptance/src/ProjectStructureTests.js
+++ b/services/web/test/acceptance/src/ProjectStructureTests.js
@@ -15,15 +15,15 @@ const MockDocUpdaterApiClass = require('./mocks/MockDocUpdaterApi')
let MockDocStoreApi, MockDocUpdaterApi
-before(function() {
+before(function () {
MockDocUpdaterApi = MockDocUpdaterApiClass.instance()
MockDocStoreApi = MockDocStoreApiClass.instance()
})
-describe('ProjectStructureChanges', function() {
+describe('ProjectStructureChanges', function () {
let owner
- beforeEach(function(done) {
+ beforeEach(function (done) {
owner = new User()
owner.login(done)
})
@@ -185,17 +185,17 @@ describe('ProjectStructureChanges', function() {
})
}
- describe('creating a project from the example template', function() {
+ describe('creating a project from the example template', function () {
let exampleProjectId
- beforeEach(function(done) {
+ beforeEach(function (done) {
createExampleProject(owner, (err, projectId) => {
exampleProjectId = projectId
done(err)
})
})
- it('should version creating a doc and a file', function() {
+ it('should version creating a doc and a file', function () {
const { updates, version } = MockDocUpdaterApi.getProjectStructureUpdates(
exampleProjectId
)
@@ -217,10 +217,10 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('duplicating a project', function() {
+ describe('duplicating a project', function () {
let dupProjectId
- beforeEach(function(done) {
+ beforeEach(function (done) {
createExampleProject(owner, (err, projectId) => {
if (err) {
return done(err)
@@ -246,7 +246,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should version the docs and files created', function() {
+ it('should version the docs and files created', function () {
const { updates, version } = MockDocUpdaterApi.getProjectStructureUpdates(
dupProjectId
)
@@ -268,10 +268,10 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('adding a doc', function() {
+ describe('adding a doc', function () {
let exampleProjectId, oldVersion
- beforeEach(function(done) {
+ beforeEach(function (done) {
createExampleProject(owner, (err, projectId) => {
if (err) {
return done(err)
@@ -289,7 +289,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should version the doc added', function(done) {
+ it('should version the doc added', function (done) {
const {
updates,
version: newVersion
@@ -311,10 +311,10 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('uploading a project', function() {
+ describe('uploading a project', function () {
let exampleProjectId
- beforeEach(function(done) {
+ beforeEach(function (done) {
uploadExampleProject(owner, 'test_project.zip', (err, projectId) => {
if (err) {
return done(err)
@@ -324,7 +324,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should version the docs and files created', function() {
+ it('should version the docs and files created', function () {
const { updates, version } = MockDocUpdaterApi.getProjectStructureUpdates(
exampleProjectId
)
@@ -341,11 +341,11 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('uploading a project with a name', function() {
+ describe('uploading a project with a name', function () {
let exampleProjectId
const testProjectName = 'wombat'
- beforeEach(function(done) {
+ beforeEach(function (done) {
uploadExampleProject(
owner,
'test_project_with_name.zip',
@@ -359,7 +359,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should set the project name from the zip contents', function(done) {
+ it('should set the project name from the zip contents', function (done) {
ProjectGetter.getProject(exampleProjectId, (error, project) => {
expect(error).not.to.exist
expect(project.name).to.equal(testProjectName)
@@ -368,11 +368,11 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('uploading a project with an invalid name', function() {
+ describe('uploading a project with an invalid name', function () {
let exampleProjectId
const testProjectMatch = /^bad[^\\]+name$/
- beforeEach(function(done) {
+ beforeEach(function (done) {
uploadExampleProject(
owner,
'test_project_with_invalid_name.zip',
@@ -386,7 +386,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should set the project name from the zip contents', function(done) {
+ it('should set the project name from the zip contents', function (done) {
ProjectGetter.getProject(exampleProjectId, (error, project) => {
expect(error).not.to.exist
expect(project.name).to.match(testProjectMatch)
@@ -395,10 +395,10 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('uploading an empty zipfile', function() {
+ describe('uploading an empty zipfile', function () {
let res
- beforeEach(function(done) {
+ beforeEach(function (done) {
uploadExampleProject(
owner,
'test_project_empty.zip',
@@ -413,15 +413,15 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should fail with 422 error', function() {
+ it('should fail with 422 error', function () {
expect(res.statusCode).to.equal(422)
})
})
- describe('uploading a zipfile containing only empty directories', function() {
+ describe('uploading a zipfile containing only empty directories', function () {
let res
- beforeEach(function(done) {
+ beforeEach(function (done) {
uploadExampleProject(
owner,
'test_project_with_empty_folder.zip',
@@ -437,15 +437,15 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should fail with 422 error', function() {
+ it('should fail with 422 error', function () {
expect(res.statusCode).to.equal(422)
})
})
- describe('uploading a project with a shared top-level folder', function() {
+ describe('uploading a project with a shared top-level folder', function () {
let exampleProjectId
- beforeEach(function(done) {
+ beforeEach(function (done) {
uploadExampleProject(
owner,
'test_project_with_shared_top_level_folder.zip',
@@ -459,7 +459,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should not create the top-level folder', function(done) {
+ it('should not create the top-level folder', function (done) {
ProjectGetter.getProject(exampleProjectId, (error, project) => {
expect(error).not.to.exist
expect(project.rootFolder[0].folders.length).to.equal(0)
@@ -469,10 +469,10 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('uploading a project with backslashes in the path names', function() {
+ describe('uploading a project with backslashes in the path names', function () {
let exampleProjectId
- beforeEach(function(done) {
+ beforeEach(function (done) {
uploadExampleProject(
owner,
'test_project_with_backslash_in_filename.zip',
@@ -486,7 +486,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should treat the backslash as a directory separator', function(done) {
+ it('should treat the backslash as a directory separator', function (done) {
ProjectGetter.getProject(exampleProjectId, (error, project) => {
expect(error).not.to.exist
expect(project.rootFolder[0].folders[0].name).to.equal('styles')
@@ -496,9 +496,9 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('uploading a project with files in different encodings', function() {
+ describe('uploading a project with files in different encodings', function () {
let updates
- beforeEach(function(done) {
+ beforeEach(function (done) {
uploadExampleProject(owner, 'charsets/charsets.zip', (err, projectId) => {
if (err) {
return done(err)
@@ -510,7 +510,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should correctly parse windows-1252', function() {
+ it('should correctly parse windows-1252', function () {
const update = _.find(
updates,
update => update.pathname === '/test-german-windows-1252.tex'
@@ -520,7 +520,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should correctly parse German utf8', function() {
+ it('should correctly parse German utf8', function () {
const update = _.find(
updates,
update => update.pathname === '/test-german-utf8x.tex'
@@ -530,7 +530,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should correctly parse little-endian utf16', function() {
+ it('should correctly parse little-endian utf16', function () {
const update = _.find(
updates,
update => update.pathname === '/test-greek-utf16-le-bom.tex'
@@ -540,7 +540,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should correctly parse Greek utf8', function() {
+ it('should correctly parse Greek utf8', function () {
const update = _.find(
updates,
update => update.pathname === '/test-greek-utf8x.tex'
@@ -551,10 +551,10 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('uploading a file', function() {
+ describe('uploading a file', function () {
let exampleProjectId, oldVersion, rootFolderId
- beforeEach(function(done) {
+ beforeEach(function (done) {
createExampleProject(owner, (err, projectId, folderId) => {
if (err) {
return done(err)
@@ -574,7 +574,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should version a newly uploaded file', function(done) {
+ it('should version a newly uploaded file', function (done) {
const { updates, version } = MockDocUpdaterApi.getProjectStructureUpdates(
exampleProjectId
)
@@ -589,7 +589,7 @@ describe('ProjectStructureChanges', function() {
verifyVersionIncremented(exampleProjectId, oldVersion, version, 1, done)
})
- it('should version a replacement file', function(done) {
+ it('should version a replacement file', function (done) {
MockDocUpdaterApi.reset()
uploadFile(
@@ -627,14 +627,14 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('moving entities', function() {
+ describe('moving entities', function () {
let exampleProjectId,
oldVersion,
exampleDocId,
exampleFileId,
exampleFolderId
- beforeEach(function(done) {
+ beforeEach(function (done) {
createExampleProject(owner, (err, projectId, rootFolderId) => {
if (err) {
return done(err)
@@ -670,7 +670,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should version moving a doc', function(done) {
+ it('should version moving a doc', function (done) {
moveItem(
owner,
exampleProjectId,
@@ -701,7 +701,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should version moving a file', function(done) {
+ it('should version moving a file', function (done) {
moveItem(
owner,
exampleProjectId,
@@ -732,7 +732,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should version moving a folder', function(done) {
+ it('should version moving a folder', function (done) {
moveItem(
owner,
exampleProjectId,
@@ -792,14 +792,14 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('renaming entities', function() {
+ describe('renaming entities', function () {
let exampleProjectId,
exampleDocId,
exampleFileId,
exampleFolderId,
oldVersion
- beforeEach(function(done) {
+ beforeEach(function (done) {
createExampleProject(owner, (err, projectId, rootFolderId) => {
if (err) {
return done(err)
@@ -841,7 +841,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should version renaming a doc', function(done) {
+ it('should version renaming a doc', function (done) {
renameItem(
owner,
exampleProjectId,
@@ -871,7 +871,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should version renaming a file', function(done) {
+ it('should version renaming a file', function (done) {
renameItem(
owner,
exampleProjectId,
@@ -901,7 +901,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should version renaming a folder', function(done) {
+ it('should version renaming a folder', function (done) {
renameItem(
owner,
exampleProjectId,
@@ -935,10 +935,10 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('deleting entities', function() {
+ describe('deleting entities', function () {
let exampleProjectId, oldVersion, exampleFolderId
- beforeEach(function(done) {
+ beforeEach(function (done) {
createExampleProject(owner, (err, projectId) => {
if (err) {
return done(err)
@@ -978,7 +978,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should version deleting a folder', function(done) {
+ it('should version deleting a folder', function (done) {
deleteItem(owner, exampleProjectId, 'folder', exampleFolderId, () => {
const {
updates,
@@ -999,8 +999,8 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('deleting docs', function() {
- beforeEach(function(done) {
+ describe('deleting docs', function () {
+ beforeEach(function (done) {
createExampleProject(owner, (err, projectId) => {
if (err) {
return done(err)
@@ -1032,7 +1032,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should pass the doc name to docstore', function(done) {
+ it('should pass the doc name to docstore', function (done) {
deleteItem(
owner,
this.exampleProjectId,
@@ -1048,8 +1048,8 @@ describe('ProjectStructureChanges', function() {
)
})
- describe('when rootDoc_id matches doc being deleted', function() {
- beforeEach(function(done) {
+ describe('when rootDoc_id matches doc being deleted', function () {
+ beforeEach(function (done) {
Project.updateOne(
{ _id: this.exampleProjectId },
{ $set: { rootDoc_id: this.exampleDocId } },
@@ -1057,7 +1057,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should clear rootDoc_id', function(done) {
+ it('should clear rootDoc_id', function (done) {
deleteItem(
owner,
this.exampleProjectId,
@@ -1079,8 +1079,8 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('when rootDoc_id does not match doc being deleted', function() {
- beforeEach(function(done) {
+ describe('when rootDoc_id does not match doc being deleted', function () {
+ beforeEach(function (done) {
this.exampleRootDocId = new ObjectId()
Project.updateOne(
{ _id: this.exampleProjectId },
@@ -1089,7 +1089,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should not clear rootDoc_id', function(done) {
+ it('should not clear rootDoc_id', function (done) {
deleteItem(
owner,
this.exampleProjectId,
@@ -1114,10 +1114,10 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('tpds', function() {
+ describe('tpds', function () {
let projectName, exampleProjectId, oldVersion, rootFolderId
- beforeEach(function(done) {
+ beforeEach(function (done) {
projectName = `tpds-project-${new ObjectId().toString()}`
owner.createProject(projectName, (error, projectId) => {
if (error) {
@@ -1138,7 +1138,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should version adding a doc', function(done) {
+ it('should version adding a doc', function (done) {
const texFile = fs.createReadStream(
Path.resolve(Path.join(__dirname, '..', 'files', 'test.tex'))
)
@@ -1182,7 +1182,7 @@ describe('ProjectStructureChanges', function() {
texFile.pipe(req)
})
- it('should version adding a new file', function(done) {
+ it('should version adding a new file', function (done) {
const imageFile = fs.createReadStream(
Path.resolve(Path.join(__dirname, '..', 'files', '1pixel.png'))
)
@@ -1226,8 +1226,8 @@ describe('ProjectStructureChanges', function() {
imageFile.pipe(req)
})
- describe('when there are files in the project', function() {
- beforeEach(function(done) {
+ describe('when there are files in the project', function () {
+ beforeEach(function (done) {
uploadExampleFile(owner, exampleProjectId, rootFolderId, () => {
createExampleDoc(owner, exampleProjectId, () => {
ProjectGetter.getProject(exampleProjectId, (error, project) => {
@@ -1242,7 +1242,7 @@ describe('ProjectStructureChanges', function() {
})
})
- it('should version replacing a file', function(done) {
+ it('should version replacing a file', function (done) {
const imageFile = fs.createReadStream(
Path.resolve(Path.join(__dirname, '..', 'files', '2pixel.png'))
)
@@ -1295,7 +1295,7 @@ describe('ProjectStructureChanges', function() {
imageFile.pipe(req)
})
- it('should version deleting a doc', function(done) {
+ it('should version deleting a doc', function (done) {
owner.request.delete(
{
uri: `/user/${owner._id}/update/${projectName}/new.tex`,
@@ -1337,9 +1337,9 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('uploading a document', function() {
+ describe('uploading a document', function () {
let exampleProjectId, rootFolderId
- beforeEach(function(done) {
+ beforeEach(function (done) {
createExampleProject(owner, (err, projectId, folderId) => {
if (err) {
return done(err)
@@ -1351,8 +1351,8 @@ describe('ProjectStructureChanges', function() {
})
})
- describe('with an unusual character set', function() {
- it('should correctly handle utf16-le data', function(done) {
+ describe('with an unusual character set', function () {
+ it('should correctly handle utf16-le data', function (done) {
uploadFile(
owner,
exampleProjectId,
@@ -1376,7 +1376,7 @@ describe('ProjectStructureChanges', function() {
)
})
- it('should correctly handle windows1252/iso-8859-1/latin1 data', function(done) {
+ it('should correctly handle windows1252/iso-8859-1/latin1 data', function (done) {
uploadFile(
owner,
exampleProjectId,
diff --git a/services/web/test/acceptance/src/ProxyUrls.js b/services/web/test/acceptance/src/ProxyUrls.js
index cb7b666202..67eed01da6 100644
--- a/services/web/test/acceptance/src/ProxyUrls.js
+++ b/services/web/test/acceptance/src/ProxyUrls.js
@@ -23,12 +23,12 @@ const assertResponse = (path, expectedStatusCode, expectedBody, cb) =>
return cb()
})
-describe('ProxyUrls', function() {
- beforeEach(function() {
+describe('ProxyUrls', function () {
+ beforeEach(function () {
return this.timeout(1000)
})
- it('proxy static URLs', function(done) {
+ it('proxy static URLs', function (done) {
return async.series(
[
cb => assertResponse('/institutions/list', 200, [], cb),
@@ -38,7 +38,7 @@ describe('ProxyUrls', function() {
)
})
- it('proxy dynamic URLs', function(done) {
+ it('proxy dynamic URLs', function (done) {
return async.series(
[
cb =>
@@ -60,14 +60,14 @@ describe('ProxyUrls', function() {
)
})
- it('return 404 if proxy is not set', function(done) {
+ it('return 404 if proxy is not set', function (done) {
return async.series(
[cb => assertResponse('/institutions/foobar', 404, null, cb)],
done
)
})
- it('handle missing baseUrl', function(done) {
+ it('handle missing baseUrl', function (done) {
return async.series(
[cb => assertResponse('/proxy/missing/baseUrl', 500, null, cb)],
done
diff --git a/services/web/test/acceptance/src/RecurlySubscriptionUpdateTests.js b/services/web/test/acceptance/src/RecurlySubscriptionUpdateTests.js
index f0d5d06306..c588e5cdd8 100644
--- a/services/web/test/acceptance/src/RecurlySubscriptionUpdateTests.js
+++ b/services/web/test/acceptance/src/RecurlySubscriptionUpdateTests.js
@@ -3,9 +3,9 @@ const async = require('async')
const User = require('./helpers/User')
const RecurlySubscription = require('./helpers/RecurlySubscription')
-describe('Subscriptions', function() {
- describe('update', function() {
- beforeEach(function(done) {
+describe('Subscriptions', function () {
+ describe('update', function () {
+ beforeEach(function (done) {
this.recurlyUser = new User()
async.series(
[
@@ -25,7 +25,7 @@ describe('Subscriptions', function() {
)
})
- it('updates the email address for the account', function(done) {
+ it('updates the email address for the account', function (done) {
let url = '/user/subscription/account/email'
this.recurlyUser.request.post({ url }, (error, { statusCode }) => {
diff --git a/services/web/test/acceptance/src/RedirectUrlsTests.js b/services/web/test/acceptance/src/RedirectUrlsTests.js
index 64cbe596bc..258c83d4a1 100644
--- a/services/web/test/acceptance/src/RedirectUrlsTests.js
+++ b/services/web/test/acceptance/src/RedirectUrlsTests.js
@@ -21,16 +21,16 @@ const assertRedirect = (method, path, expectedStatusCode, destination, cb) =>
return cb()
})
-describe('RedirectUrls', function() {
- beforeEach(function() {
+describe('RedirectUrls', function () {
+ beforeEach(function () {
return this.timeout(1000)
})
- it('proxy static URLs', function(done) {
+ it('proxy static URLs', function (done) {
return assertRedirect('get', '/redirect/one', 302, '/destination/one', done)
})
- it('proxy dynamic URLs', function(done) {
+ it('proxy dynamic URLs', function (done) {
return assertRedirect(
'get',
'/redirect/params/42',
@@ -40,7 +40,7 @@ describe('RedirectUrls', function() {
)
})
- it('proxy URLs with baseUrl', function(done) {
+ it('proxy URLs with baseUrl', function (done) {
return assertRedirect(
'get',
'/redirect/base_url',
@@ -50,7 +50,7 @@ describe('RedirectUrls', function() {
)
})
- it('proxy URLs with POST with a 307', function(done) {
+ it('proxy URLs with POST with a 307', function (done) {
return assertRedirect(
'post',
'/redirect/get_and_post',
@@ -60,7 +60,7 @@ describe('RedirectUrls', function() {
)
})
- it('proxy URLs with multiple support methods', function(done) {
+ it('proxy URLs with multiple support methods', function (done) {
return assertRedirect(
'get',
'/redirect/get_and_post',
@@ -70,7 +70,7 @@ describe('RedirectUrls', function() {
)
})
- it('redirects with query params', function(done) {
+ it('redirects with query params', function (done) {
return assertRedirect(
'get',
'/redirect/qs?foo=bar&baz[]=qux1&baz[]=qux2',
@@ -80,7 +80,7 @@ describe('RedirectUrls', function() {
)
})
- it("skips redirects if the 'skip-redirects' header is set", function(done) {
+ it("skips redirects if the 'skip-redirects' header is set", function (done) {
return request.get(
{ url: '/redirect/one', headers: { 'x-skip-redirects': 'true' } },
(error, response) => {
diff --git a/services/web/test/acceptance/src/RegistrationTests.js b/services/web/test/acceptance/src/RegistrationTests.js
index 4ddc11c238..cf36c3515d 100644
--- a/services/web/test/acceptance/src/RegistrationTests.js
+++ b/services/web/test/acceptance/src/RegistrationTests.js
@@ -13,10 +13,10 @@ const Features = require('../../../app/src/infrastructure/Features')
// whereas in production we're using the 'overleaf-integration' module.
// Expectations
-const expectProjectAccess = function(user, projectId, callback) {
+const expectProjectAccess = function (user, projectId, callback) {
// should have access to project
if (callback == null) {
- callback = function(err, result) {}
+ callback = function (err, result) {}
}
user.openProject(projectId, err => {
expect(err).to.be.oneOf([null, undefined])
@@ -24,10 +24,10 @@ const expectProjectAccess = function(user, projectId, callback) {
})
}
-const expectNoProjectAccess = function(user, projectId, callback) {
+const expectNoProjectAccess = function (user, projectId, callback) {
// should not have access to project page
if (callback == null) {
- callback = function(err, result) {}
+ callback = function (err, result) {}
}
user.openProject(projectId, err => {
expect(err).to.be.instanceof(Error)
@@ -36,14 +36,14 @@ const expectNoProjectAccess = function(user, projectId, callback) {
}
// Actions
-const tryLoginThroughRegistrationForm = function(
+const tryLoginThroughRegistrationForm = function (
user,
email,
password,
callback
) {
if (callback == null) {
- callback = function(err, response, body) {}
+ callback = function (err, response, body) {}
}
user.getCsrfToken(err => {
if (err != null) {
@@ -62,15 +62,15 @@ const tryLoginThroughRegistrationForm = function(
})
}
-describe('Registration', function() {
- describe('LoginRateLimit', function() {
- beforeEach(function() {
+describe('Registration', function () {
+ describe('LoginRateLimit', function () {
+ beforeEach(function () {
this.user = new User()
this.badEmail = 'bademail@example.com'
this.badPassword = 'badpassword'
})
- it('should rate limit login attempts after 10 within two minutes', function(done) {
+ it('should rate limit login attempts after 10 within two minutes', function (done) {
this.user.request.get('/login', (err, res, body) => {
async.timesSeries(
15,
@@ -117,24 +117,24 @@ describe('Registration', function() {
})
})
- describe('CSRF protection', function() {
- before(function() {
+ describe('CSRF protection', function () {
+ before(function () {
if (!Features.hasFeature('public-registration')) {
this.skip()
}
})
- beforeEach(function() {
+ beforeEach(function () {
this.user = new User()
this.email = `test+${Math.random()}@example.com`
this.password = 'password11'
})
- afterEach(function(done) {
+ afterEach(function (done) {
this.user.fullDeleteUser(this.email, done)
})
- it('should register with the csrf token', function(done) {
+ it('should register with the csrf token', function (done) {
this.user.request.get('/login', (err, res, body) => {
this.user.getCsrfToken(error => {
this.user.request.post(
@@ -158,7 +158,7 @@ describe('Registration', function() {
})
})
- it('should fail with no csrf token', function(done) {
+ it('should fail with no csrf token', function (done) {
this.user.request.get('/login', (err, res, body) => {
this.user.getCsrfToken(error => {
this.user.request.post(
@@ -181,7 +181,7 @@ describe('Registration', function() {
})
})
- it('should fail with a stale csrf token', function(done) {
+ it('should fail with a stale csrf token', function (done) {
this.user.request.get('/login', (err, res, body) => {
this.user.getCsrfToken(error => {
const oldCsrfToken = this.user.csrfToken
@@ -208,18 +208,18 @@ describe('Registration', function() {
})
})
- describe('Register', function() {
- before(function() {
+ describe('Register', function () {
+ before(function () {
if (!Features.hasFeature('public-registration')) {
this.skip()
}
})
- beforeEach(function() {
+ beforeEach(function () {
this.user = new User()
})
- it('Set emails attribute', function(done) {
+ it('Set emails attribute', function (done) {
this.user.register((error, user) => {
expect(error).to.not.exist
user.email.should.equal(this.user.email)
@@ -232,14 +232,14 @@ describe('Registration', function() {
})
})
- describe('Register with bonus referal id', function() {
- before(function() {
+ describe('Register with bonus referal id', function () {
+ before(function () {
if (!Features.hasFeature('public-registration')) {
this.skip()
}
})
- beforeEach(function(done) {
+ beforeEach(function (done) {
this.user1 = new User()
this.user2 = new User()
async.series(
@@ -255,7 +255,7 @@ describe('Registration', function() {
)
})
- it('Adds a referal when an id is supplied and the referal source is "bonus"', function(done) {
+ it('Adds a referal when an id is supplied and the referal source is "bonus"', function (done) {
this.user1.get((error, user) => {
expect(error).to.not.exist
user.refered_user_count.should.eql(1)
@@ -265,8 +265,8 @@ describe('Registration', function() {
})
})
- describe('LoginViaRegistration', function() {
- beforeEach(function(done) {
+ describe('LoginViaRegistration', function () {
+ beforeEach(function (done) {
this.timeout(60000)
this.user1 = new User()
this.user2 = new User()
@@ -284,14 +284,14 @@ describe('Registration', function() {
this.project_id = null
})
- describe('[Security] Trying to register/login as another user', function() {
- before(function() {
+ describe('[Security] Trying to register/login as another user', function () {
+ before(function () {
if (!Features.hasFeature('public-registration')) {
this.skip()
}
})
- it('should not allow sign in with secondary email', function(done) {
+ it('should not allow sign in with secondary email', function (done) {
const secondaryEmail = 'acceptance-test-secondary@example.com'
this.user1.addEmail(secondaryEmail, err => {
this.user1.loginWith(secondaryEmail, err => {
@@ -304,7 +304,7 @@ describe('Registration', function() {
})
})
- it('should have user1 login and create a project, which user2 cannot access', function(done) {
+ it('should have user1 login and create a project, which user2 cannot access', function (done) {
let projectId
async.series(
[
diff --git a/services/web/test/acceptance/src/RestoringFilesTest.js b/services/web/test/acceptance/src/RestoringFilesTest.js
index 1de1edd9d9..2b2d6f7f12 100644
--- a/services/web/test/acceptance/src/RestoringFilesTest.js
+++ b/services/web/test/acceptance/src/RestoringFilesTest.js
@@ -26,14 +26,14 @@ const MockFilestoreApiClass = require('./mocks/MockFilestoreApi')
let MockProjectHistoryApi, MockDocstoreApi, MockFilestoreApi
-before(function() {
+before(function () {
MockProjectHistoryApi = MockProjectHistoryApiClass.instance()
MockDocstoreApi = MockDocstoreApiClass.instance()
MockFilestoreApi = MockFilestoreApiClass.instance()
})
-describe('RestoringFiles', function() {
- beforeEach(function(done) {
+describe('RestoringFiles', function () {
+ beforeEach(function (done) {
this.owner = new User()
return this.owner.login(error => {
if (error != null) {
@@ -53,8 +53,8 @@ describe('RestoringFiles', function() {
})
})
- describe('restoring a deleted doc', function() {
- beforeEach(function(done) {
+ describe('restoring a deleted doc', function () {
+ beforeEach(function (done) {
return this.owner.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
@@ -96,7 +96,7 @@ describe('RestoringFiles', function() {
})
})
- it('should have restored the doc', function(done) {
+ it('should have restored the doc', function (done) {
return this.owner.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
@@ -117,9 +117,9 @@ describe('RestoringFiles', function() {
})
})
- describe('restoring from v2 history', function() {
- describe('restoring a text file', function() {
- beforeEach(function(done) {
+ describe('restoring from v2 history', function () {
+ describe('restoring a text file', function () {
+ beforeEach(function (done) {
MockProjectHistoryApi.addOldFile(
this.project_id,
42,
@@ -145,7 +145,7 @@ describe('RestoringFiles', function() {
)
})
- it('should have created a doc', function(done) {
+ it('should have created a doc', function (done) {
return this.owner.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
@@ -161,8 +161,8 @@ describe('RestoringFiles', function() {
})
})
- describe('restoring a binary file', function() {
- beforeEach(function(done) {
+ describe('restoring a binary file', function () {
+ beforeEach(function (done) {
this.pngData = fs.readFileSync(
Path.resolve(__dirname, '../files/1pixel.png'),
'binary'
@@ -192,7 +192,7 @@ describe('RestoringFiles', function() {
)
})
- it('should have created a file', function(done) {
+ it('should have created a file', function (done) {
return this.owner.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
@@ -208,8 +208,8 @@ describe('RestoringFiles', function() {
})
})
- describe('restoring to a directory that exists', function() {
- beforeEach(function(done) {
+ describe('restoring to a directory that exists', function () {
+ beforeEach(function (done) {
MockProjectHistoryApi.addOldFile(
this.project_id,
42,
@@ -249,7 +249,7 @@ describe('RestoringFiles', function() {
)
})
- it('should have created the doc in the named folder', function(done) {
+ it('should have created the doc in the named folder', function (done) {
return this.owner.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
@@ -266,8 +266,8 @@ describe('RestoringFiles', function() {
})
})
- describe('restoring to a directory that no longer exists', function() {
- beforeEach(function(done) {
+ describe('restoring to a directory that no longer exists', function () {
+ beforeEach(function (done) {
MockProjectHistoryApi.addOldFile(
this.project_id,
42,
@@ -293,7 +293,7 @@ describe('RestoringFiles', function() {
)
})
- it('should have created the folder and restored the doc to it', function(done) {
+ it('should have created the folder and restored the doc to it', function (done) {
return this.owner.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
@@ -311,8 +311,8 @@ describe('RestoringFiles', function() {
})
})
- describe('restoring to a filename that already exists', function() {
- beforeEach(function(done) {
+ describe('restoring to a filename that already exists', function () {
+ beforeEach(function (done) {
MockProjectHistoryApi.addOldFile(
this.project_id,
42,
@@ -338,7 +338,7 @@ describe('RestoringFiles', function() {
)
})
- it('should have created the doc in the root folder', function(done) {
+ it('should have created the doc in the root folder', function (done) {
return this.owner.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
diff --git a/services/web/test/acceptance/src/SecurityHeadersTests.js b/services/web/test/acceptance/src/SecurityHeadersTests.js
index 57dad1518a..0ad8662774 100644
--- a/services/web/test/acceptance/src/SecurityHeadersTests.js
+++ b/services/web/test/acceptance/src/SecurityHeadersTests.js
@@ -17,14 +17,14 @@ const async = require('async')
const User = require('./helpers/User')
const request = require('./helpers/request')
-const assert_has_common_headers = function(response) {
+const assert_has_common_headers = function (response) {
const { headers } = response
assert.equal(headers['x-download-options'], 'noopen')
assert.equal(headers['x-xss-protection'], '1; mode=block')
return assert.equal(headers['referrer-policy'], 'origin-when-cross-origin')
}
-const assert_has_cache_headers = function(response) {
+const assert_has_cache_headers = function (response) {
const { headers } = response
assert.equal(headers['surrogate-control'], 'no-store')
assert.equal(
@@ -35,52 +35,52 @@ const assert_has_cache_headers = function(response) {
return assert.equal(headers.expires, '0')
}
-const assert_has_no_cache_headers = function(response) {
+const assert_has_no_cache_headers = function (response) {
const { headers } = response
assert.isUndefined(headers['surrogate-control'])
assert.isUndefined(headers['cache-control'])
assert.isUndefined(headers.pragma)
return assert.isUndefined(headers.expires)
}
-const assert_has_asset_caching_headers = function(response) {
+const assert_has_asset_caching_headers = function (response) {
const { headers } = response
assert.equal(headers['cache-control'], 'public, max-age=31536000')
}
-describe('SecurityHeaders', function() {
- beforeEach(function() {
+describe('SecurityHeaders', function () {
+ beforeEach(function () {
return (this.user = new User())
})
- it('should not have x-powered-by header', function(done) {
+ it('should not have x-powered-by header', function (done) {
return request.get('/', (err, res, body) => {
assert.isUndefined(res.headers['x-powered-by'])
return done()
})
})
- it('should have all common headers', function(done) {
+ it('should have all common headers', function (done) {
return request.get('/', (err, res, body) => {
assert_has_common_headers(res)
return done()
})
})
- it('should not have cache headers on public pages', function(done) {
+ it('should not have cache headers on public pages', function (done) {
return request.get('/', (err, res, body) => {
assert_has_no_cache_headers(res)
return done()
})
})
- it('should have caching headers on static assets', function(done) {
+ it('should have caching headers on static assets', function (done) {
request.get('/favicon.ico', (err, res) => {
assert_has_asset_caching_headers(res)
done(err)
})
})
- it('should have cache headers when user is logged in', function(done) {
+ it('should have cache headers when user is logged in', function (done) {
return async.series(
[
cb => this.user.login(cb),
@@ -95,7 +95,7 @@ describe('SecurityHeaders', function() {
)
})
- it('should have cache headers on project page', function(done) {
+ it('should have cache headers on project page', function (done) {
return async.series(
[
cb => this.user.login(cb),
@@ -122,7 +122,7 @@ describe('SecurityHeaders', function() {
)
})
- it('should have caching headers on static assets when user is logged in', function(done) {
+ it('should have caching headers on static assets when user is logged in', function (done) {
async.series(
[
cb => this.user.login(cb),
diff --git a/services/web/test/acceptance/src/SessionTests.js b/services/web/test/acceptance/src/SessionTests.js
index 8f5286fd04..d3b227c902 100644
--- a/services/web/test/acceptance/src/SessionTests.js
+++ b/services/web/test/acceptance/src/SessionTests.js
@@ -3,8 +3,8 @@ const async = require('async')
const User = require('./helpers/User')
const redis = require('./helpers/redis')
-describe('Sessions', function() {
- beforeEach(function(done) {
+describe('Sessions', function () {
+ beforeEach(function (done) {
this.timeout(20000)
this.user1 = new User()
this.site_admin = new User({ email: 'admin@example.com' })
@@ -14,8 +14,8 @@ describe('Sessions', function() {
)
})
- describe('one session', function() {
- it('should have one session in UserSessions set', function(done) {
+ describe('one session', function () {
+ it('should have one session in UserSessions set', function (done) {
async.series(
[
next => {
@@ -68,15 +68,15 @@ describe('Sessions', function() {
})
})
- describe('two sessions', function() {
- beforeEach(function() {
+ describe('two sessions', function () {
+ beforeEach(function () {
// set up second session for this user
this.user2 = new User()
this.user2.email = this.user1.email
this.user2.password = this.user1.password
})
- it('should have two sessions in UserSessions set', function(done) {
+ it('should have two sessions in UserSessions set', function (done) {
async.series(
[
next => {
@@ -192,8 +192,8 @@ describe('Sessions', function() {
})
})
- describe('three sessions, password reset', function() {
- beforeEach(function() {
+ describe('three sessions, password reset', function () {
+ beforeEach(function () {
// set up second session for this user
this.user2 = new User()
this.user2.email = this.user1.email
@@ -203,7 +203,7 @@ describe('Sessions', function() {
this.user3.password = this.user1.password
})
- it('should erase both sessions when password is reset', function(done) {
+ it('should erase both sessions when password is reset', function (done) {
async.series(
[
next => {
@@ -316,8 +316,8 @@ describe('Sessions', function() {
})
})
- describe('three sessions, sessions page', function() {
- beforeEach(function(done) {
+ describe('three sessions, sessions page', function () {
+ beforeEach(function (done) {
// set up second session for this user
this.user2 = new User()
this.user2.email = this.user1.email
@@ -328,7 +328,7 @@ describe('Sessions', function() {
async.series([this.user2.login.bind(this.user2)], done)
})
- it('should allow the user to erase the other two sessions', function(done) {
+ it('should allow the user to erase the other two sessions', function (done) {
async.series(
[
next => {
diff --git a/services/web/test/acceptance/src/SettingsTests.js b/services/web/test/acceptance/src/SettingsTests.js
index 60552a65c3..0487da2b08 100644
--- a/services/web/test/acceptance/src/SettingsTests.js
+++ b/services/web/test/acceptance/src/SettingsTests.js
@@ -15,12 +15,12 @@ const MockV1ApiClass = require('./mocks/MockV1Api')
let MockV1Api
-before(function() {
+before(function () {
MockV1Api = MockV1ApiClass.instance()
})
-describe('SettingsPage', function() {
- beforeEach(function(done) {
+describe('SettingsPage', function () {
+ beforeEach(function (done) {
this.user = new User()
this.v1Id = 1234
this.v1User = {
@@ -46,14 +46,14 @@ describe('SettingsPage', function() {
)
})
- it('load settings page', function(done) {
+ it('load settings page', function (done) {
return this.user.getUserSettingsPage((err, statusCode) => {
statusCode.should.equal(200)
return done()
})
})
- it('update main email address', function(done) {
+ it('update main email address', function (done) {
const newEmail = 'foo@bar.com'
return this.user.updateSettings({ email: newEmail }, error => {
expect(error).not.to.exist
@@ -66,7 +66,7 @@ describe('SettingsPage', function() {
})
})
- describe('with third-party-references configured', function() {
+ describe('with third-party-references configured', function () {
beforeEach(function injectThirdPartyReferencesEntryIntoDb(done) {
this.user.mongoUpdate(
{ $set: { refProviders: { zotero: { encrypted: '2020.9:SNIP' } } } },
@@ -74,7 +74,7 @@ describe('SettingsPage', function() {
)
})
- it('should be able to update settings', function(done) {
+ it('should be able to update settings', function (done) {
const newName = 'third-party-references'
this.user.updateSettings({ first_name: newName }, error => {
expect(error).not.to.exist
diff --git a/services/web/test/acceptance/src/SharingTests.js b/services/web/test/acceptance/src/SharingTests.js
index 3856cf1f71..875302f4f8 100644
--- a/services/web/test/acceptance/src/SharingTests.js
+++ b/services/web/test/acceptance/src/SharingTests.js
@@ -1,8 +1,8 @@
const { expect } = require('chai')
const User = require('./helpers/User').promises
-describe('Sharing', function() {
- beforeEach(async function() {
+describe('Sharing', function () {
+ beforeEach(async function () {
this.ownerSession = new User()
this.collaboratorSession = new User()
this.strangerSession = new User()
@@ -15,8 +15,8 @@ describe('Sharing', function() {
this.projectId = await this.ownerSession.createProject('Test project')
})
- describe('with read-only collaborator', function() {
- beforeEach(async function() {
+ describe('with read-only collaborator', function () {
+ beforeEach(async function () {
await this.ownerSession.addUserToProject(
this.projectId,
this.collaborator,
@@ -24,7 +24,7 @@ describe('Sharing', function() {
)
})
- it('sets the privilege level to read-write', async function() {
+ it('sets the privilege level to read-write', async function () {
await this.ownerSession.setCollaboratorInfo(
this.projectId,
this.collaborator._id,
@@ -37,7 +37,7 @@ describe('Sharing', function() {
expect(project.readOnly_refs).to.deep.equal([])
})
- it('treats setting the privilege to read-only as a noop', async function() {
+ it('treats setting the privilege to read-only as a noop', async function () {
await this.ownerSession.setCollaboratorInfo(
this.projectId,
this.collaborator._id,
@@ -48,7 +48,7 @@ describe('Sharing', function() {
expect(project.readOnly_refs).to.be.unordered.ids([this.collaborator._id])
})
- it('prevents non-owners to set the privilege level', async function() {
+ it('prevents non-owners to set the privilege level', async function () {
await expect(
this.collaboratorSession.setCollaboratorInfo(
this.projectId,
@@ -58,7 +58,7 @@ describe('Sharing', function() {
).to.be.rejectedWith('Unexpected status code: 403')
})
- it('validates the privilege level', async function() {
+ it('validates the privilege level', async function () {
await expect(
this.collaboratorSession.setCollaboratorInfo(
this.projectId,
@@ -68,7 +68,7 @@ describe('Sharing', function() {
).to.be.rejectedWith('Unexpected status code: 400')
})
- it('returns 404 if the user is not already a collaborator', async function() {
+ it('returns 404 if the user is not already a collaborator', async function () {
await expect(
this.ownerSession.setCollaboratorInfo(
this.projectId,
@@ -79,8 +79,8 @@ describe('Sharing', function() {
})
})
- describe('with read-write collaborator', function() {
- beforeEach(async function() {
+ describe('with read-write collaborator', function () {
+ beforeEach(async function () {
await this.ownerSession.addUserToProject(
this.projectId,
this.collaborator,
@@ -88,7 +88,7 @@ describe('Sharing', function() {
)
})
- it('sets the privilege level to read-only', async function() {
+ it('sets the privilege level to read-only', async function () {
await this.ownerSession.setCollaboratorInfo(
this.projectId,
this.collaborator._id,
diff --git a/services/web/test/acceptance/src/SubscriptionDashboardTests.js b/services/web/test/acceptance/src/SubscriptionDashboardTests.js
index b191cbd6c4..2426ff8b4a 100644
--- a/services/web/test/acceptance/src/SubscriptionDashboardTests.js
+++ b/services/web/test/acceptance/src/SubscriptionDashboardTests.js
@@ -22,20 +22,20 @@ async function buildUsersSubscriptionViewModelPromise(userId) {
let MockV1Api, MockRecurlyApi
-before(function() {
+before(function () {
MockV1Api = MockV1ApiClass.instance()
MockRecurlyApi = MockRecurlyApiClass.instance()
})
-describe('Subscriptions', function() {
- describe('dashboard', function() {
+describe('Subscriptions', function () {
+ describe('dashboard', function () {
let userHelper
- beforeEach(async function() {
+ beforeEach(async function () {
userHelper = await UserHelper.createUser()
this.user = userHelper.user
})
- it('should not list personal plan', function() {
+ it('should not list personal plan', function () {
const plans = SubscriptionViewModelBuilder.buildPlansList()
expect(plans.individualMonthlyPlans).to.be.a('Array')
const personalMonthlyPlan = plans.individualMonthlyPlans.find(
@@ -44,8 +44,8 @@ describe('Subscriptions', function() {
expect(personalMonthlyPlan).to.be.undefined
})
- describe('when the user has no subscription', function() {
- beforeEach(function(done) {
+ describe('when the user has no subscription', function () {
+ beforeEach(function (done) {
SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
this.user,
(error, data) => {
@@ -58,17 +58,17 @@ describe('Subscriptions', function() {
)
})
- it('should return no personalSubscription', function() {
+ it('should return no personalSubscription', function () {
expect(this.data.personalSubscription).to.equal(null)
})
- it('should return no memberGroupSubscriptions', function() {
+ it('should return no memberGroupSubscriptions', function () {
expect(this.data.memberGroupSubscriptions).to.deep.equal([])
})
})
- describe('when the user has a subscription with recurly', function() {
- beforeEach(function(done) {
+ describe('when the user has a subscription with recurly', function () {
+ beforeEach(function (done) {
this.recurlySubscription = new RecurlySubscription({
adminId: this.user._id,
planCode: 'collaborator',
@@ -106,7 +106,7 @@ describe('Subscriptions', function() {
})
})
- after(function(done) {
+ after(function (done) {
MockRecurlyApi.mockSubscriptions = []
MockRecurlyApi.coupons = {}
MockRecurlyApi.redemptions = {}
@@ -118,7 +118,7 @@ describe('Subscriptions', function() {
)
})
- it('should return a personalSubscription with populated recurly data', function() {
+ it('should return a personalSubscription with populated recurly data', function () {
const subscription = this.data.personalSubscription
expect(subscription).to.exist
expect(subscription.planCode).to.equal('collaborator')
@@ -147,11 +147,11 @@ describe('Subscriptions', function() {
})
})
- it('should return no memberGroupSubscriptions', function() {
+ it('should return no memberGroupSubscriptions', function () {
expect(this.data.memberGroupSubscriptions).to.deep.equal([])
})
- it('should include redeemed coupons', function(done) {
+ it('should include redeemed coupons', function (done) {
MockRecurlyApi.redemptions[this.user._id] = [
{ state: 'active', coupon_code: 'test-coupon-1' },
{ state: 'inactive', coupon_code: 'test-coupon-2' },
@@ -182,15 +182,15 @@ describe('Subscriptions', function() {
)
})
- it('should return Recurly account email', function() {
+ it('should return Recurly account email', function () {
expect(this.data.personalSubscription.recurly.account.email).to.equal(
'mock@email.com'
)
})
})
- describe('when the user has a subscription without recurly', function() {
- beforeEach(function(done) {
+ describe('when the user has a subscription without recurly', function () {
+ beforeEach(function (done) {
Subscription.create(
{
admin_id: this.user._id,
@@ -215,7 +215,7 @@ describe('Subscriptions', function() {
)
})
- after(function(done) {
+ after(function (done) {
Subscription.deleteOne(
{
admin_id: this.user._id
@@ -224,20 +224,20 @@ describe('Subscriptions', function() {
)
})
- it('should return a personalSubscription with no recurly data', function() {
+ it('should return a personalSubscription with no recurly data', function () {
const subscription = this.data.personalSubscription
expect(subscription).to.exist
expect(subscription.planCode).to.equal('collaborator')
expect(subscription.recurly).to.not.exist
})
- it('should return no memberGroupSubscriptions', function() {
+ it('should return no memberGroupSubscriptions', function () {
expect(this.data.memberGroupSubscriptions).to.deep.equal([])
})
})
- describe('when the user is a member of a group subscription', function() {
- beforeEach(async function() {
+ describe('when the user is a member of a group subscription', function () {
+ beforeEach(async function () {
const userHelperOwner1 = await UserHelper.createUser()
const userHelperOwner2 = await UserHelper.createUser()
this.owner1 = userHelperOwner1.user
@@ -260,7 +260,7 @@ describe('Subscriptions', function() {
this.data = await buildUsersSubscriptionViewModelPromise(this.user._id)
})
- after(function(done) {
+ after(function (done) {
Subscription.deleteOne(
{
admin_id: this.owner1._id
@@ -279,11 +279,11 @@ describe('Subscriptions', function() {
)
})
- it('should return no personalSubscription', function() {
+ it('should return no personalSubscription', function () {
expect(this.data.personalSubscription).to.equal(null)
})
- it('should return the two memberGroupSubscriptions', function() {
+ it('should return the two memberGroupSubscriptions', function () {
expect(this.data.memberGroupSubscriptions.length).to.equal(2)
expect(
// Mongoose populates the admin_id with the user
@@ -295,8 +295,8 @@ describe('Subscriptions', function() {
})
})
- describe('when the user is a manager of a group subscription', function() {
- beforeEach(async function() {
+ describe('when the user is a manager of a group subscription', function () {
+ beforeEach(async function () {
const userHelperOwner1 = await UserHelper.createUser()
const userHelperOwner2 = await UserHelper.createUser()
this.owner1 = userHelperOwner1.user
@@ -311,7 +311,7 @@ describe('Subscriptions', function() {
this.data = await buildUsersSubscriptionViewModelPromise(this.user._id)
})
- after(function(done) {
+ after(function (done) {
Subscription.deleteOne(
{
admin_id: this.owner1._id
@@ -320,11 +320,11 @@ describe('Subscriptions', function() {
)
})
- it('should return no personalSubscription', function() {
+ it('should return no personalSubscription', function () {
expect(this.data.personalSubscription).to.equal(null)
})
- it('should return the managedGroupSubscriptions', function() {
+ it('should return the managedGroupSubscriptions', function () {
expect(this.data.managedGroupSubscriptions.length).to.equal(1)
const subscription = this.data.managedGroupSubscriptions[0]
expect(
@@ -335,8 +335,8 @@ describe('Subscriptions', function() {
})
})
- describe('when the user is a manager of an institution', function() {
- beforeEach(function(done) {
+ describe('when the user is a manager of an institution', function () {
+ beforeEach(function (done) {
this.v1Id = MockV1Api.nextV1Id()
async.series(
[
@@ -368,7 +368,7 @@ describe('Subscriptions', function() {
)
})
- after(function(done) {
+ after(function (done) {
Institution.deleteOne(
{
v1Id: this.v1Id
@@ -377,7 +377,7 @@ describe('Subscriptions', function() {
)
})
- it('should return the managedInstitutions', function() {
+ it('should return the managedInstitutions', function () {
expect(this.data.managedInstitutions.length).to.equal(1)
const institution = this.data.managedInstitutions[0]
expect(institution.v1Id).to.equal(this.v1Id)
@@ -385,8 +385,8 @@ describe('Subscriptions', function() {
})
})
- describe('when the user is a member of an affiliation', function() {
- beforeEach(async function() {
+ describe('when the user is a member of an affiliation', function () {
+ beforeEach(async function () {
const v1Id = MockV1Api.nextV1Id()
MockV1Api.setUser(v1Id, {
subscription: {},
@@ -432,7 +432,7 @@ describe('Subscriptions', function() {
this.data = await buildUsersSubscriptionViewModelPromise(this.user._id)
})
- it('should return only the affilations with confirmed institutions, and confirmed emails', function() {
+ it('should return only the affilations with confirmed institutions, and confirmed emails', function () {
expect(this.data.confirmedMemberAffiliations.length).to.equal(1)
expect(
this.data.confirmedMemberAffiliations[0].institution.name
@@ -440,8 +440,8 @@ describe('Subscriptions', function() {
})
})
- describe('when the user has a v1 subscription', function() {
- beforeEach(async function() {
+ describe('when the user has a v1 subscription', function () {
+ beforeEach(async function () {
let v1Id
MockV1Api.setUser((v1Id = MockV1Api.nextV1Id()), {
subscription: (this.subscription = {
@@ -469,15 +469,15 @@ describe('Subscriptions', function() {
this.data = await buildUsersSubscriptionViewModelPromise(this.user._id)
})
- it('should return no personalSubscription', function() {
+ it('should return no personalSubscription', function () {
expect(this.data.personalSubscription).to.equal(null)
})
- it('should return no memberGroupSubscriptions', function() {
+ it('should return no memberGroupSubscriptions', function () {
expect(this.data.memberGroupSubscriptions).to.deep.equal([])
})
- it('should return a v1SubscriptionStatus', function() {
+ it('should return a v1SubscriptionStatus', function () {
expect(this.data.v1SubscriptionStatus).to.deep.equal(
this.subscription_status
)
@@ -485,9 +485,9 @@ describe('Subscriptions', function() {
})
})
- describe('canceling', function() {
+ describe('canceling', function () {
let userHelper, v1Id
- beforeEach(async function() {
+ beforeEach(async function () {
v1Id = MockV1Api.nextV1Id()
console.log('v1Id=', v1Id)
userHelper = await UserHelper.createUser({ overleaf: { id: v1Id } })
@@ -505,11 +505,11 @@ describe('Subscriptions', function() {
)
})
- it('should tell v1 to cancel the subscription', function() {
+ it('should tell v1 to cancel the subscription', function () {
expect(this.v1_user.canceled).to.equal(true)
})
- it('should redirect to the subscription dashboard', function() {
+ it('should redirect to the subscription dashboard', function () {
expect(this.response.statusCode).to.equal(302)
expect(this.response.headers.location).to.equal('/user/subscription')
})
diff --git a/services/web/test/acceptance/src/SubscriptionDeletionTests.js b/services/web/test/acceptance/src/SubscriptionDeletionTests.js
index 6f42d2cbe5..96e17649e8 100644
--- a/services/web/test/acceptance/src/SubscriptionDeletionTests.js
+++ b/services/web/test/acceptance/src/SubscriptionDeletionTests.js
@@ -5,9 +5,9 @@ const User = require('./helpers/User')
const RecurlySubscription = require('./helpers/RecurlySubscription')
const SubscriptionUpdater = require('../../../app/src/Features/Subscription/SubscriptionUpdater')
-describe('Subscriptions', function() {
- describe('deletion', function() {
- beforeEach(function(done) {
+describe('Subscriptions', function () {
+ describe('deletion', function () {
+ beforeEach(function (done) {
this.adminUser = new User()
this.memberUser = new User()
async.series(
@@ -33,7 +33,7 @@ describe('Subscriptions', function() {
)
})
- it('deletes via Recurly callback', function(done) {
+ it('deletes via Recurly callback', function (done) {
let url = '/user/subscription/callback'
let body = this.recurlySubscription.buildCallbackXml()
@@ -46,7 +46,7 @@ describe('Subscriptions', function() {
})
})
- it('refresh features', function(done) {
+ it('refresh features', function (done) {
let url = '/user/subscription/callback'
let body = this.recurlySubscription.buildCallbackXml()
@@ -61,7 +61,7 @@ describe('Subscriptions', function() {
})
})
- it('allows deletion when deletedSubscription exists', function(done) {
+ it('allows deletion when deletedSubscription exists', function (done) {
let url = '/user/subscription/callback'
let body = this.recurlySubscription.buildCallbackXml()
diff --git a/services/web/test/acceptance/src/SubscriptionFeaturesTests.js b/services/web/test/acceptance/src/SubscriptionFeaturesTests.js
index 199205e185..8f85989624 100644
--- a/services/web/test/acceptance/src/SubscriptionFeaturesTests.js
+++ b/services/web/test/acceptance/src/SubscriptionFeaturesTests.js
@@ -3,10 +3,10 @@ const async = require('async')
const User = require('./helpers/User')
const Subscription = require('./helpers/Subscription')
-describe('Subscriptions', function() {
- describe('features', function() {
- describe('individual subscriptions', function() {
- beforeEach(function(done) {
+describe('Subscriptions', function () {
+ describe('features', function () {
+ describe('individual subscriptions', function () {
+ beforeEach(function (done) {
this.adminUser = new User()
async.series(
[
@@ -25,7 +25,7 @@ describe('Subscriptions', function() {
)
})
- it('should give features to admin', function(done) {
+ it('should give features to admin', function (done) {
this.adminUser.getFeatures((error, features) => {
expect(features.collaborators).to.equal(-1)
done(error)
@@ -33,8 +33,8 @@ describe('Subscriptions', function() {
})
})
- describe('group subscriptions', function() {
- beforeEach(function(done) {
+ describe('group subscriptions', function () {
+ beforeEach(function (done) {
this.adminUser = new User()
this.memberUser = new User()
async.series(
@@ -56,14 +56,14 @@ describe('Subscriptions', function() {
)
})
- it('should give features to member', function(done) {
+ it('should give features to member', function (done) {
this.memberUser.getFeatures((error, features) => {
expect(features.collaborators).to.equal(-1)
done(error)
})
})
- it('should not give features to admin', function(done) {
+ it('should not give features to admin', function (done) {
this.adminUser.getFeatures((error, features) => {
expect(features.collaborators).to.equal(1)
done(error)
diff --git a/services/web/test/acceptance/src/TagsTests.js b/services/web/test/acceptance/src/TagsTests.js
index cf6e4e8b28..3f7adb1d34 100644
--- a/services/web/test/acceptance/src/TagsTests.js
+++ b/services/web/test/acceptance/src/TagsTests.js
@@ -64,15 +64,15 @@ const _expectTagStructure = tag => {
expect(tag.project_ids).to.deep.equal([])
}
-describe('Tags', function() {
- beforeEach(function(done) {
+describe('Tags', function () {
+ beforeEach(function (done) {
this.user = new User()
this.otherUser = new User()
_initUsers([this.user, this.otherUser], done)
})
- describe('get tags, anonymous', function() {
- it('should refuse to get user tags', function(done) {
+ describe('get tags, anonymous', function () {
+ it('should refuse to get user tags', function (done) {
this.user.logout(err => {
if (err) {
return done(err)
@@ -86,8 +86,8 @@ describe('Tags', function() {
})
})
- describe('get tags, none', function() {
- it('should get user tags', function(done) {
+ describe('get tags, none', function () {
+ it('should get user tags', function (done) {
_getTags(this.user, (err, response, body) => {
_expect200(err, response)
expect(body).to.deep.equal([])
@@ -96,8 +96,8 @@ describe('Tags', function() {
})
})
- describe('create some tags, then get', function() {
- it('should get tags only for that user', function(done) {
+ describe('create some tags, then get', function () {
+ it('should get tags only for that user', function (done) {
// Create a few tags
_createTags(this.user, ['one', 'two', 'three'], (err, tags) => {
expect(err).to.not.exist
@@ -131,7 +131,7 @@ describe('Tags', function() {
})
})
- describe('get tags via api', function() {
+ describe('get tags via api', function () {
const auth = Buffer.from('sharelatex:password').toString('base64')
const authedRequest = request.defaults({
headers: {
@@ -139,7 +139,7 @@ describe('Tags', function() {
}
})
- it('should disallow without appropriate auth headers', function(done) {
+ it('should disallow without appropriate auth headers', function (done) {
_createTags(this.user, ['one', 'two', 'three'], (err, tags) => {
expect(err).to.not.exist
// Get the tags, but with a regular request, not authorized
@@ -155,7 +155,7 @@ describe('Tags', function() {
})
})
- it('should get the tags from api endpoint', function(done) {
+ it('should get the tags from api endpoint', function (done) {
_createTags(this.user, ['one', 'two', 'three'], (err, tags) => {
expect(err).to.not.exist
// Get tags for user
@@ -179,8 +179,8 @@ describe('Tags', function() {
})
})
- describe('rename tag', function() {
- it('should reject malformed tag id', function(done) {
+ describe('rename tag', function () {
+ it('should reject malformed tag id', function (done) {
this.user.request.post(
{ url: `/tag/lol/rename`, json: { name: 'five' } },
(err, response) => {
@@ -191,7 +191,7 @@ describe('Tags', function() {
)
})
- it('should allow user to rename a tag', function(done) {
+ it('should allow user to rename a tag', function (done) {
_createTags(this.user, ['one', 'two'], (err, tags) => {
expect(err).to.not.exist
// Pick out the first tag
@@ -220,7 +220,7 @@ describe('Tags', function() {
})
})
- it('should not allow other user to change name', function(done) {
+ it('should not allow other user to change name', function (done) {
const initialTagNames = ['one', 'two']
_createTags(this.user, initialTagNames, (err, tags) => {
expect(err).to.not.exist
@@ -247,8 +247,8 @@ describe('Tags', function() {
})
})
- describe('delete tag', function() {
- it('should reject malformed tag id', function(done) {
+ describe('delete tag', function () {
+ it('should reject malformed tag id', function (done) {
this.user.request.delete(
{ url: `/tag/lol`, json: { name: 'five' } },
(err, response) => {
@@ -259,7 +259,7 @@ describe('Tags', function() {
)
})
- it('should delete a tag', function(done) {
+ it('should delete a tag', function (done) {
const initialTagNames = ['one', 'two', 'three']
_createTags(this.user, initialTagNames, (err, tags) => {
expect(err).to.not.exist
@@ -282,8 +282,8 @@ describe('Tags', function() {
})
})
- describe('add project to tag', function() {
- beforeEach(function(done) {
+ describe('add project to tag', function () {
+ beforeEach(function (done) {
this.user.createProject('test 1', (err, projectId) => {
if (err) {
return done(err)
@@ -293,7 +293,7 @@ describe('Tags', function() {
})
})
- it('should reject malformed tag id', function(done) {
+ it('should reject malformed tag id', function (done) {
this.user.request.post(
{ url: `/tag/lol/project/bad` },
(err, response) => {
@@ -304,7 +304,7 @@ describe('Tags', function() {
)
})
- it('should allow the user to add a project to a tag, and remove it', function(done) {
+ it('should allow the user to add a project to a tag, and remove it', function (done) {
_createTags(this.user, ['one', 'two'], (err, tags) => {
expect(err).to.not.exist
const firstTagId = tags[0]._id
@@ -349,7 +349,7 @@ describe('Tags', function() {
})
})
- it('should not allow another user to add a project to the tag', function(done) {
+ it('should not allow another user to add a project to the tag', function (done) {
_createTags(this.user, ['one', 'two'], (err, tags) => {
expect(err).to.not.exist
const firstTagId = tags[0]._id
diff --git a/services/web/test/acceptance/src/TokenAccessTests.js b/services/web/test/acceptance/src/TokenAccessTests.js
index 9b37377922..3402465742 100644
--- a/services/web/test/acceptance/src/TokenAccessTests.js
+++ b/services/web/test/acceptance/src/TokenAccessTests.js
@@ -9,7 +9,7 @@ const expectErrorResponse = require('./helpers/expectErrorResponse')
let MockV1Api
-before(function() {
+before(function () {
MockV1Api = MockV1ApiClass.instance()
})
@@ -168,8 +168,8 @@ const tryAnonContentAccess = (user, projectId, token, test, callback) => {
)
}
-describe('TokenAccess', function() {
- beforeEach(function(done) {
+describe('TokenAccess', function () {
+ beforeEach(function (done) {
this.timeout(90000)
this.owner = new User()
this.other1 = new User()
@@ -194,8 +194,8 @@ describe('TokenAccess', function() {
)
})
- describe('no token-access', function() {
- beforeEach(function(done) {
+ describe('no token-access', function () {
+ beforeEach(function (done) {
this.owner.createProject(
`token-ro-test${Math.random()}`,
(err, projectId) => {
@@ -210,7 +210,7 @@ describe('TokenAccess', function() {
)
})
- it('should deny access ', function(done) {
+ it('should deny access ', function (done) {
async.series(
[
cb => {
@@ -238,8 +238,8 @@ describe('TokenAccess', function() {
})
})
- describe('read-only token', function() {
- beforeEach(function(done) {
+ describe('read-only token', function () {
+ beforeEach(function (done) {
this.owner.createProject(
`token-ro-test${Math.random()}`,
(err, projectId) => {
@@ -263,7 +263,7 @@ describe('TokenAccess', function() {
)
})
- it('allow the user read-only access to the project', function(done) {
+ it('allow the user read-only access to the project', function (done) {
async.series(
[
cb => {
@@ -324,7 +324,7 @@ describe('TokenAccess', function() {
)
})
- it('should redirect the admin to the project (with rw access)', function(done) {
+ it('should redirect the admin to the project (with rw access)', function (done) {
async.series(
[
cb => {
@@ -359,12 +359,12 @@ describe('TokenAccess', function() {
)
})
- describe('made private again', function() {
- beforeEach(function(done) {
+ describe('made private again', function () {
+ beforeEach(function (done) {
this.owner.makePrivate(this.projectId, () => setTimeout(done, 1000))
})
- it('should not allow the user to access the project', function(done) {
+ it('should not allow the user to access the project', function (done) {
async.series(
[
// no access before token is used
@@ -413,8 +413,8 @@ describe('TokenAccess', function() {
})
})
- describe('anonymous read-only token', function() {
- beforeEach(function(done) {
+ describe('anonymous read-only token', function () {
+ beforeEach(function (done) {
this.owner.createProject(
`token-anon-ro-test${Math.random()}`,
(err, projectId) => {
@@ -438,7 +438,7 @@ describe('TokenAccess', function() {
)
})
- it('should allow the user to access project via read-only token url', function(done) {
+ it('should allow the user to access project via read-only token url', function (done) {
async.series(
[
cb =>
@@ -493,12 +493,12 @@ describe('TokenAccess', function() {
)
})
- describe('made private again', function() {
- beforeEach(function(done) {
+ describe('made private again', function () {
+ beforeEach(function (done) {
this.owner.makePrivate(this.projectId, () => setTimeout(done, 1000))
})
- it('should deny access to project', function(done) {
+ it('should deny access to project', function (done) {
async.series(
[
cb =>
@@ -548,8 +548,8 @@ describe('TokenAccess', function() {
})
})
- describe('read-and-write token', function() {
- beforeEach(function(done) {
+ describe('read-and-write token', function () {
+ beforeEach(function (done) {
this.owner.createProject(
`token-rw-test${Math.random()}`,
(err, projectId) => {
@@ -573,7 +573,7 @@ describe('TokenAccess', function() {
)
})
- it('should allow the user to access project via read-and-write token url', function(done) {
+ it('should allow the user to access project via read-and-write token url', function (done) {
async.series(
[
// deny access before the token is used
@@ -630,8 +630,8 @@ describe('TokenAccess', function() {
)
})
- describe('upgrading from a read-only token', function() {
- beforeEach(function(done) {
+ describe('upgrading from a read-only token', function () {
+ beforeEach(function (done) {
this.owner.createProject(
`token-rw-upgrade-test${Math.random()}`,
(err, projectId) => {
@@ -655,7 +655,7 @@ describe('TokenAccess', function() {
)
})
- it('should allow user to access project via read-only, then upgrade to read-write', function(done) {
+ it('should allow user to access project via read-only, then upgrade to read-write', function (done) {
async.series(
[
// deny access before the token is used
@@ -760,12 +760,12 @@ describe('TokenAccess', function() {
})
})
- describe('made private again', function() {
- beforeEach(function(done) {
+ describe('made private again', function () {
+ beforeEach(function (done) {
this.owner.makePrivate(this.projectId, () => setTimeout(done, 1000))
})
- it('should deny access to project', function(done) {
+ it('should deny access to project', function (done) {
async.series(
[
cb => {
@@ -816,8 +816,8 @@ describe('TokenAccess', function() {
})
if (!settings.allowAnonymousReadAndWriteSharing) {
- describe('anonymous read-and-write token, disabled', function() {
- beforeEach(function(done) {
+ describe('anonymous read-and-write token, disabled', function () {
+ beforeEach(function (done) {
this.owner.createProject(
`token-anon-rw-test${Math.random()}`,
(err, projectId) => {
@@ -841,7 +841,7 @@ describe('TokenAccess', function() {
)
})
- it('should not allow the user to access read-and-write token', function(done) {
+ it('should not allow the user to access read-and-write token', function (done) {
async.series(
[
cb =>
@@ -891,8 +891,8 @@ describe('TokenAccess', function() {
})
})
} else {
- describe('anonymous read-and-write token, enabled', function() {
- beforeEach(function(done) {
+ describe('anonymous read-and-write token, enabled', function () {
+ beforeEach(function (done) {
this.owner.createProject(
`token-anon-rw-test${Math.random()}`,
(err, projectId) => {
@@ -916,7 +916,7 @@ describe('TokenAccess', function() {
)
})
- it('should allow the user to access project via read-and-write token url', function(done) {
+ it('should allow the user to access project via read-and-write token url', function (done) {
async.series(
[
cb =>
@@ -964,12 +964,12 @@ describe('TokenAccess', function() {
)
})
- describe('made private again', function() {
- beforeEach(function(done) {
+ describe('made private again', function () {
+ beforeEach(function (done) {
this.owner.makePrivate(this.projectId, () => setTimeout(done, 1000))
})
- it('should not allow the user to access read-and-write token', function(done) {
+ it('should not allow the user to access read-and-write token', function (done) {
async.series(
[
cb =>
@@ -1017,8 +1017,8 @@ describe('TokenAccess', function() {
})
}
- describe('private overleaf project', function() {
- beforeEach(function(done) {
+ describe('private overleaf project', function () {
+ beforeEach(function (done) {
this.owner.createProject('overleaf-import', (err, projectId) => {
expect(err).not.to.exist
this.projectId = projectId
@@ -1046,7 +1046,7 @@ describe('TokenAccess', function() {
})
})
- it('should only allow the owner access to the project', function(done) {
+ it('should only allow the owner access to the project', function (done) {
async.series(
[
// should redirect to canonical path, when owner uses read-write token
@@ -1101,8 +1101,8 @@ describe('TokenAccess', function() {
})
})
- describe('private project, with higher access', function() {
- beforeEach(function(done) {
+ describe('private project, with higher access', function () {
+ beforeEach(function (done) {
this.owner.createProject(
`higher-access-test-${Math.random()}`,
(err, projectId) => {
@@ -1130,7 +1130,7 @@ describe('TokenAccess', function() {
)
})
- it('should allow the user access to the project', function(done) {
+ it('should allow the user access to the project', function (done) {
async.series(
[
// should redirect to canonical path, when user uses read-write token
@@ -1211,16 +1211,16 @@ describe('TokenAccess', function() {
})
})
- describe('unimported v1 project', function() {
- beforeEach(function() {
+ describe('unimported v1 project', function () {
+ beforeEach(function () {
settings.overleaf = { host: 'http://localhost:5000' }
})
- afterEach(function() {
+ afterEach(function () {
delete settings.overleaf
})
- it('should show error page for read and write token', function(done) {
+ it('should show error page for read and write token', function (done) {
const unimportedV1Token = '123abcdefabcdef'
tryReadAndWriteTokenAccess(
this.owner,
@@ -1236,7 +1236,7 @@ describe('TokenAccess', function() {
)
})
- it('should show error page for read only token to v1', function(done) {
+ it('should show error page for read only token to v1', function (done) {
const unimportedV1Token = 'aaaaaabbbbbb'
tryReadOnlyTokenAccess(
this.owner,
@@ -1253,8 +1253,8 @@ describe('TokenAccess', function() {
})
})
- describe('importing v1 project', function() {
- beforeEach(function(done) {
+ describe('importing v1 project', function () {
+ beforeEach(function (done) {
settings.projectImportingCheckMaxCreateDelta = 3600
settings.overleaf = { host: 'http://localhost:5000' }
this.owner.createProject(
@@ -1306,12 +1306,12 @@ describe('TokenAccess', function() {
)
})
- afterEach(function() {
+ afterEach(function () {
delete settings.projectImportingCheckMaxCreateDelta
delete settings.overleaf
})
- it('should show importing page for read, and read-write tokens', function(done) {
+ it('should show importing page for read, and read-write tokens', function (done) {
async.series(
[
cb =>
@@ -1377,15 +1377,15 @@ describe('TokenAccess', function() {
)
})
- describe('when the v1 doc does not exist', function(done) {
- beforeEach(function(done) {
+ describe('when the v1 doc does not exist', function (done) {
+ beforeEach(function (done) {
const docInfo = null
MockV1Api.setDocInfo(this.tokens.readAndWrite, docInfo)
MockV1Api.setDocInfo(this.tokens.readOnly, docInfo)
done()
})
- it('should get a 404 response on the post endpoint', function(done) {
+ it('should get a 404 response on the post endpoint', function (done) {
async.series(
[
cb =>
diff --git a/services/web/test/acceptance/src/TpdsUpdateTests.js b/services/web/test/acceptance/src/TpdsUpdateTests.js
index 56d23f2ca7..046e7642fe 100644
--- a/services/web/test/acceptance/src/TpdsUpdateTests.js
+++ b/services/web/test/acceptance/src/TpdsUpdateTests.js
@@ -16,8 +16,8 @@ const ProjectGetter = require('../../../app/src/Features/Project/ProjectGetter.j
const request = require('./helpers/request')
const User = require('./helpers/User')
-describe('TpdsUpdateTests', function() {
- beforeEach(function(done) {
+describe('TpdsUpdateTests', function () {
+ beforeEach(function (done) {
this.owner = new User()
return this.owner.login(error => {
if (error != null) {
@@ -37,8 +37,8 @@ describe('TpdsUpdateTests', function() {
})
})
- describe('adding a file', function() {
- beforeEach(function(done) {
+ describe('adding a file', function () {
+ beforeEach(function (done) {
return request(
{
method: 'POST',
@@ -60,7 +60,7 @@ describe('TpdsUpdateTests', function() {
)
})
- it('should have added the file', function(done) {
+ it('should have added the file', function (done) {
return ProjectGetter.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
@@ -73,8 +73,8 @@ describe('TpdsUpdateTests', function() {
})
})
- describe('deleting a file', function() {
- beforeEach(function(done) {
+ describe('deleting a file', function () {
+ beforeEach(function (done) {
return request(
{
method: 'DELETE',
@@ -95,7 +95,7 @@ describe('TpdsUpdateTests', function() {
)
})
- it('should have deleted the file', function(done) {
+ it('should have deleted the file', function (done) {
return ProjectGetter.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
@@ -111,8 +111,8 @@ describe('TpdsUpdateTests', function() {
})
})
- describe('update a new file', function() {
- beforeEach(function(done) {
+ describe('update a new file', function () {
+ beforeEach(function (done) {
return request(
{
method: 'POST',
@@ -134,7 +134,7 @@ describe('TpdsUpdateTests', function() {
)
})
- it('should have added the file', function(done) {
+ it('should have added the file', function (done) {
return ProjectGetter.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
@@ -147,8 +147,8 @@ describe('TpdsUpdateTests', function() {
})
})
- describe('update when the project is archived', function() {
- beforeEach(function(done) {
+ describe('update when the project is archived', function () {
+ beforeEach(function (done) {
this.owner.request(
{
url: `/Project/${this.project_id}/archive`,
@@ -179,7 +179,7 @@ describe('TpdsUpdateTests', function() {
)
})
- it('should not have created a new project', function(done) {
+ it('should not have created a new project', function (done) {
ProjectGetter.findAllUsersProjects(
this.owner._id,
'name',
@@ -191,7 +191,7 @@ describe('TpdsUpdateTests', function() {
)
})
- it('should not have added the file', function(done) {
+ it('should not have added the file', function (done) {
return ProjectGetter.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
diff --git a/services/web/test/acceptance/src/UserEmailsTests.js b/services/web/test/acceptance/src/UserEmailsTests.js
index 0d2155cfe0..da9a80db53 100644
--- a/services/web/test/acceptance/src/UserEmailsTests.js
+++ b/services/web/test/acceptance/src/UserEmailsTests.js
@@ -11,19 +11,19 @@ const expectErrorResponse = require('./helpers/expectErrorResponse')
let MockV1Api
-before(function() {
+before(function () {
MockV1Api = MockV1ApiClass.instance()
})
-describe('UserEmails', function() {
- beforeEach(function(done) {
+describe('UserEmails', function () {
+ beforeEach(function (done) {
this.timeout(20000)
this.user = new User()
this.user.login(done)
})
- describe('confirming an email', function() {
- it('should confirm the email', function(done) {
+ describe('confirming an email', function () {
+ it('should confirm the email', function (done) {
let token = null
async.series(
[
@@ -126,7 +126,7 @@ describe('UserEmails', function() {
)
})
- it('should not allow confirmation of the email if the user has changed', function(done) {
+ it('should not allow confirmation of the email if the user has changed', function (done) {
let token1 = null
let token2 = null
this.user2 = new User()
@@ -253,9 +253,9 @@ describe('UserEmails', function() {
})
})
- describe('reconfirm an email', function() {
+ describe('reconfirm an email', function () {
let email, userHelper, confirmedAtDate
- beforeEach(async function() {
+ beforeEach(async function () {
userHelper = new UserHelper()
email = userHelper.getDefaultEmail()
userHelper = await UserHelper.createUser({ email })
@@ -270,7 +270,7 @@ describe('UserEmails', function() {
expect(user.emails[0].confirmedAt).to.exist
expect(user.emails[0].reconfirmedAt).to.exist
})
- it('should set reconfirmedAt and not reset confirmedAt', async function() {
+ it('should set reconfirmedAt and not reset confirmedAt', async function () {
await userHelper.confirmEmail(userHelper.user._id, email)
const user = (await UserHelper.getUser({ email })).user
expect(user.emails[0].confirmedAt).to.exist
@@ -284,8 +284,8 @@ describe('UserEmails', function() {
})
})
- describe('with an expired token', function() {
- it('should not confirm the email', function(done) {
+ describe('with an expired token', function () {
+ it('should not confirm the email', function (done) {
let token = null
async.series(
[
@@ -357,8 +357,8 @@ describe('UserEmails', function() {
})
})
- describe('resending the confirmation', function() {
- it('should generate a new token', function(done) {
+ describe('resending the confirmation', function () {
+ it('should generate a new token', function (done) {
async.series(
[
cb => {
@@ -438,7 +438,7 @@ describe('UserEmails', function() {
)
})
- it('should create a new token if none exists', function(done) {
+ it('should create a new token if none exists', function (done) {
// This should only be for users that have sign up with their main
// emails before the confirmation system existed
async.series(
@@ -490,7 +490,7 @@ describe('UserEmails', function() {
)
})
- it("should not allow reconfirmation if the email doesn't match the user", function(done) {
+ it("should not allow reconfirmation if the email doesn't match the user", function (done) {
async.series(
[
cb => {
@@ -528,8 +528,8 @@ describe('UserEmails', function() {
})
})
- describe('setting a default email', function() {
- it('should update confirmed emails for users not in v1', function(done) {
+ describe('setting a default email', function () {
+ it('should update confirmed emails for users not in v1', function (done) {
async.series(
[
cb => {
@@ -597,7 +597,7 @@ describe('UserEmails', function() {
)
})
- it('should not allow changing unconfirmed emails in v1', function(done) {
+ it('should not allow changing unconfirmed emails in v1', function (done) {
async.series(
[
cb => {
@@ -661,7 +661,7 @@ describe('UserEmails', function() {
)
})
- it('should not update the email in v1', function(done) {
+ it('should not update the email in v1', function (done) {
async.series(
[
cb => {
@@ -732,7 +732,7 @@ describe('UserEmails', function() {
)
})
- it('should not return an error if the email exists in v1', function(done) {
+ it('should not return an error if the email exists in v1', function (done) {
MockV1Api.existingEmails.push('exists-in-v1@example.com')
async.series(
[
@@ -811,10 +811,10 @@ describe('UserEmails', function() {
)
})
- describe('audit log', function() {
+ describe('audit log', function () {
const originalEmail = 'original@overleaf.com'
let otherEmail, response, userHelper, user, userId
- beforeEach(async function() {
+ beforeEach(async function () {
otherEmail = 'other@overleaf.com'
userHelper = new UserHelper()
userHelper = await UserHelper.createUser({
@@ -856,7 +856,7 @@ describe('UserEmails', function() {
userHelper = await UserHelper.getUser(userId)
user = userHelper.user
})
- it('should be updated', function() {
+ it('should be updated', function () {
const auditLog = userHelper.getAuditLogWithoutNoise()
const entry = auditLog[auditLog.length - 1]
expect(typeof entry.initiatorId).to.equal('object')
@@ -869,7 +869,7 @@ describe('UserEmails', function() {
})
})
- describe('session cleanup', function() {
+ describe('session cleanup', function () {
beforeEach(function setupSecondSession(done) {
this.userSession2 = new User()
this.userSession2.email = this.user.email
@@ -929,7 +929,7 @@ describe('UserEmails', function() {
)
})
- it('should logout the other sessions', function(done) {
+ it('should logout the other sessions', function (done) {
this.userSession2.request(
{ method: 'GET', url: '/project', followRedirect: false },
(error, response) => {
@@ -945,12 +945,12 @@ describe('UserEmails', function() {
})
})
- describe('when not logged in', function() {
- beforeEach(function(done) {
+ describe('when not logged in', function () {
+ beforeEach(function (done) {
this.anonymous = new User()
this.anonymous.getCsrfToken(done)
})
- it('should return a plain 403 when setting the email', function(done) {
+ it('should return a plain 403 when setting the email', function (done) {
this.anonymous.request(
{
method: 'POST',
@@ -970,9 +970,9 @@ describe('UserEmails', function() {
})
})
- describe('secondary email', function() {
+ describe('secondary email', function () {
let newEmail, userHelper, userId, user
- beforeEach(async function() {
+ beforeEach(async function () {
newEmail = 'a-new-email@overleaf.com'
userHelper = new UserHelper()
userHelper = await UserHelper.createUser()
@@ -991,10 +991,10 @@ describe('UserEmails', function() {
userHelper = await UserHelper.getUser(userId)
user = userHelper.user
})
- it('should add the email', async function() {
+ it('should add the email', async function () {
expect(user.emails[1].email).to.equal(newEmail)
})
- it('should add to the user audit log', async function() {
+ it('should add to the user audit log', async function () {
const auditLog = userHelper.getAuditLogWithoutNoise()
expect(typeof auditLog[0].initiatorId).to.equal('object')
expect(auditLog[0].initiatorId).to.deep.equal(user._id)
@@ -1003,7 +1003,7 @@ describe('UserEmails', function() {
})
})
- describe('notification period', function() {
+ describe('notification period', function () {
let defaultEmail, userHelper, email1, email2, email3
const maxConfirmationMonths = 12
const lastDayToReconfirm = moment()
@@ -1015,7 +1015,7 @@ describe('UserEmails', function() {
const daysToBackdate = moment().diff(oneDayBeforeLastDayToReconfirm, 'day')
const daysToBackdateForAfterDate = daysToBackdate + 1
- beforeEach(async function() {
+ beforeEach(async function () {
if (!Features.hasFeature('affiliations')) {
this.skip()
}
@@ -1039,8 +1039,8 @@ describe('UserEmails', function() {
email3 = `bones@${domain}`
})
- describe('non SSO affiliations', function() {
- beforeEach(async function() {
+ describe('non SSO affiliations', function () {
+ beforeEach(async function () {
// create a user with 3 affiliations at the institution.
// all are within in the notification period
const userId = userHelper.user._id
@@ -1056,8 +1056,8 @@ describe('UserEmails', function() {
)
})
- describe('when all affiliations in notification period or past reconfirm date', function() {
- it('should flag inReconfirmNotificationPeriod for all affiliations in period', async function() {
+ describe('when all affiliations in notification period or past reconfirm date', function () {
+ it('should flag inReconfirmNotificationPeriod for all affiliations in period', async function () {
const response = await userHelper.request.get('/user/emails')
expect(response.statusCode).to.equal(200)
const fullEmails = JSON.parse(response.body)
@@ -1074,7 +1074,7 @@ describe('UserEmails', function() {
).to.equal(true)
})
- it('should set pastReconfirmDate and emailHasInstitutionLicence:false for lapsed confirmations', async function() {
+ it('should set pastReconfirmDate and emailHasInstitutionLicence:false for lapsed confirmations', async function () {
const response = await userHelper.request.get('/user/emails')
expect(response.statusCode).to.equal(200)
const fullEmails = JSON.parse(response.body)
@@ -1089,8 +1089,8 @@ describe('UserEmails', function() {
})
})
- describe('should flag emails before their confirmation expires, but within the notification period', function() {
- beforeEach(async function() {
+ describe('should flag emails before their confirmation expires, but within the notification period', function () {
+ beforeEach(async function () {
const dateInPeriodButNotExpired = moment()
.subtract(maxConfirmationMonths, 'months')
.add(14, 'days')
@@ -1113,7 +1113,7 @@ describe('UserEmails', function() {
)
})
- it('should flag the emails', async function() {
+ it('should flag the emails', async function () {
const response = await userHelper.request.get('/user/emails')
expect(response.statusCode).to.equal(200)
const fullEmails = JSON.parse(response.body)
@@ -1152,8 +1152,8 @@ describe('UserEmails', function() {
})
})
- describe('missing reconfirmedAt', function() {
- beforeEach(async function() {
+ describe('missing reconfirmedAt', function () {
+ beforeEach(async function () {
const userId = userHelper.user._id
const query = {
_id: userId,
@@ -1165,7 +1165,7 @@ describe('UserEmails', function() {
await UserUpdater.promises.updateUser(query, update)
})
- it('should fallback to confirmedAt for date check', async function() {
+ it('should fallback to confirmedAt for date check', async function () {
const response = await userHelper.request.get('/user/emails')
expect(response.statusCode).to.equal(200)
const fullEmails = JSON.parse(response.body)
diff --git a/services/web/test/acceptance/src/UserHelperTests.js b/services/web/test/acceptance/src/UserHelperTests.js
index 9bddee37b9..3a2b7c06fb 100644
--- a/services/web/test/acceptance/src/UserHelperTests.js
+++ b/services/web/test/acceptance/src/UserHelperTests.js
@@ -3,17 +3,17 @@ const UserHelper = require('./helpers/UserHelper')
const Features = require('../../../app/src/infrastructure/Features')
const { expect } = require('chai')
-describe('UserHelper', function() {
+describe('UserHelper', function () {
// Disable all tests unless the public-registration feature is enabled
- beforeEach(function() {
+ beforeEach(function () {
if (!Features.hasFeature('public-registration')) {
this.skip()
}
})
- describe('UserHelper.createUser', function() {
- describe('with no args', function() {
- it('should create new user with default username and password', async function() {
+ describe('UserHelper.createUser', function () {
+ describe('with no args', function () {
+ it('should create new user with default username and password', async function () {
const userHelper = await UserHelper.createUser()
userHelper.user.email.should.equal(userHelper.getDefaultEmail())
const authedUser = await AuthenticationManager.promises.authenticate(
@@ -24,8 +24,8 @@ describe('UserHelper', function() {
})
})
- describe('with email', function() {
- it('should create new user with provided email and default password', async function() {
+ describe('with email', function () {
+ it('should create new user with provided email and default password', async function () {
const userHelper = await UserHelper.createUser({
email: 'foo@test.com'
})
@@ -38,8 +38,8 @@ describe('UserHelper', function() {
})
})
- describe('with password', function() {
- it('should create new user with provided password and default email', async function() {
+ describe('with password', function () {
+ it('should create new user with provided password and default email', async function () {
const userHelper = await UserHelper.createUser({
password: 'foofoofoo'
})
@@ -53,37 +53,37 @@ describe('UserHelper', function() {
})
})
- describe('UserHelper.getUser', function() {
+ describe('UserHelper.getUser', function () {
let user
- beforeEach(async function() {
+ beforeEach(async function () {
user = (await UserHelper.createUser()).user
})
- describe('with string id', function() {
- it('should fetch user', async function() {
+ describe('with string id', function () {
+ it('should fetch user', async function () {
const userHelper = await UserHelper.getUser(user._id.toString())
userHelper.user.email.should.equal(user.email)
})
})
- describe('with _id', function() {
- it('should fetch user', async function() {
+ describe('with _id', function () {
+ it('should fetch user', async function () {
const userHelper = await UserHelper.getUser({ _id: user._id })
userHelper.user.email.should.equal(user.email)
})
})
})
- describe('UserHelper.loginUser', function() {
+ describe('UserHelper.loginUser', function () {
let userHelper
- beforeEach(async function() {
+ beforeEach(async function () {
userHelper = await UserHelper.createUser()
})
- describe('with email and password', function() {
- it('should login user', async function() {
+ describe('with email and password', function () {
+ it('should login user', async function () {
const newUserHelper = await UserHelper.loginUser({
email: userHelper.getDefaultEmail(),
password: userHelper.getDefaultPassword()
@@ -92,24 +92,24 @@ describe('UserHelper', function() {
})
})
- describe('without email', function() {
- it('should throw error', async function() {
+ describe('without email', function () {
+ it('should throw error', async function () {
await UserHelper.loginUser({
password: userHelper.getDefaultPassword()
}).should.be.rejectedWith('email and password required')
})
})
- describe('without password', function() {
- it('should throw error', async function() {
+ describe('without password', function () {
+ it('should throw error', async function () {
await UserHelper.loginUser({
email: userHelper.getDefaultEmail()
}).should.be.rejectedWith('email and password required')
})
})
- describe('without email and password', function() {
- it('should throw error', async function() {
+ describe('without email and password', function () {
+ it('should throw error', async function () {
await UserHelper.loginUser().should.be.rejectedWith(
'email and password required'
)
@@ -117,9 +117,9 @@ describe('UserHelper', function() {
})
})
- describe('UserHelper.registerUser', function() {
- describe('with no args', function() {
- it('should create new user with default username and password', async function() {
+ describe('UserHelper.registerUser', function () {
+ describe('with no args', function () {
+ it('should create new user with default username and password', async function () {
const userHelper = await UserHelper.registerUser()
userHelper.user.email.should.equal(userHelper.getDefaultEmail())
const authedUser = await AuthenticationManager.promises.authenticate(
@@ -130,8 +130,8 @@ describe('UserHelper', function() {
})
})
- describe('with email', function() {
- it('should create new user with provided email and default password', async function() {
+ describe('with email', function () {
+ it('should create new user with provided email and default password', async function () {
const userHelper = await UserHelper.registerUser({
email: 'foo2@test.com'
})
@@ -144,8 +144,8 @@ describe('UserHelper', function() {
})
})
- describe('with password', function() {
- it('should create new user with provided password and default email', async function() {
+ describe('with password', function () {
+ it('should create new user with provided password and default email', async function () {
const userHelper = await UserHelper.registerUser({
password: 'foofoofoo'
})
@@ -159,23 +159,23 @@ describe('UserHelper', function() {
})
})
- describe('getCsrfToken', function() {
- it('should fetch csrfToken', async function() {
+ describe('getCsrfToken', function () {
+ it('should fetch csrfToken', async function () {
const userHelper = new UserHelper()
await userHelper.getCsrfToken()
expect(userHelper.csrfToken).to.be.a.string
})
})
- describe('after logout', function() {
+ describe('after logout', function () {
let userHelper, oldCsrfToken
- beforeEach(async function() {
+ beforeEach(async function () {
userHelper = await UserHelper.registerUser()
oldCsrfToken = userHelper.csrfToken
})
- it('refreshes csrf token after logout', async function() {
+ it('refreshes csrf token after logout', async function () {
await userHelper.logout()
expect(userHelper._csrfToken).to.equal('')
await userHelper.getCsrfToken()
diff --git a/services/web/test/acceptance/src/UserMembershipAuthorizationTests.js b/services/web/test/acceptance/src/UserMembershipAuthorizationTests.js
index 4dc77ea996..743e3ac884 100644
--- a/services/web/test/acceptance/src/UserMembershipAuthorizationTests.js
+++ b/services/web/test/acceptance/src/UserMembershipAuthorizationTests.js
@@ -5,14 +5,14 @@ const Institution = require('./helpers/Institution')
const Subscription = require('./helpers/Subscription')
const Publisher = require('./helpers/Publisher')
-describe('UserMembershipAuthorization', function() {
- beforeEach(function(done) {
+describe('UserMembershipAuthorization', function () {
+ beforeEach(function (done) {
this.user = new User()
async.series([this.user.ensureUserExists.bind(this.user)], done)
})
- describe('group', function() {
- beforeEach(function(done) {
+ describe('group', function () {
+ beforeEach(function (done) {
this.subscription = new Subscription({
groupPlan: true
})
@@ -25,8 +25,8 @@ describe('UserMembershipAuthorization', function() {
)
})
- describe('users management', function() {
- it('should allow managers only', function(done) {
+ describe('users management', function () {
+ it('should allow managers only', function (done) {
const url = `/manage/groups/${this.subscription._id}/members`
async.series(
[
@@ -39,8 +39,8 @@ describe('UserMembershipAuthorization', function() {
})
})
- describe('managers management', function() {
- it('should allow managers only', function(done) {
+ describe('managers management', function () {
+ it('should allow managers only', function (done) {
const url = `/manage/groups/${this.subscription._id}/managers`
async.series(
[
@@ -54,14 +54,14 @@ describe('UserMembershipAuthorization', function() {
})
})
- describe('institution', function() {
- beforeEach(function(done) {
+ describe('institution', function () {
+ beforeEach(function (done) {
this.institution = new Institution()
async.series([this.institution.ensureExists.bind(this.institution)], done)
})
- describe('users management', function() {
- it('should allow managers only', function(done) {
+ describe('users management', function () {
+ it('should allow managers only', function (done) {
const url = `/manage/institutions/${this.institution.v1Id}/managers`
async.series(
[
@@ -75,8 +75,8 @@ describe('UserMembershipAuthorization', function() {
})
})
- describe('creation', function() {
- it('should allow staff only', function(done) {
+ describe('creation', function () {
+ it('should allow staff only', function (done) {
const url = `/entities/institution/create/foo`
async.series(
[
@@ -92,8 +92,8 @@ describe('UserMembershipAuthorization', function() {
})
})
- describe('publisher', function() {
- beforeEach(function(done) {
+ describe('publisher', function () {
+ beforeEach(function (done) {
this.publisher = new Publisher({})
async.series(
[
@@ -104,8 +104,8 @@ describe('UserMembershipAuthorization', function() {
)
})
- describe('managers management', function() {
- it('should allow managers only', function(done) {
+ describe('managers management', function () {
+ it('should allow managers only', function (done) {
const url = `/manage/publishers/${this.publisher.slug}/managers`
async.series(
[
@@ -118,8 +118,8 @@ describe('UserMembershipAuthorization', function() {
})
})
- describe('creation', function() {
- it('should redirect staff only', function(done) {
+ describe('creation', function () {
+ it('should redirect staff only', function (done) {
const url = `/manage/publishers/foo/managers`
async.series(
[
@@ -133,7 +133,7 @@ describe('UserMembershipAuthorization', function() {
)
})
- it('should allow staff only', function(done) {
+ it('should allow staff only', function (done) {
const url = `/entities/publisher/create/foo`
async.series(
[
diff --git a/services/web/test/acceptance/src/UserReconfirmTests.js b/services/web/test/acceptance/src/UserReconfirmTests.js
index fe7bfbb04b..a58f2ca1c0 100644
--- a/services/web/test/acceptance/src/UserReconfirmTests.js
+++ b/services/web/test/acceptance/src/UserReconfirmTests.js
@@ -15,8 +15,8 @@ const { expect } = require('chai')
const async = require('async')
const User = require('./helpers/User')
-describe('User Must Reconfirm', function() {
- beforeEach(function(done) {
+describe('User Must Reconfirm', function () {
+ beforeEach(function (done) {
this.user = new User()
return async.series(
[
@@ -27,7 +27,7 @@ describe('User Must Reconfirm', function() {
)
})
- it('should not allow sign in', function(done) {
+ it('should not allow sign in', function (done) {
return this.user.login(err => {
expect(err != null).to.equal(false)
return this.user.isLoggedIn((err, isLoggedIn) => {
@@ -37,8 +37,8 @@ describe('User Must Reconfirm', function() {
})
})
- describe('Requesting reconfirmation email', function() {
- it('should return a success to client for existing account', function(done) {
+ describe('Requesting reconfirmation email', function () {
+ it('should return a success to client for existing account', function (done) {
return this.user.reconfirmAccountRequest(
this.user.email,
(err, response) => {
@@ -49,7 +49,7 @@ describe('User Must Reconfirm', function() {
)
})
- it('should return a 404 to client for non-existent account', function(done) {
+ it('should return a 404 to client for non-existent account', function (done) {
return this.user.reconfirmAccountRequest(
'fake@overleaf.com',
(err, response) => {
diff --git a/services/web/test/acceptance/src/UserThirdPartyIdentityTests.js b/services/web/test/acceptance/src/UserThirdPartyIdentityTests.js
index b3d91007a0..a99257f813 100644
--- a/services/web/test/acceptance/src/UserThirdPartyIdentityTests.js
+++ b/services/web/test/acceptance/src/UserThirdPartyIdentityTests.js
@@ -16,8 +16,8 @@ const User = require('./helpers/User')
const ThirdPartyIdentityManager = require('../../../app/src/Features/User/ThirdPartyIdentityManager')
const { expect } = require('chai')
-describe('ThirdPartyIdentityManager', function() {
- beforeEach(function(done) {
+describe('ThirdPartyIdentityManager', function () {
+ beforeEach(function (done) {
this.provider = 'provider'
this.externalUserId = 'external-user-id'
this.externalData = { test: 'data' }
@@ -25,13 +25,13 @@ describe('ThirdPartyIdentityManager', function() {
this.user.ensureUserExists(done)
})
- afterEach(function(done) {
+ afterEach(function (done) {
return this.user.fullDeleteUser(this.user.email, done)
})
- describe('login', function() {
- describe('when third party identity exists', function() {
- beforeEach(function(done) {
+ describe('login', function () {
+ describe('when third party identity exists', function () {
+ beforeEach(function (done) {
return ThirdPartyIdentityManager.link(
this.user.id,
this.provider,
@@ -42,7 +42,7 @@ describe('ThirdPartyIdentityManager', function() {
)
})
- it('should return user', function(done) {
+ it('should return user', function (done) {
ThirdPartyIdentityManager.login(
this.provider,
this.externalUserId,
@@ -55,7 +55,7 @@ describe('ThirdPartyIdentityManager', function() {
)
})
- it('should merge external data', function(done) {
+ it('should merge external data', function (done) {
this.externalData = {
test: 'different',
another: 'key'
@@ -75,8 +75,8 @@ describe('ThirdPartyIdentityManager', function() {
})
})
- describe('when third party identity does not exists', function() {
- it('should return error', function(done) {
+ describe('when third party identity does not exists', function () {
+ it('should return error', function (done) {
ThirdPartyIdentityManager.login(
this.provider,
this.externalUserId,
@@ -90,9 +90,9 @@ describe('ThirdPartyIdentityManager', function() {
})
})
- describe('link', function() {
- describe('when provider not already linked', function() {
- it('should link provider to user', function(done) {
+ describe('link', function () {
+ describe('when provider not already linked', function () {
+ it('should link provider to user', function (done) {
ThirdPartyIdentityManager.link(
this.user.id,
this.provider,
@@ -107,8 +107,8 @@ describe('ThirdPartyIdentityManager', function() {
})
})
- describe('when provider is already linked', function() {
- beforeEach(function(done) {
+ describe('when provider is already linked', function () {
+ beforeEach(function (done) {
ThirdPartyIdentityManager.link(
this.user.id,
this.provider,
@@ -119,7 +119,7 @@ describe('ThirdPartyIdentityManager', function() {
)
})
- it('should link provider to user', function(done) {
+ it('should link provider to user', function (done) {
ThirdPartyIdentityManager.link(
this.user.id,
this.provider,
@@ -133,7 +133,7 @@ describe('ThirdPartyIdentityManager', function() {
)
})
- it('should not create duplicate thirdPartyIdentifiers', function(done) {
+ it('should not create duplicate thirdPartyIdentifiers', function (done) {
ThirdPartyIdentityManager.link(
this.user.id,
this.provider,
@@ -147,7 +147,7 @@ describe('ThirdPartyIdentityManager', function() {
)
})
- it('should replace existing data', function(done) {
+ it('should replace existing data', function (done) {
this.externalData = { replace: 'data' }
return ThirdPartyIdentityManager.link(
this.user.id,
@@ -185,9 +185,9 @@ describe('ThirdPartyIdentityManager', function() {
})
})
- describe('unlink', function() {
- describe('when provider not already linked', function() {
- it('should succeed', function(done) {
+ describe('unlink', function () {
+ describe('when provider not already linked', function () {
+ it('should succeed', function (done) {
return ThirdPartyIdentityManager.unlink(
this.user.id,
this.provider,
@@ -201,8 +201,8 @@ describe('ThirdPartyIdentityManager', function() {
})
})
- describe('when provider is already linked', function() {
- beforeEach(function(done) {
+ describe('when provider is already linked', function () {
+ beforeEach(function (done) {
return ThirdPartyIdentityManager.link(
this.user.id,
this.provider,
@@ -213,7 +213,7 @@ describe('ThirdPartyIdentityManager', function() {
)
})
- it('should remove thirdPartyIdentifiers entry', function(done) {
+ it('should remove thirdPartyIdentifiers entry', function (done) {
return ThirdPartyIdentityManager.unlink(
this.user.id,
this.provider,
diff --git a/services/web/test/acceptance/src/helpers/InitApp.js b/services/web/test/acceptance/src/helpers/InitApp.js
index 5cb94335bd..2c55e38b3b 100644
--- a/services/web/test/acceptance/src/helpers/InitApp.js
+++ b/services/web/test/acceptance/src/helpers/InitApp.js
@@ -8,11 +8,11 @@ MongoHelper.initialize()
let server
-before('start main app', function(done) {
+before('start main app', function (done) {
server = App.listen(3000, 'localhost', done)
})
-after('stop main app', function(done) {
+after('stop main app', function (done) {
if (!server) {
return done()
}
diff --git a/services/web/test/acceptance/src/helpers/MongoHelper.js b/services/web/test/acceptance/src/helpers/MongoHelper.js
index 7a14467f6c..c81666f120 100644
--- a/services/web/test/acceptance/src/helpers/MongoHelper.js
+++ b/services/web/test/acceptance/src/helpers/MongoHelper.js
@@ -5,7 +5,7 @@ module.exports = {
initialize() {
before(waitForDb)
- before(function(done) {
+ before(function (done) {
exec('bin/east migrate', (error, stdout, stderr) => {
console.log(stdout)
console.error(stderr)
@@ -16,7 +16,7 @@ module.exports = {
})
})
- afterEach(async function() {
+ afterEach(async function () {
return Promise.all(
Object.values(db).map(collection => collection.deleteMany({}))
)
diff --git a/services/web/test/acceptance/src/helpers/RecurlySubscription.js b/services/web/test/acceptance/src/helpers/RecurlySubscription.js
index e349775d54..1cbb1ee3e1 100644
--- a/services/web/test/acceptance/src/helpers/RecurlySubscription.js
+++ b/services/web/test/acceptance/src/helpers/RecurlySubscription.js
@@ -5,7 +5,7 @@ const RecurlyWrapper = require('../../../../app/src/Features/Subscription/Recurl
let MockRecurlyApi
-before(function() {
+before(function () {
MockRecurlyApi = MockRecurlyApiClass.instance()
})
diff --git a/services/web/test/acceptance/src/helpers/UserHelper.js b/services/web/test/acceptance/src/helpers/UserHelper.js
index cbbf82f81d..fc025ee116 100644
--- a/services/web/test/acceptance/src/helpers/UserHelper.js
+++ b/services/web/test/acceptance/src/helpers/UserHelper.js
@@ -325,9 +325,7 @@ class UserHelper {
}
async backdateConfirmation(userId, email, days) {
- const confirmedDate = moment()
- .subtract(days, 'days')
- .toDate()
+ const confirmedDate = moment().subtract(days, 'days').toDate()
const query = {
_id: userId,
'emails.email': email
diff --git a/services/web/test/acceptance/src/helpers/redis.js b/services/web/test/acceptance/src/helpers/redis.js
index d9e1c15dc6..1e48d51fb9 100644
--- a/services/web/test/acceptance/src/helpers/redis.js
+++ b/services/web/test/acceptance/src/helpers/redis.js
@@ -23,7 +23,7 @@ const rclient = UserSessionsRedis.client()
module.exports = {
getUserSessions(user, callback) {
if (callback == null) {
- callback = function(err, sessionsSet) {}
+ callback = function (err, sessionsSet) {}
}
return rclient.smembers(
UserSessionsRedis.sessionSetKey(user),
@@ -33,7 +33,7 @@ module.exports = {
clearUserSessions(user, callback) {
if (callback == null) {
- callback = function(err) {}
+ callback = function (err) {}
}
const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
return rclient.smembers(sessionSetKey, (err, sessionKeys) => {
diff --git a/services/web/test/acceptance/src/helpers/request.js b/services/web/test/acceptance/src/helpers/request.js
index b3f0dc12cc..939cc1f802 100644
--- a/services/web/test/acceptance/src/helpers/request.js
+++ b/services/web/test/acceptance/src/helpers/request.js
@@ -9,7 +9,7 @@ const request = require('request').defaults({
module.exports = request
module.exports.promises = {
- request: function(options) {
+ request: function (options) {
return new Promise((resolve, reject) => {
request(options, (err, response) => {
if (err) {
diff --git a/services/web/test/frontend/features/chat/components/chat-pane.test.js b/services/web/test/frontend/features/chat/components/chat-pane.test.js
index 7daaa6cd1d..6377d879f5 100644
--- a/services/web/test/frontend/features/chat/components/chat-pane.test.js
+++ b/services/web/test/frontend/features/chat/components/chat-pane.test.js
@@ -10,7 +10,7 @@ import {
} from '../../../helpers/render-with-context'
import { stubMathJax, tearDownMathJaxStubs } from './stubs'
-describe('', function() {
+describe('', function () {
const user = {
id: 'fake_user',
first_name: 'fake_user_first_name',
@@ -32,18 +32,18 @@ describe('', function() {
}
]
- beforeEach(function() {
+ beforeEach(function () {
fetchMock.reset()
cleanUpContext()
stubMathJax()
})
- afterEach(function() {
+ afterEach(function () {
tearDownMathJaxStubs()
})
- it('renders multiple messages', async function() {
+ it('renders multiple messages', async function () {
fetchMock.get(/messages/, testMessages)
renderWithChatContext(, { user })
@@ -52,7 +52,7 @@ describe('', function() {
await screen.findByText('another message')
})
- it('A loading spinner is rendered while the messages are loading, then disappears', async function() {
+ it('A loading spinner is rendered while the messages are loading, then disappears', async function () {
fetchMock.get(/messages/, [])
renderWithChatContext(, { user })
@@ -60,8 +60,8 @@ describe('', function() {
await waitForElementToBeRemoved(() => screen.getByText('Loading…'))
})
- describe('"send your first message" placeholder', function() {
- it('is rendered when there are no messages ', async function() {
+ describe('"send your first message" placeholder', function () {
+ it('is rendered when there are no messages ', async function () {
fetchMock.get(/messages/, [])
renderWithChatContext(, { user })
@@ -69,7 +69,7 @@ describe('', function() {
await screen.findByText('Send your first message to your collaborators')
})
- it('is not rendered when messages are displayed', function() {
+ it('is not rendered when messages are displayed', function () {
fetchMock.get(/messages/, testMessages)
renderWithChatContext(, { user })
diff --git a/services/web/test/frontend/features/chat/components/message-input.test.js b/services/web/test/frontend/features/chat/components/message-input.test.js
index 57cd6502f5..08de88e452 100644
--- a/services/web/test/frontend/features/chat/components/message-input.test.js
+++ b/services/web/test/frontend/features/chat/components/message-input.test.js
@@ -5,15 +5,15 @@ import { screen, render, fireEvent } from '@testing-library/react'
import MessageInput from '../../../../../frontend/js/features/chat/components/message-input'
-describe('', function() {
+describe('', function () {
let resetUnreadMessages, sendMessage
- beforeEach(function() {
+ beforeEach(function () {
resetUnreadMessages = sinon.stub()
sendMessage = sinon.stub()
})
- it('renders successfully', function() {
+ it('renders successfully', function () {
render(
', function() {
screen.getByLabelText('Your Message')
})
- it('sends a message after typing and hitting enter', function() {
+ it('sends a message after typing and hitting enter', function () {
render(
', function() {
expect(sendMessage).to.be.calledWith('hello world')
})
- it('resets the number of unread messages after clicking on the input', function() {
+ it('resets the number of unread messages after clicking on the input', function () {
render(
', function() {
+describe('', function () {
const currentUser = {
id: 'fake_user',
first_name: 'fake_user_first_name',
@@ -30,15 +30,15 @@ describe('', function() {
]
}
- before(function() {
+ before(function () {
stubMathJax()
})
- after(function() {
+ after(function () {
tearDownMathJaxStubs()
})
- it('renders multiple messages', function() {
+ it('renders multiple messages', function () {
render(
', function() {
screen.getByText('another message')
})
- it('renders a single timestamp for all messages within 5 minutes', function() {
+ it('renders a single timestamp for all messages within 5 minutes', function () {
const msgs = createMessages()
msgs[0].timestamp = new Date(2019, 6, 3, 4, 23).getTime()
msgs[1].timestamp = new Date(2019, 6, 3, 4, 27).getTime()
@@ -68,7 +68,7 @@ describe('', function() {
expect(screen.queryByText('4:27 am Wed, 3rd Jul 19')).to.not.exist
})
- it('renders a timestamp for each messages separated for more than 5 minutes', function() {
+ it('renders a timestamp for each messages separated for more than 5 minutes', function () {
const msgs = createMessages()
msgs[0].timestamp = new Date(2019, 6, 3, 4, 23).getTime()
msgs[1].timestamp = new Date(2019, 6, 3, 4, 31).getTime()
@@ -85,7 +85,7 @@ describe('', function() {
screen.getByText('4:31 am Wed, 3rd Jul 19')
})
- it('resets the number of unread messages after clicking on the input', function() {
+ it('resets the number of unread messages after clicking on the input', function () {
const resetUnreadMessages = sinon.stub()
render(
', function() {
+describe('', function () {
const currentUser = {
id: 'fake_user',
first_name: 'fake_user_first_name',
email: 'fake@example.com'
}
- beforeEach(function() {
+ beforeEach(function () {
window.user = currentUser
stubMathJax()
})
- afterEach(function() {
+ afterEach(function () {
delete window.user
tearDownMathJaxStubs()
})
- it('renders a basic message', function() {
+ it('renders a basic message', function () {
const message = {
contents: ['a message'],
user: currentUser
@@ -33,7 +33,7 @@ describe('', function() {
screen.getByText('a message')
})
- it('renders a message with multiple contents', function() {
+ it('renders a message with multiple contents', function () {
const message = {
contents: ['a message', 'another message'],
user: currentUser
@@ -45,7 +45,7 @@ describe('', function() {
screen.getByText('another message')
})
- it('renders HTML links within messages', function() {
+ it('renders HTML links within messages', function () {
const message = {
contents: [
'a message with a link to Overleaf'
@@ -58,13 +58,13 @@ describe('', function() {
screen.getByRole('link', { name: 'https://overleaf.com' })
})
- describe('when the message is from the user themselves', function() {
+ describe('when the message is from the user themselves', function () {
const message = {
contents: ['a message'],
user: currentUser
}
- it('does not render the user name nor the email', function() {
+ it('does not render the user name nor the email', function () {
render()
expect(screen.queryByText(currentUser.first_name)).to.not.exist
@@ -72,7 +72,7 @@ describe('', function() {
})
})
- describe('when the message is from other user', function() {
+ describe('when the message is from other user', function () {
const otherUser = {
id: 'other_user',
first_name: 'other_user_first_name'
@@ -83,13 +83,13 @@ describe('', function() {
user: otherUser
}
- it('should render the other user name', function() {
+ it('should render the other user name', function () {
render()
screen.getByText(otherUser.first_name)
})
- it('should render the other user email when their name is not available', function() {
+ it('should render the other user email when their name is not available', function () {
const msg = {
contents: message.contents,
user: {
diff --git a/services/web/test/frontend/features/chat/store/chat-store.test.js b/services/web/test/frontend/features/chat/store/chat-store.test.js
index ceb14c290d..d3c75e69a3 100644
--- a/services/web/test/frontend/features/chat/store/chat-store.test.js
+++ b/services/web/test/frontend/features/chat/store/chat-store.test.js
@@ -6,7 +6,7 @@ import {
MESSAGE_LIMIT
} from '../../../../../frontend/js/features/chat/store/chat-store'
-describe('ChatStore', function() {
+describe('ChatStore', function () {
let store, socket, mockSocketMessage
const user = {
@@ -22,7 +22,7 @@ describe('ChatStore', function() {
user
}
- beforeEach(function() {
+ beforeEach(function () {
fetchMock.reset()
window.csrfToken = 'csrf_tok'
@@ -34,7 +34,7 @@ describe('ChatStore', function() {
store = new ChatStore(user, testProjectId)
})
- afterEach(function() {
+ afterEach(function () {
fetchMock.restore()
delete window._ide
delete window.csrfToken
@@ -42,19 +42,19 @@ describe('ChatStore', function() {
delete window.project_id
})
- describe('new message events', function() {
- it('subscribes to the socket for new message events', function() {
+ describe('new message events', function () {
+ it('subscribes to the socket for new message events', function () {
expect(socket.on).to.be.calledWith('new-chat-message')
})
- it('notifies an update event after new messages are received', function() {
+ it('notifies an update event after new messages are received', function () {
const subscriber = sinon.stub()
store.on('updated', subscriber)
mockSocketMessage(testMessage)
expect(subscriber).to.be.calledOnce
})
- it('can unsubscribe from events', function() {
+ it('can unsubscribe from events', function () {
const subscriber = sinon.stub()
store.on('updated', subscriber)
store.off('updated', subscriber)
@@ -62,7 +62,7 @@ describe('ChatStore', function() {
expect(subscriber).not.to.be.called
})
- it('when the message is from other user, it is added to the messages list', function() {
+ it('when the message is from other user, it is added to the messages list', function () {
mockSocketMessage({ ...testMessage, id: 'other_user_msg' })
expect(store.messages[store.messages.length - 1]).to.deep.equal({
id: 'other_user_msg',
@@ -72,12 +72,12 @@ describe('ChatStore', function() {
})
})
- describe('messages sent by the user', function() {
- beforeEach(function() {
+ describe('messages sent by the user', function () {
+ beforeEach(function () {
fetchMock.post(/messages/, 204)
})
- it('are not added to the message list', async function() {
+ it('are not added to the message list', async function () {
await store.sendMessage(testMessage.content)
const originalMessageList = store.messages.slice(0)
mockSocketMessage(testMessage)
@@ -100,7 +100,7 @@ describe('ChatStore', function() {
})
})
- it("don't notify an update event after new messages are received", async function() {
+ it("don't notify an update event after new messages are received", async function () {
await store.sendMessage(testMessage.content)
const subscriber = sinon.stub()
@@ -110,22 +110,22 @@ describe('ChatStore', function() {
expect(subscriber).not.to.be.called
})
- it("have an 'id' property", async function() {
+ it("have an 'id' property", async function () {
await store.sendMessage(testMessage.content)
expect(typeof store.messages[0].id).to.equal('string')
})
})
})
- describe('loadMoreMessages()', function() {
- it('aborts the request when the entire message list is loaded', async function() {
+ describe('loadMoreMessages()', function () {
+ it('aborts the request when the entire message list is loaded', async function () {
store.atEnd = true
await store.loadMoreMessages()
expect(fetchMock.calls().length).to.equal(0)
expect(store.loading).to.equal(false)
})
- it('updates the list of messages', async function() {
+ it('updates the list of messages', async function () {
const originalMessageList = store.messages.slice(0)
fetchMock.get(/messages/, [testMessage])
await store.loadMoreMessages()
@@ -138,7 +138,7 @@ describe('ChatStore', function() {
})
})
- it('notifies an update event for when the loading starts, and a second one once data is available', async function() {
+ it('notifies an update event for when the loading starts, and a second one once data is available', async function () {
const subscriber = sinon.stub()
store.on('updated', subscriber)
fetchMock.get(/messages/, [testMessage])
@@ -146,14 +146,14 @@ describe('ChatStore', function() {
expect(subscriber).to.be.calledTwice
})
- it('marks `atEnd` flag to true when there are no more messages to retrieve', async function() {
+ it('marks `atEnd` flag to true when there are no more messages to retrieve', async function () {
expect(store.atEnd).to.equal(false)
fetchMock.get(/messages/, [testMessage])
await store.loadMoreMessages()
expect(store.atEnd).to.equal(true)
})
- it('marks `atEnd` flag to false when there are still messages to retrieve', async function() {
+ it('marks `atEnd` flag to false when there are still messages to retrieve', async function () {
const messages = []
for (let i = 0; i < MESSAGE_LIMIT; i++) {
messages.push({ ...testMessage, content: `message #${i}` })
@@ -164,7 +164,7 @@ describe('ChatStore', function() {
expect(store.atEnd).to.equal(false)
})
- it('subsequent requests for new messages start at the timestamp of the latest message', async function() {
+ it('subsequent requests for new messages start at the timestamp of the latest message', async function () {
const messages = []
for (let i = 0; i < MESSAGE_LIMIT - 1; i++) {
// sending enough messages so it doesn't mark `atEnd === true`
@@ -186,12 +186,12 @@ describe('ChatStore', function() {
})
})
- describe('sendMessage()', function() {
- beforeEach(function() {
+ describe('sendMessage()', function () {
+ beforeEach(function () {
fetchMock.post(/messages/, 204)
})
- it('appends the message to the list', async function() {
+ it('appends the message to the list', async function () {
const originalMessageList = store.messages.slice(0)
await store.sendMessage('a message')
expect(store.messages.length).to.equal(originalMessageList.length + 1)
@@ -201,14 +201,14 @@ describe('ChatStore', function() {
expect(lastMessage.timestamp).to.be.greaterThan(0)
})
- it('notifies an update event', async function() {
+ it('notifies an update event', async function () {
const subscriber = sinon.stub()
store.on('updated', subscriber)
await store.sendMessage('a message')
expect(subscriber).to.be.calledOnce
})
- it('sends an http POST request to the server', async function() {
+ it('sends an http POST request to the server', async function () {
await store.sendMessage('a message')
expect(fetchMock.calls().length).to.equal(1)
const body = fetchMock.lastCall()[1].body
@@ -218,7 +218,7 @@ describe('ChatStore', function() {
})
})
- it('ignores empty messages', async function() {
+ it('ignores empty messages', async function () {
const subscriber = sinon.stub()
store.on('updated', subscriber)
await store.sendMessage('')
@@ -227,12 +227,12 @@ describe('ChatStore', function() {
})
})
- describe('destroy', function() {
- beforeEach(function() {
+ describe('destroy', function () {
+ beforeEach(function () {
fetchMock.post(/messages/, 204)
})
- it('removes event listeners', async function() {
+ it('removes event listeners', async function () {
const subscriber = sinon.stub()
store.on('updated', subscriber)
store.destroy()
diff --git a/services/web/test/frontend/features/chat/store/message-list-appender.test.js b/services/web/test/frontend/features/chat/store/message-list-appender.test.js
index 8b7f347f14..0a41dcf689 100644
--- a/services/web/test/frontend/features/chat/store/message-list-appender.test.js
+++ b/services/web/test/frontend/features/chat/store/message-list-appender.test.js
@@ -29,7 +29,7 @@ function createTestMessageList() {
]
}
-describe('prependMessages()', function() {
+describe('prependMessages()', function () {
function createTestMessages() {
const message1 = {
id: 'prepended_message',
@@ -41,7 +41,7 @@ describe('prependMessages()', function() {
return [message1, message2]
}
- it('to an empty list', function() {
+ it('to an empty list', function () {
const messages = createTestMessages()
expect(prependMessages([], messages)).to.deep.equal([
{
@@ -53,16 +53,16 @@ describe('prependMessages()', function() {
])
})
- describe('when the messages to prepend are from the same user', function() {
+ describe('when the messages to prepend are from the same user', function () {
let list, messages
- beforeEach(function() {
+ beforeEach(function () {
list = createTestMessageList()
messages = createTestMessages()
messages[0].user = testUser // makes all the messages have the same author
})
- it('when the prepended messages are close in time, contents should be merged into the same message', function() {
+ it('when the prepended messages are close in time, contents should be merged into the same message', function () {
const result = prependMessages(createTestMessageList(), messages)
expect(result.length).to.equal(list.length + 1)
expect(result[0]).to.deep.equal({
@@ -73,7 +73,7 @@ describe('prependMessages()', function() {
})
})
- it('when the prepended messages are separated in time, each message is prepended', function() {
+ it('when the prepended messages are separated in time, each message is prepended', function () {
messages[0].timestamp = messages[1].timestamp - 6 * 60 * 1000 // 6 minutes before the next message
const result = prependMessages(createTestMessageList(), messages)
expect(result.length).to.equal(list.length + 2)
@@ -92,15 +92,15 @@ describe('prependMessages()', function() {
})
})
- describe('when the messages to prepend are from different users', function() {
+ describe('when the messages to prepend are from different users', function () {
let list, messages
- beforeEach(function() {
+ beforeEach(function () {
list = createTestMessageList()
messages = createTestMessages()
})
- it('should prepend separate messages to the list', function() {
+ it('should prepend separate messages to the list', function () {
messages[0].user = otherUser
const result = prependMessages(createTestMessageList(), messages)
expect(result.length).to.equal(list.length + 2)
@@ -119,7 +119,7 @@ describe('prependMessages()', function() {
})
})
- it('should merge the prepended messages into the first existing one when user is same user and are close in time', function() {
+ it('should merge the prepended messages into the first existing one when user is same user and are close in time', function () {
const list = createTestMessageList()
const messages = createTestMessages()
messages[0].user = messages[1].user = list[0].user
@@ -135,7 +135,7 @@ describe('prependMessages()', function() {
})
})
-describe('appendMessage()', function() {
+describe('appendMessage()', function () {
function createTestMessage() {
return {
id: 'appended_message',
@@ -145,7 +145,7 @@ describe('appendMessage()', function() {
}
}
- it('to an empty list', function() {
+ it('to an empty list', function () {
const testMessage = createTestMessage()
expect(appendMessage([], testMessage)).to.deep.equal([
{
@@ -157,17 +157,17 @@ describe('appendMessage()', function() {
])
})
- describe('messages appended shortly after the last message on the list', function() {
+ describe('messages appended shortly after the last message on the list', function () {
let list, message
- beforeEach(function() {
+ beforeEach(function () {
list = createTestMessageList()
message = createTestMessage()
message.timestamp = list[1].timestamp + 6 * 1000 // 6 seconds after the last message in the list
})
- describe('when the author is the same as the last message', function() {
- it('should append the content to the last message', function() {
+ describe('when the author is the same as the last message', function () {
+ it('should append the content to the last message', function () {
const result = appendMessage(list, message)
expect(result.length).to.equal(list.length)
expect(result[1].contents).to.deep.equal(
@@ -175,18 +175,18 @@ describe('appendMessage()', function() {
)
})
- it('should update the last message timestamp', function() {
+ it('should update the last message timestamp', function () {
const result = appendMessage(list, message)
expect(result[1].timestamp).to.equal(message.timestamp)
})
})
- describe('when the author is different than the last message', function() {
- beforeEach(function() {
+ describe('when the author is different than the last message', function () {
+ beforeEach(function () {
message.user = otherUser
})
- it('should append the new message to the list', function() {
+ it('should append the new message to the list', function () {
const result = appendMessage(list, message)
expect(result.length).to.equal(list.length + 1)
expect(result[2]).to.deep.equal({
@@ -199,16 +199,16 @@ describe('appendMessage()', function() {
})
})
- describe('messages appended later after the last message on the list', function() {
+ describe('messages appended later after the last message on the list', function () {
let list, message
- beforeEach(function() {
+ beforeEach(function () {
list = createTestMessageList()
message = createTestMessage()
message.timestamp = list[1].timestamp + 6 * 60 * 1000 // 6 minutes after the last message in the list
})
- it('when the author is the same as the last message, should be appended as new message', function() {
+ it('when the author is the same as the last message, should be appended as new message', function () {
const result = appendMessage(list, message)
expect(result.length).to.equal(3)
expect(result[2]).to.deep.equal({
@@ -219,7 +219,7 @@ describe('appendMessage()', function() {
})
})
- it('when the author is the different than the last message, should be appended as new message', function() {
+ it('when the author is the different than the last message, should be appended as new message', function () {
message.user = otherUser
const result = appendMessage(list, message)
diff --git a/services/web/test/frontend/features/clone-project-modal/components/clone-project-modal.test.js b/services/web/test/frontend/features/clone-project-modal/components/clone-project-modal.test.js
index 7c774879f6..fe6325a9b0 100644
--- a/services/web/test/frontend/features/clone-project-modal/components/clone-project-modal.test.js
+++ b/services/web/test/frontend/features/clone-project-modal/components/clone-project-modal.test.js
@@ -5,8 +5,8 @@ import CloneProjectModal from '../../../../../frontend/js/features/clone-project
import sinon from 'sinon'
import fetchMock from 'fetch-mock'
-describe('', function() {
- afterEach(function() {
+describe('', function () {
+ afterEach(function () {
fetchMock.reset()
})
@@ -18,13 +18,13 @@ describe('', function() {
show: true
}
- it('renders the translated modal title', async function() {
+ it('renders the translated modal title', async function () {
render()
await screen.findByText('Copy Project')
})
- it('posts the generated project name', async function() {
+ it('posts the generated project name', async function () {
fetchMock.post(
'express:/project/:projectId/clone',
{
@@ -81,7 +81,7 @@ describe('', function() {
})
})
- it('handles a generic error response', async function() {
+ it('handles a generic error response', async function () {
const matcher = 'express:/project/:projectId/clone'
fetchMock.postOnce(matcher, {
@@ -110,7 +110,7 @@ describe('', function() {
expect(cancelButton.disabled).to.be.false
})
- it('handles a specific error response', async function() {
+ it('handles a specific error response', async function () {
const matcher = 'express:/project/:projectId/clone'
fetchMock.postOnce(matcher, {
diff --git a/services/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-create-name-input.test.js b/services/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-create-name-input.test.js
index 9a9431b764..796a4ec0ea 100644
--- a/services/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-create-name-input.test.js
+++ b/services/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-create-name-input.test.js
@@ -9,19 +9,19 @@ import FileTreeCreateNameInput from '../../../../../../frontend/js/features/file
import FileTreeContext from '../../../../../../frontend/js/features/file-tree/components/file-tree-context'
import FileTreeCreateNameProvider from '../../../../../../frontend/js/features/file-tree/contexts/file-tree-create-name'
-describe('', function() {
+describe('', function () {
const sandbox = sinon.createSandbox()
- beforeEach(function() {
+ beforeEach(function () {
sandbox.spy(window, 'requestAnimationFrame')
})
- afterEach(function() {
+ afterEach(function () {
sandbox.restore()
cleanup()
})
- it('renders an empty input', async function() {
+ it('renders an empty input', async function () {
render(
@@ -34,7 +34,7 @@ describe('', function() {
await screen.getByPlaceholderText('File Name')
})
- it('renders a custom label and placeholder', async function() {
+ it('renders a custom label and placeholder', async function () {
render(
@@ -50,7 +50,7 @@ describe('', function() {
await screen.getByPlaceholderText('Enter a file name…')
})
- it('uses an initial name', async function() {
+ it('uses an initial name', async function () {
render(
@@ -63,7 +63,7 @@ describe('', function() {
expect(input.value).to.equal('test.tex')
})
- it('focuses the name', async function() {
+ it('focuses the name', async function () {
render(
diff --git a/services/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-modal-create-file.test.js b/services/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-modal-create-file.test.js
index d23ad7cf43..029e224d7b 100644
--- a/services/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-modal-create-file.test.js
+++ b/services/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-modal-create-file.test.js
@@ -16,13 +16,13 @@ import FileTreeContext from '../../../../../../frontend/js/features/file-tree/co
import { useFileTreeActionable } from '../../../../../../frontend/js/features/file-tree/contexts/file-tree-actionable'
import { useFileTreeMutable } from '../../../../../../frontend/js/features/file-tree/contexts/file-tree-mutable'
-describe('', function() {
- afterEach(function() {
+describe('', function () {
+ afterEach(function () {
fetchMock.restore()
cleanup()
})
- it('handles invalid file names', async function() {
+ it('handles invalid file names', async function () {
render(
@@ -56,7 +56,7 @@ describe('', function() {
)
})
- it('displays an error when the file limit is reached', async function() {
+ it('displays an error when the file limit is reached', async function () {
const rootFolder = [
{
docs: Array.from({ length: 10 }, (_, index) => ({
@@ -84,7 +84,7 @@ describe('', function() {
)
})
- it('displays a warning when the file limit is nearly reached', async function() {
+ it('displays a warning when the file limit is nearly reached', async function () {
const rootFolder = [
{
docs: Array.from({ length: 9 }, (_, index) => ({
@@ -108,7 +108,7 @@ describe('', function() {
screen.getByText(/This project is approaching the file limit \(\d+\/\d+\)/)
})
- it('counts files in nested folders', async function() {
+ it('counts files in nested folders', async function () {
const rootFolder = [
{
docs: [{ _id: 'entity-1' }],
@@ -150,7 +150,7 @@ describe('', function() {
screen.getByText(/This project is approaching the file limit \(\d+\/\d+\)/)
})
- it('creates a new file when the form is submitted', async function() {
+ it('creates a new file when the form is submitted', async function () {
fetchMock.post('express:/project/:projectId/doc', () => 204)
render(
@@ -173,7 +173,7 @@ describe('', function() {
).to.be.true
})
- it('imports a new file from a project', async function() {
+ it('imports a new file from a project', async function () {
fetchMock
.get('path:/user/projects', {
projects: [
@@ -289,7 +289,7 @@ describe('', function() {
).to.be.true
})
- it('import from a URL when the form is submitted', async function() {
+ it('import from a URL when the form is submitted', async function () {
fetchMock.post('express:/project/:projectId/linked_file', () => 204)
render(
@@ -331,7 +331,7 @@ describe('', function() {
})
// eslint-disable-next-line mocha/no-skipped-tests
- it.skip('uploads a new file', async function() {
+ it.skip('uploads a new file', async function () {
fetchMock.post('express:/project/:projectId/linked_file', () => 204)
render(
diff --git a/services/web/test/frontend/features/file-tree/components/file-tree-doc.test.js b/services/web/test/frontend/features/file-tree/components/file-tree-doc.test.js
index 6158f61939..9652165bda 100644
--- a/services/web/test/frontend/features/file-tree/components/file-tree-doc.test.js
+++ b/services/web/test/frontend/features/file-tree/components/file-tree-doc.test.js
@@ -5,8 +5,8 @@ import renderWithContext from '../helpers/render-with-context'
import FileTreeDoc from '../../../../../frontend/js/features/file-tree/components/file-tree-doc'
-describe('', function() {
- it('renders unselected', function() {
+describe('', function () {
+ it('renders unselected', function () {
const { container } = renderWithContext(
)
@@ -15,7 +15,7 @@ describe('', function() {
expect(container.querySelector('i.linked-file-highlight')).to.not.exist
})
- it('renders selected', function() {
+ it('renders selected', function () {
renderWithContext(
,
{
@@ -42,7 +42,7 @@ describe('', function() {
screen.getByRole('menuitem', { name: 'Upload' })
})
- it('renders as linked file', function() {
+ it('renders as linked file', function () {
const { container } = renderWithContext(
)
@@ -51,7 +51,7 @@ describe('', function() {
expect(container.querySelector('i.linked-file-highlight')).to.exist
})
- it('selects', function() {
+ it('selects', function () {
renderWithContext(, {
contextProps: {
rootFolder: [
@@ -70,7 +70,7 @@ describe('', function() {
screen.getByRole('treeitem', { selected: true })
})
- it('multi-selects', function() {
+ it('multi-selects', function () {
renderWithContext(, {
contextProps: {
rootFolder: [
diff --git a/services/web/test/frontend/features/file-tree/components/file-tree-folder-list.test.js b/services/web/test/frontend/features/file-tree/components/file-tree-folder-list.test.js
index f05e1eef1b..e9bcfaf903 100644
--- a/services/web/test/frontend/features/file-tree/components/file-tree-folder-list.test.js
+++ b/services/web/test/frontend/features/file-tree/components/file-tree-folder-list.test.js
@@ -5,15 +5,15 @@ import renderWithContext from '../helpers/render-with-context'
import FileTreeFolderList from '../../../../../frontend/js/features/file-tree/components/file-tree-folder-list'
-describe('', function() {
- it('renders empty', function() {
+describe('', function () {
+ it('renders empty', function () {
renderWithContext()
screen.queryByRole('tree')
expect(screen.queryByRole('treeitem')).to.not.exist
})
- it('renders docs, files and folders', function() {
+ it('renders docs, files and folders', function () {
const aFolder = {
_id: '456def',
name: 'A Folder',
@@ -33,8 +33,8 @@ describe('', function() {
screen.queryByRole('treeitem', { name: 'file.bib' })
})
- describe('selection and multi-selection', function() {
- it('without write permissions', function() {
+ describe('selection and multi-selection', function () {
+ it('without write permissions', function () {
const docs = [
{ _id: '1', name: '1.tex' },
{ _id: '2', name: '2.tex' }
@@ -69,7 +69,7 @@ describe('', function() {
screen.getByRole('treeitem', { name: '2.tex', selected: false })
})
- it('with write permissions', function() {
+ it('with write permissions', function () {
const docs = [
{ _id: '1', name: '1.tex' },
{ _id: '2', name: '2.tex' },
diff --git a/services/web/test/frontend/features/file-tree/components/file-tree-folder.test.js b/services/web/test/frontend/features/file-tree/components/file-tree-folder.test.js
index a5f0bce36d..f6ca725440 100644
--- a/services/web/test/frontend/features/file-tree/components/file-tree-folder.test.js
+++ b/services/web/test/frontend/features/file-tree/components/file-tree-folder.test.js
@@ -5,12 +5,12 @@ import renderWithContext from '../helpers/render-with-context'
import FileTreeFolder from '../../../../../frontend/js/features/file-tree/components/file-tree-folder'
-describe('', function() {
- beforeEach(function() {
+describe('', function () {
+ beforeEach(function () {
global.localStorage.clear()
})
- it('renders unselected', function() {
+ it('renders unselected', function () {
renderWithContext(
', function() {
expect(screen.queryByRole('tree')).to.not.exist
})
- it('renders selected', function() {
+ it('renders selected', function () {
renderWithContext(
', function() {
expect(screen.queryByRole('tree')).to.not.exist
})
- it('expands', function() {
+ it('expands', function () {
renderWithContext(
', function() {
screen.getByRole('tree')
})
- it('saves the expanded state for the next render', function() {
+ it('saves the expanded state for the next render', function () {
const { unmount } = renderWithContext(
', function() {
+describe('', function () {
const setContextMenuCoords = sinon.stub()
- beforeEach(function() {
+ beforeEach(function () {
global.requestAnimationFrame = sinon.stub()
})
- afterEach(function() {
+ afterEach(function () {
setContextMenuCoords.reset()
delete global.requestAnimationFrame
})
- describe('menu', function() {
- it('does not display if file is not selected', function() {
+ describe('menu', function () {
+ it('does not display if file is not selected', function () {
renderWithContext(
,
{}
@@ -29,8 +29,8 @@ describe('', function() {
})
})
- describe('context menu', function() {
- it('does not display without write permissions', function() {
+ describe('context menu', function () {
+ it('does not display without write permissions', function () {
renderWithContext(
,
{ contextProps: { hasWritePermissions: false } }
@@ -39,7 +39,7 @@ describe('', function() {
expect(screen.queryByRole('menu', { visible: false })).to.not.exist
})
- it('open / close', function() {
+ it('open / close', function () {
const { container } = renderWithContext(
)
@@ -56,8 +56,8 @@ describe('', function() {
})
})
- describe('name', function() {
- it('renders name', function() {
+ describe('name', function () {
+ it('renders name', function () {
renderWithContext(
)
@@ -66,7 +66,7 @@ describe('', function() {
expect(screen.queryByRole('textbox')).to.not.exist
})
- it('starts rename on menu item click', function() {
+ it('starts rename on menu item click', function () {
renderWithContext(
,
{
diff --git a/services/web/test/frontend/features/file-tree/components/file-tree-item/file-tree-item-menu.test.js b/services/web/test/frontend/features/file-tree/components/file-tree-item/file-tree-item-menu.test.js
index 7cb99bc9a7..76caaa9be9 100644
--- a/services/web/test/frontend/features/file-tree/components/file-tree-item/file-tree-item-menu.test.js
+++ b/services/web/test/frontend/features/file-tree/components/file-tree-item/file-tree-item-menu.test.js
@@ -5,14 +5,14 @@ import renderWithContext from '../../helpers/render-with-context'
import FileTreeitemMenu from '../../../../../../frontend/js/features/file-tree/components/file-tree-item/file-tree-item-menu'
-describe('', function() {
+describe('', function () {
const setContextMenuCoords = sinon.stub()
- afterEach(function() {
+ afterEach(function () {
setContextMenuCoords.reset()
})
- it('renders dropdown', function() {
+ it('renders dropdown', function () {
renderWithContext(
', function() {
screen.getByRole('menu')
})
- it('open / close', function() {
+ it('open / close', function () {
renderWithContext(
', function() {
+describe('', function () {
const sandbox = sinon.createSandbox()
const setIsDraggable = sinon.stub()
- beforeEach(function() {
+ beforeEach(function () {
sandbox.spy(window, 'requestAnimationFrame')
})
- afterEach(function() {
+ afterEach(function () {
sandbox.restore()
setIsDraggable.reset()
cleanup()
})
- it('renders name as button', function() {
+ it('renders name as button', function () {
renderWithContext(
', function() {
expect(screen.queryByRole('textbox')).to.not.exist
})
- it("doesn't start renaming on unselected component", function() {
+ it("doesn't start renaming on unselected component", function () {
renderWithContext(
', function() {
expect(screen.queryByRole('textbox')).to.not.exist
})
- it('start renaming on double-click', function() {
+ it('start renaming on double-click', function () {
renderWithContext(
', function() {
expect(setIsDraggable).to.be.calledWith(false)
})
- it('cannot start renaming in read-only', function() {
+ it('cannot start renaming in read-only', function () {
renderWithContext(
', function() {
expect(screen.queryByRole('textbox')).to.not.exist
})
- describe('stop renaming', function() {
- beforeEach(function() {
+ describe('stop renaming', function () {
+ beforeEach(function () {
renderWithContext(
', function() {
fireEvent.change(input, { target: { value: 'bar.tex' } })
})
- it('on Escape', function() {
+ it('on Escape', function () {
const input = screen.getByRole('textbox')
fireEvent.keyDown(input, { key: 'Escape' })
diff --git a/services/web/test/frontend/features/file-tree/components/file-tree-root.test.js b/services/web/test/frontend/features/file-tree/components/file-tree-root.test.js
index 6f92946e64..70771bb22a 100644
--- a/services/web/test/frontend/features/file-tree/components/file-tree-root.test.js
+++ b/services/web/test/frontend/features/file-tree/components/file-tree-root.test.js
@@ -6,15 +6,15 @@ import fetchMock from 'fetch-mock'
import FileTreeRoot from '../../../../../frontend/js/features/file-tree/components/file-tree-root'
-describe('', function() {
+describe('', function () {
const onSelect = sinon.stub()
const onInit = sinon.stub()
- beforeEach(function() {
+ beforeEach(function () {
global.requestAnimationFrame = sinon.stub()
})
- afterEach(function() {
+ afterEach(function () {
delete global.requestAnimationFrame
fetchMock.restore()
onSelect.reset()
@@ -22,7 +22,7 @@ describe('', function() {
global.localStorage.clear()
})
- it('renders', function() {
+ it('renders', function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -54,7 +54,7 @@ describe('', function() {
expect(container.querySelector('.disconnected-overlay')).to.not.exist
})
- it('renders with invalid selected doc in local storage', async function() {
+ it('renders with invalid selected doc in local storage', async function () {
global.localStorage.setItem(
'doc.open_id.123abc',
JSON.stringify('not-a-valid-id')
@@ -94,7 +94,7 @@ describe('', function() {
await waitFor(() => screen.getByRole('button', { name: 'Cancel' }))
})
- it('renders disconnected overlay', function() {
+ it('renders disconnected overlay', function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -124,7 +124,7 @@ describe('', function() {
expect(container.querySelector('.disconnected-overlay')).to.exist
})
- it('fire onSelect', function() {
+ it('fire onSelect', function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -177,7 +177,7 @@ describe('', function() {
])
})
- it('listen to editor.openDoc', function() {
+ it('listen to editor.openDoc', function () {
const rootFolder = [
{
_id: 'root-folder-id',
diff --git a/services/web/test/frontend/features/file-tree/components/file-tree-toolbar.test.js b/services/web/test/frontend/features/file-tree/components/file-tree-toolbar.test.js
index 6861750285..67e6a4b7eb 100644
--- a/services/web/test/frontend/features/file-tree/components/file-tree-toolbar.test.js
+++ b/services/web/test/frontend/features/file-tree/components/file-tree-toolbar.test.js
@@ -5,12 +5,12 @@ import renderWithContext from '../helpers/render-with-context'
import FileTreeToolbar from '../../../../../frontend/js/features/file-tree/components/file-tree-toolbar'
-describe('', function() {
- beforeEach(function() {
+describe('', function () {
+ beforeEach(function () {
global.localStorage.clear()
})
- it('without selected files', function() {
+ it('without selected files', function () {
renderWithContext()
screen.getByRole('button', { name: 'New File' })
@@ -20,7 +20,7 @@ describe('', function() {
expect(screen.queryByRole('button', { name: 'Delete' })).to.not.exist
})
- it('read-only', function() {
+ it('read-only', function () {
renderWithContext(, {
contextProps: { hasWritePermissions: false }
})
@@ -28,7 +28,7 @@ describe('', function() {
expect(screen.queryByRole('button')).to.not.exist
})
- it('with one selected file', function() {
+ it('with one selected file', function () {
renderWithContext(, {
contextProps: {
rootDocId: '456def',
diff --git a/services/web/test/frontend/features/file-tree/flows/context-menu.test.js b/services/web/test/frontend/features/file-tree/flows/context-menu.test.js
index 2143644802..42c0037194 100644
--- a/services/web/test/frontend/features/file-tree/flows/context-menu.test.js
+++ b/services/web/test/frontend/features/file-tree/flows/context-menu.test.js
@@ -5,11 +5,11 @@ import { screen, render, fireEvent } from '@testing-library/react'
import FileTreeRoot from '../../../../../frontend/js/features/file-tree/components/file-tree-root'
-describe('FileTree Context Menu Flow', function() {
+describe('FileTree Context Menu Flow', function () {
const onSelect = sinon.stub()
const onInit = sinon.stub()
- it('opens on contextMenu event', async function() {
+ it('opens on contextMenu event', async function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -43,7 +43,7 @@ describe('FileTree Context Menu Flow', function() {
expect(screen.getAllByRole('menu').length).to.equal(2) // toolbar + menu
})
- it("doesn't open in read only mode", async function() {
+ it("doesn't open in read only mode", async function () {
const rootFolder = [
{
_id: 'root-folder-id',
diff --git a/services/web/test/frontend/features/file-tree/flows/create-folder.test.js b/services/web/test/frontend/features/file-tree/flows/create-folder.test.js
index 2ff6c466c7..34057b0d45 100644
--- a/services/web/test/frontend/features/file-tree/flows/create-folder.test.js
+++ b/services/web/test/frontend/features/file-tree/flows/create-folder.test.js
@@ -7,18 +7,18 @@ import MockedSocket from 'socket.io-mock'
import FileTreeRoot from '../../../../../frontend/js/features/file-tree/components/file-tree-root'
-describe('FileTree Create Folder Flow', function() {
+describe('FileTree Create Folder Flow', function () {
const onSelect = sinon.stub()
const onInit = sinon.stub()
- beforeEach(function() {
+ beforeEach(function () {
global.requestAnimationFrame = sinon.stub()
window._ide = {
socket: new MockedSocket()
}
})
- afterEach(function() {
+ afterEach(function () {
delete global.requestAnimationFrame
fetchMock.restore()
onSelect.reset()
@@ -26,7 +26,7 @@ describe('FileTree Create Folder Flow', function() {
delete window._ide
})
- it('add to root when no files are selected', async function() {
+ it('add to root when no files are selected', async function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -78,7 +78,7 @@ describe('FileTree Create Folder Flow', function() {
await screen.findByRole('treeitem', { name: newFolderName })
})
- it('add to folder from folder', async function() {
+ it('add to folder from folder', async function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -148,7 +148,7 @@ describe('FileTree Create Folder Flow', function() {
expect(screen.queryByRole('treeitem', { name: newFolderName })).to.not.exist
})
- it('add to folder from child', async function() {
+ it('add to folder from child', async function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -215,7 +215,7 @@ describe('FileTree Create Folder Flow', function() {
expect(screen.queryByRole('treeitem', { name: newFolderName })).to.not.exist
})
- it('prevents adding duplicate or invalid names', async function() {
+ it('prevents adding duplicate or invalid names', async function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -278,9 +278,7 @@ describe('FileTree Create Folder Flow', function() {
}
function fakeId() {
- return Math.random()
- .toString(16)
- .replace(/0\./, 'random-test-id-')
+ return Math.random().toString(16).replace(/0\./, 'random-test-id-')
}
async function getModalCreateButton() {
diff --git a/services/web/test/frontend/features/file-tree/flows/delete-entity.test.js b/services/web/test/frontend/features/file-tree/flows/delete-entity.test.js
index f438f3f368..3039fa85b6 100644
--- a/services/web/test/frontend/features/file-tree/flows/delete-entity.test.js
+++ b/services/web/test/frontend/features/file-tree/flows/delete-entity.test.js
@@ -7,25 +7,25 @@ import MockedSocket from 'socket.io-mock'
import FileTreeRoot from '../../../../../frontend/js/features/file-tree/components/file-tree-root'
-describe('FileTree Delete Entity Flow', function() {
+describe('FileTree Delete Entity Flow', function () {
const onSelect = sinon.stub()
const onInit = sinon.stub()
- beforeEach(function() {
+ beforeEach(function () {
window._ide = {
socket: new MockedSocket()
}
})
- afterEach(function() {
+ afterEach(function () {
fetchMock.restore()
onSelect.reset()
onInit.reset()
delete window._ide
})
- describe('single entity', function() {
- beforeEach(function() {
+ describe('single entity', function () {
+ beforeEach(function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -57,7 +57,7 @@ describe('FileTree Delete Entity Flow', function() {
fireEvent.click(deleteButton)
})
- it('removes item', async function() {
+ it('removes item', async function () {
const fetchMatcher = /\/project\/\w+\/doc\/\w+/
fetchMock.delete(fetchMatcher, 204)
@@ -88,7 +88,7 @@ describe('FileTree Delete Entity Flow', function() {
expect(lastFetchPath).to.equal('/project/123abc/doc/456def')
})
- it('continues delete on 404s', async function() {
+ it('continues delete on 404s', async function () {
fetchMock.delete(/\/project\/\w+\/doc\/\w+/, 404)
const modalDeleteButton = await getModalDeleteButton()
@@ -119,7 +119,7 @@ describe('FileTree Delete Entity Flow', function() {
})
})
- it('aborts delete on error', async function() {
+ it('aborts delete on error', async function () {
const fetchMatcher = /\/project\/\w+\/doc\/\w+/
fetchMock.delete(fetchMatcher, 500)
@@ -131,8 +131,8 @@ describe('FileTree Delete Entity Flow', function() {
})
})
- describe('folders', function() {
- beforeEach(function() {
+ describe('folders', function () {
+ beforeEach(function () {
const rootFolder = [
{
docs: [{ _id: '456def', name: 'main.tex' }],
@@ -174,15 +174,15 @@ describe('FileTree Delete Entity Flow', function() {
window._ide.socket.socketClient.emit('removeEntity', '123abc')
})
- it('removes the folder', function() {
+ it('removes the folder', function () {
expect(screen.queryByRole('treeitem', { name: 'folder' })).to.not.exist
})
- it('leaves the main file selected', function() {
+ it('leaves the main file selected', function () {
screen.getByRole('treeitem', { name: 'main.tex', selected: true })
})
- it('unselect the child entity', async function() {
+ it('unselect the child entity', async function () {
// as a proxy to check that the child entity has been unselect we start
// a delete and ensure the modal is displayed (the cancel button can be
// selected) This is needed to make sure the test fail.
@@ -192,8 +192,8 @@ describe('FileTree Delete Entity Flow', function() {
})
})
- describe('multiple entities', function() {
- beforeEach(function() {
+ describe('multiple entities', function () {
+ beforeEach(function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -229,7 +229,7 @@ describe('FileTree Delete Entity Flow', function() {
fireEvent.click(deleteButton)
})
- it('removes all items', async function() {
+ it('removes all items', async function () {
const fetchMatcher = /\/project\/\w+\/(doc|file)\/\w+/
fetchMock.delete(fetchMatcher, 204)
diff --git a/services/web/test/frontend/features/file-tree/flows/rename-entity.test.js b/services/web/test/frontend/features/file-tree/flows/rename-entity.test.js
index 0349f258ca..b12a0e5498 100644
--- a/services/web/test/frontend/features/file-tree/flows/rename-entity.test.js
+++ b/services/web/test/frontend/features/file-tree/flows/rename-entity.test.js
@@ -7,18 +7,18 @@ import MockedSocket from 'socket.io-mock'
import FileTreeRoot from '../../../../../frontend/js/features/file-tree/components/file-tree-root'
-describe('FileTree Rename Entity Flow', function() {
+describe('FileTree Rename Entity Flow', function () {
const onSelect = sinon.stub()
const onInit = sinon.stub()
- beforeEach(function() {
+ beforeEach(function () {
window._ide = {
socket: new MockedSocket()
}
global.requestAnimationFrame = sinon.stub()
})
- afterEach(function() {
+ afterEach(function () {
delete global.requestAnimationFrame
fetchMock.restore()
onSelect.reset()
@@ -26,7 +26,7 @@ describe('FileTree Rename Entity Flow', function() {
delete window._ide
})
- beforeEach(function() {
+ beforeEach(function () {
const rootFolder = [
{
_id: 'root-folder-id',
@@ -63,7 +63,7 @@ describe('FileTree Rename Entity Flow', function() {
)
})
- it('renames doc', function() {
+ it('renames doc', function () {
const fetchMatcher = /\/project\/\w+\/doc\/\w+\/rename/
fetchMock.post(fetchMatcher, 204)
@@ -77,7 +77,7 @@ describe('FileTree Rename Entity Flow', function() {
expect(lastFetchBody.name).to.equal('b.tex')
})
- it('renames folder', function() {
+ it('renames folder', function () {
const fetchMatcher = /\/project\/\w+\/folder\/\w+\/rename/
fetchMock.post(fetchMatcher, 204)
@@ -91,7 +91,7 @@ describe('FileTree Rename Entity Flow', function() {
expect(lastFetchBody.name).to.equal('new folder name')
})
- it('renames file in subfolder', function() {
+ it('renames file in subfolder', function () {
const fetchMatcher = /\/project\/\w+\/file\/\w+\/rename/
fetchMock.post(fetchMatcher, 204)
@@ -109,7 +109,7 @@ describe('FileTree Rename Entity Flow', function() {
expect(lastFetchBody.name).to.equal('d.tex')
})
- it('reverts rename on error', async function() {
+ it('reverts rename on error', async function () {
const fetchMatcher = /\/project\/\w+\/doc\/\w+\/rename/
fetchMock.post(fetchMatcher, 500)
@@ -120,7 +120,7 @@ describe('FileTree Rename Entity Flow', function() {
screen.getByRole('treeitem', { name: 'b.tex' })
})
- it('shows error modal on invalid filename', async function() {
+ it('shows error modal on invalid filename', async function () {
const input = initItemRename('a.tex')
fireEvent.change(input, { target: { value: '///' } })
fireEvent.keyDown(input, { key: 'Enter' })
@@ -131,7 +131,7 @@ describe('FileTree Rename Entity Flow', function() {
})
})
- it('shows error modal on duplicate filename', async function() {
+ it('shows error modal on duplicate filename', async function () {
const input = initItemRename('a.tex')
fireEvent.change(input, { target: { value: 'folder' } })
fireEvent.keyDown(input, { key: 'Enter' })
@@ -142,7 +142,7 @@ describe('FileTree Rename Entity Flow', function() {
})
})
- it('shows error modal on duplicate filename in subfolder', async function() {
+ it('shows error modal on duplicate filename in subfolder', async function () {
const expandButton = screen.queryByRole('button', { name: 'Expand' })
if (expandButton) fireEvent.click(expandButton)
@@ -156,7 +156,7 @@ describe('FileTree Rename Entity Flow', function() {
})
})
- it('shows error modal on blocked filename', async function() {
+ it('shows error modal on blocked filename', async function () {
const input = initItemRename('a.tex')
fireEvent.change(input, { target: { value: 'prototype' } })
fireEvent.keyDown(input, { key: 'Enter' })
@@ -167,8 +167,8 @@ describe('FileTree Rename Entity Flow', function() {
})
})
- describe('via socket event', function() {
- it('renames doc', function() {
+ describe('via socket event', function () {
+ it('renames doc', function () {
screen.getByRole('treeitem', { name: 'a.tex' })
window._ide.socket.socketClient.emit(
diff --git a/services/web/test/frontend/features/file-tree/util/icon-type-from-name.test.js b/services/web/test/frontend/features/file-tree/util/icon-type-from-name.test.js
index 2adab9bfad..4da1c29401 100644
--- a/services/web/test/frontend/features/file-tree/util/icon-type-from-name.test.js
+++ b/services/web/test/frontend/features/file-tree/util/icon-type-from-name.test.js
@@ -2,8 +2,8 @@ import { expect } from 'chai'
import iconTypeFromName from '../../../../../frontend/js/features/file-tree/util/icon-type-from-name'
-describe('iconTypeFromName', function() {
- it('returns correct icon type', function() {
+describe('iconTypeFromName', function () {
+ it('returns correct icon type', function () {
expect(iconTypeFromName('main.tex')).to.equal('file')
expect(iconTypeFromName('main.png')).to.equal('image')
expect(iconTypeFromName('main.csv')).to.equal('table')
@@ -11,11 +11,11 @@ describe('iconTypeFromName', function() {
expect(iconTypeFromName('main.bib')).to.equal('book')
})
- it('handles missing extensions', function() {
+ it('handles missing extensions', function () {
expect(iconTypeFromName('main')).to.equal('file')
})
- it('lowercases extension', function() {
+ it('lowercases extension', function () {
expect(iconTypeFromName('ZOTERO.BIB')).to.equal('book')
})
})
diff --git a/services/web/test/frontend/features/hotkeys-modal/components/hotkeys-modal.test.js b/services/web/test/frontend/features/hotkeys-modal/components/hotkeys-modal.test.js
index 0c56c528c3..6b425a4f1f 100644
--- a/services/web/test/frontend/features/hotkeys-modal/components/hotkeys-modal.test.js
+++ b/services/web/test/frontend/features/hotkeys-modal/components/hotkeys-modal.test.js
@@ -10,8 +10,8 @@ const modalProps = {
trackChangesVisible: false
}
-describe('', function() {
- it('renders the translated modal title', async function() {
+describe('', function () {
+ it('renders the translated modal title', async function () {
const { baseElement } = render()
expect(baseElement.querySelector('.modal-title').textContent).to.equal(
@@ -19,14 +19,14 @@ describe('', function() {
)
})
- it('renders translated heading with embedded code', function() {
+ it('renders translated heading with embedded code', function () {
const { baseElement } = render()
const results = baseElement.querySelectorAll('h3 code')
expect(results).to.have.length(1)
})
- it('renders the hotkey descriptions', function() {
+ it('renders the hotkey descriptions', function () {
const { baseElement } = render()
const hotkeys = baseElement.querySelectorAll(
@@ -35,7 +35,7 @@ describe('', function() {
expect(hotkeys).to.have.length(19)
})
- it('adds extra hotkey descriptions when Track Changes is enabled', function() {
+ it('adds extra hotkey descriptions when Track Changes is enabled', function () {
const { baseElement } = render(
)
@@ -46,14 +46,14 @@ describe('', function() {
expect(hotkeys).to.have.length(22)
})
- it('uses Ctrl for non-macOS', function() {
+ it('uses Ctrl for non-macOS', function () {
render()
expect(screen.getAllByText(/Ctrl/)).to.have.length(16)
expect(screen.queryByText(/Cmd/)).to.not.exist
})
- it('uses Cmd for macOS', function() {
+ it('uses Cmd for macOS', function () {
render()
expect(screen.getAllByText(/Cmd/)).to.have.length(16)
diff --git a/services/web/test/frontend/features/outline/components/outline-item.test.js b/services/web/test/frontend/features/outline/components/outline-item.test.js
index 0895392c99..bc7fe5be13 100644
--- a/services/web/test/frontend/features/outline/components/outline-item.test.js
+++ b/services/web/test/frontend/features/outline/components/outline-item.test.js
@@ -5,14 +5,14 @@ import { screen, render, fireEvent } from '@testing-library/react'
import OutlineItem from '../../../../../frontend/js/features/outline/components/outline-item'
-describe('', function() {
+describe('', function () {
const jumpToLine = sinon.stub()
- afterEach(function() {
+ afterEach(function () {
jumpToLine.reset()
})
- it('renders basic item', function() {
+ it('renders basic item', function () {
const outlineItem = {
title: 'Test Title',
line: 1
@@ -24,7 +24,7 @@ describe('', function() {
expect(screen.queryByRole('button', { name: 'Collapse' })).to.not.exist
})
- it('collapses and expands', function() {
+ it('collapses and expands', function () {
const outlineItem = {
title: 'Parent',
line: 1,
@@ -44,7 +44,7 @@ describe('', function() {
expect(screen.queryByRole('button', { name: 'Child' })).to.not.exist
})
- it('highlights', function() {
+ it('highlights', function () {
const outlineItem = {
title: 'Parent',
line: 1
@@ -61,7 +61,7 @@ describe('', function() {
screen.getByRole('treeitem', { current: true })
})
- it('highlights when has collapsed highlighted child', function() {
+ it('highlights when has collapsed highlighted child', function () {
const outlineItem = {
title: 'Parent',
line: 1,
@@ -83,7 +83,7 @@ describe('', function() {
screen.getByRole('treeitem', { name: 'Parent', current: true })
})
- it('click and double-click jump to location', function() {
+ it('click and double-click jump to location', function () {
const outlineItem = {
title: 'Parent',
line: 1
diff --git a/services/web/test/frontend/features/outline/components/outline-list.test.js b/services/web/test/frontend/features/outline/components/outline-list.test.js
index 8a4b3ace46..d05551a18a 100644
--- a/services/web/test/frontend/features/outline/components/outline-list.test.js
+++ b/services/web/test/frontend/features/outline/components/outline-list.test.js
@@ -3,10 +3,10 @@ import { screen, render } from '@testing-library/react'
import OutlineList from '../../../../../frontend/js/features/outline/components/outline-list'
-describe('', function() {
+describe('', function () {
const jumpToLine = () => {}
- it('renders items', function() {
+ it('renders items', function () {
const outline = [
{
title: 'Section 1',
@@ -25,7 +25,7 @@ describe('', function() {
screen.getByRole('treeitem', { name: 'Section 2' })
})
- it('renders as root', function() {
+ it('renders as root', function () {
const outline = [
{
title: 'Section',
@@ -38,7 +38,7 @@ describe('', function() {
screen.getByRole('tree')
})
- it('renders as non-root', function() {
+ it('renders as non-root', function () {
const outline = [
{
title: 'Section',
diff --git a/services/web/test/frontend/features/outline/components/outline-pane.test.js b/services/web/test/frontend/features/outline/components/outline-pane.test.js
index 74d287686a..75c0f3204c 100644
--- a/services/web/test/frontend/features/outline/components/outline-pane.test.js
+++ b/services/web/test/frontend/features/outline/components/outline-pane.test.js
@@ -6,7 +6,7 @@ import { screen, fireEvent } from '@testing-library/react'
import OutlinePane from '../../../../../frontend/js/features/outline/components/outline-pane'
import { renderWithEditorContext } from '../../../helpers/render-with-context'
-describe('', function() {
+describe('', function () {
const jumpToLine = () => {}
const onToggle = sinon.stub()
const eventTracking = { sendMB: sinon.stub() }
@@ -16,7 +16,7 @@ describe('', function() {
}
let originalLocalStorage
- before(function() {
+ before(function () {
originalLocalStorage = global.localStorage
Object.defineProperty(global, 'localStorage', {
@@ -27,20 +27,20 @@ describe('', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
onToggle.reset()
eventTracking.sendMB.reset()
global.localStorage.getItem.resetHistory()
global.localStorage.setItem.resetHistory()
})
- after(function() {
+ after(function () {
Object.defineProperty(global, 'localStorage', {
value: originalLocalStorage
})
})
- it('renders expanded outline', function() {
+ it('renders expanded outline', function () {
const outline = [
{
title: 'Section',
@@ -61,7 +61,7 @@ describe('', function() {
screen.getByRole('tree')
})
- it('renders disabled outline', function() {
+ it('renders disabled outline', function () {
const outline = []
render(
', function() {
expect(screen.queryByRole('tree')).to.be.null
})
- it('expand outline and use local storage', function() {
+ it('expand outline and use local storage', function () {
global.localStorage.getItem.returns(false)
const outline = [
{
diff --git a/services/web/test/frontend/features/outline/components/outline-root.test.js b/services/web/test/frontend/features/outline/components/outline-root.test.js
index b7b1434aa1..faed37c8cd 100644
--- a/services/web/test/frontend/features/outline/components/outline-root.test.js
+++ b/services/web/test/frontend/features/outline/components/outline-root.test.js
@@ -4,10 +4,10 @@ import { screen, render } from '@testing-library/react'
import OutlineRoot from '../../../../../frontend/js/features/outline/components/outline-root'
-describe('', function() {
+describe('', function () {
const jumpToLine = () => {}
- it('renders outline', function() {
+ it('renders outline', function () {
const outline = [
{
title: 'Section',
@@ -21,7 +21,7 @@ describe('', function() {
expect(screen.queryByRole('link')).to.be.null
})
- it('renders placeholder', function() {
+ it('renders placeholder', function () {
const outline = []
render()
diff --git a/services/web/test/frontend/features/outline/outline-parser.test.js b/services/web/test/frontend/features/outline/outline-parser.test.js
index 7af793d31a..cff041a0a5 100644
--- a/services/web/test/frontend/features/outline/outline-parser.test.js
+++ b/services/web/test/frontend/features/outline/outline-parser.test.js
@@ -5,9 +5,9 @@ import {
nestOutline
} from '../../../../frontend/js/features/outline/outline-parser'
-describe('OutlineParser', function() {
- describe('matchOutline', function() {
- it('matches all levels', function() {
+describe('OutlineParser', function () {
+ describe('matchOutline', function () {
+ it('matches all levels', function () {
const content = `
\\book{Book}
\\part{Part}
@@ -41,7 +41,7 @@ describe('OutlineParser', function() {
])
})
- it('matches display titles', function() {
+ it('matches display titles', function () {
const content = `
\\section{\\label{foo} Label before}
\\section{Label after \\label{foo}}
@@ -59,7 +59,7 @@ describe('OutlineParser', function() {
])
})
- it('removes spurious commands after title definition', function() {
+ it('removes spurious commands after title definition', function () {
const content = `
\\section{Plain title} more text \\href{link}{link}
\\section{\\label{foo} Label before} more text \\href{link}{link}
@@ -71,24 +71,24 @@ describe('OutlineParser', function() {
])
})
- it('matches empty sections', function() {
+ it('matches empty sections', function () {
const outline = matchOutline('\\section{}')
expect(outline).to.deep.equal([{ line: 1, title: '', level: 40 }])
})
- it('matches indented sections', function() {
+ it('matches indented sections', function () {
const outline = matchOutline('\t\\section{Indented}')
expect(outline).to.deep.equal([{ line: 1, title: 'Indented', level: 40 }])
})
- it('matches unnumbered sections', function() {
+ it('matches unnumbered sections', function () {
const outline = matchOutline('\\section*{Unnumbered}')
expect(outline).to.deep.equal([
{ line: 1, title: 'Unnumbered', level: 40 }
])
})
- it('matches short titles', function() {
+ it('matches short titles', function () {
const outline = matchOutline(
'\\chapter[Short Title For TOC]{Very Long Title for Text}'
)
@@ -97,7 +97,7 @@ describe('OutlineParser', function() {
])
})
- it('handles spacing', function() {
+ it('handles spacing', function () {
const content = `
\\section {Weird Spacing}
\\section * {Weird Spacing Unnumbered}
@@ -111,7 +111,7 @@ describe('OutlineParser', function() {
])
})
- it("doesn't match commented lines", function() {
+ it("doesn't match commented lines", function () {
const content = `
% \\section{I should not appear in the outline}
`
@@ -119,7 +119,7 @@ describe('OutlineParser', function() {
expect(outline).to.deep.equal([])
})
- it("doesn't match inline sections", function() {
+ it("doesn't match inline sections", function () {
const content = `
I like to write \\section{inline} on one line.
`
@@ -128,8 +128,8 @@ describe('OutlineParser', function() {
})
})
- describe('nestOutline', function() {
- it('matches all levels', function() {
+ describe('nestOutline', function () {
+ it('matches all levels', function () {
const flatOutline = [
{ line: 10, title: 'Book', level: 10 },
{ line: 20, title: 'Part A', level: 20 },
diff --git a/services/web/test/frontend/features/preview/components/preview-download-button.test.js b/services/web/test/frontend/features/preview/components/preview-download-button.test.js
index abd24c78a1..271394e2e9 100644
--- a/services/web/test/frontend/features/preview/components/preview-download-button.test.js
+++ b/services/web/test/frontend/features/preview/components/preview-download-button.test.js
@@ -4,7 +4,7 @@ import { screen, render } from '@testing-library/react'
import PreviewDownloadButton from '../../../../../frontend/js/features/preview/components/preview-download-button'
-describe('', function() {
+describe('', function () {
const projectId = 'projectId123'
const pdfDownloadUrl = `/download/project/${projectId}/build/17523aaafdf-1ad9063af140f004/output/output.pdf?compileGroup=priority&popupDownload=true`
@@ -26,17 +26,14 @@ describe('', function() {
)
}
- it('should disable the button and dropdown toggle when compiling', function() {
+ it('should disable the button and dropdown toggle when compiling', function () {
const isCompiling = true
const outputFiles = undefined
renderPreviewDownloadButton(isCompiling, outputFiles)
expect(
- screen
- .getByText('Download PDF')
- .closest('a')
- .getAttribute('disabled')
+ screen.getByText('Download PDF').closest('a').getAttribute('disabled')
).to.exist
const buttons = screen.getAllByRole('button')
expect(buttons.length).to.equal(1) // the dropdown toggle
@@ -45,35 +42,26 @@ describe('', function() {
'Toggle output files list'
)
})
- it('should disable the PDF button when there is no PDF', function() {
+ it('should disable the PDF button when there is no PDF', function () {
const isCompiling = false
const outputFiles = []
renderPreviewDownloadButton(isCompiling, outputFiles)
expect(
- screen
- .getByText('Download PDF')
- .closest('a')
- .getAttribute('disabled')
+ screen.getByText('Download PDF').closest('a').getAttribute('disabled')
).to.exist
})
- it('should enable the PDF button when there is a main PDF', function() {
+ it('should enable the PDF button when there is a main PDF', function () {
const isCompiling = false
const outputFiles = []
renderPreviewDownloadButton(isCompiling, outputFiles, pdfDownloadUrl)
expect(
- screen
- .getByText('Download PDF')
- .closest('a')
- .getAttribute('href')
+ screen.getByText('Download PDF').closest('a').getAttribute('href')
).to.equal(pdfDownloadUrl)
expect(
- screen
- .getByText('Download PDF')
- .closest('a')
- .getAttribute('disabled')
+ screen.getByText('Download PDF').closest('a').getAttribute('disabled')
).to.not.exist
})
- it('should enable the dropdown when not compiling', function() {
+ it('should enable the dropdown when not compiling', function () {
const isCompiling = false
const outputFiles = []
renderPreviewDownloadButton(isCompiling, outputFiles, pdfDownloadUrl)
@@ -82,13 +70,13 @@ describe('', function() {
expect(buttons[0].getAttribute('disabled')).to.not.exist
})
- it('should show the button text when prop showText=true', function() {
+ it('should show the button text when prop showText=true', function () {
const isCompiling = false
const showText = true
renderPreviewDownloadButton(isCompiling, [], pdfDownloadUrl, showText)
expect(screen.getByText('Download PDF').getAttribute('style')).to.be.null
})
- it('should not show the button text when prop showText=false', function() {
+ it('should not show the button text when prop showText=false', function () {
const isCompiling = false
const showText = false
renderPreviewDownloadButton(isCompiling, [], pdfDownloadUrl, showText)
diff --git a/services/web/test/frontend/features/preview/components/preview-download-file-list.test.js b/services/web/test/frontend/features/preview/components/preview-download-file-list.test.js
index 3805228e51..eaddd6632c 100644
--- a/services/web/test/frontend/features/preview/components/preview-download-file-list.test.js
+++ b/services/web/test/frontend/features/preview/components/preview-download-file-list.test.js
@@ -6,7 +6,7 @@ import PreviewDownloadFileList, {
topFileTypes
} from '../../../../../frontend/js/features/preview/components/preview-download-file-list'
-describe('', function() {
+describe('', function () {
const projectId = 'projectId123'
function makeFile(fileName, main) {
@@ -18,7 +18,7 @@ describe('', function() {
}
}
- it('should list all output files and group them', function() {
+ it('should list all output files and group them', function () {
const outputFiles = [
makeFile('output.ind'),
makeFile('output.log'),
@@ -55,15 +55,12 @@ describe('', function() {
.map(file => file.type)
const topMenuItems = menuItems.slice(0, outputTopFileTypes.length)
topMenuItems.forEach(item => {
- const fileType = item.textContent
- .split('.')
- .pop()
- .replace(' file', '')
+ const fileType = item.textContent.split('.').pop().replace(' file', '')
expect(topFileTypes.includes(fileType)).to.be.true
})
})
- it('should list all files when there are duplicate types', function() {
+ it('should list all files when there are duplicate types', function () {
const pdfFile = makeFile('output.pdf', true)
const bblFile = makeFile('output.bbl')
const outputFiles = [Object.assign({}, { ...bblFile }), bblFile, pdfFile]
@@ -76,7 +73,7 @@ describe('', function() {
expect(bblMenuItems.length).to.equal(2)
})
- it('should list the non-main PDF in the dropdown', function() {
+ it('should list the non-main PDF in the dropdown', function () {
const pdfFile = makeFile('output.pdf', true)
const pdfAltFile = makeFile('alt.pdf')
const outputFiles = [pdfFile, pdfAltFile]
@@ -84,8 +81,8 @@ describe('', function() {
screen.getAllByRole('menuitem', { name: 'alt.pdf' })
})
- describe('list divider and header', function() {
- it('should display when there are top files and other files', function() {
+ describe('list divider and header', function () {
+ it('should display when there are top files and other files', function () {
const outputFiles = [
makeFile('output.bbl'),
makeFile('output.ind'),
@@ -99,7 +96,7 @@ describe('', function() {
screen.getByRole('separator')
})
- it('should not display when there are top files and no other files', function() {
+ it('should not display when there are top files and no other files', function () {
const outputFiles = [
makeFile('output.bbl'),
makeFile('output.ind'),
@@ -112,7 +109,7 @@ describe('', function() {
expect(screen.queryByRole('separator')).to.not.exist
})
- it('should not display when there are other files and no top files', function() {
+ it('should not display when there are other files and no top files', function () {
const outputFiles = [makeFile('output.log')]
render()
diff --git a/services/web/test/frontend/features/preview/components/preview-logs-pane-entry.test.js b/services/web/test/frontend/features/preview/components/preview-logs-pane-entry.test.js
index 3e30d6431e..03fe1afcf2 100644
--- a/services/web/test/frontend/features/preview/components/preview-logs-pane-entry.test.js
+++ b/services/web/test/frontend/features/preview/components/preview-logs-pane-entry.test.js
@@ -5,10 +5,10 @@ import { screen, render, fireEvent } from '@testing-library/react'
import PreviewLogsPaneEntry from '../../../../../frontend/js/features/preview/components/preview-logs-pane-entry.js'
-describe('', function() {
+describe('', function () {
const level = 'error'
- it('renders a configurable aria-label', function() {
+ it('renders a configurable aria-label', function () {
const sampleAriaLabel = 'lorem ipsum dolor sit amet'
render(
@@ -16,17 +16,17 @@ describe('', function() {
screen.getByLabelText(sampleAriaLabel)
})
- describe('logs pane source location link', function() {
+ describe('logs pane source location link', function () {
const file = 'foo.tex'
const line = 42
const column = 21
const onSourceLocationClick = sinon.stub()
- afterEach(function() {
+ afterEach(function () {
onSourceLocationClick.reset()
})
- it('renders both file and line', function() {
+ it('renders both file and line', function () {
render(
)
@@ -35,14 +35,14 @@ describe('', function() {
})
})
- it('renders only file when line information is not available', function() {
+ it('renders only file when line information is not available', function () {
render()
screen.getByRole('button', {
name: `Navigate to log position in source code: ${file}`
})
})
- it('does not render when file information is not available', function() {
+ it('does not render when file information is not available', function () {
render()
expect(
screen.queryByRole('button', {
@@ -51,7 +51,7 @@ describe('', function() {
).to.not.exist
})
- it('calls the callback with file, line and column on click', function() {
+ it('calls the callback with file, line and column on click', function () {
render(
', function() {
})
})
- describe('logs pane entry raw contents', function() {
+ describe('logs pane entry raw contents', function () {
const rawContent = 'foo bar latex error stuff baz'
// JSDom doesn't compute layout/sizing, so we need to simulate sizing for the elements
@@ -88,7 +88,7 @@ describe('', function() {
'offsetWidth'
)
- beforeEach(function() {
+ beforeEach(function () {
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {
configurable: true,
value: 500
@@ -99,7 +99,7 @@ describe('', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
Object.defineProperty(
HTMLElement.prototype,
'scrollHeight',
@@ -112,7 +112,7 @@ describe('', function() {
)
})
- it('renders collapsed contents by default', function() {
+ it('renders collapsed contents by default', function () {
render()
screen.getByText(rawContent)
screen.getByRole('button', {
@@ -120,7 +120,7 @@ describe('', function() {
})
})
- it('supports expanding contents', function() {
+ it('supports expanding contents', function () {
render()
screen.getByText(rawContent)
const expandCollapseBtn = screen.getByRole('button', {
@@ -132,19 +132,19 @@ describe('', function() {
})
})
- it('should not render at all when there are no log contents', function() {
+ it('should not render at all when there are no log contents', function () {
const { container } = render()
expect(container.querySelector('.log-entry-content')).to.not.exist
})
})
- describe('formatted content', function() {
+ describe('formatted content', function () {
const rawContent = 'foo bar latex error stuff baz'
const formattedContentText = 'foo bar baz'
const formattedContent = <>{formattedContentText}>
const infoURL = 'www.overleaf.com/learn/latex'
- it('renders the hint', function() {
+ it('renders the hint', function () {
render(
', function() {
screen.getByText(formattedContentText)
})
- it('renders the link to learn more', function() {
+ it('renders the link to learn more', function () {
render(
', function() {
screen.getByRole('link', { name: 'Learn more' })
})
- it('does not render the link when it is not available', function() {
+ it('does not render the link when it is not available', function () {
render(
', function() {
+describe('', function () {
const sampleError1 = {
content: 'error 1 content',
file: 'main.tex',
@@ -59,8 +59,8 @@ entering extended mode
const noOp = () => {}
const onLogEntryLocationClick = sinon.stub()
- describe('with logs', function() {
- beforeEach(function() {
+ describe('with logs', function () {
+ beforeEach(function () {
renderWithEditorContext(
)
})
- it('renders all log entries with appropriate labels', function() {
+ it('renders all log entries with appropriate labels', function () {
const errorEntries = screen.getAllByLabelText(
`Log entry with level: error`
)
@@ -85,11 +85,11 @@ entering extended mode
expect(typesettingEntries).to.have.lengthOf(typesetting.length)
})
- it('renders the raw log', function() {
+ it('renders the raw log', function () {
screen.getByLabelText('Raw logs from the LaTeX compiler')
})
- it('renders a link to location button for every error and warning log entry', function() {
+ it('renders a link to location button for every error and warning log entry', function () {
logEntries.all.forEach((entry, index) => {
const linkToSourceButton = screen.getByRole('button', {
name: `Navigate to log position in source code: ${entry.file}, ${entry.line}`
@@ -106,7 +106,7 @@ entering extended mode
).to.be.true
})
})
- it(' does not render a link to location button for the raw log entry', function() {
+ it(' does not render a link to location button for the raw log entry', function () {
const rawLogEntry = screen.getByLabelText(
'Raw logs from the LaTeX compiler'
)
@@ -114,7 +114,7 @@ entering extended mode
})
})
- describe('with validation issues', function() {
+ describe('with validation issues', function () {
const sampleValidationIssues = {
sizeCheck: {
resources: [
@@ -125,7 +125,7 @@ entering extended mode
mainFile: true
}
- it('renders a validation entry for known issues', function() {
+ it('renders a validation entry for known issues', function () {
renderWithEditorContext(
)
})
- it('renders a code check failed entry', function() {
+ it('renders a code check failed entry', function () {
screen.getByText(
'Your code has errors that need to be fixed before the auto-compile can run'
)
diff --git a/services/web/test/frontend/features/preview/components/preview-logs-toggle-button.test.js b/services/web/test/frontend/features/preview/components/preview-logs-toggle-button.test.js
index 78cfffc808..bb67cfbf6b 100644
--- a/services/web/test/frontend/features/preview/components/preview-logs-toggle-button.test.js
+++ b/services/web/test/frontend/features/preview/components/preview-logs-toggle-button.test.js
@@ -4,7 +4,7 @@ import { screen, render } from '@testing-library/react'
import PreviewLogsToggleButton from '../../../../../frontend/js/features/preview/components/preview-logs-toggle-button'
-describe('', function() {
+describe('', function () {
function renderPreviewLogsToggleButton(
logsState,
onToggleLogs,
@@ -25,27 +25,27 @@ describe('', function() {
)
}
- describe('basic toggle functionality', function() {
+ describe('basic toggle functionality', function () {
const logsState = {
nErrors: 0,
nWarnings: 0
}
const onToggleLogs = () => {}
- it('should render a view logs button when previewing the PDF', function() {
+ it('should render a view logs button when previewing the PDF', function () {
const showLogs = false
renderPreviewLogsToggleButton(logsState, onToggleLogs, showLogs)
screen.getByText('View logs')
})
- it('should render a view PDF button when viewing logs', function() {
+ it('should render a view PDF button when viewing logs', function () {
const showLogs = true
renderPreviewLogsToggleButton(logsState, onToggleLogs, showLogs)
screen.getByText('View PDF')
})
})
- describe('compile status indicator', function() {
+ describe('compile status indicator', function () {
const showLogs = false
const onToggleLogs = () => {}
- it('should render a view logs button by default', function() {
+ it('should render a view logs button by default', function () {
const logsState = {
nErrors: 0,
nWarnings: 0
@@ -54,7 +54,7 @@ describe('', function() {
screen.getByText('View logs')
})
- it('should render the code check failed notice', function() {
+ it('should render the code check failed notice', function () {
const logsState = {
nErrors: 1,
nWarnings: 0
@@ -69,7 +69,7 @@ describe('', function() {
screen.getByText('Code check failed')
})
- it('should render an error status message when there are errors', function() {
+ it('should render an error status message when there are errors', function () {
const logsState = {
nErrors: 1,
nWarnings: 0
@@ -78,7 +78,7 @@ describe('', function() {
screen.getByText(`This project has errors (${logsState.nErrors})`)
})
- it('should render an error status message when there are both errors and warnings', function() {
+ it('should render an error status message when there are both errors and warnings', function () {
const logsState = {
nErrors: 1,
nWarnings: 1
@@ -87,7 +87,7 @@ describe('', function() {
screen.getByText(`This project has errors (${logsState.nErrors})`)
})
- it('should render a warning status message when there are warnings but no errors', function() {
+ it('should render a warning status message when there are warnings but no errors', function () {
const logsState = {
nErrors: 0,
nWarnings: 1
@@ -96,7 +96,7 @@ describe('', function() {
screen.getByText(`View warnings (${logsState.nWarnings})`)
})
- it('should render 99+ errors when there are more than 99 errors', function() {
+ it('should render 99+ errors when there are more than 99 errors', function () {
const logsState = {
nErrors: 100,
nWarnings: 0
@@ -104,7 +104,7 @@ describe('', function() {
renderPreviewLogsToggleButton(logsState, onToggleLogs, showLogs)
screen.getByText('This project has errors (99+)')
})
- it('should show the button text when prop showText=true', function() {
+ it('should show the button text when prop showText=true', function () {
const logsState = {
nErrors: 0,
nWarnings: 0
@@ -113,7 +113,7 @@ describe('', function() {
renderPreviewLogsToggleButton(logsState, onToggleLogs, showLogs, showText)
expect(screen.getByText('View logs').getAttribute('style')).to.be.null
})
- it('should not show the button text when prop showText=false', function() {
+ it('should not show the button text when prop showText=false', function () {
const logsState = {
nErrors: 0,
nWarnings: 0
diff --git a/services/web/test/frontend/features/preview/components/preview-pane.test.js b/services/web/test/frontend/features/preview/components/preview-pane.test.js
index 1f5792408a..9d727a1b52 100644
--- a/services/web/test/frontend/features/preview/components/preview-pane.test.js
+++ b/services/web/test/frontend/features/preview/components/preview-pane.test.js
@@ -3,7 +3,7 @@ import { screen, render, fireEvent } from '@testing-library/react'
import PreviewPane from '../../../../../frontend/js/features/preview/components/preview-pane'
const { expect } = require('chai')
-describe('', function() {
+describe('', function () {
const sampleError1 = {
content: 'error 1 content',
file: 'main.tex',
@@ -25,8 +25,8 @@ describe('', function() {
message: "Reference `idontexist' on page 1 undefined on input line 30."
}
- describe('first error pop-up', function() {
- it('renders a first error pop-up with the first error', function() {
+ describe('first error pop-up', function () {
+ it('renders a first error pop-up with the first error', function () {
const propsAfterCompileWithErrors = getProps(false, {
errors: [sampleError1, sampleError2],
warnings: [sampleWarning]
@@ -38,7 +38,7 @@ describe('', function() {
screen.getByText(sampleError1.message)
})
- it('does not render a first error pop-up when there are only warnings', function() {
+ it('does not render a first error pop-up when there are only warnings', function () {
const propsAfterCompileWithWarningsOnly = getProps(false, {
errors: [],
warnings: [sampleWarning]
@@ -51,7 +51,7 @@ describe('', function() {
).to.not.exist
})
- it('does not render a first error pop-up when a compile is ongoing', function() {
+ it('does not render a first error pop-up when a compile is ongoing', function () {
const propsWhileCompiling = getProps(true, {
errors: [sampleError1, sampleError2],
warnings: [sampleWarning]
@@ -64,7 +64,7 @@ describe('', function() {
).to.not.exist
})
- it('does not render a first error pop-up when viewing logs', function() {
+ it('does not render a first error pop-up when viewing logs', function () {
const propsWithErrorsViewingLogs = getProps(
false,
{
@@ -82,7 +82,7 @@ describe('', function() {
).to.not.exist
})
- it('does not render a first error pop-up when going back to the PDF view after viewing logs', function() {
+ it('does not render a first error pop-up when going back to the PDF view after viewing logs', function () {
const nowTimestamp = Date.now()
const propsWithErrorsViewingLogs = getProps(
false,
@@ -113,7 +113,7 @@ describe('', function() {
).to.not.exist
})
- it('renders a first error pop-up with updated errors after recompiling', function() {
+ it('renders a first error pop-up with updated errors after recompiling', function () {
const nowTimestamp = Date.now()
const laterTimestamp = Date.now() + 1000
const propsWithErrorsAfterFirstCompile = getProps(
@@ -144,7 +144,7 @@ describe('', function() {
screen.getByText(sampleError2.message)
})
- it('allows dismissing the first error pop-up', function() {
+ it('allows dismissing the first error pop-up', function () {
const propsWithErrors = getProps(false, {
errors: [sampleError1, sampleError2],
warnings: [sampleWarning]
@@ -162,7 +162,7 @@ describe('', function() {
).to.not.exist
})
- it('does not render the first error pop-up with new recompiles after it being dismissed once', function() {
+ it('does not render the first error pop-up with new recompiles after it being dismissed once', function () {
const nowTimestamp = Date.now()
const laterTimestamp = Date.now() + 1000
const propsWithErrorsForFirstCompile = getProps(
@@ -197,8 +197,8 @@ describe('', function() {
})
})
- describe('accessible description of the compile result', function() {
- it('renders an accessible description with the errors and warnings count', function() {
+ describe('accessible description of the compile result', function () {
+ it('renders an accessible description with the errors and warnings count', function () {
const errors = [sampleError1, sampleError2]
const warnings = [sampleWarning]
const propsWithErrorsAndWarnings = getProps(false, {
@@ -212,7 +212,7 @@ describe('', function() {
`${warnings.length} warning${warnings.length > 1 ? 's' : ''}`
)
})
- it('renders an accessible description for failed compiles with CLSI errors', function() {
+ it('renders an accessible description for failed compiles with CLSI errors', function () {
const sampleCLSIError = {
clsiMaintenance: true
}
@@ -231,7 +231,7 @@ describe('', function() {
screen.getByText('This project did not compile because of an error')
})
- it('renders an accessible description for failed compiles with validation issues', function() {
+ it('renders an accessible description for failed compiles with validation issues', function () {
const sampleValidationIssue = {
clsiMaintenance: true
}
diff --git a/services/web/test/frontend/features/preview/components/preview-recompile-button.test.js b/services/web/test/frontend/features/preview/components/preview-recompile-button.test.js
index 5696c4cb09..8799d3b34c 100644
--- a/services/web/test/frontend/features/preview/components/preview-recompile-button.test.js
+++ b/services/web/test/frontend/features/preview/components/preview-recompile-button.test.js
@@ -4,16 +4,16 @@ import { screen, render, fireEvent } from '@testing-library/react'
import PreviewRecompileButton from '../../../../../frontend/js/features/preview/components/preview-recompile-button'
const { expect } = require('chai')
-describe('', function() {
+describe('', function () {
let onRecompile, onRecompileFromScratch, onStopCompilation
- beforeEach(function() {
+ beforeEach(function () {
onRecompile = sinon.stub().resolves()
onRecompileFromScratch = sinon.stub().resolves()
onStopCompilation = sinon.stub().resolves()
})
- it('renders all items', function() {
+ it('renders all items', function () {
renderPreviewRecompileButton()
const menuItems = screen.getAllByRole('menuitem')
@@ -39,9 +39,9 @@ describe('', function() {
])
})
- describe('Recompile from scratch', function() {
- describe('click', function() {
- it('should call onRecompileFromScratch', async function() {
+ describe('Recompile from scratch', function () {
+ describe('click', function () {
+ it('should call onRecompileFromScratch', async function () {
renderPreviewRecompileButton()
const button = screen.getByRole('menuitem', {
@@ -51,8 +51,8 @@ describe('', function() {
expect(onRecompileFromScratch).to.have.been.calledOnce
})
})
- describe('processing', function() {
- it('shows processing view and disable menuItem when recompiling', function() {
+ describe('processing', function () {
+ it('shows processing view and disable menuItem when recompiling', function () {
renderPreviewRecompileButton({ isCompiling: true })
screen.getByRole('button', { name: 'Compiling…' })
@@ -75,12 +75,12 @@ describe('', function() {
})
})
- it('should show the button text when prop showText=true', function() {
+ it('should show the button text when prop showText=true', function () {
const showText = true
renderPreviewRecompileButton({}, showText)
expect(screen.getByText('Recompile').getAttribute('style')).to.be.null
})
- it('should not show the button text when prop showText=false', function() {
+ it('should not show the button text when prop showText=false', function () {
const showText = false
renderPreviewRecompileButton({}, showText)
expect(screen.getByText('Recompile').getAttribute('style')).to.equal(
@@ -88,8 +88,8 @@ describe('', function() {
)
})
- describe('Autocompile feedback', function() {
- it('shows animated visual feedback via CSS class when there are uncompiled changes', function() {
+ describe('Autocompile feedback', function () {
+ it('shows animated visual feedback via CSS class when there are uncompiled changes', function () {
const { container } = renderPreviewRecompileButton({
autoCompileHasChanges: true,
autoCompileHasLintingError: false
@@ -103,7 +103,7 @@ describe('', function() {
)
).to.be.true
})
- it('does not show animated visual feedback via CSS class when there are no uncompiled changes', function() {
+ it('does not show animated visual feedback via CSS class when there are no uncompiled changes', function () {
const { container } = renderPreviewRecompileButton({
autoCompileHasChanges: false,
autoCompileHasLintingError: false
diff --git a/services/web/test/frontend/features/preview/components/preview-toolbar.test.js b/services/web/test/frontend/features/preview/components/preview-toolbar.test.js
index f5b772298e..fe6643c2d9 100644
--- a/services/web/test/frontend/features/preview/components/preview-toolbar.test.js
+++ b/services/web/test/frontend/features/preview/components/preview-toolbar.test.js
@@ -4,7 +4,7 @@ import { expect } from 'chai'
import { screen, render, fireEvent } from '@testing-library/react'
import PreviewToolbar from '../../../../../frontend/js/features/preview/components/preview-toolbar'
-describe('', function() {
+describe('', function () {
const onRecompile = sinon.stub()
const onRecompileFromScratch = sinon.stub()
const onRunSyntaxCheckNow = sinon.stub()
@@ -53,14 +53,14 @@ describe('', function() {
)
}
- it('renders the toolbar', function() {
+ it('renders the toolbar', function () {
renderPreviewToolbar()
screen.getByText('Recompile')
screen.getByText('Download PDF')
screen.getByText('View logs')
})
- it('all toolbar items have "toolbar-item" class and text has "toolbar-text"', function() {
+ it('all toolbar items have "toolbar-item" class and text has "toolbar-text"', function () {
renderPreviewToolbar()
const toolbar = screen.getByTestId('toolbar-preview')
for (const toolbarSection of toolbar.children) {
@@ -77,7 +77,7 @@ describe('', function() {
}
})
- it('renders a full-screen button with a tooltip when when in split-screen mode', function() {
+ it('renders a full-screen button with a tooltip when when in split-screen mode', function () {
renderPreviewToolbar()
const btn = screen.getByLabelText('Full screen')
fireEvent.click(btn)
@@ -86,7 +86,7 @@ describe('', function() {
screen.getByRole('tooltip', { name: 'Full screen' })
})
- it('renders a split-screen button with a tooltip when when in full-screen mode', function() {
+ it('renders a split-screen button with a tooltip when when in full-screen mode', function () {
renderPreviewToolbar({}, {}, false, false)
const btn = screen.getByLabelText('Split screen')
fireEvent.click(btn)
diff --git a/services/web/test/frontend/features/share-project-modal/components/share-project-modal.test.js b/services/web/test/frontend/features/share-project-modal/components/share-project-modal.test.js
index 958f323243..93c252a277 100644
--- a/services/web/test/frontend/features/share-project-modal/components/share-project-modal.test.js
+++ b/services/web/test/frontend/features/share-project-modal/components/share-project-modal.test.js
@@ -13,7 +13,7 @@ import fetchMock from 'fetch-mock'
import ShareProjectModal from '../../../../../frontend/js/features/share-project-modal/components/share-project-modal'
import * as locationModule from '../../../../../frontend/js/features/share-project-modal/utils/location'
-describe('', function() {
+describe('', function () {
const project = {
_id: 'test-project',
name: 'Test Project',
@@ -88,30 +88,30 @@ describe('', function() {
const originalExposedSettings = window.ExposedSettings
- before(function() {
+ before(function () {
window.ExposedSettings = { appName: 'Overleaf' }
})
- after(function() {
+ after(function () {
window.ExposedSettings = originalExposedSettings
})
- beforeEach(function() {
+ beforeEach(function () {
fetchMock.get('/user/contacts', { contacts })
})
- afterEach(function() {
+ afterEach(function () {
fetchMock.restore()
cleanup()
})
- it('renders the modal', async function() {
+ it('renders the modal', async function () {
render()
await screen.findByText('Share Project')
})
- it('calls handleHide when a Close button is pressed', async function() {
+ it('calls handleHide when a Close button is pressed', async function () {
const handleHide = sinon.stub()
render()
@@ -127,7 +127,7 @@ describe('', function() {
expect(handleHide.callCount).to.equal(2)
})
- it('handles access level "private"', async function() {
+ it('handles access level "private"', async function () {
render(
', function() {
.be.null
})
- it('handles access level "tokenBased"', async function() {
+ it('handles access level "tokenBased"', async function () {
render(
', function() {
.not.to.be.null
})
- it('handles legacy access level "readAndWrite"', async function() {
+ it('handles legacy access level "readAndWrite"', async function () {
render(
', function() {
await screen.findByRole('button', { name: 'Make Private' })
})
- it('handles legacy access level "readOnly"', async function() {
+ it('handles legacy access level "readOnly"', async function () {
render(
', function() {
await screen.findByRole('button', { name: 'Make Private' })
})
- it('hides actions from non-admins', async function() {
+ it('hides actions from non-admins', async function () {
const invites = [
{
_id: 'invited-author',
@@ -263,7 +263,7 @@ describe('', function() {
expect(screen.queryByRole('button', { name: 'Resend' })).to.be.null
})
- it('only shows read-only token link to restricted token members', async function() {
+ it('only shows read-only token link to restricted token members', async function () {
window.isRestrictedTokenMember = true
render(
@@ -287,7 +287,7 @@ describe('', function() {
.be.null
})
- it('displays project members and invites', async function() {
+ it('displays project members and invites', async function () {
const members = [
{
_id: 'member-author',
@@ -344,7 +344,7 @@ describe('', function() {
)
})
- it('resends an invite', async function() {
+ it('resends an invite', async function () {
fetchMock.postOnce(
'express:/project/:projectId/invite/:inviteId/resend',
204
@@ -382,7 +382,7 @@ describe('', function() {
expect(closeButton.disabled).to.be.false
})
- it('revokes an invite', async function() {
+ it('revokes an invite', async function () {
fetchMock.deleteOnce('express:/project/:projectId/invite/:inviteId', 204)
const invites = [
@@ -416,7 +416,7 @@ describe('', function() {
expect(closeButton.disabled).to.be.false
})
- it('changes member privileges to read + write', async function() {
+ it('changes member privileges to read + write', async function () {
fetchMock.putOnce('express:/project/:projectId/users/:userId', 204)
const members = [
@@ -459,7 +459,7 @@ describe('', function() {
expect(closeButton.disabled).to.be.false
})
- it('removes a member from the project', async function() {
+ it('removes a member from the project', async function () {
fetchMock.deleteOnce('express:/project/:projectId/users/:userId', 204)
const members = [
@@ -499,7 +499,7 @@ describe('', function() {
)
})
- it('changes member privileges to owner with confirmation', async function() {
+ it('changes member privileges to owner with confirmation', async function () {
fetchMock.postOnce('express:/project/:projectId/transfer-ownership', 204)
const members = [
@@ -552,7 +552,7 @@ describe('', function() {
reloadStub.restore()
})
- it('sends invites to input email addresses', async function() {
+ it('sends invites to input email addresses', async function () {
render(
', function() {
screen.getByText('An email address is invalid')
})
- it('displays a message when the collaborator limit is reached', async function() {
+ it('displays a message when the collaborator limit is reached', async function () {
const originalUser = window.user
window.user = { allowedFreeTrial: true }
@@ -667,7 +667,7 @@ describe('', function() {
window.user = originalUser
})
- it('handles server error responses', async function() {
+ it('handles server error responses', async function () {
render(
', function() {
const submitButton = screen.getByRole('button', { name: 'Share' })
- const respondWithError = async function(errorReason) {
+ const respondWithError = async function (errorReason) {
inputElement.focus()
fireEvent.change(inputElement, {
target: { value: 'invited-author-1@example.com' }
@@ -733,7 +733,7 @@ describe('', function() {
)
})
- it('handles switching between access levels', async function() {
+ it('handles switching between access levels', async function () {
fetchMock.post('express:/project/:projectId/settings/admin', 204)
render(
@@ -775,7 +775,7 @@ describe('', function() {
)
})
- it('avoids selecting unmatched contact', async function() {
+ it('avoids selecting unmatched contact', async function () {
render()
const [inputElement] = await screen.findAllByLabelText(
diff --git a/services/web/test/frontend/features/word-count-modal/components/word-count-modal.test.js b/services/web/test/frontend/features/word-count-modal/components/word-count-modal.test.js
index 1a658b8db5..24f579619c 100644
--- a/services/web/test/frontend/features/word-count-modal/components/word-count-modal.test.js
+++ b/services/web/test/frontend/features/word-count-modal/components/word-count-modal.test.js
@@ -5,8 +5,8 @@ import { expect } from 'chai'
import sinon from 'sinon'
import fetchMock from 'fetch-mock'
-describe('', function() {
- afterEach(function() {
+describe('', function () {
+ afterEach(function () {
fetchMock.reset()
cleanup()
})
@@ -18,13 +18,13 @@ describe('', function() {
handleHide: sinon.stub()
}
- it('renders the translated modal title', async function() {
+ it('renders the translated modal title', async function () {
render()
await screen.findByText('Word Count')
})
- it('renders a loading message when loading', async function() {
+ it('renders a loading message when loading', async function () {
fetchMock.get('express:/project/:projectId/wordcount', () => {
return { status: 200, body: { texcount: {} } }
})
@@ -34,7 +34,7 @@ describe('', function() {
await screen.findByText('Loading…')
})
- it('renders an error message and hides loading message on error', async function() {
+ it('renders an error message and hides loading message on error', async function () {
fetchMock.get('express:/project/:projectId/wordcount', 500)
render()
@@ -44,7 +44,7 @@ describe('', function() {
expect(screen.queryByText(/Loading/)).to.not.exist
})
- it('displays messages', async function() {
+ it('displays messages', async function () {
fetchMock.get('express:/project/:projectId/wordcount', () => {
return {
status: 200,
@@ -61,7 +61,7 @@ describe('', function() {
await screen.findByText('This is a test')
})
- it('displays counts data', async function() {
+ it('displays counts data', async function () {
fetchMock.get('express:/project/:projectId/wordcount', () => {
return {
status: 200,
diff --git a/services/web/test/frontend/ide/history/util/displayNameForUserTests.js b/services/web/test/frontend/ide/history/util/displayNameForUserTests.js
index cc10e767eb..c186a61660 100644
--- a/services/web/test/frontend/ide/history/util/displayNameForUserTests.js
+++ b/services/web/test/frontend/ide/history/util/displayNameForUserTests.js
@@ -13,16 +13,16 @@ import { expect } from 'chai'
import displayNameForUser from '../../../../../frontend/js/ide/history/util/displayNameForUser'
-export default describe('displayNameForUser', function() {
- beforeEach(function() {
+export default describe('displayNameForUser', function () {
+ beforeEach(function () {
return (window.user = { id: 42 })
})
- it("should return 'Anonymous' with no user", function() {
+ it("should return 'Anonymous' with no user", function () {
return expect(displayNameForUser(null)).to.equal('Anonymous')
})
- it("should return 'you' when the user has the same id as the window", function() {
+ it("should return 'you' when the user has the same id as the window", function () {
return expect(
displayNameForUser({
id: window.user.id,
@@ -33,7 +33,7 @@ export default describe('displayNameForUser', function() {
).to.equal('you')
})
- it('should return the first_name and last_name when present', function() {
+ it('should return the first_name and last_name when present', function () {
return expect(
displayNameForUser({
id: window.user.id + 1,
@@ -44,7 +44,7 @@ export default describe('displayNameForUser', function() {
).to.equal('James Allen')
})
- it('should return only the firstAname if no last_name', function() {
+ it('should return only the firstAname if no last_name', function () {
return expect(
displayNameForUser({
id: window.user.id + 1,
@@ -55,7 +55,7 @@ export default describe('displayNameForUser', function() {
).to.equal('James')
})
- it('should return the email username if there are no names', function() {
+ it('should return the email username if there are no names', function () {
return expect(
displayNameForUser({
id: window.user.id + 1,
@@ -66,7 +66,7 @@ export default describe('displayNameForUser', function() {
).to.equal('james.allen')
})
- it("should return the '?' if it has nothing", function() {
+ it("should return the '?' if it has nothing", function () {
return expect(
displayNameForUser({
id: window.user.id + 1,
diff --git a/services/web/test/frontend/infrastructure/fetch-json.test.js b/services/web/test/frontend/infrastructure/fetch-json.test.js
index c8ff7ea8c9..5dde14a5bf 100644
--- a/services/web/test/frontend/infrastructure/fetch-json.test.js
+++ b/services/web/test/frontend/infrastructure/fetch-json.test.js
@@ -8,12 +8,12 @@ import {
putJSON
} from '../../../frontend/js/infrastructure/fetch-json'
-describe('fetchJSON', function() {
- before(function() {
+describe('fetchJSON', function () {
+ before(function () {
fetchMock.restore()
})
- afterEach(function() {
+ afterEach(function () {
fetchMock.restore()
})
@@ -22,7 +22,7 @@ describe('fetchJSON', function() {
'Content-Type': 'application/json'
}
- it('handles GET requests', function() {
+ it('handles GET requests', function () {
fetchMock.once(
{ method: 'GET', url: '/test', headers },
{ status: 200, body: { result: 'success' } }
@@ -33,7 +33,7 @@ describe('fetchJSON', function() {
})
})
- it('handles 4xx responses', function() {
+ it('handles 4xx responses', function () {
fetchMock.get('/test', {
status: 400,
body: { message: 'The request was invalid' }
@@ -50,7 +50,7 @@ describe('fetchJSON', function() {
})
})
- it('handles 5xx responses', async function() {
+ it('handles 5xx responses', async function () {
fetchMock.get('/test', { status: 500 })
return expect(getJSON('/test'))
@@ -62,7 +62,7 @@ describe('fetchJSON', function() {
})
})
- it('handles POST requests', function() {
+ it('handles POST requests', function () {
const body = { example: true }
fetchMock.once(
@@ -75,7 +75,7 @@ describe('fetchJSON', function() {
})
})
- it('handles PUT requests', function() {
+ it('handles PUT requests', function () {
const body = { example: true }
fetchMock.once(
@@ -88,7 +88,7 @@ describe('fetchJSON', function() {
})
})
- it('handles DELETE requests', function() {
+ it('handles DELETE requests', function () {
fetchMock.once({ method: 'DELETE', url: '/test', headers }, { status: 204 })
return expect(deleteJSON('/test')).to.eventually.deep.equal({})
diff --git a/services/web/test/frontend/infrastructure/local-storage.test.js b/services/web/test/frontend/infrastructure/local-storage.test.js
index 0c8959a436..bbc8e06c31 100644
--- a/services/web/test/frontend/infrastructure/local-storage.test.js
+++ b/services/web/test/frontend/infrastructure/local-storage.test.js
@@ -3,19 +3,19 @@ import sinon from 'sinon'
import customLocalStorage from '../../../frontend/js/infrastructure/local-storage'
-describe('localStorage', function() {
+describe('localStorage', function () {
let originalLocalStorage
- before(function() {
+ before(function () {
originalLocalStorage = global.localStorage
})
- after(function() {
+ after(function () {
Object.defineProperty(global, 'localStorage', {
value: originalLocalStorage
})
})
- beforeEach(function() {
+ beforeEach(function () {
Object.defineProperty(global, 'localStorage', {
value: {
getItem: sinon.stub().returns(null),
@@ -28,12 +28,12 @@ describe('localStorage', function() {
global.console.error = sinon.stub()
})
- afterEach(function() {
+ afterEach(function () {
global.console.error.reset()
Object.defineProperty(global, 'localStorage', { value: undefined })
})
- it('getItem', function() {
+ it('getItem', function () {
expect(customLocalStorage.getItem('foo')).to.be.null
global.localStorage.getItem.returns('false')
@@ -47,7 +47,7 @@ describe('localStorage', function() {
expect(global.console.error).to.be.calledOnce
})
- it('setItem', function() {
+ it('setItem', function () {
customLocalStorage.setItem('foo', 'bar')
expect(global.localStorage.setItem).to.be.calledOnceWith('foo', '"bar"')
global.localStorage.setItem.reset()
@@ -65,7 +65,7 @@ describe('localStorage', function() {
expect(global.console.error).to.be.calledOnce
})
- it('clear', function() {
+ it('clear', function () {
customLocalStorage.clear()
expect(global.localStorage.clear).to.be.calledOnce
@@ -74,7 +74,7 @@ describe('localStorage', function() {
expect(global.console.error).to.be.calledOnce
})
- it('removeItem', function() {
+ it('removeItem', function () {
customLocalStorage.removeItem('foo')
expect(global.localStorage.removeItem).to.be.calledOnceWith('foo')
global.localStorage.removeItem.reset()
diff --git a/services/web/test/frontend/prop-types.test.js b/services/web/test/frontend/prop-types.test.js
index 6c41bc8727..3927739d36 100644
--- a/services/web/test/frontend/prop-types.test.js
+++ b/services/web/test/frontend/prop-types.test.js
@@ -9,7 +9,7 @@
* to fail the tests when prop-types errors.
*/
const originalConsoleError = global.console.error
-before(function() {
+before(function () {
global.console.error = (message, ...args) => {
// Ensure we still log the error
originalConsoleError(message, ...args)
@@ -23,6 +23,6 @@ before(function() {
})
// Restore the original method
-after(function() {
+after(function () {
global.console.error = originalConsoleError
})
diff --git a/services/web/test/frontend/shared/components/icon.test.js b/services/web/test/frontend/shared/components/icon.test.js
index f05d3fd784..4e9dd9d41d 100644
--- a/services/web/test/frontend/shared/components/icon.test.js
+++ b/services/web/test/frontend/shared/components/icon.test.js
@@ -4,37 +4,37 @@ import { screen, render } from '@testing-library/react'
import Icon from '../../../../frontend/js/shared/components/icon'
-describe('', function() {
- it('renders basic fa classes', function() {
+describe('', function () {
+ it('renders basic fa classes', function () {
const { container } = render()
const element = container.querySelector('i.fa.fa-angle-down')
expect(element).to.exist
})
- it('renders with aria-hidden', function() {
+ it('renders with aria-hidden', function () {
const { container } = render()
const element = container.querySelector('i[aria-hidden="true"]')
expect(element).to.exist
})
- it('renders accessible label', function() {
+ it('renders accessible label', function () {
render()
screen.getByText('Accessible Foo')
})
- it('renders with spin', function() {
+ it('renders with spin', function () {
const { container } = render()
const element = container.querySelector('i.fa.fa-angle-down.fa-spin')
expect(element).to.exist
})
- it('renders with modifier', function() {
+ it('renders with modifier', function () {
const { container } = render()
const element = container.querySelector('i.fa.fa-angle-down.fa-2x')
expect(element).to.exist
})
- it('renders with custom clases', function() {
+ it('renders with custom clases', function () {
const { container } = render(
)
@@ -44,7 +44,7 @@ describe('', function() {
expect(element).to.exist
})
- it('renders children', function() {
+ it('renders children', function () {
const { container } = render(
diff --git a/services/web/test/frontend/shared/hooks/use-expand-collapse.test.js b/services/web/test/frontend/shared/hooks/use-expand-collapse.test.js
index e15d9c3b2d..9d7e76324d 100644
--- a/services/web/test/frontend/shared/hooks/use-expand-collapse.test.js
+++ b/services/web/test/frontend/shared/hooks/use-expand-collapse.test.js
@@ -35,11 +35,11 @@ ExpandCollapseTestUI.propTypes = {
expandCollapseArgs: PropTypes.object
}
-describe('useExpandCollapse', function() {
+describe('useExpandCollapse', function () {
// JSDom doesn't compute layout/sizing, so we need to simulate sizing for the elements
// Here we are simulating that the content is bigger than the `collapsedSize`, so
// the expand-collapse widget is used
- beforeEach(function() {
+ beforeEach(function () {
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {
configurable: true,
value: 500
@@ -50,7 +50,7 @@ describe('useExpandCollapse', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
Object.defineProperty(
HTMLElement.prototype,
'scrollHeight',
@@ -63,8 +63,8 @@ describe('useExpandCollapse', function() {
)
})
- describe('custom CSS classes', function() {
- it('supports a custom CSS class', function() {
+ describe('custom CSS classes', function () {
+ it('supports a custom CSS class', function () {
const testArgs = {
classes: {
container: 'my-custom-class'
@@ -76,7 +76,7 @@ describe('useExpandCollapse', function() {
const elWithCustomCSSClass = container.querySelector('div')
expect(elWithCustomCSSClass).to.exist
})
- it('supports an extra custom CSS class for the collapsed state', function() {
+ it('supports an extra custom CSS class for the collapsed state', function () {
const testArgs = {
classes: {
containerCollapsed: 'my-custom-collapsed-class'
@@ -91,7 +91,7 @@ describe('useExpandCollapse', function() {
)
expect(elWithCustomCollapsedCSSClass).to.exist
})
- it('ignores the collapsed CSS class when expanded', function() {
+ it('ignores the collapsed CSS class when expanded', function () {
const testArgs = {
initiallyExpanded: true,
classes: {
@@ -107,14 +107,14 @@ describe('useExpandCollapse', function() {
expect(elWithCustomCollapsedCSSClass).to.not.exist
})
})
- describe('height and width support via dimension argument', function() {
- it('defaults to height', function() {
+ describe('height and width support via dimension argument', function () {
+ it('defaults to height', function () {
const { container } = render()
const expandCollapseEl = container.firstChild
expect(expandCollapseEl.style.height).to.not.be.empty
expect(expandCollapseEl.style.width).to.be.empty
})
- it('supports width', function() {
+ it('supports width', function () {
const testArgs = {
dimension: 'width'
}
@@ -126,13 +126,13 @@ describe('useExpandCollapse', function() {
expect(expandCollapseEl.style.width).to.not.be.empty
})
})
- describe('collapsed size support via collapsedSize argument', function() {
- it('defaults to 0px', function() {
+ describe('collapsed size support via collapsedSize argument', function () {
+ it('defaults to 0px', function () {
const { container } = render()
const expandCollapseEl = container.firstChild
expect(expandCollapseEl.style.height).to.equal('0px')
})
- it('supports a custom collapsed size', function() {
+ it('supports a custom collapsed size', function () {
const testArgs = {
collapsedSize: 200
}
@@ -142,7 +142,7 @@ describe('useExpandCollapse', function() {
const expandCollapseEl = container.firstChild
expect(expandCollapseEl.style.height).to.equal('200px')
})
- it('supports a custom collapsed size for width', function() {
+ it('supports a custom collapsed size for width', function () {
const testArgs = {
collapsedSize: 200,
dimension: 'width'
diff --git a/services/web/test/frontend/utils/EventEmitterTests.js b/services/web/test/frontend/utils/EventEmitterTests.js
index 543eaa73e2..a36f02e2d5 100644
--- a/services/web/test/frontend/utils/EventEmitterTests.js
+++ b/services/web/test/frontend/utils/EventEmitterTests.js
@@ -15,12 +15,12 @@ import sinon from 'sinon'
import EventEmitter from '../../../frontend/js/utils/EventEmitter'
-export default describe('EventEmitter', function() {
- beforeEach(function() {
+export default describe('EventEmitter', function () {
+ beforeEach(function () {
return (this.eventEmitter = new EventEmitter())
})
- it('calls listeners', function() {
+ it('calls listeners', function () {
const cb1 = sinon.stub()
const cb2 = sinon.stub()
this.eventEmitter.on('foo', cb1)
@@ -32,7 +32,7 @@ export default describe('EventEmitter', function() {
return expect(cb2).to.not.have.been.called
})
- it('calls multiple listeners', function() {
+ it('calls multiple listeners', function () {
const cb1 = sinon.stub()
const cb2 = sinon.stub()
this.eventEmitter.on('foo', cb1)
@@ -44,7 +44,7 @@ export default describe('EventEmitter', function() {
return expect(cb2).to.have.been.called
})
- it('calls listeners with namespace', function() {
+ it('calls listeners with namespace', function () {
const cb1 = sinon.stub()
const cb2 = sinon.stub()
this.eventEmitter.on('foo', cb1)
@@ -56,7 +56,7 @@ export default describe('EventEmitter', function() {
return expect(cb2).to.have.been.called
})
- it('removes listeners', function() {
+ it('removes listeners', function () {
const cb = sinon.stub()
this.eventEmitter.on('foo', cb)
this.eventEmitter.off('foo')
@@ -66,7 +66,7 @@ export default describe('EventEmitter', function() {
return expect(cb).to.not.have.been.called
})
- it('removes namespaced listeners', function() {
+ it('removes namespaced listeners', function () {
const cb = sinon.stub()
this.eventEmitter.on('foo.bar', cb)
this.eventEmitter.off('foo.bar')
@@ -76,7 +76,7 @@ export default describe('EventEmitter', function() {
return expect(cb).to.not.have.been.called
})
- it('does not remove unnamespaced listeners if off called with namespace', function() {
+ it('does not remove unnamespaced listeners if off called with namespace', function () {
const cb1 = sinon.stub()
const cb2 = sinon.stub()
this.eventEmitter.on('foo', cb1)
diff --git a/services/web/test/karma/ide/editor/aceEditor/spell-check/SpellCheckManagerTests.js b/services/web/test/karma/ide/editor/aceEditor/spell-check/SpellCheckManagerTests.js
index 6f2fadb8d6..18f82fc44c 100644
--- a/services/web/test/karma/ide/editor/aceEditor/spell-check/SpellCheckManagerTests.js
+++ b/services/web/test/karma/ide/editor/aceEditor/spell-check/SpellCheckManagerTests.js
@@ -11,8 +11,8 @@
*/
import SpellCheckManager from '../../../../../../frontend/js/ide/editor/directives/aceEditor/spell-check/SpellCheckManager'
-export default describe('SpellCheckManager', function() {
- beforeEach(function(done) {
+export default describe('SpellCheckManager', function () {
+ beforeEach(function (done) {
this.timelord = sinon.useFakeTimers()
window.user = { id: 1 }
window.csrfToken = 'token'
@@ -48,11 +48,11 @@ export default describe('SpellCheckManager', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
return this.timelord.restore()
})
- it('adds an highlight when a misspelling is found', function() {
+ it('adds an highlight when a misspelling is found', function () {
this.$httpBackend.when('POST', '/spelling/check').respond({
misspellings: [
{
@@ -68,8 +68,8 @@ export default describe('SpellCheckManager', function() {
expect(this.highlightedWordManager.addHighlight).to.have.been.called
})
- describe('runSpellCheck', function() {
- beforeEach(function() {
+ describe('runSpellCheck', function () {
+ beforeEach(function () {
this.adapter.getLineCount.returns(10)
this.adapter.getFirstVisibleRowNum.returns(3)
this.adapter.getLastVisibleRowNum.returns(5)
@@ -87,16 +87,16 @@ export default describe('SpellCheckManager', function() {
]
})
})
- describe('when doing the first check', function() {
- beforeEach(function() {
+ describe('when doing the first check', function () {
+ beforeEach(function () {
this.spellCheckManager.init()
})
- it('initially flags all lines as dirty ', function() {
+ it('initially flags all lines as dirty ', function () {
expect(this.spellCheckManager.changedLines)
.to.have.lengthOf(10)
.and.to.not.include(false)
})
- it('checks beyond the currently visible viewport', function() {
+ it('checks beyond the currently visible viewport', function () {
this.timelord.tick(500)
this.$httpBackend.flush()
expect(this.adapter.getLinesByRows).to.have.been.calledWith([
@@ -113,20 +113,20 @@ export default describe('SpellCheckManager', function() {
])
})
})
- describe('after the initial check', function() {
- beforeEach(function() {
+ describe('after the initial check', function () {
+ beforeEach(function () {
this.spellCheckManager.init()
this.spellCheckManager.firstCheck = false
})
- it('only checks visible lines', function() {
+ it('only checks visible lines', function () {
this.spellCheckManager.runSpellCheck()
this.spellCheckManager.timeoutId = null
this.$httpBackend.flush()
expect(this.adapter.getLinesByRows).to.have.been.calledWith([3, 4, 5])
})
- it('flags checked lines as non-dirty', function() {
+ it('flags checked lines as non-dirty', function () {
this.spellCheckManager.runSpellCheck()
this.spellCheckManager.timeoutId = null
this.$httpBackend.flush()
@@ -137,7 +137,7 @@ export default describe('SpellCheckManager', function() {
expect(this.spellCheckManager.changedLines[6]).to.equal(true)
})
- it('ignores updated lines', function() {
+ it('ignores updated lines', function () {
this.spellCheckManager.changedLines[4] = false
this.spellCheckManager.runSpellCheck()
this.spellCheckManager.timeoutId = null
@@ -145,7 +145,7 @@ export default describe('SpellCheckManager', function() {
expect(this.adapter.getLinesByRows).to.have.been.calledWith([3, 5])
})
- it('clears highlights for changed lines', function() {
+ it('clears highlights for changed lines', function () {
this.spellCheckManager.runSpellCheck()
this.spellCheckManager.timeoutId = null
this.$httpBackend.flush()
@@ -162,8 +162,8 @@ export default describe('SpellCheckManager', function() {
})
})
- describe('cache', function() {
- beforeEach(function() {
+ describe('cache', function () {
+ beforeEach(function () {
this.adapter.getLineCount.returns(1)
this.adapter.getFirstVisibleRowNum.returns(1)
this.adapter.getLastVisibleRowNum.returns(1)
@@ -178,7 +178,7 @@ export default describe('SpellCheckManager', function() {
})
})
- it('adds already checked words to the spellchecker cache', function() {
+ it('adds already checked words to the spellchecker cache', function () {
expect(this.spellCheckManager.cache.info().size).to.equal(0)
this.spellCheckManager.init()
this.timelord.tick(500)
@@ -186,7 +186,7 @@ export default describe('SpellCheckManager', function() {
expect(this.spellCheckManager.cache.info().size).to.equal(3)
})
- it('adds misspeled word suggestions to the cache', function() {
+ it('adds misspeled word suggestions to the cache', function () {
this.spellCheckManager.init()
this.timelord.tick(500)
this.$httpBackend.flush()
@@ -198,7 +198,7 @@ export default describe('SpellCheckManager', function() {
).to.eql(['foobarbaz'])
})
- it('adds non-misspeled words to the cache as a boolean', function() {
+ it('adds non-misspeled words to the cache as a boolean', function () {
this.spellCheckManager.init()
this.timelord.tick(500)
this.$httpBackend.flush()
@@ -210,15 +210,15 @@ export default describe('SpellCheckManager', function() {
})
})
- describe('backend', function() {
- beforeEach(function() {
+ describe('backend', function () {
+ beforeEach(function () {
this.adapter.getLineCount.returns(1)
this.adapter.getFirstVisibleRowNum.returns(1)
this.adapter.getLastVisibleRowNum.returns(1)
this.adapter.getLinesByRows.returns(['Lorem ipsum dolor'])
})
- it('hits the backend with all words at startup', function() {
+ it('hits the backend with all words at startup', function () {
this.$httpBackend
.expect('POST', '/spelling/check', {
language: this.scope.spellCheckLanguage,
@@ -239,7 +239,7 @@ export default describe('SpellCheckManager', function() {
this.$httpBackend.flush()
})
- it('does not hit the backend when all words are already in the cache', function() {
+ it('does not hit the backend when all words are already in the cache', function () {
this.$httpBackend
.expect('POST', '/spelling/check', {
language: this.scope.spellCheckLanguage,
@@ -262,7 +262,7 @@ export default describe('SpellCheckManager', function() {
this.timelord.tick(500)
})
- it('hits the backend only with non-cached words', function() {
+ it('hits the backend only with non-cached words', function () {
this.$httpBackend
.expect('POST', '/spelling/check', {
language: this.scope.spellCheckLanguage,
@@ -303,7 +303,7 @@ export default describe('SpellCheckManager', function() {
this.$httpBackend.flush()
})
- afterEach(function() {
+ afterEach(function () {
this.$httpBackend.verifyNoOutstandingRequest()
this.$httpBackend.verifyNoOutstandingExpectation()
})
diff --git a/services/web/test/karma/ide/history/HistoryV2ManagerTests.js b/services/web/test/karma/ide/history/HistoryV2ManagerTests.js
index cb5beda5b0..ef5f5872f0 100644
--- a/services/web/test/karma/ide/history/HistoryV2ManagerTests.js
+++ b/services/web/test/karma/ide/history/HistoryV2ManagerTests.js
@@ -12,8 +12,8 @@
*/
import HistoryV2Manager from '../../../../frontend/js/ide/history/HistoryV2Manager'
-export default describe('HistoryV2Manager', function() {
- beforeEach(function(done) {
+export default describe('HistoryV2Manager', function () {
+ beforeEach(function (done) {
this.defaultHistoryScope = {
isV2: true,
updates: [],
@@ -167,11 +167,11 @@ export default describe('HistoryV2Manager', function() {
})
})
- it('should setup the history scope on initialization', function() {
+ it('should setup the history scope on initialization', function () {
expect(this.$scope.history).to.deep.equal(this.defaultHistoryScope)
})
- it('should keep history updates after performing a soft reset', function() {
+ it('should keep history updates after performing a soft reset', function () {
let historyScopeWithUpdates = Object.assign({}, this.defaultHistoryScope, {
updates: this.sampleUpdates
})
@@ -180,18 +180,18 @@ export default describe('HistoryV2Manager', function() {
expect(this.$scope.history).to.deep.equal(historyScopeWithUpdates)
})
- it('should discard history updates after performing a hard reset', function() {
+ it('should discard history updates after performing a hard reset', function () {
this.$scope.history.updates = this.sampleUpdates
this.historyManager.hardReset()
expect(this.$scope.history).to.deep.equal(this.defaultHistoryScope)
})
- it('should setup history with full access to the feature if the project has versioning', function() {
+ it('should setup history with full access to the feature if the project has versioning', function () {
this.$scope.$digest()
expect(this.$scope.history.userHasFullFeature).to.equal(true)
})
- it('should setup history without full access to the feature if the project does not have versioning', function() {
+ it('should setup history without full access to the feature if the project does not have versioning', function () {
this.$scope.project.features.versioning = false
this.historyManager = new HistoryV2Manager(
this.ide,
@@ -202,7 +202,7 @@ export default describe('HistoryV2Manager', function() {
expect(this.$scope.history.userHasFullFeature).to.equal(false)
})
- it('should setup history with full access to the feature for admin users even if the project does not have versioning', function() {
+ it('should setup history with full access to the feature for admin users even if the project does not have versioning', function () {
this.$scope.project.features.versioning = false
this.$scope.user.isAdmin = true
this.historyManager = new HistoryV2Manager(
@@ -214,9 +214,9 @@ export default describe('HistoryV2Manager', function() {
expect(this.$scope.history.userHasFullFeature).to.equal(true)
})
- describe('autoSelectFile', function() {
- describe('for compare mode', function() {
- beforeEach(function() {
+ describe('autoSelectFile', function () {
+ describe('for compare mode', function () {
+ beforeEach(function () {
this.mockedFilesList = [
{
pathname: 'main.tex'
@@ -260,8 +260,8 @@ export default describe('HistoryV2Manager', function() {
this.$scope.history.selection.files = this.mockedFilesList
})
- describe('with a previously selected file', function() {
- it('should prefer the previously selected file if it is available and has operations', function() {
+ describe('with a previously selected file', function () {
+ it('should prefer the previously selected file if it is available and has operations', function () {
this.historyManager._previouslySelectedPathname = this.mockedAddedFile.pathname
this.historyManager.autoSelectFile()
expect(this.$scope.history.selection.file).to.deep.equal(
@@ -269,13 +269,13 @@ export default describe('HistoryV2Manager', function() {
)
})
- it('should prefer a file with ops if the previously selected file is available but has no operations', function() {
+ it('should prefer a file with ops if the previously selected file is available but has no operations', function () {
this.historyManager._previouslySelectedPathname = this.mockedReferencesFile.pathname
this.historyManager.autoSelectFile()
expect(this.$scope.history.selection.file.operation).to.exist
})
- it('should ignore the previously selected file if it is not available', function() {
+ it('should ignore the previously selected file if it is not available', function () {
this.historyManager._previouslySelectedPathname = 'non/existent.file'
this.historyManager.autoSelectFile()
expect(this.$scope.history.selection.file.pathname).to.not.equal(
@@ -284,15 +284,15 @@ export default describe('HistoryV2Manager', function() {
})
})
- describe('without a previously selected file, with a list of files containing operations', function() {
- it('should prefer edited files', function() {
+ describe('without a previously selected file, with a list of files containing operations', function () {
+ it('should prefer edited files', function () {
this.historyManager.autoSelectFile()
expect(this.$scope.history.selection.file).to.deep.equal(
this.mockedEditedFile
)
})
- it('should prefer added files if no edited files are present', function() {
+ it('should prefer added files if no edited files are present', function () {
const indexOfEditedFile = this.$scope.history.selection.files.indexOf(
this.mockedEditedFile
)
@@ -303,7 +303,7 @@ export default describe('HistoryV2Manager', function() {
)
})
- it('should prefer renamed files if no edited or added files are present', function() {
+ it('should prefer renamed files if no edited or added files are present', function () {
const indexOfEditedFile = this.$scope.history.selection.files.indexOf(
this.mockedEditedFile
)
@@ -318,7 +318,7 @@ export default describe('HistoryV2Manager', function() {
)
})
- it('should prefer removed files if no edited, added or renamed files are present', function() {
+ it('should prefer removed files if no edited, added or renamed files are present', function () {
const indexOfEditedFile = this.$scope.history.selection.files.indexOf(
this.mockedEditedFile
)
@@ -338,8 +338,8 @@ export default describe('HistoryV2Manager', function() {
})
})
- describe('without a previously selected file, with a list of files without operations', function() {
- beforeEach(function() {
+ describe('without a previously selected file, with a list of files without operations', function () {
+ beforeEach(function () {
this.mockedFilesListWithNoOps = [
{
pathname: 'main.tex'
@@ -361,14 +361,14 @@ export default describe('HistoryV2Manager', function() {
this.$scope.history.selection.files = this.mockedFilesListWithNoOps
})
- it('should prefer main.tex if it exists', function() {
+ it('should prefer main.tex if it exists', function () {
this.historyManager.autoSelectFile()
expect(this.$scope.history.selection.file).to.deep.equal(
this.mockedMainTex
)
})
- it('should prefer another tex file if main.tex does not exist', function() {
+ it('should prefer another tex file if main.tex does not exist', function () {
const indexOfMainTex = this.$scope.history.selection.files.indexOf(
this.mockedMainTex
)
@@ -379,7 +379,7 @@ export default describe('HistoryV2Manager', function() {
)
})
- it('should pick the first available file if no tex files are available', function() {
+ it('should pick the first available file if no tex files are available', function () {
const indexOfMainTex = this.$scope.history.selection.files.indexOf(
this.mockedMainTex
)
@@ -396,8 +396,8 @@ export default describe('HistoryV2Manager', function() {
})
})
- describe('for point-in-time mode', function() {
- beforeEach(function() {
+ describe('for point-in-time mode', function () {
+ beforeEach(function () {
this.$scope.history.viewMode = 'point_in_time'
this.sampleUpdates[0] = {
fromV: 4,
@@ -468,8 +468,8 @@ export default describe('HistoryV2Manager', function() {
this.$scope.history.selection.files = this.mockedFilesList
})
- describe('with a previously selected file', function() {
- it('should prefer the previously selected file if it is available and has operations', function() {
+ describe('with a previously selected file', function () {
+ it('should prefer the previously selected file if it is available and has operations', function () {
this.historyManager._previouslySelectedPathname = 'main.tex'
this.historyManager.autoSelectFile()
expect(this.$scope.history.selection.file.pathname).to.equal(
@@ -477,7 +477,7 @@ export default describe('HistoryV2Manager', function() {
)
})
- it('should prefer a file with ops if the previously selected file is available but has no operations', function() {
+ it('should prefer a file with ops if the previously selected file is available but has no operations', function () {
this.historyManager._previouslySelectedPathname = 'main.tex'
this.sampleUpdates[0].pathnames = []
this.historyManager.autoSelectFile()
@@ -486,7 +486,7 @@ export default describe('HistoryV2Manager', function() {
)
})
- it('should ignore the previously selected file if it is not available', function() {
+ it('should ignore the previously selected file if it is not available', function () {
this.historyManager._previouslySelectedPathname = 'non/existent.file'
this.historyManager.autoSelectFile()
expect(this.$scope.history.selection.file.pathname).to.not.equal(
@@ -495,15 +495,15 @@ export default describe('HistoryV2Manager', function() {
})
})
- describe('without a previously selected file, with a list of files containing operations', function() {
- it('should prefer edited files', function() {
+ describe('without a previously selected file, with a list of files containing operations', function () {
+ it('should prefer edited files', function () {
this.historyManager.autoSelectFile()
expect(this.$scope.history.selection.file.pathname).to.equal(
this.sampleUpdateEditedFile
)
})
- it('should prefer added files if no edited files are present', function() {
+ it('should prefer added files if no edited files are present', function () {
this.sampleUpdates[0].pathnames = []
this.historyManager.autoSelectFile()
expect(this.$scope.history.selection.file.pathname).to.equal(
@@ -511,7 +511,7 @@ export default describe('HistoryV2Manager', function() {
)
})
- it('should prefer renamed files if no edited or added files are present', function() {
+ it('should prefer renamed files if no edited or added files are present', function () {
this.sampleUpdates[0].pathnames = []
this.sampleUpdates[0].project_ops.shift()
this.historyManager.autoSelectFile()
@@ -521,22 +521,22 @@ export default describe('HistoryV2Manager', function() {
})
})
- describe('without a previously selected file, with a list of files without operations', function() {
- beforeEach(function() {
+ describe('without a previously selected file, with a list of files without operations', function () {
+ beforeEach(function () {
this.sampleUpdates[0].pathnames = []
this.sampleUpdates[0].project_ops = []
this.mockedMainTex = this.mockedFilesList[0]
this.mockedReferencesFile = this.mockedFilesList[1]
})
- it('should prefer main.tex if it exists', function() {
+ it('should prefer main.tex if it exists', function () {
this.historyManager.autoSelectFile()
expect(this.$scope.history.selection.file.pathname).to.equal(
this.mockedMainTex.pathname
)
})
- it('should prefer another tex file if main.tex does not exist', function() {
+ it('should prefer another tex file if main.tex does not exist', function () {
const indexOfMainTex = this.$scope.history.selection.files.indexOf(
this.mockedMainTex
)
@@ -547,8 +547,8 @@ export default describe('HistoryV2Manager', function() {
})
})
- describe('_loadLabels', function() {
- it('should return labels list as is if there is a label for the last version', function() {
+ describe('_loadLabels', function () {
+ it('should return labels list as is if there is a label for the last version', function () {
const labels = [
{
id: '1',
@@ -576,7 +576,7 @@ export default describe('HistoryV2Manager', function() {
expect(labelsResult).to.have.members(labels)
})
- it('should return a labels list with a pseudo current state label if there is no label for the last version', function() {
+ it('should return a labels list with a pseudo current state label if there is no label for the last version', function () {
const labels = [
{
id: '1',
@@ -606,7 +606,7 @@ export default describe('HistoryV2Manager', function() {
expect(labelsResult[0].version).to.equal(5)
})
- it('should keep pseudo label when deleting label', function() {
+ it('should keep pseudo label when deleting label', function () {
this.historyManager.$scope.history.labels = [
{
id: '1',
diff --git a/services/web/test/karma/import_tests.js b/services/web/test/karma/import_tests.js
index 678778413d..412fcad96d 100644
--- a/services/web/test/karma/import_tests.js
+++ b/services/web/test/karma/import_tests.js
@@ -9,7 +9,7 @@ import 'angular-mocks'
* A deep comparison will fail because CodeMirror inserts additional properties
* that we want to ignore.
*/
-chai.Assertion.addMethod('equalPos', function(expectedPos) {
+chai.Assertion.addMethod('equalPos', function (expectedPos) {
const { line: actualLine, ch: actualCh } = this._obj
const { line: expectedLine, ch: expectedCh } = expectedPos
diff --git a/services/web/test/unit/src/Analytics/AnalyticsControllerTests.js b/services/web/test/unit/src/Analytics/AnalyticsControllerTests.js
index 80a35f75d2..a52440be9e 100644
--- a/services/web/test/unit/src/Analytics/AnalyticsControllerTests.js
+++ b/services/web/test/unit/src/Analytics/AnalyticsControllerTests.js
@@ -6,8 +6,8 @@ const modulePath = path.join(
)
const sinon = require('sinon')
-describe('AnalyticsController', function() {
- beforeEach(function() {
+describe('AnalyticsController', function () {
+ beforeEach(function () {
this.AuthenticationController = { getLoggedInUserId: sinon.stub() }
this.AnalyticsManager = {
@@ -42,8 +42,8 @@ describe('AnalyticsController', function() {
}
})
- describe('updateEditingSession', function() {
- beforeEach(function() {
+ describe('updateEditingSession', function () {
+ beforeEach(function () {
this.req = {
params: {
projectId: 'a project id'
@@ -54,7 +54,7 @@ describe('AnalyticsController', function() {
.callsArgWith(1, null, { country_code: 'XY' })
})
- it('delegates to the AnalyticsManager', function(done) {
+ it('delegates to the AnalyticsManager', function (done) {
this.AuthenticationController.getLoggedInUserId.returns('1234')
this.controller.updateEditingSession(this.req, this.res)
@@ -65,8 +65,8 @@ describe('AnalyticsController', function() {
})
})
- describe('recordEvent', function() {
- beforeEach(function() {
+ describe('recordEvent', function () {
+ beforeEach(function () {
this.req = {
params: {
event: 'i_did_something'
@@ -77,7 +77,7 @@ describe('AnalyticsController', function() {
}
})
- it('should use the user_id', function(done) {
+ it('should use the user_id', function (done) {
this.AuthenticationController.getLoggedInUserId.returns('1234')
this.controller.recordEvent(this.req, this.res)
this.AnalyticsManager.recordEvent
@@ -86,7 +86,7 @@ describe('AnalyticsController', function() {
done()
})
- it('should use the session id', function(done) {
+ it('should use the session id', function (done) {
this.controller.recordEvent(this.req, this.res)
this.AnalyticsManager.recordEvent
.calledWith(this.req.sessionID, this.req.params.event, this.req.body)
@@ -95,8 +95,8 @@ describe('AnalyticsController', function() {
})
})
- describe('licences', function() {
- beforeEach(function() {
+ describe('licences', function () {
+ beforeEach(function () {
this.req = {
query: {
resource_id: 1,
@@ -109,7 +109,7 @@ describe('AnalyticsController', function() {
}
})
- it('should trigger institutions api to fetch licences graph data', function(done) {
+ it('should trigger institutions api to fetch licences graph data', function (done) {
this.controller.licences(this.req, this.res)
this.InstitutionsAPI.getInstitutionLicences
.calledWith(
diff --git a/services/web/test/unit/src/Analytics/AnalyticsManagerTests.js b/services/web/test/unit/src/Analytics/AnalyticsManagerTests.js
index ac3eea81bc..1bca1bbfbc 100644
--- a/services/web/test/unit/src/Analytics/AnalyticsManagerTests.js
+++ b/services/web/test/unit/src/Analytics/AnalyticsManagerTests.js
@@ -7,8 +7,8 @@ const MODULE_PATH = path.join(
'../../../../app/src/Features/Analytics/AnalyticsManager'
)
-describe('AnalyticsManager', function() {
- beforeEach(function() {
+describe('AnalyticsManager', function () {
+ beforeEach(function () {
this.fakeUserId = '123abc'
this.Settings = {
analytics: { enabled: true }
@@ -47,22 +47,22 @@ describe('AnalyticsManager', function() {
})
})
- describe('ignores when', function() {
- it('user is smoke test user', function() {
+ describe('ignores when', function () {
+ it('user is smoke test user', function () {
this.Settings.smokeTest = { userId: this.fakeUserId }
this.AnalyticsManager.identifyUser(this.fakeUserId, '')
sinon.assert.notCalled(this.analyticsEventsQueue.add)
})
- it('analytics service is disabled', function() {
+ it('analytics service is disabled', function () {
this.Settings.analytics.enabled = false
this.AnalyticsManager.identifyUser(this.fakeUserId, '')
sinon.assert.notCalled(this.analyticsEventsQueue.add)
})
})
- describe('queues the appropriate message for', function() {
- it('identifyUser', function() {
+ describe('queues the appropriate message for', function () {
+ it('identifyUser', function () {
const oldUserId = '456def'
this.AnalyticsManager.identifyUser(this.fakeUserId, oldUserId)
sinon.assert.calledWithMatch(this.analyticsEventsQueue.add, 'identify', {
@@ -71,7 +71,7 @@ describe('AnalyticsManager', function() {
})
})
- it('recordEvent', function() {
+ it('recordEvent', function () {
const event = 'fake-event'
this.AnalyticsManager.recordEvent(this.fakeUserId, event, null)
sinon.assert.calledWithMatch(this.analyticsEventsQueue.add, 'event', {
@@ -81,7 +81,7 @@ describe('AnalyticsManager', function() {
})
})
- it('updateEditingSession', function() {
+ it('updateEditingSession', function () {
const projectId = '789ghi'
const countryCode = 'fr'
this.AnalyticsManager.updateEditingSession(
diff --git a/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js b/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js
index cee6e16cca..613a875fbc 100644
--- a/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js
+++ b/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js
@@ -8,14 +8,12 @@ const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
const { ObjectId } = require('mongodb')
-describe('AuthenticationController', function() {
- beforeEach(function() {
+describe('AuthenticationController', function () {
+ beforeEach(function () {
tk.freeze(Date.now())
this.UserModel = { findOne: sinon.stub() }
this.httpAuthUsers = {
- 'valid-test-user': Math.random()
- .toString(16)
- .slice(2)
+ 'valid-test-user': Math.random().toString(16).slice(2)
}
this.AuthenticationController = SandboxedModule.require(modulePath, {
requires: {
@@ -95,12 +93,12 @@ describe('AuthenticationController', function() {
this.next = sinon.stub()
})
- afterEach(function() {
+ afterEach(function () {
tk.reset()
})
- describe('validateAdmin', function() {
- beforeEach(function() {
+ describe('validateAdmin', function () {
+ beforeEach(function () {
this.Settings.adminDomains = ['good.example.com']
this.goodAdmin = {
email: 'alice@good.example.com',
@@ -116,7 +114,7 @@ describe('AuthenticationController', function() {
}
})
- it('should skip when adminDomains are not configured', function(done) {
+ it('should skip when adminDomains are not configured', function (done) {
this.Settings.adminDomains = []
this.AuthenticationController.getSessionUser = sinon
.stub()
@@ -128,7 +126,7 @@ describe('AuthenticationController', function() {
})
})
- it('should skip non-admin user', function(done) {
+ it('should skip non-admin user', function (done) {
this.AuthenticationController.getSessionUser = sinon
.stub()
.returns(this.normalUser)
@@ -139,7 +137,7 @@ describe('AuthenticationController', function() {
})
})
- it('should permit an admin with the right doman', function(done) {
+ it('should permit an admin with the right doman', function (done) {
this.AuthenticationController.getSessionUser = sinon
.stub()
.returns(this.goodAdmin)
@@ -150,7 +148,7 @@ describe('AuthenticationController', function() {
})
})
- it('should block an admin with a missing email', function(done) {
+ it('should block an admin with a missing email', function (done) {
this.AuthenticationController.getSessionUser = sinon
.stub()
.returns({ isAdmin: true })
@@ -161,7 +159,7 @@ describe('AuthenticationController', function() {
})
})
- it('should block an admin with a bad domain', function(done) {
+ it('should block an admin with a bad domain', function (done) {
this.AuthenticationController.getSessionUser = sinon
.stub()
.returns(this.badAdmin)
@@ -173,16 +171,16 @@ describe('AuthenticationController', function() {
})
})
- describe('isUserLoggedIn', function() {
- beforeEach(function() {
+ describe('isUserLoggedIn', function () {
+ beforeEach(function () {
this.stub = sinon.stub(this.AuthenticationController, 'getLoggedInUserId')
})
- afterEach(function() {
+ afterEach(function () {
this.stub.restore()
})
- it('should do the right thing in all cases', function() {
+ it('should do the right thing in all cases', function () {
this.AuthenticationController.getLoggedInUserId.returns('some_id')
expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
true
@@ -202,8 +200,8 @@ describe('AuthenticationController', function() {
})
})
- describe('setInSessionUser', function() {
- beforeEach(function() {
+ describe('setInSessionUser', function () {
+ beforeEach(function () {
this.user = {
_id: 'id',
first_name: 'a',
@@ -215,7 +213,7 @@ describe('AuthenticationController', function() {
.returns(this.user)
})
- it('should update the right properties', function() {
+ it('should update the right properties', function () {
this.AuthenticationController.setInSessionUser(this.req, {
first_name: 'new_first_name',
email: 'new_email'
@@ -231,8 +229,8 @@ describe('AuthenticationController', function() {
})
})
- describe('passportLogin', function() {
- beforeEach(function() {
+ describe('passportLogin', function () {
+ beforeEach(function () {
this.info = null
this.req.login = sinon.stub().callsArgWith(1, null)
this.res.json = sinon.stub()
@@ -248,17 +246,17 @@ describe('AuthenticationController', function() {
this.err = new Error('woops')
})
- it('should call passport.authenticate', function() {
+ it('should call passport.authenticate', function () {
this.AuthenticationController.passportLogin(this.req, this.res, this.next)
this.passport.authenticate.callCount.should.equal(1)
})
- describe('when authenticate produces an error', function() {
- beforeEach(function() {
+ describe('when authenticate produces an error', function () {
+ beforeEach(function () {
this.passport.authenticate.callsArgWith(1, this.err)
})
- it('should return next with an error', function() {
+ it('should return next with an error', function () {
this.AuthenticationController.passportLogin(
this.req,
this.res,
@@ -268,17 +266,17 @@ describe('AuthenticationController', function() {
})
})
- describe('when authenticate produces a user', function() {
- beforeEach(function() {
+ describe('when authenticate produces a user', function () {
+ beforeEach(function () {
this.req.session.postLoginRedirect = 'some_redirect'
this.passport.authenticate.callsArgWith(1, null, this.user, this.info)
})
- afterEach(function() {
+ afterEach(function () {
delete this.req.session.postLoginRedirect
})
- it('should call finishLogin', function() {
+ it('should call finishLogin', function () {
this.AuthenticationController.passportLogin(
this.req,
this.res,
@@ -291,13 +289,13 @@ describe('AuthenticationController', function() {
})
})
- describe('when authenticate does not produce a user', function() {
- beforeEach(function() {
+ describe('when authenticate does not produce a user', function () {
+ beforeEach(function () {
this.info = { text: 'a', type: 'b' }
this.passport.authenticate.callsArgWith(1, null, false, this.info)
})
- it('should not call finishLogin', function() {
+ it('should not call finishLogin', function () {
this.AuthenticationController.passportLogin(
this.req,
this.res,
@@ -306,7 +304,7 @@ describe('AuthenticationController', function() {
this.AuthenticationController.finishLogin.callCount.should.equal(0)
})
- it('should not send a json response with redirect', function() {
+ it('should not send a json response with redirect', function () {
this.AuthenticationController.passportLogin(
this.req,
this.res,
@@ -319,8 +317,8 @@ describe('AuthenticationController', function() {
})
})
- describe('doPassportLogin', function() {
- beforeEach(function() {
+ describe('doPassportLogin', function () {
+ beforeEach(function () {
this.AuthenticationController._recordFailedLogin = sinon.stub()
this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
this.Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [])
@@ -335,14 +333,14 @@ describe('AuthenticationController', function() {
this.cb = sinon.stub()
})
- describe('when the preDoPassportLogin hooks produce an info object', function() {
- beforeEach(function() {
+ describe('when the preDoPassportLogin hooks produce an info object', function () {
+ beforeEach(function () {
this.Modules.hooks.fire = sinon
.stub()
.callsArgWith(3, null, [null, { redir: '/somewhere' }, null])
})
- it('should stop early and call done with this info object', function(done) {
+ it('should stop early and call done with this info object', function (done) {
this.AuthenticationController.doPassportLogin(
this.req,
this.req.body.email,
@@ -358,12 +356,12 @@ describe('AuthenticationController', function() {
})
})
- describe('when the users rate limit', function() {
- beforeEach(function() {
+ describe('when the users rate limit', function () {
+ beforeEach(function () {
this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
})
- it('should block the request if the limit has been exceeded', function(done) {
+ it('should block the request if the limit has been exceeded', function (done) {
this.AuthenticationController.doPassportLogin(
this.req,
this.req.body.email,
@@ -376,8 +374,8 @@ describe('AuthenticationController', function() {
})
})
- describe('when the user is authenticated', function() {
- beforeEach(function() {
+ describe('when the user is authenticated', function () {
+ beforeEach(function () {
this.cb = sinon.stub()
this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
this.AuthenticationManager.authenticate = sinon
@@ -392,19 +390,19 @@ describe('AuthenticationController', function() {
)
})
- it('should attempt to authorise the user', function() {
+ it('should attempt to authorise the user', function () {
this.AuthenticationManager.authenticate
.calledWith({ email: this.email.toLowerCase() }, this.password)
.should.equal(true)
})
- it("should establish the user's session", function() {
+ it("should establish the user's session", function () {
this.cb.calledWith(null, this.user).should.equal(true)
})
})
- describe('when the user is not authenticated', function() {
- beforeEach(function() {
+ describe('when the user is not authenticated', function () {
+ beforeEach(function () {
this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
this.AuthenticationManager.authenticate = sinon
.stub()
@@ -418,7 +416,7 @@ describe('AuthenticationController', function() {
)
})
- it('should not establish the login', function() {
+ it('should not establish the login', function () {
this.cb.callCount.should.equal(1)
this.cb.calledWith(null, false)
// @res.body.should.exist
@@ -428,17 +426,17 @@ describe('AuthenticationController', function() {
// text: 'Your email or password were incorrect. Please try again',
// type: 'error'
- it('should not setup the user data in the background', function() {
+ it('should not setup the user data in the background', function () {
this.UserHandler.setupLoginData.called.should.equal(false)
})
- it('should record a failed login', function() {
+ it('should record a failed login', function () {
this.AuthenticationController._recordFailedLogin.called.should.equal(
true
)
})
- it('should log the failed login', function() {
+ it('should log the failed login', function () {
this.logger.log
.calledWith({ email: this.email.toLowerCase() }, 'failed log in')
.should.equal(true)
@@ -446,19 +444,19 @@ describe('AuthenticationController', function() {
})
})
- describe('getLoggedInUserId', function() {
- beforeEach(function() {
+ describe('getLoggedInUserId', function () {
+ beforeEach(function () {
this.req = { session: {} }
})
- it('should return the user id from the session', function() {
+ it('should return the user id from the session', function () {
this.user_id = '2134'
this.req.session.user = { _id: this.user_id }
const result = this.AuthenticationController.getLoggedInUserId(this.req)
expect(result).to.equal(this.user_id)
})
- it('should return user for passport session', function() {
+ it('should return user for passport session', function () {
this.user_id = '2134'
this.req.session = {
passport: {
@@ -471,26 +469,26 @@ describe('AuthenticationController', function() {
expect(result).to.equal(this.user_id)
})
- it('should return null if there is no user on the session', function() {
+ it('should return null if there is no user on the session', function () {
const result = this.AuthenticationController.getLoggedInUserId(this.req)
expect(result).to.equal(null)
})
- it('should return null if there is no session', function() {
+ it('should return null if there is no session', function () {
this.req = {}
const result = this.AuthenticationController.getLoggedInUserId(this.req)
expect(result).to.equal(null)
})
- it('should return null if there is no req', function() {
+ it('should return null if there is no req', function () {
this.req = {}
const result = this.AuthenticationController.getLoggedInUserId(this.req)
expect(result).to.equal(null)
})
})
- describe('requireLogin', function() {
- beforeEach(function() {
+ describe('requireLogin', function () {
+ beforeEach(function () {
this.user = {
_id: 'user-id-123',
email: 'user@sharelatex.com'
@@ -498,8 +496,8 @@ describe('AuthenticationController', function() {
this.middleware = this.AuthenticationController.requireLogin()
})
- describe('when the user is logged in', function() {
- beforeEach(function() {
+ describe('when the user is logged in', function () {
+ beforeEach(function () {
this.req.session = {
user: (this.user = {
_id: 'user-id-123',
@@ -509,20 +507,20 @@ describe('AuthenticationController', function() {
this.middleware(this.req, this.res, this.next)
})
- it('should call the next method in the chain', function() {
+ it('should call the next method in the chain', function () {
this.next.called.should.equal(true)
})
})
- describe('when the user is not logged in', function() {
- beforeEach(function() {
+ describe('when the user is not logged in', function () {
+ beforeEach(function () {
this.req.session = {}
this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
this.req.query = {}
this.middleware(this.req, this.res, this.next)
})
- it('should redirect to the register or login page', function() {
+ it('should redirect to the register or login page', function () {
this.AuthenticationController._redirectToLoginOrRegisterPage
.calledWith(this.req, this.res)
.should.equal(true)
@@ -530,8 +528,8 @@ describe('AuthenticationController', function() {
})
})
- describe('validateUserSession', function() {
- beforeEach(function() {
+ describe('validateUserSession', function () {
+ beforeEach(function () {
this.user = {
_id: 'user-id-123',
email: 'user@sharelatex.com'
@@ -539,20 +537,20 @@ describe('AuthenticationController', function() {
this.middleware = this.AuthenticationController.validateUserSession()
})
- describe('when the user has a session token', function() {
- beforeEach(function() {
+ describe('when the user has a session token', function () {
+ beforeEach(function () {
this.req.user = this.user
this.SessionStoreManager.hasValidationToken = sinon.stub().returns(true)
this.middleware(this.req, this.res, this.next)
})
- it('should call the next method in the chain', function() {
+ it('should call the next method in the chain', function () {
this.next.called.should.equal(true)
})
})
- describe('when the user does not have a session token', function() {
- beforeEach(function() {
+ describe('when the user does not have a session token', function () {
+ beforeEach(function () {
this.req.session = {
user: this.user,
regenerate: sinon.stub().yields()
@@ -566,11 +564,11 @@ describe('AuthenticationController', function() {
this.middleware(this.req, this.res, this.next)
})
- it('should destroy the current session', function() {
+ it('should destroy the current session', function () {
this.req.session.regenerate.called.should.equal(true)
})
- it('should redirect to the register or login page', function() {
+ it('should redirect to the register or login page', function () {
this.AuthenticationController._redirectToLoginOrRegisterPage
.calledWith(this.req, this.res)
.should.equal(true)
@@ -578,16 +576,16 @@ describe('AuthenticationController', function() {
})
})
- describe('requireOauth', function() {
- beforeEach(function() {
+ describe('requireOauth', function () {
+ beforeEach(function () {
this.res.send = sinon.stub()
this.res.status = sinon.stub().returns(this.res)
this.res.sendStatus = sinon.stub()
this.middleware = this.AuthenticationController.requireOauth()
})
- describe('when Oauth2Server authenticates', function() {
- beforeEach(function() {
+ describe('when Oauth2Server authenticates', function () {
+ beforeEach(function () {
this.token = {
accessToken: 'token',
user: 'user'
@@ -596,41 +594,41 @@ describe('AuthenticationController', function() {
this.middleware(this.req, this.res, this.next)
})
- it('should set oauth_token on request', function() {
+ it('should set oauth_token on request', function () {
this.req.oauth_token.should.equal(this.token)
})
- it('should set oauth on request', function() {
+ it('should set oauth on request', function () {
this.req.oauth.access_token.should.equal(this.token.accessToken)
})
- it('should set oauth_user on request', function() {
+ it('should set oauth_user on request', function () {
this.req.oauth_user.should.equal('user')
})
- it('should call next', function() {
+ it('should call next', function () {
this.next.should.have.been.calledOnce
})
})
- describe('when Oauth2Server returns 401 error', function() {
- beforeEach(function() {
+ describe('when Oauth2Server returns 401 error', function () {
+ beforeEach(function () {
this.Oauth2Server.server.authenticate.yields({ code: 401 })
this.middleware(this.req, this.res, this.next)
})
- it('should return 401 error', function() {
+ it('should return 401 error', function () {
this.res.status.should.have.been.calledWith(401)
})
- it('should not call next', function() {
+ it('should not call next', function () {
this.next.should.have.not.been.calledOnce
})
})
})
- describe('requireGlobalLogin', function() {
- beforeEach(function() {
+ describe('requireGlobalLogin', function () {
+ beforeEach(function () {
this.req.headers = {}
this.AuthenticationController.httpAuth = sinon.stub()
this.setRedirect = sinon.spy(
@@ -639,12 +637,12 @@ describe('AuthenticationController', function() {
)
})
- afterEach(function() {
+ afterEach(function () {
this.setRedirect.restore()
})
- describe('with white listed url', function() {
- beforeEach(function() {
+ describe('with white listed url', function () {
+ beforeEach(function () {
this.AuthenticationController.addEndpointToLoginWhitelist('/login')
this.req._parsedUrl.pathname = '/login'
this.AuthenticationController.requireGlobalLogin(
@@ -654,13 +652,13 @@ describe('AuthenticationController', function() {
)
})
- it('should call next() directly', function() {
+ it('should call next() directly', function () {
this.next.called.should.equal(true)
})
})
- describe('with white listed url and a query string', function() {
- beforeEach(function() {
+ describe('with white listed url and a query string', function () {
+ beforeEach(function () {
this.AuthenticationController.addEndpointToLoginWhitelist('/login')
this.req._parsedUrl.pathname = '/login'
this.req.url = '/login?query=something'
@@ -671,13 +669,13 @@ describe('AuthenticationController', function() {
)
})
- it('should call next() directly', function() {
+ it('should call next() directly', function () {
this.next.called.should.equal(true)
})
})
- describe('with http auth', function() {
- beforeEach(function() {
+ describe('with http auth', function () {
+ beforeEach(function () {
this.req.headers.authorization = 'Mock Basic Auth'
this.AuthenticationController.requireGlobalLogin(
this.req,
@@ -686,15 +684,15 @@ describe('AuthenticationController', function() {
)
})
- it('should pass the request onto httpAuth', function() {
+ it('should pass the request onto httpAuth', function () {
this.AuthenticationController.httpAuth
.calledWith(this.req, this.res, this.next)
.should.equal(true)
})
})
- describe('with a user session', function() {
- beforeEach(function() {
+ describe('with a user session', function () {
+ beforeEach(function () {
this.req.session = { user: { mock: 'user', _id: 'some_id' } }
this.AuthenticationController.requireGlobalLogin(
this.req,
@@ -703,13 +701,13 @@ describe('AuthenticationController', function() {
)
})
- it('should call next() directly', function() {
+ it('should call next() directly', function () {
this.next.called.should.equal(true)
})
})
- describe('with no login credentials', function() {
- beforeEach(function() {
+ describe('with no login credentials', function () {
+ beforeEach(function () {
this.req.session = {}
this.AuthenticationController.requireGlobalLogin(
this.req,
@@ -718,19 +716,19 @@ describe('AuthenticationController', function() {
)
})
- it('should have called setRedirectInSession', function() {
+ it('should have called setRedirectInSession', function () {
this.setRedirect.callCount.should.equal(1)
})
- it('should redirect to the /login page', function() {
+ it('should redirect to the /login page', function () {
this.res.redirectedTo.should.equal('/login')
})
})
})
- describe('httpAuth', function() {
- describe('with http auth', function() {
- it('should error with incorrect user', function(done) {
+ describe('httpAuth', function () {
+ describe('with http auth', function () {
+ it('should error with incorrect user', function (done) {
this.req.headers = {
authorization: `Basic ${Buffer.from('user:nope').toString('base64')}`
}
@@ -741,7 +739,7 @@ describe('AuthenticationController', function() {
this.AuthenticationController.httpAuth(this.req, this.req)
})
- it('should error with incorrect password', function(done) {
+ it('should error with incorrect password', function (done) {
this.req.headers = {
authorization: `Basic ${Buffer.from('valid-test-user:nope').toString(
'base64'
@@ -754,7 +752,7 @@ describe('AuthenticationController', function() {
this.AuthenticationController.httpAuth(this.req, this.req)
})
- it('should fail with empty pass', function(done) {
+ it('should fail with empty pass', function (done) {
this.req.headers = {
authorization: `Basic ${Buffer.from(`invalid-test-user:`).toString(
'base64'
@@ -767,7 +765,7 @@ describe('AuthenticationController', function() {
this.AuthenticationController.httpAuth(this.req, this.req)
})
- it('should succeed with correct user/pass', function(done) {
+ it('should succeed with correct user/pass', function (done) {
this.req.headers = {
authorization: `Basic ${Buffer.from(
`valid-test-user:${this.httpAuthUsers['valid-test-user']}`
@@ -778,8 +776,8 @@ describe('AuthenticationController', function() {
})
})
- describe('_redirectToLoginOrRegisterPage', function() {
- beforeEach(function() {
+ describe('_redirectToLoginOrRegisterPage', function () {
+ beforeEach(function () {
this.middleware = this.AuthenticationController.requireLogin(
(this.options = { load_from_db: false })
)
@@ -789,13 +787,13 @@ describe('AuthenticationController', function() {
this.req.query = {}
})
- describe('they have come directly to the url', function() {
- beforeEach(function() {
+ describe('they have come directly to the url', function () {
+ beforeEach(function () {
this.req.query = {}
this.middleware(this.req, this.res, this.next)
})
- it('should redirect to the login page', function() {
+ it('should redirect to the login page', function () {
this.AuthenticationController._redirectToRegisterPage
.calledWith(this.req, this.res)
.should.equal(false)
@@ -805,13 +803,13 @@ describe('AuthenticationController', function() {
})
})
- describe('they have come via a templates link', function() {
- beforeEach(function() {
+ describe('they have come via a templates link', function () {
+ beforeEach(function () {
this.req.query.zipUrl = 'something'
this.middleware(this.req, this.res, this.next)
})
- it('should redirect to the register page', function() {
+ it('should redirect to the register page', function () {
this.AuthenticationController._redirectToRegisterPage
.calledWith(this.req, this.res)
.should.equal(true)
@@ -821,13 +819,13 @@ describe('AuthenticationController', function() {
})
})
- describe('they have been invited to a project', function() {
- beforeEach(function() {
+ describe('they have been invited to a project', function () {
+ beforeEach(function () {
this.req.query.project_name = 'something'
this.middleware(this.req, this.res, this.next)
})
- it('should redirect to the register page', function() {
+ it('should redirect to the register page', function () {
this.AuthenticationController._redirectToRegisterPage
.calledWith(this.req, this.res)
.should.equal(true)
@@ -838,21 +836,21 @@ describe('AuthenticationController', function() {
})
})
- describe('_redirectToRegisterPage', function() {
- beforeEach(function() {
+ describe('_redirectToRegisterPage', function () {
+ beforeEach(function () {
this.req.path = '/target/url'
this.req.query = { extra_query: 'foo' }
this.AuthenticationController._redirectToRegisterPage(this.req, this.res)
})
- it('should redirect to the register page with a query string attached', function() {
+ it('should redirect to the register page with a query string attached', function () {
this.req.session.postLoginRedirect.should.equal(
'/target/url?extra_query=foo'
)
this.res.redirectedTo.should.equal('/register?extra_query=foo')
})
- it('should log out a message', function() {
+ it('should log out a message', function () {
this.logger.log
.calledWith(
{ url: this.url },
@@ -862,14 +860,14 @@ describe('AuthenticationController', function() {
})
})
- describe('_redirectToLoginPage', function() {
- beforeEach(function() {
+ describe('_redirectToLoginPage', function () {
+ beforeEach(function () {
this.req.path = '/target/url'
this.req.query = { extra_query: 'foo' }
this.AuthenticationController._redirectToLoginPage(this.req, this.res)
})
- it('should redirect to the register page with a query string attached', function() {
+ it('should redirect to the register page with a query string attached', function () {
this.req.session.postLoginRedirect.should.equal(
'/target/url?extra_query=foo'
)
@@ -877,8 +875,8 @@ describe('AuthenticationController', function() {
})
})
- describe('_recordSuccessfulLogin', function() {
- beforeEach(function() {
+ describe('_recordSuccessfulLogin', function () {
+ beforeEach(function () {
this.UserUpdater.updateUser = sinon.stub().callsArg(2)
this.AuthenticationController._recordSuccessfulLogin(
this.user._id,
@@ -886,49 +884,49 @@ describe('AuthenticationController', function() {
)
})
- it('should increment the user.login.success metric', function() {
+ it('should increment the user.login.success metric', function () {
this.Metrics.inc.calledWith('user.login.success').should.equal(true)
})
- it("should update the user's login count and last logged in date", function() {
+ it("should update the user's login count and last logged in date", function () {
this.UserUpdater.updateUser.args[0][1].$set.lastLoggedIn.should.not.equal(
undefined
)
this.UserUpdater.updateUser.args[0][1].$inc.loginCount.should.equal(1)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('_recordFailedLogin', function() {
- beforeEach(function() {
+ describe('_recordFailedLogin', function () {
+ beforeEach(function () {
this.AuthenticationController._recordFailedLogin(this.callback)
})
- it('should increment the user.login.failed metric', function() {
+ it('should increment the user.login.failed metric', function () {
this.Metrics.inc.calledWith('user.login.failed').should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('setRedirectInSession', function() {
- beforeEach(function() {
+ describe('setRedirectInSession', function () {
+ beforeEach(function () {
this.req = { session: {} }
this.req.path = '/somewhere'
this.req.query = { one: '1' }
})
- it('should set redirect property on session', function() {
+ it('should set redirect property on session', function () {
this.AuthenticationController.setRedirectInSession(this.req)
expect(this.req.session.postLoginRedirect).to.equal('/somewhere?one=1')
})
- it('should set the supplied value', function() {
+ it('should set the supplied value', function () {
this.AuthenticationController.setRedirectInSession(
this.req,
'/somewhere/specific'
@@ -936,7 +934,7 @@ describe('AuthenticationController', function() {
expect(this.req.session.postLoginRedirect).to.equal('/somewhere/specific')
})
- it('should not allow open redirects', function() {
+ it('should not allow open redirects', function () {
this.AuthenticationController.setRedirectInSession(
this.req,
'https://evil.com'
@@ -944,12 +942,12 @@ describe('AuthenticationController', function() {
expect(this.req.session.postLoginRedirect).to.be.undefined
})
- describe('with a png', function() {
- beforeEach(function() {
+ describe('with a png', function () {
+ beforeEach(function () {
this.req = { session: {} }
})
- it('should not set the redirect', function() {
+ it('should not set the redirect', function () {
this.AuthenticationController.setRedirectInSession(
this.req,
'/something.png'
@@ -958,12 +956,12 @@ describe('AuthenticationController', function() {
})
})
- describe('with a js path', function() {
- beforeEach(function() {
+ describe('with a js path', function () {
+ beforeEach(function () {
this.req = { session: {} }
})
- it('should not set the redirect', function() {
+ it('should not set the redirect', function () {
this.AuthenticationController.setRedirectInSession(
this.req,
'/js/something.js'
@@ -973,45 +971,45 @@ describe('AuthenticationController', function() {
})
})
- describe('_getRedirectFromSession', function() {
- it('should get redirect property from session', function() {
+ describe('_getRedirectFromSession', function () {
+ it('should get redirect property from session', function () {
this.req = { session: { postLoginRedirect: '/a?b=c' } }
expect(
this.AuthenticationController._getRedirectFromSession(this.req)
).to.equal('/a?b=c')
})
- it('should not allow open redirects', function() {
+ it('should not allow open redirects', function () {
this.req = { session: { postLoginRedirect: 'https://evil.com' } }
expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
.be.null
})
- it('handle null values', function() {
+ it('handle null values', function () {
this.req = { session: {} }
expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
.be.null
})
})
- describe('_clearRedirectFromSession', function() {
- beforeEach(function() {
+ describe('_clearRedirectFromSession', function () {
+ beforeEach(function () {
this.req = { session: { postLoginRedirect: '/a?b=c' } }
})
- it('should remove the redirect property from session', function() {
+ it('should remove the redirect property from session', function () {
this.AuthenticationController._clearRedirectFromSession(this.req)
expect(this.req.session.postLoginRedirect).to.equal(undefined)
})
})
- describe('finishLogin', function() {
+ describe('finishLogin', function () {
// - get redirect
// - async handlers
// - afterLoginSessionSetup
// - clear redirect
// - issue redir, two ways
- beforeEach(function() {
+ beforeEach(function () {
this.AuthenticationController._getRedirectFromSession = sinon
.stub()
.returns('/some/page')
@@ -1038,7 +1036,7 @@ describe('AuthenticationController', function() {
this.res.redirect = sinon.stub()
})
- it('should extract the redirect from the session', function() {
+ it('should extract the redirect from the session', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1055,7 +1053,7 @@ describe('AuthenticationController', function() {
).to.equal(true)
})
- it('should clear redirect from session', function() {
+ it('should clear redirect from session', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1072,7 +1070,7 @@ describe('AuthenticationController', function() {
).to.equal(true)
})
- it('should issue a json response with a redirect', function() {
+ it('should issue a json response with a redirect', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1088,14 +1086,14 @@ describe('AuthenticationController', function() {
).to.equal(true)
})
- describe('with a non-json request', function() {
- beforeEach(function() {
+ describe('with a non-json request', function () {
+ beforeEach(function () {
this.acceptsJson.returns(false)
this.res.json = sinon.stub()
this.res.redirect = sinon.stub()
})
- it('should issue a plain redirect', function() {
+ it('should issue a plain redirect', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1112,12 +1110,12 @@ describe('AuthenticationController', function() {
})
})
- describe('when user is flagged to reconfirm', function() {
- beforeEach(function() {
+ describe('when user is flagged to reconfirm', function () {
+ beforeEach(function () {
this.req.session = {}
this.user.must_reconfirm = true
})
- it('should redirect to reconfirm page', function() {
+ it('should redirect to reconfirm page', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1132,8 +1130,8 @@ describe('AuthenticationController', function() {
})
})
- describe('preFinishLogin hook', function() {
- it('call hook and proceed', function() {
+ describe('preFinishLogin hook', function () {
+ it('call hook and proceed', function () {
this.Modules.hooks.fire = sinon.stub().yields(null, [])
this.AuthenticationController.finishLogin(
this.user,
@@ -1151,7 +1149,7 @@ describe('AuthenticationController', function() {
expect(this.AsyncFormHelper.redirect.called).to.equal(true)
})
- it('stop if hook has redirected', function(done) {
+ it('stop if hook has redirected', function (done) {
this.Modules.hooks.fire = sinon
.stub()
.yields(null, [{ doNotFinish: true }])
@@ -1166,7 +1164,7 @@ describe('AuthenticationController', function() {
done()
})
- it('call next with hook errors', function(done) {
+ it('call next with hook errors', function (done) {
this.Modules.hooks.fire = sinon.stub().yields(new Error())
this.AuthenticationController.finishLogin(
this.user,
@@ -1181,8 +1179,8 @@ describe('AuthenticationController', function() {
})
})
- describe('UserAuditLog', function() {
- it('should add an audit log entry', function() {
+ describe('UserAuditLog', function () {
+ it('should add an audit log entry', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1197,7 +1195,7 @@ describe('AuthenticationController', function() {
)
})
- it('should add an audit log entry before logging the user in', function() {
+ it('should add an audit log entry before logging the user in', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1209,7 +1207,7 @@ describe('AuthenticationController', function() {
)
})
- it('should not log the user in without an audit log entry', function() {
+ it('should not log the user in without an audit log entry', function () {
const theError = new Error()
this.UserAuditLogHandler.addEntry.yields(theError)
this.AuthenticationController.finishLogin(
@@ -1223,10 +1221,10 @@ describe('AuthenticationController', function() {
})
})
- describe('_afterLoginSessionSetup', function() {
- beforeEach(function() {})
+ describe('_afterLoginSessionSetup', function () {
+ beforeEach(function () {})
- it('should call req.login', function() {
+ it('should call req.login', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1236,7 +1234,7 @@ describe('AuthenticationController', function() {
this.req.login.callCount.should.equal(1)
})
- it('should erase the CSRF secret', function() {
+ it('should erase the CSRF secret', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1246,7 +1244,7 @@ describe('AuthenticationController', function() {
expect(this.req.session.csrfSecret).to.not.exist
})
- it('should call req.session.save', function() {
+ it('should call req.session.save', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1256,7 +1254,7 @@ describe('AuthenticationController', function() {
this.req.session.save.callCount.should.equal(1)
})
- it('should call UserSessionsManager.trackSession', function() {
+ it('should call UserSessionsManager.trackSession', function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1266,14 +1264,14 @@ describe('AuthenticationController', function() {
this.UserSessionsManager.trackSession.callCount.should.equal(1)
})
- describe('when req.session.save produces an error', function() {
- beforeEach(function() {
+ describe('when req.session.save produces an error', function () {
+ beforeEach(function () {
this.req.session.save = sinon
.stub()
.callsArgWith(0, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1286,7 +1284,7 @@ describe('AuthenticationController', function() {
)
})
- it('should not call UserSessionsManager.trackSession', function(done) {
+ it('should not call UserSessionsManager.trackSession', function (done) {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1301,8 +1299,8 @@ describe('AuthenticationController', function() {
})
})
- describe('_loginAsyncHandlers', function() {
- beforeEach(function() {
+ describe('_loginAsyncHandlers', function () {
+ beforeEach(function () {
this.AuthenticationController.finishLogin(
this.user,
this.req,
@@ -1311,33 +1309,33 @@ describe('AuthenticationController', function() {
)
})
- it('should call identifyUser', function() {
+ it('should call identifyUser', function () {
this.AnalyticsManager.identifyUser
.calledWith(this.user._id, this.req.sessionID)
.should.equal(true)
})
- it('should setup the user data in the background', function() {
+ it('should setup the user data in the background', function () {
this.UserHandler.setupLoginData.calledWith(this.user).should.equal(true)
})
- it('should set res.session.justLoggedIn', function() {
+ it('should set res.session.justLoggedIn', function () {
this.req.session.justLoggedIn.should.equal(true)
})
- it('should record the successful login', function() {
+ it('should record the successful login', function () {
this.AuthenticationController._recordSuccessfulLogin
.calledWith(this.user._id)
.should.equal(true)
})
- it('should tell the rate limiter that there was a success for that email', function() {
+ it('should tell the rate limiter that there was a success for that email', function () {
this.LoginRateLimiter.recordSuccessfulLogin
.calledWith(this.user.email)
.should.equal(true)
})
- it('should log the successful login', function() {
+ it('should log the successful login', function () {
this.logger.log
.calledWith(
{ email: this.user.email, user_id: this.user._id.toString() },
@@ -1346,7 +1344,7 @@ describe('AuthenticationController', function() {
.should.equal(true)
})
- it('should track the login event', function() {
+ it('should track the login event', function () {
this.AnalyticsManager.recordEvent
.calledWith(this.user._id, 'user-logged-in')
.should.equal(true)
diff --git a/services/web/test/unit/src/Authentication/AuthenticationManagerTests.js b/services/web/test/unit/src/Authentication/AuthenticationManagerTests.js
index 2df236ca5a..c39c4f3eef 100644
--- a/services/web/test/unit/src/Authentication/AuthenticationManagerTests.js
+++ b/services/web/test/unit/src/Authentication/AuthenticationManagerTests.js
@@ -7,8 +7,8 @@ const AuthenticationErrors = require('../../../../app/src/Features/Authenticatio
const modulePath =
'../../../../app/src/Features/Authentication/AuthenticationManager.js'
-describe('AuthenticationManager', function() {
- beforeEach(function() {
+describe('AuthenticationManager', function () {
+ beforeEach(function () {
this.settings = { security: { bcryptRounds: 4 } }
this.AuthenticationManager = SandboxedModule.require(modulePath, {
requires: {
@@ -28,8 +28,8 @@ describe('AuthenticationManager', function() {
this.callback = sinon.stub()
})
- describe('with real bcrypt', function() {
- beforeEach(function() {
+ describe('with real bcrypt', function () {
+ beforeEach(function () {
const bcrypt = require('bcrypt')
this.bcrypt.compare = bcrypt.compare
this.bcrypt.getRounds = bcrypt.getRounds
@@ -40,8 +40,8 @@ describe('AuthenticationManager', function() {
'$2a$04$DcU/3UeJf1PfsWlQL./5H.rGTQL1Z1iyz6r7bN9Do8cy6pVWxpKpK'
})
- describe('authenticate', function() {
- beforeEach(function() {
+ describe('authenticate', function () {
+ beforeEach(function () {
this.user = {
_id: 'user-id',
email: (this.email = 'USER@sharelatex.com')
@@ -49,8 +49,8 @@ describe('AuthenticationManager', function() {
this.User.findOne = sinon.stub().callsArgWith(1, null, this.user)
})
- describe('when the hashed password matches', function() {
- beforeEach(function(done) {
+ describe('when the hashed password matches', function () {
+ beforeEach(function (done) {
this.unencryptedPassword = 'testpassword'
this.user.hashedPassword = this.testPassword
this.AuthenticationManager.authenticate(
@@ -63,17 +63,17 @@ describe('AuthenticationManager', function() {
)
})
- it('should look up the correct user in the database', function() {
+ it('should look up the correct user in the database', function () {
this.User.findOne.calledWith({ email: this.email }).should.equal(true)
})
- it('should return the user', function() {
+ it('should return the user', function () {
this.callback.calledWith(null, this.user).should.equal(true)
})
})
- describe('when the encrypted passwords do not match', function() {
- beforeEach(function() {
+ describe('when the encrypted passwords do not match', function () {
+ beforeEach(function () {
this.AuthenticationManager.authenticate(
{ email: this.email },
'notthecorrectpassword',
@@ -81,14 +81,14 @@ describe('AuthenticationManager', function() {
)
})
- it('should not return the user', function() {
+ it('should not return the user', function () {
this.callback.calledWith(null, null).should.equal(true)
})
})
})
- describe('setUserPasswordInV2', function() {
- beforeEach(function() {
+ describe('setUserPasswordInV2', function () {
+ beforeEach(function () {
this.user = {
_id: '5c8791477192a80b5e76ca7e',
email: (this.email = 'USER@sharelatex.com')
@@ -100,7 +100,7 @@ describe('AuthenticationManager', function() {
.callsArgWith(2, null, { modifiedCount: 1 })
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
this.AuthenticationManager.setUserPasswordInV2(
this.user,
'testpassword',
@@ -112,7 +112,7 @@ describe('AuthenticationManager', function() {
)
})
- it('should set the hashed password', function(done) {
+ it('should set the hashed password', function (done) {
this.AuthenticationManager.setUserPasswordInV2(
this.user,
'testpassword',
@@ -131,9 +131,9 @@ describe('AuthenticationManager', function() {
})
})
- describe('authenticate', function() {
- describe('when the user exists in the database', function() {
- beforeEach(function() {
+ describe('authenticate', function () {
+ describe('when the user exists in the database', function () {
+ beforeEach(function () {
this.user = {
_id: 'user-id',
email: (this.email = 'USER@sharelatex.com')
@@ -142,8 +142,8 @@ describe('AuthenticationManager', function() {
this.User.findOne = sinon.stub().callsArgWith(1, null, this.user)
})
- describe('when the hashed password matches', function() {
- beforeEach(function(done) {
+ describe('when the hashed password matches', function () {
+ beforeEach(function (done) {
this.user.hashedPassword = this.hashedPassword = 'asdfjadflasdf'
this.bcrypt.compare = sinon.stub().callsArgWith(2, null, true)
this.bcrypt.getRounds = sinon.stub().returns(4)
@@ -157,23 +157,23 @@ describe('AuthenticationManager', function() {
)
})
- it('should look up the correct user in the database', function() {
+ it('should look up the correct user in the database', function () {
this.User.findOne.calledWith({ email: this.email }).should.equal(true)
})
- it('should check that the passwords match', function() {
+ it('should check that the passwords match', function () {
this.bcrypt.compare
.calledWith(this.unencryptedPassword, this.hashedPassword)
.should.equal(true)
})
- it('should return the user', function() {
+ it('should return the user', function () {
this.callback.calledWith(null, this.user).should.equal(true)
})
})
- describe('when the encrypted passwords do not match', function() {
- beforeEach(function() {
+ describe('when the encrypted passwords do not match', function () {
+ beforeEach(function () {
this.AuthenticationManager.authenticate(
{ email: this.email },
this.unencryptedPassword,
@@ -181,13 +181,13 @@ describe('AuthenticationManager', function() {
)
})
- it('should not return the user', function() {
+ it('should not return the user', function () {
this.callback.calledWith(null, null).should.equal(true)
})
})
- describe('when the hashed password matches but the number of rounds is too low', function() {
- beforeEach(function(done) {
+ describe('when the hashed password matches but the number of rounds is too low', function () {
+ beforeEach(function (done) {
this.user.hashedPassword = this.hashedPassword = 'asdfjadflasdf'
this.bcrypt.compare = sinon.stub().callsArgWith(2, null, true)
this.bcrypt.getRounds = sinon.stub().returns(1)
@@ -204,33 +204,33 @@ describe('AuthenticationManager', function() {
)
})
- it('should look up the correct user in the database', function() {
+ it('should look up the correct user in the database', function () {
this.User.findOne.calledWith({ email: this.email }).should.equal(true)
})
- it('should check that the passwords match', function() {
+ it('should check that the passwords match', function () {
this.bcrypt.compare
.calledWith(this.unencryptedPassword, this.hashedPassword)
.should.equal(true)
})
- it('should check the number of rounds', function() {
+ it('should check the number of rounds', function () {
this.bcrypt.getRounds.called.should.equal(true)
})
- it('should set the users password (with a higher number of rounds)', function() {
+ it('should set the users password (with a higher number of rounds)', function () {
this.AuthenticationManager.setUserPassword
.calledWith(this.user, this.unencryptedPassword)
.should.equal(true)
})
- it('should return the user', function() {
+ it('should return the user', function () {
this.callback.calledWith(null, this.user).should.equal(true)
})
})
- describe('when the hashed password matches but the number of rounds is too low, but upgrades disabled', function() {
- beforeEach(function(done) {
+ describe('when the hashed password matches but the number of rounds is too low, but upgrades disabled', function () {
+ beforeEach(function (done) {
this.settings.security.disableBcryptRoundsUpgrades = true
this.user.hashedPassword = this.hashedPassword = 'asdfjadflasdf'
this.bcrypt.compare = sinon.stub().callsArgWith(2, null, true)
@@ -248,24 +248,24 @@ describe('AuthenticationManager', function() {
)
})
- it('should not check the number of rounds', function() {
+ it('should not check the number of rounds', function () {
this.bcrypt.getRounds.called.should.equal(false)
})
- it('should not set the users password (with a higher number of rounds)', function() {
+ it('should not set the users password (with a higher number of rounds)', function () {
this.AuthenticationManager.setUserPassword
.calledWith(this.user, this.unencryptedPassword)
.should.equal(false)
})
- it('should return the user', function() {
+ it('should return the user', function () {
this.callback.calledWith(null, this.user).should.equal(true)
})
})
})
- describe('when the user does not exist in the database', function() {
- beforeEach(function() {
+ describe('when the user does not exist in the database', function () {
+ beforeEach(function () {
this.User.findOne = sinon.stub().callsArgWith(1, null, null)
this.AuthenticationManager.authenticate(
{ email: this.email },
@@ -274,15 +274,15 @@ describe('AuthenticationManager', function() {
)
})
- it('should not return a user', function() {
+ it('should not return a user', function () {
this.callback.calledWith(null, null).should.equal(true)
})
})
})
- describe('validateEmail', function() {
- describe('valid', function() {
- it('should return null', function() {
+ describe('validateEmail', function () {
+ describe('valid', function () {
+ it('should return null', function () {
const result = this.AuthenticationManager.validateEmail(
'foo@example.com'
)
@@ -290,14 +290,14 @@ describe('AuthenticationManager', function() {
})
})
- describe('invalid', function() {
- it('should return validation error object for no email', function() {
+ describe('invalid', function () {
+ it('should return validation error object for no email', function () {
const result = this.AuthenticationManager.validateEmail('')
expect(result).to.an.instanceOf(AuthenticationErrors.InvalidEmailError)
expect(result.message).to.equal('email not valid')
})
- it('should return validation error object for invalid', function() {
+ it('should return validation error object for invalid', function () {
const result = this.AuthenticationManager.validateEmail('notanemail')
expect(result).to.be.an.instanceOf(
AuthenticationErrors.InvalidEmailError
@@ -307,15 +307,15 @@ describe('AuthenticationManager', function() {
})
})
- describe('validatePassword', function() {
- beforeEach(function() {
+ describe('validatePassword', function () {
+ beforeEach(function () {
// 73 characters:
this.longPassword =
'0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef012345678'
})
- describe('with a null password', function() {
- it('should return an error', function() {
+ describe('with a null password', function () {
+ it('should return an error', function () {
const result = this.AuthenticationManager.validatePassword()
expect(result).to.be.an.instanceOf(
@@ -326,9 +326,9 @@ describe('AuthenticationManager', function() {
})
})
- describe('password length', function() {
- describe('with the default password length options', function() {
- it('should reject passwords that are too short', function() {
+ describe('password length', function () {
+ describe('with the default password length options', function () {
+ it('should reject passwords that are too short', function () {
const result1 = this.AuthenticationManager.validatePassword('')
expect(result1).to.be.an.instanceOf(
AuthenticationErrors.InvalidPasswordError
@@ -344,7 +344,7 @@ describe('AuthenticationManager', function() {
expect(result2.info.code).to.equal('too_short')
})
- it('should reject passwords that are too long', function() {
+ it('should reject passwords that are too long', function () {
const result = this.AuthenticationManager.validatePassword(
this.longPassword
)
@@ -356,15 +356,15 @@ describe('AuthenticationManager', function() {
expect(result.info.code).to.equal('too_long')
})
- it('should accept passwords that are a good length', function() {
+ it('should accept passwords that are a good length', function () {
expect(
this.AuthenticationManager.validatePassword('l337h4x0r')
).to.equal(null)
})
})
- describe('when the password length is specified in settings', function() {
- beforeEach(function() {
+ describe('when the password length is specified in settings', function () {
+ beforeEach(function () {
this.settings.passwordStrengthOptions = {
length: {
min: 10,
@@ -373,7 +373,7 @@ describe('AuthenticationManager', function() {
}
})
- it('should reject passwords that are too short', function() {
+ it('should reject passwords that are too short', function () {
const result = this.AuthenticationManager.validatePassword(
'012345678'
)
@@ -385,13 +385,13 @@ describe('AuthenticationManager', function() {
expect(result.info.code).to.equal('too_short')
})
- it('should accept passwords of exactly minimum length', function() {
+ it('should accept passwords of exactly minimum length', function () {
expect(
this.AuthenticationManager.validatePassword('0123456789')
).to.equal(null)
})
- it('should reject passwords that are too long', function() {
+ it('should reject passwords that are too long', function () {
const result = this.AuthenticationManager.validatePassword(
'0123456789abc'
)
@@ -403,15 +403,15 @@ describe('AuthenticationManager', function() {
expect(result.info.code).to.equal('too_long')
})
- it('should accept passwords of exactly maximum length', function() {
+ it('should accept passwords of exactly maximum length', function () {
expect(
this.AuthenticationManager.validatePassword('0123456789ab')
).to.equal(null)
})
})
- describe('when the maximum password length is set to >72 characters in settings', function() {
- beforeEach(function() {
+ describe('when the maximum password length is set to >72 characters in settings', function () {
+ beforeEach(function () {
this.settings.passwordStrengthOptions = {
length: {
max: 128
@@ -419,7 +419,7 @@ describe('AuthenticationManager', function() {
}
})
- it('should still reject passwords > 72 characters in length', function() {
+ it('should still reject passwords > 72 characters in length', function () {
const result = this.AuthenticationManager.validatePassword(
this.longPassword
)
@@ -433,9 +433,9 @@ describe('AuthenticationManager', function() {
})
})
- describe('allowed characters', function() {
- describe('with the default settings for allowed characters', function() {
- it('should allow passwords with valid characters', function() {
+ describe('allowed characters', function () {
+ describe('with the default settings for allowed characters', function () {
+ it('should allow passwords with valid characters', function () {
expect(
this.AuthenticationManager.validatePassword(
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
@@ -448,7 +448,7 @@ describe('AuthenticationManager', function() {
).to.equal(null)
})
- it('should not allow passwords with invalid characters', function() {
+ it('should not allow passwords with invalid characters', function () {
const result = this.AuthenticationManager.validatePassword(
'correct horse battery staple'
)
@@ -463,8 +463,8 @@ describe('AuthenticationManager', function() {
})
})
- describe('when valid characters are overridden in settings', function() {
- beforeEach(function() {
+ describe('when valid characters are overridden in settings', function () {
+ beforeEach(function () {
this.settings.passwordStrengthOptions = {
chars: {
symbols: ' '
@@ -472,7 +472,7 @@ describe('AuthenticationManager', function() {
}
})
- it('should allow passwords with valid characters', function() {
+ it('should allow passwords with valid characters', function () {
expect(
this.AuthenticationManager.validatePassword(
'correct horse battery staple'
@@ -480,7 +480,7 @@ describe('AuthenticationManager', function() {
).to.equal(null)
})
- it('should disallow passwords with invalid characters', function() {
+ it('should disallow passwords with invalid characters', function () {
const result = this.AuthenticationManager.validatePassword(
'1234567890@#$%^&*()-_=+[]{};:<>/?!£€.,'
)
@@ -495,14 +495,14 @@ describe('AuthenticationManager', function() {
})
})
- describe('when allowAnyChars is set', function() {
- beforeEach(function() {
+ describe('when allowAnyChars is set', function () {
+ beforeEach(function () {
this.settings.passwordStrengthOptions = {
allowAnyChars: true
}
})
- it('should allow any characters', function() {
+ it('should allow any characters', function () {
expect(
this.AuthenticationManager.validatePassword(
'correct horse battery staple'
@@ -518,8 +518,8 @@ describe('AuthenticationManager', function() {
})
})
- describe('setUserPassword', function() {
- beforeEach(function() {
+ describe('setUserPassword', function () {
+ beforeEach(function () {
this.user_id = ObjectId()
this.user = {
_id: this.user_id,
@@ -534,8 +534,8 @@ describe('AuthenticationManager', function() {
this.db.users.updateOne = sinon.stub().callsArg(2)
})
- describe('too long', function() {
- beforeEach(function() {
+ describe('too long', function () {
+ beforeEach(function () {
this.settings.passwordStrengthOptions = {
length: {
max: 10
@@ -544,7 +544,7 @@ describe('AuthenticationManager', function() {
this.password = 'dsdsadsadsadsadsadkjsadjsadjsadljs'
})
- it('should return and error', function(done) {
+ it('should return and error', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
@@ -555,7 +555,7 @@ describe('AuthenticationManager', function() {
)
})
- it('should not start the bcrypt process', function(done) {
+ it('should not start the bcrypt process', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
@@ -568,12 +568,12 @@ describe('AuthenticationManager', function() {
})
})
- describe('contains full email', function() {
- beforeEach(function() {
+ describe('contains full email', function () {
+ beforeEach(function () {
this.password = `some${this.user.email}password`
})
- it('should reject the password', function(done) {
+ it('should reject the password', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
@@ -586,12 +586,12 @@ describe('AuthenticationManager', function() {
})
})
- describe('contains first part of email', function() {
- beforeEach(function() {
+ describe('contains first part of email', function () {
+ beforeEach(function () {
this.password = `some${this.user.email.split('@')[0]}password`
})
- it('should reject the password', function(done) {
+ it('should reject the password', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
@@ -604,8 +604,8 @@ describe('AuthenticationManager', function() {
})
})
- describe('too short', function() {
- beforeEach(function() {
+ describe('too short', function () {
+ beforeEach(function () {
this.settings.passwordStrengthOptions = {
length: {
max: 10,
@@ -615,7 +615,7 @@ describe('AuthenticationManager', function() {
this.password = 'dsd'
})
- it('should return and error', function(done) {
+ it('should return and error', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
@@ -626,7 +626,7 @@ describe('AuthenticationManager', function() {
)
})
- it('should not start the bcrypt process', function(done) {
+ it('should not start the bcrypt process', function (done) {
this.AuthenticationManager.setUserPassword(
this.user,
this.password,
@@ -639,8 +639,8 @@ describe('AuthenticationManager', function() {
})
})
- describe('successful password set attempt', function() {
- beforeEach(function() {
+ describe('successful password set attempt', function () {
+ beforeEach(function () {
this.UserGetter.getUser = sinon.stub().yields(null, { overleaf: null })
this.AuthenticationManager.setUserPassword(
this.user,
@@ -649,7 +649,7 @@ describe('AuthenticationManager', function() {
)
})
- it("should update the user's password in the database", function() {
+ it("should update the user's password in the database", function () {
const { args } = this.db.users.updateOne.lastCall
expect(args[0]).to.deep.equal({
_id: ObjectId(this.user_id.toString())
@@ -664,12 +664,12 @@ describe('AuthenticationManager', function() {
})
})
- it('should hash the password', function() {
+ it('should hash the password', function () {
this.bcrypt.genSalt.calledWith(4).should.equal(true)
this.bcrypt.hash.calledWith(this.password, this.salt).should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Authorization/AuthorizationManagerTests.js b/services/web/test/unit/src/Authorization/AuthorizationManagerTests.js
index 79ae4a13d3..9a7d88eba8 100644
--- a/services/web/test/unit/src/Authorization/AuthorizationManagerTests.js
+++ b/services/web/test/unit/src/Authorization/AuthorizationManagerTests.js
@@ -19,8 +19,8 @@ const SandboxedModule = require('sandboxed-module')
const Errors = require('../../../../app/src/Features/Errors/Errors.js')
const { ObjectId } = require('mongodb')
-describe('AuthorizationManager', function() {
- beforeEach(function() {
+describe('AuthorizationManager', function () {
+ beforeEach(function () {
this.AuthorizationManager = SandboxedModule.require(modulePath, {
requires: {
mongodb: { ObjectId },
@@ -44,8 +44,8 @@ describe('AuthorizationManager', function() {
return (this.callback = sinon.stub())
})
- describe('isRestrictedUser', function() {
- it('should produce the correct values', function() {
+ describe('isRestrictedUser', function () {
+ it('should produce the correct values', function () {
const notRestrictedScenarios = [
[null, 'readAndWrite', false],
['id', 'readAndWrite', true],
@@ -72,22 +72,22 @@ describe('AuthorizationManager', function() {
})
})
- describe('getPrivilegeLevelForProject', function() {
- beforeEach(function() {
+ describe('getPrivilegeLevelForProject', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject = sinon.stub()
this.AuthorizationManager.isUserSiteAdmin = sinon.stub()
return (this.CollaboratorsGetter.getMemberIdPrivilegeLevel = sinon.stub())
})
- describe('with a token-based project', function() {
- beforeEach(function() {
+ describe('with a token-based project', function () {
+ beforeEach(function () {
return this.ProjectGetter.getProject
.withArgs(this.project_id, { publicAccesLevel: 1 })
.yields(null, { publicAccesLevel: 'tokenBased' })
})
- describe('with a user_id with a privilege level', function() {
- beforeEach(function() {
+ describe('with a user_id with a privilege level', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.user_id)
.yields(null, false)
@@ -102,15 +102,15 @@ describe('AuthorizationManager', function() {
)
})
- it("should return the user's privilege level", function() {
+ it("should return the user's privilege level", function () {
return this.callback
.calledWith(null, 'readOnly', false, false)
.should.equal(true)
})
})
- describe('with a user_id with no privilege level', function() {
- beforeEach(function() {
+ describe('with a user_id with no privilege level', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.user_id)
.yields(null, false)
@@ -125,15 +125,15 @@ describe('AuthorizationManager', function() {
)
})
- it('should return false', function() {
+ it('should return false', function () {
return this.callback
.calledWith(null, false, false, false)
.should.equal(true)
})
})
- describe('with a user_id who is an admin', function() {
- beforeEach(function() {
+ describe('with a user_id who is an admin', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.user_id)
.yields(null, true)
@@ -148,16 +148,16 @@ describe('AuthorizationManager', function() {
)
})
- it('should return the user as an owner', function() {
+ it('should return the user as an owner', function () {
return this.callback
.calledWith(null, 'owner', false, true)
.should.equal(true)
})
})
- describe('with no user (anonymous)', function() {
- describe('when the token is not valid', function() {
- beforeEach(function() {
+ describe('with no user (anonymous)', function () {
+ describe('when the token is not valid', function () {
+ beforeEach(function () {
this.TokenAccessHandler.validateTokenForAnonymousAccess = sinon
.stub()
.withArgs(this.project_id, this.token)
@@ -170,33 +170,33 @@ describe('AuthorizationManager', function() {
)
})
- it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function() {
+ it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function () {
return this.CollaboratorsGetter.getMemberIdPrivilegeLevel.called.should.equal(
false
)
})
- it('should not call AuthorizationManager.isUserSiteAdmin', function() {
+ it('should not call AuthorizationManager.isUserSiteAdmin', function () {
return this.AuthorizationManager.isUserSiteAdmin.called.should.equal(
false
)
})
- it('should check if the token is valid', function() {
+ it('should check if the token is valid', function () {
return this.TokenAccessHandler.validateTokenForAnonymousAccess
.calledWith(this.project_id, this.token)
.should.equal(true)
})
- it('should return false', function() {
+ it('should return false', function () {
return this.callback
.calledWith(null, false, false, false)
.should.equal(true)
})
})
- describe('when the token is valid for read-and-write', function() {
- beforeEach(function() {
+ describe('when the token is valid for read-and-write', function () {
+ beforeEach(function () {
this.TokenAccessHandler.validateTokenForAnonymousAccess = sinon
.stub()
.withArgs(this.project_id, this.token)
@@ -209,33 +209,33 @@ describe('AuthorizationManager', function() {
)
})
- it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function() {
+ it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function () {
return this.CollaboratorsGetter.getMemberIdPrivilegeLevel.called.should.equal(
false
)
})
- it('should not call AuthorizationManager.isUserSiteAdmin', function() {
+ it('should not call AuthorizationManager.isUserSiteAdmin', function () {
return this.AuthorizationManager.isUserSiteAdmin.called.should.equal(
false
)
})
- it('should check if the token is valid', function() {
+ it('should check if the token is valid', function () {
return this.TokenAccessHandler.validateTokenForAnonymousAccess
.calledWith(this.project_id, this.token)
.should.equal(true)
})
- it('should give read-write access', function() {
+ it('should give read-write access', function () {
return this.callback
.calledWith(null, 'readAndWrite', false)
.should.equal(true)
})
})
- describe('when the token is valid for read-only', function() {
- beforeEach(function() {
+ describe('when the token is valid for read-only', function () {
+ beforeEach(function () {
this.TokenAccessHandler.validateTokenForAnonymousAccess = sinon
.stub()
.withArgs(this.project_id, this.token)
@@ -248,25 +248,25 @@ describe('AuthorizationManager', function() {
)
})
- it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function() {
+ it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function () {
return this.CollaboratorsGetter.getMemberIdPrivilegeLevel.called.should.equal(
false
)
})
- it('should not call AuthorizationManager.isUserSiteAdmin', function() {
+ it('should not call AuthorizationManager.isUserSiteAdmin', function () {
return this.AuthorizationManager.isUserSiteAdmin.called.should.equal(
false
)
})
- it('should check if the token is valid', function() {
+ it('should check if the token is valid', function () {
return this.TokenAccessHandler.validateTokenForAnonymousAccess
.calledWith(this.project_id, this.token)
.should.equal(true)
})
- it('should give read-only access', function() {
+ it('should give read-only access', function () {
return this.callback
.calledWith(null, 'readOnly', false)
.should.equal(true)
@@ -275,15 +275,15 @@ describe('AuthorizationManager', function() {
})
})
- describe('with a private project', function() {
- beforeEach(function() {
+ describe('with a private project', function () {
+ beforeEach(function () {
return this.ProjectGetter.getProject
.withArgs(this.project_id, { publicAccesLevel: 1 })
.yields(null, { publicAccesLevel: 'private' })
})
- describe('with a user_id with a privilege level', function() {
- beforeEach(function() {
+ describe('with a user_id with a privilege level', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.user_id)
.yields(null, false)
@@ -298,15 +298,15 @@ describe('AuthorizationManager', function() {
)
})
- it("should return the user's privilege level", function() {
+ it("should return the user's privilege level", function () {
return this.callback
.calledWith(null, 'readOnly', false, false)
.should.equal(true)
})
})
- describe('with a user_id with no privilege level', function() {
- beforeEach(function() {
+ describe('with a user_id with no privilege level', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.user_id)
.yields(null, false)
@@ -321,15 +321,15 @@ describe('AuthorizationManager', function() {
)
})
- it('should return false', function() {
+ it('should return false', function () {
return this.callback
.calledWith(null, false, false, false)
.should.equal(true)
})
})
- describe('with a user_id who is an admin', function() {
- beforeEach(function() {
+ describe('with a user_id who is an admin', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.user_id)
.yields(null, true)
@@ -344,15 +344,15 @@ describe('AuthorizationManager', function() {
)
})
- it('should return the user as an owner', function() {
+ it('should return the user as an owner', function () {
return this.callback
.calledWith(null, 'owner', false, true)
.should.equal(true)
})
})
- describe('with no user (anonymous)', function() {
- beforeEach(function() {
+ describe('with no user (anonymous)', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject(
null,
this.project_id,
@@ -361,19 +361,19 @@ describe('AuthorizationManager', function() {
)
})
- it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function() {
+ it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function () {
return this.CollaboratorsGetter.getMemberIdPrivilegeLevel.called.should.equal(
false
)
})
- it('should not call AuthorizationManager.isUserSiteAdmin', function() {
+ it('should not call AuthorizationManager.isUserSiteAdmin', function () {
return this.AuthorizationManager.isUserSiteAdmin.called.should.equal(
false
)
})
- it('should return false', function() {
+ it('should return false', function () {
return this.callback
.calledWith(null, false, false, false)
.should.equal(true)
@@ -381,15 +381,15 @@ describe('AuthorizationManager', function() {
})
})
- describe('with a public project', function() {
- beforeEach(function() {
+ describe('with a public project', function () {
+ beforeEach(function () {
return this.ProjectGetter.getProject
.withArgs(this.project_id, { publicAccesLevel: 1 })
.yields(null, { publicAccesLevel: 'readAndWrite' })
})
- describe('with a user_id with a privilege level', function() {
- beforeEach(function() {
+ describe('with a user_id with a privilege level', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.user_id)
.yields(null, false)
@@ -404,15 +404,15 @@ describe('AuthorizationManager', function() {
)
})
- it("should return the user's privilege level", function() {
+ it("should return the user's privilege level", function () {
return this.callback
.calledWith(null, 'readOnly', false)
.should.equal(true)
})
})
- describe('with a user_id with no privilege level', function() {
- beforeEach(function() {
+ describe('with a user_id with no privilege level', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.user_id)
.yields(null, false)
@@ -427,15 +427,15 @@ describe('AuthorizationManager', function() {
)
})
- it('should return the public privilege level', function() {
+ it('should return the public privilege level', function () {
return this.callback
.calledWith(null, 'readAndWrite', true)
.should.equal(true)
})
})
- describe('with a user_id who is an admin', function() {
- beforeEach(function() {
+ describe('with a user_id who is an admin', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.user_id)
.yields(null, true)
@@ -450,15 +450,15 @@ describe('AuthorizationManager', function() {
)
})
- it('should return the user as an owner', function() {
+ it('should return the user as an owner', function () {
return this.callback
.calledWith(null, 'owner', false)
.should.equal(true)
})
})
- describe('with no user (anonymous)', function() {
- beforeEach(function() {
+ describe('with no user (anonymous)', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject(
null,
this.project_id,
@@ -467,19 +467,19 @@ describe('AuthorizationManager', function() {
)
})
- it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function() {
+ it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function () {
return this.CollaboratorsGetter.getMemberIdPrivilegeLevel.called.should.equal(
false
)
})
- it('should not call AuthorizationManager.isUserSiteAdmin', function() {
+ it('should not call AuthorizationManager.isUserSiteAdmin', function () {
return this.AuthorizationManager.isUserSiteAdmin.called.should.equal(
false
)
})
- it('should return the public privilege level', function() {
+ it('should return the public privilege level', function () {
return this.callback
.calledWith(null, 'readAndWrite', true)
.should.equal(true)
@@ -487,14 +487,14 @@ describe('AuthorizationManager', function() {
})
})
- describe("when the project doesn't exist", function() {
- beforeEach(function() {
+ describe("when the project doesn't exist", function () {
+ beforeEach(function () {
return this.ProjectGetter.getProject
.withArgs(this.project_id, { publicAccesLevel: 1 })
.yields(null, null)
})
- it('should return a NotFoundError', function() {
+ it('should return a NotFoundError', function () {
return this.AuthorizationManager.getPrivilegeLevelForProject(
this.user_id,
this.project_id,
@@ -504,8 +504,8 @@ describe('AuthorizationManager', function() {
})
})
- describe('when the project id is not valid', function() {
- beforeEach(function() {
+ describe('when the project id is not valid', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.user_id)
.yields(null, false)
@@ -514,7 +514,7 @@ describe('AuthorizationManager', function() {
.yields(null, 'readOnly')
})
- it('should return a error', function(done) {
+ it('should return a error', function (done) {
return this.AuthorizationManager.getPrivilegeLevelForProject(
undefined,
'not project id',
@@ -529,19 +529,19 @@ describe('AuthorizationManager', function() {
})
})
- describe('canUserReadProject', function() {
- beforeEach(function() {
+ describe('canUserReadProject', function () {
+ beforeEach(function () {
return (this.AuthorizationManager.getPrivilegeLevelForProject = sinon.stub())
})
- describe('when user is owner', function() {
- beforeEach(function() {
+ describe('when user is owner', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'owner', false)
})
- it('should return true', function(done) {
+ it('should return true', function (done) {
return this.AuthorizationManager.canUserReadProject(
this.user_id,
this.project_id,
@@ -554,14 +554,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has read-write access', function() {
- beforeEach(function() {
+ describe('when user has read-write access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'readAndWrite', false)
})
- it('should return true', function(done) {
+ it('should return true', function (done) {
return this.AuthorizationManager.canUserReadProject(
this.user_id,
this.project_id,
@@ -574,14 +574,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has read-only access', function() {
- beforeEach(function() {
+ describe('when user has read-only access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'readOnly', false)
})
- it('should return true', function(done) {
+ it('should return true', function (done) {
return this.AuthorizationManager.canUserReadProject(
this.user_id,
this.project_id,
@@ -594,14 +594,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has no access', function() {
- beforeEach(function() {
+ describe('when user has no access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, false, false)
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.canUserReadProject(
this.user_id,
this.project_id,
@@ -615,19 +615,19 @@ describe('AuthorizationManager', function() {
})
})
- describe('canUserWriteProjectContent', function() {
- beforeEach(function() {
+ describe('canUserWriteProjectContent', function () {
+ beforeEach(function () {
return (this.AuthorizationManager.getPrivilegeLevelForProject = sinon.stub())
})
- describe('when user is owner', function() {
- beforeEach(function() {
+ describe('when user is owner', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'owner', false)
})
- it('should return true', function(done) {
+ it('should return true', function (done) {
return this.AuthorizationManager.canUserWriteProjectContent(
this.user_id,
this.project_id,
@@ -640,14 +640,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has read-write access', function() {
- beforeEach(function() {
+ describe('when user has read-write access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'readAndWrite', false)
})
- it('should return true', function(done) {
+ it('should return true', function (done) {
return this.AuthorizationManager.canUserWriteProjectContent(
this.user_id,
this.project_id,
@@ -660,14 +660,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has read-only access', function() {
- beforeEach(function() {
+ describe('when user has read-only access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'readOnly', false)
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.canUserWriteProjectContent(
this.user_id,
this.project_id,
@@ -680,14 +680,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has no access', function() {
- beforeEach(function() {
+ describe('when user has no access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, false, false)
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.canUserWriteProjectContent(
this.user_id,
this.project_id,
@@ -701,19 +701,19 @@ describe('AuthorizationManager', function() {
})
})
- describe('canUserWriteProjectSettings', function() {
- beforeEach(function() {
+ describe('canUserWriteProjectSettings', function () {
+ beforeEach(function () {
return (this.AuthorizationManager.getPrivilegeLevelForProject = sinon.stub())
})
- describe('when user is owner', function() {
- beforeEach(function() {
+ describe('when user is owner', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'owner', false)
})
- it('should return true', function(done) {
+ it('should return true', function (done) {
return this.AuthorizationManager.canUserWriteProjectSettings(
this.user_id,
this.project_id,
@@ -726,14 +726,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has read-write access as a collaborator', function() {
- beforeEach(function() {
+ describe('when user has read-write access as a collaborator', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'readAndWrite', false)
})
- it('should return true', function(done) {
+ it('should return true', function (done) {
return this.AuthorizationManager.canUserWriteProjectSettings(
this.user_id,
this.project_id,
@@ -746,14 +746,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has read-write access as the public', function() {
- beforeEach(function() {
+ describe('when user has read-write access as the public', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'readAndWrite', true)
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.canUserWriteProjectSettings(
this.user_id,
this.project_id,
@@ -766,14 +766,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has read-only access', function() {
- beforeEach(function() {
+ describe('when user has read-only access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'readOnly', false)
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.canUserWriteProjectSettings(
this.user_id,
this.project_id,
@@ -786,14 +786,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has no access', function() {
- beforeEach(function() {
+ describe('when user has no access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, false, false)
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.canUserWriteProjectSettings(
this.user_id,
this.project_id,
@@ -807,19 +807,19 @@ describe('AuthorizationManager', function() {
})
})
- describe('canUserAdminProject', function() {
- beforeEach(function() {
+ describe('canUserAdminProject', function () {
+ beforeEach(function () {
return (this.AuthorizationManager.getPrivilegeLevelForProject = sinon.stub())
})
- describe('when user is owner', function() {
- beforeEach(function() {
+ describe('when user is owner', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'owner', false)
})
- it('should return true', function(done) {
+ it('should return true', function (done) {
return this.AuthorizationManager.canUserAdminProject(
this.user_id,
this.project_id,
@@ -832,14 +832,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has read-write access', function() {
- beforeEach(function() {
+ describe('when user has read-write access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'readAndWrite', false)
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.canUserAdminProject(
this.user_id,
this.project_id,
@@ -852,14 +852,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has read-only access', function() {
- beforeEach(function() {
+ describe('when user has read-only access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, 'readOnly', false)
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.canUserAdminProject(
this.user_id,
this.project_id,
@@ -872,14 +872,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user has no access', function() {
- beforeEach(function() {
+ describe('when user has no access', function () {
+ beforeEach(function () {
return this.AuthorizationManager.getPrivilegeLevelForProject
.withArgs(this.user_id, this.project_id, this.token)
.yields(null, false, false)
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.canUserAdminProject(
this.user_id,
this.project_id,
@@ -893,19 +893,19 @@ describe('AuthorizationManager', function() {
})
})
- describe('isUserSiteAdmin', function() {
- beforeEach(function() {
+ describe('isUserSiteAdmin', function () {
+ beforeEach(function () {
return (this.User.findOne = sinon.stub())
})
- describe('when user is admin', function() {
- beforeEach(function() {
+ describe('when user is admin', function () {
+ beforeEach(function () {
return this.User.findOne
.withArgs({ _id: this.user_id }, { isAdmin: 1 })
.yields(null, { isAdmin: true })
})
- it('should return true', function(done) {
+ it('should return true', function (done) {
return this.AuthorizationManager.isUserSiteAdmin(
this.user_id,
(error, isAdmin) => {
@@ -916,14 +916,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user is not admin', function() {
- beforeEach(function() {
+ describe('when user is not admin', function () {
+ beforeEach(function () {
return this.User.findOne
.withArgs({ _id: this.user_id }, { isAdmin: 1 })
.yields(null, { isAdmin: false })
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.isUserSiteAdmin(
this.user_id,
(error, isAdmin) => {
@@ -934,14 +934,14 @@ describe('AuthorizationManager', function() {
})
})
- describe('when user is not found', function() {
- beforeEach(function() {
+ describe('when user is not found', function () {
+ beforeEach(function () {
return this.User.findOne
.withArgs({ _id: this.user_id }, { isAdmin: 1 })
.yields(null, null)
})
- it('should return false', function(done) {
+ it('should return false', function (done) {
return this.AuthorizationManager.isUserSiteAdmin(
this.user_id,
(error, isAdmin) => {
@@ -952,8 +952,8 @@ describe('AuthorizationManager', function() {
})
})
- describe('when no user is passed', function() {
- it('should return false', function(done) {
+ describe('when no user is passed', function () {
+ it('should return false', function (done) {
return this.AuthorizationManager.isUserSiteAdmin(
null,
(error, isAdmin) => {
diff --git a/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js b/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js
index ebee3a8834..0deba99cc4 100644
--- a/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js
+++ b/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js
@@ -6,8 +6,8 @@ const Errors = require('../../../../app/src/Features/Errors/Errors.js')
const MODULE_PATH =
'../../../../app/src/Features/Authorization/AuthorizationMiddleware.js'
-describe('AuthorizationMiddleware', function() {
- beforeEach(function() {
+describe('AuthorizationMiddleware', function () {
+ beforeEach(function () {
this.userId = 'user-id-123'
this.project_id = 'project-id-123'
this.token = 'some-token'
@@ -23,10 +23,7 @@ describe('AuthorizationMiddleware', function() {
getRequestToken: sinon.stub().returns(this.token)
}
this.ObjectId = {
- isValid: sinon
- .stub()
- .withArgs(this.project_id)
- .returns(true)
+ isValid: sinon.stub().withArgs(this.project_id).returns(true)
}
this.AuthorizationManager = {}
this.AuthorizationMiddleware = SandboxedModule.require(MODULE_PATH, {
@@ -46,12 +43,12 @@ describe('AuthorizationMiddleware', function() {
this.next = sinon.stub()
})
- describe('_getUserId', function() {
- beforeEach(function() {
+ describe('_getUserId', function () {
+ beforeEach(function () {
this.req = {}
})
- it('should get the user from session', function(done) {
+ it('should get the user from session', function (done) {
this.AuthenticationController.getLoggedInUserId = sinon
.stub()
.returns('1234')
@@ -62,7 +59,7 @@ describe('AuthorizationMiddleware', function() {
})
})
- it('should get oauth_user from request', function(done) {
+ it('should get oauth_user from request', function (done) {
this.AuthenticationController.getLoggedInUserId = sinon
.stub()
.returns(null)
@@ -74,7 +71,7 @@ describe('AuthorizationMiddleware', function() {
})
})
- it('should fall back to null', function(done) {
+ it('should fall back to null', function (done) {
this.AuthenticationController.getLoggedInUserId = sinon
.stub()
.returns(null)
@@ -94,19 +91,19 @@ describe('AuthorizationMiddleware', function() {
}
Object.entries(METHODS_TO_TEST).forEach(
([middlewareMethod, managerMethod]) => {
- describe(middlewareMethod, function() {
- beforeEach(function() {
+ describe(middlewareMethod, function () {
+ beforeEach(function () {
this.req.params = { project_id: this.project_id }
this.AuthorizationManager[managerMethod] = sinon.stub()
this.AuthorizationMiddleware.redirectToRestricted = sinon.stub()
})
- describe('with missing project_id', function() {
- beforeEach(function() {
+ describe('with missing project_id', function () {
+ beforeEach(function () {
this.req.params = {}
})
- it('should return an error to next', function() {
+ it('should return an error to next', function () {
this.AuthorizationMiddleware[middlewareMethod](
this.req,
this.res,
@@ -118,19 +115,19 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('with logged in user', function() {
- beforeEach(function() {
+ describe('with logged in user', function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(this.userId)
})
- describe('when user has permission', function() {
- beforeEach(function() {
+ describe('when user has permission', function () {
+ beforeEach(function () {
this.AuthorizationManager[managerMethod]
.withArgs(this.userId, this.project_id, this.token)
.yields(null, true)
})
- it('should return next', function() {
+ it('should return next', function () {
this.AuthorizationMiddleware[middlewareMethod](
this.req,
this.res,
@@ -140,14 +137,14 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe("when user doesn't have permission", function() {
- beforeEach(function() {
+ describe("when user doesn't have permission", function () {
+ beforeEach(function () {
this.AuthorizationManager[managerMethod]
.withArgs(this.userId, this.project_id, this.token)
.yields(null, false)
})
- it('should raise a 403', function() {
+ it('should raise a 403', function () {
this.AuthorizationMiddleware[middlewareMethod](
this.req,
this.res,
@@ -161,16 +158,16 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('with anonymous user', function() {
- describe('when user has permission', function() {
- beforeEach(function() {
+ describe('with anonymous user', function () {
+ describe('when user has permission', function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(null)
this.AuthorizationManager[managerMethod]
.withArgs(null, this.project_id, this.token)
.yields(null, true)
})
- it('should return next', function() {
+ it('should return next', function () {
this.AuthorizationMiddleware[middlewareMethod](
this.req,
this.res,
@@ -180,15 +177,15 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe("when user doesn't have permission", function() {
- beforeEach(function() {
+ describe("when user doesn't have permission", function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(null)
this.AuthorizationManager[managerMethod]
.withArgs(null, this.project_id, this.token)
.yields(null, false)
})
- it('should redirect to redirectToRestricted', function() {
+ it('should redirect to redirectToRestricted', function () {
this.AuthorizationMiddleware[middlewareMethod](
this.req,
this.res,
@@ -202,13 +199,13 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('with malformed project id', function() {
- beforeEach(function() {
+ describe('with malformed project id', function () {
+ beforeEach(function () {
this.req.params = { project_id: 'blah' }
this.ObjectId.isValid = sinon.stub().returns(false)
})
- it('should return a not found error', function(done) {
+ it('should return a not found error', function (done) {
this.AuthorizationMiddleware[middlewareMethod](
this.req,
this.res,
@@ -223,19 +220,19 @@ describe('AuthorizationMiddleware', function() {
}
)
- describe('ensureUserCanAdminProject', function() {
- beforeEach(function() {
+ describe('ensureUserCanAdminProject', function () {
+ beforeEach(function () {
this.req.params = { project_id: this.project_id }
this.AuthorizationManager.canUserAdminProject = sinon.stub()
this.AuthorizationMiddleware.redirectToRestricted = sinon.stub()
})
- describe('with missing project_id', function() {
- beforeEach(function() {
+ describe('with missing project_id', function () {
+ beforeEach(function () {
this.req.params = {}
})
- it('should return an error to next', function() {
+ it('should return an error to next', function () {
this.AuthorizationMiddleware.ensureUserCanAdminProject(
this.req,
this.res,
@@ -245,19 +242,19 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('with logged in user', function() {
- beforeEach(function() {
+ describe('with logged in user', function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(this.userId)
})
- describe('when user has permission', function() {
- beforeEach(function() {
+ describe('when user has permission', function () {
+ beforeEach(function () {
this.AuthorizationManager.canUserAdminProject
.withArgs(this.userId, this.project_id, this.token)
.yields(null, true)
})
- it('should return next', function() {
+ it('should return next', function () {
this.AuthorizationMiddleware.ensureUserCanAdminProject(
this.req,
this.res,
@@ -267,14 +264,14 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe("when user doesn't have permission", function() {
- beforeEach(function() {
+ describe("when user doesn't have permission", function () {
+ beforeEach(function () {
this.AuthorizationManager.canUserAdminProject
.withArgs(this.userId, this.project_id, this.token)
.yields(null, false)
})
- it('should invoke HTTP forbidden error handler', function(done) {
+ it('should invoke HTTP forbidden error handler', function (done) {
this.HttpErrorHandler.forbidden = sinon.spy(() => done())
this.AuthorizationMiddleware.ensureUserCanAdminProject(
this.req,
@@ -284,16 +281,16 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('with anonymous user', function() {
- describe('when user has permission', function() {
- beforeEach(function() {
+ describe('with anonymous user', function () {
+ describe('when user has permission', function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(null)
this.AuthorizationManager.canUserAdminProject
.withArgs(null, this.project_id, this.token)
.yields(null, true)
})
- it('should return next', function() {
+ it('should return next', function () {
this.AuthorizationMiddleware.ensureUserCanAdminProject(
this.req,
this.res,
@@ -303,15 +300,15 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe("when user doesn't have permission", function() {
- beforeEach(function() {
+ describe("when user doesn't have permission", function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(null)
this.AuthorizationManager.canUserAdminProject
.withArgs(null, this.project_id, this.token)
.yields(null, false)
})
- it('should invoke HTTP forbidden error handler', function(done) {
+ it('should invoke HTTP forbidden error handler', function (done) {
this.HttpErrorHandler.forbidden = sinon.spy(() => done())
this.AuthorizationMiddleware.ensureUserCanAdminProject(
this.req,
@@ -321,13 +318,13 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('with malformed project id', function() {
- beforeEach(function() {
+ describe('with malformed project id', function () {
+ beforeEach(function () {
this.req.params = { project_id: 'blah' }
this.ObjectId.isValid = sinon.stub().returns(false)
})
- it('should return a not found error', function(done) {
+ it('should return a not found error', function (done) {
this.AuthorizationMiddleware.ensureUserCanAdminProject(
this.req,
this.res,
@@ -340,25 +337,25 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('ensureUserIsSiteAdmin', function() {
- beforeEach(function() {
+ describe('ensureUserIsSiteAdmin', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin = sinon.stub()
this.AuthorizationMiddleware.redirectToRestricted = sinon.stub()
})
- describe('with logged in user', function() {
- beforeEach(function() {
+ describe('with logged in user', function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(this.userId)
})
- describe('when user has permission', function() {
- beforeEach(function() {
+ describe('when user has permission', function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.userId)
.yields(null, true)
})
- it('should return next', function() {
+ it('should return next', function () {
this.AuthorizationMiddleware.ensureUserIsSiteAdmin(
this.req,
this.res,
@@ -368,14 +365,14 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe("when user doesn't have permission", function() {
- beforeEach(function() {
+ describe("when user doesn't have permission", function () {
+ beforeEach(function () {
this.AuthorizationManager.isUserSiteAdmin
.withArgs(this.userId)
.yields(null, false)
})
- it('should redirect to redirectToRestricted', function() {
+ it('should redirect to redirectToRestricted', function () {
this.AuthorizationMiddleware.ensureUserIsSiteAdmin(
this.req,
this.res,
@@ -389,16 +386,16 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('with anonymous user', function() {
- describe('when user has permission', function() {
- beforeEach(function() {
+ describe('with anonymous user', function () {
+ describe('when user has permission', function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(null)
this.AuthorizationManager.isUserSiteAdmin
.withArgs(null)
.yields(null, true)
})
- it('should return next', function() {
+ it('should return next', function () {
this.AuthorizationMiddleware.ensureUserIsSiteAdmin(
this.req,
this.res,
@@ -408,15 +405,15 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe("when user doesn't have permission", function() {
- beforeEach(function() {
+ describe("when user doesn't have permission", function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(null)
this.AuthorizationManager.isUserSiteAdmin
.withArgs(null)
.yields(null, false)
})
- it('should redirect to redirectToRestricted', function() {
+ it('should redirect to redirectToRestricted', function () {
this.AuthorizationMiddleware.ensureUserIsSiteAdmin(
this.req,
this.res,
@@ -431,14 +428,14 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('blockRestrictedUserFromProject', function() {
- beforeEach(function() {
+ describe('blockRestrictedUserFromProject', function () {
+ beforeEach(function () {
this.AuthorizationMiddleware._getUserAndProjectId = sinon
.stub()
.callsArgWith(1, null, this.userId, this.project_id)
})
- it('should issue a 401 response for a restricted user', function(done) {
+ it('should issue a 401 response for a restricted user', function (done) {
this.AuthorizationManager.isRestrictedUserForProject = sinon
.stub()
.callsArgWith(3, null, true)
@@ -459,7 +456,7 @@ describe('AuthorizationMiddleware', function() {
)
})
- it('should pass through for a regular user', function(done) {
+ it('should pass through for a regular user', function (done) {
this.AuthorizationManager.isRestrictedUserForProject = sinon
.stub()
.callsArgWith(3, null, false)
@@ -480,20 +477,20 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('ensureUserCanReadMultipleProjects', function() {
- beforeEach(function() {
+ describe('ensureUserCanReadMultipleProjects', function () {
+ beforeEach(function () {
this.AuthorizationManager.canUserReadProject = sinon.stub()
this.AuthorizationMiddleware.redirectToRestricted = sinon.stub()
this.req.query = { project_ids: 'project1,project2' }
})
- describe('with logged in user', function() {
- beforeEach(function() {
+ describe('with logged in user', function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(this.userId)
})
- describe('when user has permission to access all projects', function() {
- beforeEach(function() {
+ describe('when user has permission to access all projects', function () {
+ beforeEach(function () {
this.AuthorizationManager.canUserReadProject
.withArgs(this.userId, 'project1', this.token)
.yields(null, true)
@@ -502,7 +499,7 @@ describe('AuthorizationMiddleware', function() {
.yields(null, true)
})
- it('should return next', function() {
+ it('should return next', function () {
this.AuthorizationMiddleware.ensureUserCanReadMultipleProjects(
this.req,
this.res,
@@ -512,8 +509,8 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe("when user doesn't have permission to access one of the projects", function() {
- beforeEach(function() {
+ describe("when user doesn't have permission to access one of the projects", function () {
+ beforeEach(function () {
this.AuthorizationManager.canUserReadProject
.withArgs(this.userId, 'project1', this.token)
.yields(null, true)
@@ -522,7 +519,7 @@ describe('AuthorizationMiddleware', function() {
.yields(null, false)
})
- it('should redirect to redirectToRestricted', function() {
+ it('should redirect to redirectToRestricted', function () {
this.AuthorizationMiddleware.ensureUserCanReadMultipleProjects(
this.req,
this.res,
@@ -536,10 +533,10 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe('with anonymous user', function() {
- describe('when user has permission', function() {
- describe('when user has permission to access all projects', function() {
- beforeEach(function() {
+ describe('with anonymous user', function () {
+ describe('when user has permission', function () {
+ describe('when user has permission to access all projects', function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(null)
this.AuthorizationManager.canUserReadProject
.withArgs(null, 'project1', this.token)
@@ -549,7 +546,7 @@ describe('AuthorizationMiddleware', function() {
.yields(null, true)
})
- it('should return next', function() {
+ it('should return next', function () {
this.AuthorizationMiddleware.ensureUserCanReadMultipleProjects(
this.req,
this.res,
@@ -559,8 +556,8 @@ describe('AuthorizationMiddleware', function() {
})
})
- describe("when user doesn't have permission to access one of the projects", function() {
- beforeEach(function() {
+ describe("when user doesn't have permission to access one of the projects", function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId.returns(null)
this.AuthorizationManager.canUserReadProject
.withArgs(null, 'project1', this.token)
@@ -570,7 +567,7 @@ describe('AuthorizationMiddleware', function() {
.yields(null, false)
})
- it('should redirect to redirectToRestricted', function() {
+ it('should redirect to redirectToRestricted', function () {
this.AuthorizationMiddleware.ensureUserCanReadMultipleProjects(
this.req,
this.res,
diff --git a/services/web/test/unit/src/BetaProgram/BetaProgramControllerTests.js b/services/web/test/unit/src/BetaProgram/BetaProgramControllerTests.js
index 484d1f0682..f3ce4aaf40 100644
--- a/services/web/test/unit/src/BetaProgram/BetaProgramControllerTests.js
+++ b/services/web/test/unit/src/BetaProgram/BetaProgramControllerTests.js
@@ -7,8 +7,8 @@ const modulePath = path.join(
'../../../../app/src/Features/BetaProgram/BetaProgramController'
)
-describe('BetaProgramController', function() {
- beforeEach(function() {
+describe('BetaProgramController', function () {
+ beforeEach(function () {
this.user = {
_id: (this.user_id = 'a_simple_id'),
email: 'user@example.com',
@@ -46,38 +46,38 @@ describe('BetaProgramController', function() {
this.next = sinon.stub()
})
- describe('optIn', function() {
- beforeEach(function() {
+ describe('optIn', function () {
+ beforeEach(function () {
this.BetaProgramHandler.optIn.callsArgWith(1, null)
})
- it("should redirect to '/beta/participate'", function() {
+ it("should redirect to '/beta/participate'", function () {
this.BetaProgramController.optIn(this.req, this.res, this.next)
this.res.redirect.callCount.should.equal(1)
this.res.redirect.firstCall.args[0].should.equal('/beta/participate')
})
- it('should not call next with an error', function() {
+ it('should not call next with an error', function () {
this.BetaProgramController.optIn(this.req, this.res, this.next)
this.next.callCount.should.equal(0)
})
- it('should call BetaProgramHandler.optIn', function() {
+ it('should call BetaProgramHandler.optIn', function () {
this.BetaProgramController.optIn(this.req, this.res, this.next)
this.BetaProgramHandler.optIn.callCount.should.equal(1)
})
- describe('when BetaProgramHandler.opIn produces an error', function() {
- beforeEach(function() {
+ describe('when BetaProgramHandler.opIn produces an error', function () {
+ beforeEach(function () {
this.BetaProgramHandler.optIn.callsArgWith(1, new Error('woops'))
})
- it("should not redirect to '/beta/participate'", function() {
+ it("should not redirect to '/beta/participate'", function () {
this.BetaProgramController.optIn(this.req, this.res, this.next)
this.res.redirect.callCount.should.equal(0)
})
- it('should produce an error', function() {
+ it('should produce an error', function () {
this.BetaProgramController.optIn(this.req, this.res, this.next)
this.next.callCount.should.equal(1)
this.next.firstCall.args[0].should.be.instanceof(Error)
@@ -85,38 +85,38 @@ describe('BetaProgramController', function() {
})
})
- describe('optOut', function() {
- beforeEach(function() {
+ describe('optOut', function () {
+ beforeEach(function () {
this.BetaProgramHandler.optOut.callsArgWith(1, null)
})
- it("should redirect to '/beta/participate'", function() {
+ it("should redirect to '/beta/participate'", function () {
this.BetaProgramController.optOut(this.req, this.res, this.next)
this.res.redirect.callCount.should.equal(1)
this.res.redirect.firstCall.args[0].should.equal('/beta/participate')
})
- it('should not call next with an error', function() {
+ it('should not call next with an error', function () {
this.BetaProgramController.optOut(this.req, this.res, this.next)
this.next.callCount.should.equal(0)
})
- it('should call BetaProgramHandler.optOut', function() {
+ it('should call BetaProgramHandler.optOut', function () {
this.BetaProgramController.optOut(this.req, this.res, this.next)
this.BetaProgramHandler.optOut.callCount.should.equal(1)
})
- describe('when BetaProgramHandler.optOut produces an error', function() {
- beforeEach(function() {
+ describe('when BetaProgramHandler.optOut produces an error', function () {
+ beforeEach(function () {
this.BetaProgramHandler.optOut.callsArgWith(1, new Error('woops'))
})
- it("should not redirect to '/beta/participate'", function() {
+ it("should not redirect to '/beta/participate'", function () {
this.BetaProgramController.optOut(this.req, this.res, this.next)
this.res.redirect.callCount.should.equal(0)
})
- it('should produce an error', function() {
+ it('should produce an error', function () {
this.BetaProgramController.optOut(this.req, this.res, this.next)
this.next.callCount.should.equal(1)
this.next.firstCall.args[0].should.be.instanceof(Error)
@@ -124,29 +124,29 @@ describe('BetaProgramController', function() {
})
})
- describe('optInPage', function() {
- beforeEach(function() {
+ describe('optInPage', function () {
+ beforeEach(function () {
this.UserGetter.getUser.callsArgWith(1, null, this.user)
})
- it('should render the opt-in page', function() {
+ it('should render the opt-in page', function () {
this.BetaProgramController.optInPage(this.req, this.res, this.next)
this.res.render.callCount.should.equal(1)
const { args } = this.res.render.firstCall
args[0].should.equal('beta_program/opt_in')
})
- describe('when UserGetter.getUser produces an error', function() {
- beforeEach(function() {
+ describe('when UserGetter.getUser produces an error', function () {
+ beforeEach(function () {
this.UserGetter.getUser.callsArgWith(1, new Error('woops'))
})
- it('should not render the opt-in page', function() {
+ it('should not render the opt-in page', function () {
this.BetaProgramController.optInPage(this.req, this.res, this.next)
this.res.render.callCount.should.equal(0)
})
- it('should produce an error', function() {
+ it('should produce an error', function () {
this.BetaProgramController.optInPage(this.req, this.res, this.next)
this.next.callCount.should.equal(1)
this.next.firstCall.args[0].should.be.instanceof(Error)
diff --git a/services/web/test/unit/src/BetaProgram/BetaProgramHandlerTests.js b/services/web/test/unit/src/BetaProgram/BetaProgramHandlerTests.js
index 649b56782e..1ebe1b5563 100644
--- a/services/web/test/unit/src/BetaProgram/BetaProgramHandlerTests.js
+++ b/services/web/test/unit/src/BetaProgram/BetaProgramHandlerTests.js
@@ -7,8 +7,8 @@ const modulePath = path.join(
const sinon = require('sinon')
const { expect } = require('chai')
-describe('BetaProgramHandler', function() {
- beforeEach(function() {
+describe('BetaProgramHandler', function () {
+ beforeEach(function () {
this.user_id = 'some_id'
this.user = {
_id: this.user_id,
@@ -31,15 +31,15 @@ describe('BetaProgramHandler', function() {
})
})
- describe('optIn', function() {
- beforeEach(function() {
+ describe('optIn', function () {
+ beforeEach(function () {
this.user.betaProgram = false
this.call = callback => {
this.handler.optIn(this.user_id, callback)
}
})
- it('should call userUpdater', function(done) {
+ it('should call userUpdater', function (done) {
this.call(err => {
expect(err).to.not.exist
this.UserUpdater.promises.updateUser.callCount.should.equal(1)
@@ -47,19 +47,19 @@ describe('BetaProgramHandler', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
this.call(err => {
expect(err).to.not.exist
done()
})
})
- describe('when userUpdater produces an error', function() {
- beforeEach(function() {
+ describe('when userUpdater produces an error', function () {
+ beforeEach(function () {
this.UserUpdater.promises.updateUser.rejects()
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
this.call(err => {
expect(err).to.exist
expect(err).to.be.instanceof(Error)
@@ -69,15 +69,15 @@ describe('BetaProgramHandler', function() {
})
})
- describe('optOut', function() {
- beforeEach(function() {
+ describe('optOut', function () {
+ beforeEach(function () {
this.user.betaProgram = true
this.call = callback => {
this.handler.optOut(this.user_id, callback)
}
})
- it('should call userUpdater', function(done) {
+ it('should call userUpdater', function (done) {
this.call(err => {
expect(err).to.not.exist
this.UserUpdater.promises.updateUser.callCount.should.equal(1)
@@ -85,19 +85,19 @@ describe('BetaProgramHandler', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
this.call(err => {
expect(err).to.not.exist
done()
})
})
- describe('when userUpdater produces an error', function() {
- beforeEach(function() {
+ describe('when userUpdater produces an error', function () {
+ beforeEach(function () {
this.UserUpdater.promises.updateUser.rejects()
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
this.call(err => {
expect(err).to.exist
expect(err).to.be.instanceof(Error)
diff --git a/services/web/test/unit/src/BrandVariations/BrandVariationsHandlerTests.js b/services/web/test/unit/src/BrandVariations/BrandVariationsHandlerTests.js
index 80f948620c..6162ce4a6f 100644
--- a/services/web/test/unit/src/BrandVariations/BrandVariationsHandlerTests.js
+++ b/services/web/test/unit/src/BrandVariations/BrandVariationsHandlerTests.js
@@ -21,8 +21,8 @@ const modulePath = path.join(
'../../../../app/src/Features/BrandVariations/BrandVariationsHandler'
)
-describe('BrandVariationsHandler', function() {
- beforeEach(function() {
+describe('BrandVariationsHandler', function () {
+ beforeEach(function () {
this.settings = {
apis: {
v1: {
@@ -48,8 +48,8 @@ describe('BrandVariationsHandler', function() {
})
})
- describe('getBrandVariationById', function() {
- it('should call the callback with an error when the branding variation id is not provided', function(done) {
+ describe('getBrandVariationById', function () {
+ it('should call the callback with an error when the branding variation id is not provided', function (done) {
return this.BrandVariationsHandler.getBrandVariationById(
null,
(err, brandVariationDetails) => {
@@ -59,7 +59,7 @@ describe('BrandVariationsHandler', function() {
)
})
- it('should call the callback with an error when the request errors', function(done) {
+ it('should call the callback with an error when the request errors', function (done) {
this.V1Api.request.callsArgWith(1, new Error())
return this.BrandVariationsHandler.getBrandVariationById(
'12',
@@ -70,7 +70,7 @@ describe('BrandVariationsHandler', function() {
)
})
- it('should call the callback with branding details when request succeeds', function(done) {
+ it('should call the callback with branding details when request succeeds', function (done) {
this.V1Api.request.callsArgWith(
1,
null,
@@ -89,7 +89,7 @@ describe('BrandVariationsHandler', function() {
)
})
- it('should transform relative URLs in v1 absolute ones', function(done) {
+ it('should transform relative URLs in v1 absolute ones', function (done) {
this.mockedBrandVariationDetails.logo_url = '/journal-logo.png'
this.V1Api.request.callsArgWith(
1,
diff --git a/services/web/test/unit/src/Chat/ChatApiHandlerTests.js b/services/web/test/unit/src/Chat/ChatApiHandlerTests.js
index 2a75bd5e62..00fa10fa7f 100644
--- a/services/web/test/unit/src/Chat/ChatApiHandlerTests.js
+++ b/services/web/test/unit/src/Chat/ChatApiHandlerTests.js
@@ -20,8 +20,8 @@ const modulePath = path.join(
)
const { expect } = require('chai')
-describe('ChatApiHandler', function() {
- beforeEach(function() {
+describe('ChatApiHandler', function () {
+ beforeEach(function () {
this.settings = {
apis: {
chat: {
@@ -42,9 +42,9 @@ describe('ChatApiHandler', function() {
return (this.callback = sinon.stub())
})
- describe('sendGlobalMessage', function() {
- describe('successfully', function() {
- beforeEach(function() {
+ describe('sendGlobalMessage', function () {
+ describe('successfully', function () {
+ beforeEach(function () {
this.message = { mock: 'message' }
this.request.callsArgWith(1, null, { statusCode: 200 }, this.message)
return this.ChatApiHandler.sendGlobalMessage(
@@ -55,7 +55,7 @@ describe('ChatApiHandler', function() {
)
})
- it('should post the data to the chat api', function() {
+ it('should post the data to the chat api', function () {
return this.request
.calledWith({
url: `${this.settings.apis.chat.internal_url}/project/${this.project_id}/messages`,
@@ -68,13 +68,13 @@ describe('ChatApiHandler', function() {
.should.equal(true)
})
- it('should return the message from the post', function() {
+ it('should return the message from the post', function () {
return this.callback.calledWith(null, this.message).should.equal(true)
})
})
- describe('with a non-success status code', function() {
- beforeEach(function() {
+ describe('with a non-success status code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 })
return this.ChatApiHandler.sendGlobalMessage(
this.project_id,
@@ -84,7 +84,7 @@ describe('ChatApiHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
expect(this.callback).to.have.been.calledWith(
sinon.match.instanceOf(Error).and(sinon.match.has('statusCode', 500))
)
@@ -92,15 +92,15 @@ describe('ChatApiHandler', function() {
})
})
- describe('getGlobalMessages', function() {
- beforeEach(function() {
+ describe('getGlobalMessages', function () {
+ beforeEach(function () {
this.messages = [{ mock: 'message' }]
this.limit = 30
return (this.before = '1234')
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 200 }, this.messages)
return this.ChatApiHandler.getGlobalMessages(
this.project_id,
@@ -110,7 +110,7 @@ describe('ChatApiHandler', function() {
)
})
- it('should make get request for room to chat api', function() {
+ it('should make get request for room to chat api', function () {
return this.request
.calledWith({
method: 'GET',
@@ -124,13 +124,13 @@ describe('ChatApiHandler', function() {
.should.equal(true)
})
- it('should return the messages from the request', function() {
+ it('should return the messages from the request', function () {
return this.callback.calledWith(null, this.messages).should.equal(true)
})
})
- describe('with failure error code', function() {
- beforeEach(function() {
+ describe('with failure error code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 }, null)
return this.ChatApiHandler.getGlobalMessages(
this.project_id,
@@ -140,7 +140,7 @@ describe('ChatApiHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
expect(this.callback).to.have.been.calledWith(
sinon.match.instanceOf(Error).and(sinon.match.has('statusCode', 500))
)
diff --git a/services/web/test/unit/src/Chat/ChatControllerTests.js b/services/web/test/unit/src/Chat/ChatControllerTests.js
index 0122336e77..b6dfdee70d 100644
--- a/services/web/test/unit/src/Chat/ChatControllerTests.js
+++ b/services/web/test/unit/src/Chat/ChatControllerTests.js
@@ -22,8 +22,8 @@ const modulePath = path.join(
)
const { expect } = require('chai')
-describe('ChatController', function() {
- beforeEach(function() {
+describe('ChatController', function () {
+ beforeEach(function () {
this.user_id = 'mock-user-id'
this.settings = {}
this.ChatApiHandler = {}
@@ -54,8 +54,8 @@ describe('ChatController', function() {
}
})
- describe('sendMessage', function() {
- beforeEach(function() {
+ describe('sendMessage', function () {
+ beforeEach(function () {
this.req.body = { content: (this.content = 'message-content') }
this.UserInfoManager.getPersonalInfo = sinon
.stub()
@@ -72,38 +72,38 @@ describe('ChatController', function() {
return this.ChatController.sendMessage(this.req, this.res)
})
- it('should look up the user', function() {
+ it('should look up the user', function () {
return this.UserInfoManager.getPersonalInfo
.calledWith(this.user_id)
.should.equal(true)
})
- it('should format and inject the user into the message', function() {
+ it('should format and inject the user into the message', function () {
this.UserInfoController.formatPersonalInfo
.calledWith(this.user)
.should.equal(true)
return this.message.user.should.deep.equal(this.formatted_user)
})
- it('should tell the chat handler about the message', function() {
+ it('should tell the chat handler about the message', function () {
return this.ChatApiHandler.sendGlobalMessage
.calledWith(this.project_id, this.user_id, this.content)
.should.equal(true)
})
- it('should tell the editor real time controller about the update with the data from the chat handler', function() {
+ it('should tell the editor real time controller about the update with the data from the chat handler', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'new-chat-message', this.message)
.should.equal(true)
})
- it('should return a 204 status code', function() {
+ it('should return a 204 status code', function () {
return this.res.sendStatus.calledWith(204).should.equal(true)
})
})
- describe('getMessages', function() {
- beforeEach(function() {
+ describe('getMessages', function () {
+ beforeEach(function () {
this.req.query = {
limit: (this.limit = '30'),
before: (this.before = '12345')
@@ -115,19 +115,19 @@ describe('ChatController', function() {
return this.ChatController.getMessages(this.req, this.res)
})
- it('should ask the chat handler about the request', function() {
+ it('should ask the chat handler about the request', function () {
return this.ChatApiHandler.getGlobalMessages
.calledWith(this.project_id, this.limit, this.before)
.should.equal(true)
})
- it('should return the messages', function() {
+ it('should return the messages', function () {
return this.res.json.calledWith(this.messages).should.equal(true)
})
})
- describe('_injectUserInfoIntoThreads', function() {
- beforeEach(function() {
+ describe('_injectUserInfoIntoThreads', function () {
+ beforeEach(function () {
this.users = {
user_id_1: {
mock: 'user_1'
@@ -145,7 +145,7 @@ describe('ChatController', function() {
}))
})
- it('should inject a user object into messaged and resolved data', function(done) {
+ it('should inject a user object into messaged and resolved data', function (done) {
return this.ChatController._injectUserInfoIntoThreads(
{
thread1: {
@@ -205,7 +205,7 @@ describe('ChatController', function() {
)
})
- it('should only need to look up each user once', function(done) {
+ it('should only need to look up each user once', function (done) {
return this.ChatController._injectUserInfoIntoThreads(
[
{
diff --git a/services/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js b/services/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js
index 346aae5786..692a97e407 100644
--- a/services/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js
+++ b/services/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js
@@ -9,8 +9,8 @@ const MockResponse = require('../helpers/MockResponse')
const MODULE_PATH =
'../../../../app/src/Features/Collaborators/CollaboratorsController.js'
-describe('CollaboratorsController', function() {
- beforeEach(function() {
+describe('CollaboratorsController', function () {
+ beforeEach(function () {
this.res = new MockResponse()
this.req = new MockRequest()
@@ -66,8 +66,8 @@ describe('CollaboratorsController', function() {
})
})
- describe('removeUserFromProject', function() {
- beforeEach(function(done) {
+ describe('removeUserFromProject', function () {
+ beforeEach(function (done) {
this.req.params = {
Project_id: this.projectId,
user_id: this.user._id
@@ -78,13 +78,13 @@ describe('CollaboratorsController', function() {
this.CollaboratorsController.removeUserFromProject(this.req, this.res)
})
- it('should from the user from the project', function() {
+ it('should from the user from the project', function () {
expect(
this.CollaboratorsHandler.promises.removeUserFromProject
).to.have.been.calledWith(this.projectId, this.user._id)
})
- it('should emit a userRemovedFromProject event to the proejct', function() {
+ it('should emit a userRemovedFromProject event to the proejct', function () {
expect(this.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
this.projectId,
'userRemovedFromProject',
@@ -92,11 +92,11 @@ describe('CollaboratorsController', function() {
)
})
- it('should send the back a success response', function() {
+ it('should send the back a success response', function () {
this.res.sendStatus.calledWith(204).should.equal(true)
})
- it('should have called emitToRoom', function() {
+ it('should have called emitToRoom', function () {
expect(this.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
this.projectId,
'project:membership:changed'
@@ -104,8 +104,8 @@ describe('CollaboratorsController', function() {
})
})
- describe('removeSelfFromProject', function() {
- beforeEach(function(done) {
+ describe('removeSelfFromProject', function () {
+ beforeEach(function (done) {
this.req.params = { Project_id: this.projectId }
this.res.sendStatus = sinon.spy(() => {
done()
@@ -113,13 +113,13 @@ describe('CollaboratorsController', function() {
this.CollaboratorsController.removeSelfFromProject(this.req, this.res)
})
- it('should remove the logged in user from the project', function() {
+ it('should remove the logged in user from the project', function () {
expect(
this.CollaboratorsHandler.promises.removeUserFromProject
).to.have.been.calledWith(this.projectId, this.user._id)
})
- it('should emit a userRemovedFromProject event to the proejct', function() {
+ it('should emit a userRemovedFromProject event to the proejct', function () {
expect(this.EditorRealTimeController.emitToRoom).to.have.been.calledWith(
this.projectId,
'userRemovedFromProject',
@@ -127,19 +127,19 @@ describe('CollaboratorsController', function() {
)
})
- it('should remove the project from all tags', function() {
+ it('should remove the project from all tags', function () {
expect(
this.TagsHandler.promises.removeProjectFromAllTags
).to.have.been.calledWith(this.user._id, this.projectId)
})
- it('should return a success code', function() {
+ it('should return a success code', function () {
this.res.sendStatus.calledWith(204).should.equal(true)
})
})
- describe('getAllMembers', function() {
- beforeEach(function(done) {
+ describe('getAllMembers', function () {
+ beforeEach(function (done) {
this.req.params = { Project_id: this.projectId }
this.res.json = sinon.spy(() => {
done()
@@ -152,22 +152,22 @@ describe('CollaboratorsController', function() {
this.CollaboratorsController.getAllMembers(this.req, this.res, this.next)
})
- it('should not produce an error', function() {
+ it('should not produce an error', function () {
this.next.callCount.should.equal(0)
})
- it('should produce a json response', function() {
+ it('should produce a json response', function () {
this.res.json.callCount.should.equal(1)
this.res.json.calledWith({ members: this.members }).should.equal(true)
})
- it('should call CollaboratorsGetter.getAllInvitedMembers', function() {
+ it('should call CollaboratorsGetter.getAllInvitedMembers', function () {
expect(this.CollaboratorsGetter.promises.getAllInvitedMembers).to.have
.been.calledOnce
})
- describe('when CollaboratorsGetter.getAllInvitedMembers produces an error', function() {
- beforeEach(function(done) {
+ describe('when CollaboratorsGetter.getAllInvitedMembers produces an error', function () {
+ beforeEach(function (done) {
this.res.json = sinon.stub()
this.next = sinon.spy(() => {
done()
@@ -182,21 +182,21 @@ describe('CollaboratorsController', function() {
)
})
- it('should produce an error', function() {
+ it('should produce an error', function () {
expect(this.next).to.have.been.calledOnce
expect(this.next).to.have.been.calledWithMatch(
sinon.match.instanceOf(Error)
)
})
- it('should not produce a json response', function() {
+ it('should not produce a json response', function () {
this.res.json.callCount.should.equal(0)
})
})
})
- describe('setCollaboratorInfo', function() {
- beforeEach(function() {
+ describe('setCollaboratorInfo', function () {
+ beforeEach(function () {
this.req.params = {
Project_id: this.projectId,
user_id: this.user._id
@@ -204,7 +204,7 @@ describe('CollaboratorsController', function() {
this.req.body = { privilegeLevel: 'readOnly' }
})
- it('should set the collaborator privilege level', function(done) {
+ it('should set the collaborator privilege level', function (done) {
this.res.sendStatus = status => {
expect(status).to.equal(204)
expect(
@@ -215,7 +215,7 @@ describe('CollaboratorsController', function() {
this.CollaboratorsController.setCollaboratorInfo(this.req, this.res)
})
- it('should return a 404 when the project or collaborator is not found', function(done) {
+ it('should return a 404 when the project or collaborator is not found', function (done) {
this.HttpErrorHandler.notFound = sinon.spy((req, res) => {
expect(req).to.equal(this.req)
expect(res).to.equal(this.res)
@@ -228,7 +228,7 @@ describe('CollaboratorsController', function() {
this.CollaboratorsController.setCollaboratorInfo(this.req, this.res)
})
- it('should pass the error to the next handler when setting the privilege level fails', function(done) {
+ it('should pass the error to the next handler when setting the privilege level fails', function (done) {
this.next = sinon.spy(err => {
expect(err).instanceOf(Error)
done()
@@ -245,12 +245,12 @@ describe('CollaboratorsController', function() {
})
})
- describe('transferOwnership', function() {
- beforeEach(function() {
+ describe('transferOwnership', function () {
+ beforeEach(function () {
this.req.body = { user_id: this.user._id.toString() }
})
- it('returns 204 on success', function(done) {
+ it('returns 204 on success', function (done) {
this.res.sendStatus = status => {
expect(status).to.equal(204)
done()
@@ -258,7 +258,7 @@ describe('CollaboratorsController', function() {
this.CollaboratorsController.transferOwnership(this.req, this.res)
})
- it('returns 404 if the project does not exist', function(done) {
+ it('returns 404 if the project does not exist', function (done) {
this.HttpErrorHandler.notFound = sinon.spy((req, res, message) => {
expect(req).to.equal(this.req)
expect(res).to.equal(this.res)
@@ -271,7 +271,7 @@ describe('CollaboratorsController', function() {
this.CollaboratorsController.transferOwnership(this.req, this.res)
})
- it('returns 404 if the user does not exist', function(done) {
+ it('returns 404 if the user does not exist', function (done) {
this.HttpErrorHandler.notFound = sinon.spy((req, res, message) => {
expect(req).to.equal(this.req)
expect(res).to.equal(this.res)
@@ -284,7 +284,7 @@ describe('CollaboratorsController', function() {
this.CollaboratorsController.transferOwnership(this.req, this.res)
})
- it('invokes HTTP forbidden error handler if the user is not a collaborator', function(done) {
+ it('invokes HTTP forbidden error handler if the user is not a collaborator', function (done) {
this.HttpErrorHandler.forbidden = sinon.spy(() => done())
this.OwnershipTransferHandler.promises.transferOwnership.rejects(
new Errors.UserNotCollaboratorError()
diff --git a/services/web/test/unit/src/Collaborators/CollaboratorsGetterTests.js b/services/web/test/unit/src/Collaborators/CollaboratorsGetterTests.js
index 3626f3b384..9a9b604ff1 100644
--- a/services/web/test/unit/src/Collaborators/CollaboratorsGetterTests.js
+++ b/services/web/test/unit/src/Collaborators/CollaboratorsGetterTests.js
@@ -11,8 +11,8 @@ const MODULE_PATH = Path.join(
'../../../../app/src/Features/Collaborators/CollaboratorsGetter'
)
-describe('CollaboratorsGetter', function() {
- beforeEach(function() {
+describe('CollaboratorsGetter', function () {
+ beforeEach(function () {
this.userId = 'mock-user-id'
this.ownerRef = ObjectId()
this.readOnlyRef1 = ObjectId()
@@ -57,13 +57,13 @@ describe('CollaboratorsGetter', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
this.ProjectMock.verify()
})
- describe('getMemberIdsWithPrivilegeLevels', function() {
- describe('with project', function() {
- it('should return an array of member ids with their privilege levels', async function() {
+ describe('getMemberIdsWithPrivilegeLevels', function () {
+ describe('with project', function () {
+ it('should return an array of member ids with their privilege levels', async function () {
const result = await this.CollaboratorsGetter.promises.getMemberIdsWithPrivilegeLevels(
this.project._id
)
@@ -107,12 +107,12 @@ describe('CollaboratorsGetter', function() {
})
})
- describe('with a missing project', function() {
- beforeEach(function() {
+ describe('with a missing project', function () {
+ beforeEach(function () {
this.ProjectGetter.promises.getProject.resolves(null)
})
- it('should return a NotFoundError', async function() {
+ it('should return a NotFoundError', async function () {
await expect(
this.CollaboratorsGetter.promises.getMemberIdsWithPrivilegeLevels(
this.project._id
@@ -122,8 +122,8 @@ describe('CollaboratorsGetter', function() {
})
})
- describe('getMemberIds', function() {
- it('should return the ids', async function() {
+ describe('getMemberIds', function () {
+ it('should return the ids', async function () {
const memberIds = await this.CollaboratorsGetter.promises.getMemberIds(
this.project._id
)
@@ -139,8 +139,8 @@ describe('CollaboratorsGetter', function() {
})
})
- describe('getInvitedMemberIds', function() {
- it('should return the invited ids', async function() {
+ describe('getInvitedMemberIds', function () {
+ it('should return the invited ids', async function () {
const memberIds = await this.CollaboratorsGetter.promises.getInvitedMemberIds(
this.project._id
)
@@ -154,8 +154,8 @@ describe('CollaboratorsGetter', function() {
})
})
- describe('getInvitedMembersWithPrivilegeLevels', function() {
- beforeEach(function() {
+ describe('getInvitedMembersWithPrivilegeLevels', function () {
+ beforeEach(function () {
this.UserGetter.promises.getUser
.withArgs(this.readOnlyRef1.toString())
.resolves({ _id: this.readOnlyRef1 })
@@ -170,7 +170,7 @@ describe('CollaboratorsGetter', function() {
.resolves({ _id: this.readWriteTokenRef })
})
- it('should return an array of invited members with their privilege levels', async function() {
+ it('should return an array of invited members with their privilege levels', async function () {
const result = await this.CollaboratorsGetter.promises.getInvitedMembersWithPrivilegeLevels(
this.project._id
)
@@ -181,8 +181,8 @@ describe('CollaboratorsGetter', function() {
})
})
- describe('getMemberIdPrivilegeLevel', function() {
- it('should return the privilege level if it exists', async function() {
+ describe('getMemberIdPrivilegeLevel', function () {
+ it('should return the privilege level if it exists', async function () {
const level = await this.CollaboratorsGetter.promises.getMemberIdPrivilegeLevel(
this.readOnlyRef1,
this.project._id
@@ -190,7 +190,7 @@ describe('CollaboratorsGetter', function() {
expect(level).to.equal('readOnly')
})
- it('should return false if the member has no privilege level', async function() {
+ it('should return false if the member has no privilege level', async function () {
const level = await this.CollaboratorsGetter.promises.getMemberIdPrivilegeLevel(
this.nonMemberRef,
this.project._id
@@ -199,9 +199,9 @@ describe('CollaboratorsGetter', function() {
})
})
- describe('isUserInvitedMemberOfProject', function() {
- describe('when user is a member of the project', function() {
- it('should return true and the privilegeLevel', async function() {
+ describe('isUserInvitedMemberOfProject', function () {
+ describe('when user is a member of the project', function () {
+ it('should return true and the privilegeLevel', async function () {
const isMember = await this.CollaboratorsGetter.promises.isUserInvitedMemberOfProject(
this.readOnlyRef1
)
@@ -209,8 +209,8 @@ describe('CollaboratorsGetter', function() {
})
})
- describe('when user is not a member of the project', function() {
- it('should return false', async function() {
+ describe('when user is not a member of the project', function () {
+ it('should return false', async function () {
const isMember = await this.CollaboratorsGetter.promises.isUserInvitedMemberOfProject(
this.nonMemberRef
)
@@ -219,8 +219,8 @@ describe('CollaboratorsGetter', function() {
})
})
- describe('getProjectsUserIsMemberOf', function() {
- beforeEach(function() {
+ describe('getProjectsUserIsMemberOf', function () {
+ beforeEach(function () {
this.fields = 'mock fields'
this.ProjectMock.expects('find')
.withArgs({ collaberator_refs: this.userId }, this.fields)
@@ -259,7 +259,7 @@ describe('CollaboratorsGetter', function() {
])
})
- it('should call the callback with the projects', async function() {
+ it('should call the callback with the projects', async function () {
const projects = await this.CollaboratorsGetter.promises.getProjectsUserIsMemberOf(
this.userId,
this.fields
@@ -282,8 +282,8 @@ describe('CollaboratorsGetter', function() {
})
})
- describe('getAllInvitedMembers', function() {
- beforeEach(async function() {
+ describe('getAllInvitedMembers', function () {
+ beforeEach(async function () {
this.owningUser = {
_id: this.ownerRef,
email: 'owner@example.com',
@@ -316,11 +316,11 @@ describe('CollaboratorsGetter', function() {
)
})
- it('should produce a list of members', function() {
+ it('should produce a list of members', function () {
expect(this.result).to.deep.equal(this.views.members)
})
- it('should call ProjectEditorHandler.buildOwnerAndMembersViews', function() {
+ it('should call ProjectEditorHandler.buildOwnerAndMembersViews', function () {
expect(this.ProjectEditorHandler.buildOwnerAndMembersViews).to.have.been
.calledOnce
expect(
@@ -329,11 +329,9 @@ describe('CollaboratorsGetter', function() {
})
})
- describe('userIsTokenMember', function() {
- it('should return true when the project is found', async function() {
- this.ProjectMock.expects('findOne')
- .chain('exec')
- .resolves(this.project)
+ describe('userIsTokenMember', function () {
+ it('should return true when the project is found', async function () {
+ this.ProjectMock.expects('findOne').chain('exec').resolves(this.project)
const isMember = await this.CollaboratorsGetter.promises.userIsTokenMember(
this.userId,
this.project._id
@@ -341,10 +339,8 @@ describe('CollaboratorsGetter', function() {
expect(isMember).to.be.true
})
- it('should return false when the project is not found', async function() {
- this.ProjectMock.expects('findOne')
- .chain('exec')
- .resolves(null)
+ it('should return false when the project is not found', async function () {
+ this.ProjectMock.expects('findOne').chain('exec').resolves(null)
const isMember = await this.CollaboratorsGetter.promises.userIsTokenMember(
this.userId,
this.project._id
diff --git a/services/web/test/unit/src/Collaborators/CollaboratorsHandlerTests.js b/services/web/test/unit/src/Collaborators/CollaboratorsHandlerTests.js
index 27f0b15ee6..3b3790c7fc 100644
--- a/services/web/test/unit/src/Collaborators/CollaboratorsHandlerTests.js
+++ b/services/web/test/unit/src/Collaborators/CollaboratorsHandlerTests.js
@@ -14,8 +14,8 @@ const MODULE_PATH = path.join(
const sleep = promisify(setTimeout)
-describe('CollaboratorsHandler', function() {
- beforeEach(function() {
+describe('CollaboratorsHandler', function () {
+ beforeEach(function () {
this.userId = ObjectId()
this.addingUserId = ObjectId()
this.project = {
@@ -73,13 +73,13 @@ describe('CollaboratorsHandler', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
this.ProjectMock.verify()
})
- describe('removeUserFromProject', function() {
- describe('a non-archived project', function() {
- beforeEach(function() {
+ describe('removeUserFromProject', function () {
+ describe('a non-archived project', function () {
+ beforeEach(function () {
this.ProjectMock.expects('findOne')
.withArgs({
_id: this.project._id
@@ -88,7 +88,7 @@ describe('CollaboratorsHandler', function() {
.resolves(this.project)
})
- it('should remove the user from mongo', async function() {
+ it('should remove the user from mongo', async function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{
@@ -114,8 +114,8 @@ describe('CollaboratorsHandler', function() {
})
})
- describe('an archived project, archived with a boolean value', function() {
- beforeEach(function() {
+ describe('an archived project, archived with a boolean value', function () {
+ beforeEach(function () {
let archived = [ObjectId(this.userId)]
this.ProjectHelper.calculateArchivedArray.returns(archived)
@@ -127,7 +127,7 @@ describe('CollaboratorsHandler', function() {
.resolves(this.oldArchivedProject)
})
- it('should remove the user from mongo', async function() {
+ it('should remove the user from mongo', async function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{
@@ -154,8 +154,8 @@ describe('CollaboratorsHandler', function() {
})
})
- describe('an archived project, archived with an array value', function() {
- beforeEach(function() {
+ describe('an archived project, archived with an array value', function () {
+ beforeEach(function () {
this.ProjectMock.expects('findOne')
.withArgs({
_id: this.archivedProject._id
@@ -164,7 +164,7 @@ describe('CollaboratorsHandler', function() {
.resolves(this.archivedProject)
})
- it('should remove the user from mongo', async function() {
+ it('should remove the user from mongo', async function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{
@@ -190,9 +190,9 @@ describe('CollaboratorsHandler', function() {
})
})
- describe('addUserIdToProject', function() {
- describe('as readOnly', function() {
- beforeEach(async function() {
+ describe('addUserIdToProject', function () {
+ describe('as readOnly', function () {
+ beforeEach(async function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{
@@ -212,13 +212,13 @@ describe('CollaboratorsHandler', function() {
)
})
- it('should flush the project to the TPDS', function() {
+ it('should flush the project to the TPDS', function () {
expect(
this.TpdsProjectFlusher.promises.flushProjectToTpds
).to.have.been.calledWith(this.project._id)
})
- it('should add the user as a contact for the adding user', function() {
+ it('should add the user as a contact for the adding user', function () {
expect(this.ContactManager.addContact).to.have.been.calledWith(
this.addingUserId,
this.userId
@@ -226,8 +226,8 @@ describe('CollaboratorsHandler', function() {
})
})
- describe('as readAndWrite', function() {
- beforeEach(async function() {
+ describe('as readAndWrite', function () {
+ beforeEach(async function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{
@@ -247,15 +247,15 @@ describe('CollaboratorsHandler', function() {
)
})
- it('should flush the project to the TPDS', function() {
+ it('should flush the project to the TPDS', function () {
expect(
this.TpdsProjectFlusher.promises.flushProjectToTpds
).to.have.been.calledWith(this.project._id)
})
})
- describe('with invalid privilegeLevel', function() {
- it('should call the callback with an error', async function() {
+ describe('with invalid privilegeLevel', function () {
+ it('should call the callback with an error', async function () {
await expect(
this.CollaboratorsHandler.promises.addUserIdToProject(
this.project._id,
@@ -267,12 +267,12 @@ describe('CollaboratorsHandler', function() {
})
})
- describe('when user already exists as a collaborator', function() {
- beforeEach(function() {
+ describe('when user already exists as a collaborator', function () {
+ beforeEach(function () {
this.project.collaberator_refs = [this.userId]
})
- it('should not add the user again', async function() {
+ it('should not add the user again', async function () {
await this.CollaboratorsHandler.promises.addUserIdToProject(
this.project._id,
this.addingUserId,
@@ -284,8 +284,8 @@ describe('CollaboratorsHandler', function() {
})
})
- describe('with null addingUserId', function() {
- beforeEach(function() {
+ describe('with null addingUserId', function () {
+ beforeEach(function () {
this.CollaboratorsHandler.promises.addUserIdToProject(
this.project._id,
null,
@@ -295,14 +295,14 @@ describe('CollaboratorsHandler', function() {
)
})
- it('should not add the adding user as a contact', function() {
+ it('should not add the adding user as a contact', function () {
expect(this.ContactManager.addContact).not.to.have.been.called
})
})
})
- describe('removeUserFromAllProjects', function() {
- it('should remove the user from each project', async function() {
+ describe('removeUserFromAllProjects', function () {
+ it('should remove the user from each project', async function () {
this.CollaboratorsGetter.promises.getProjectsUserIsMemberOf
.withArgs(this.userId, { _id: 1 })
.resolves({
@@ -362,8 +362,8 @@ describe('CollaboratorsHandler', function() {
})
})
- describe('transferProjects', function() {
- beforeEach(function() {
+ describe('transferProjects', function () {
+ beforeEach(function () {
this.fromUserId = ObjectId()
this.toUserId = ObjectId()
this.projects = [
@@ -429,8 +429,8 @@ describe('CollaboratorsHandler', function() {
.resolves()
})
- describe('successfully', function() {
- it('should flush each project to the TPDS', async function() {
+ describe('successfully', function () {
+ it('should flush each project to the TPDS', async function () {
await this.CollaboratorsHandler.promises.transferProjects(
this.fromUserId,
this.toUserId
@@ -444,8 +444,8 @@ describe('CollaboratorsHandler', function() {
})
})
- describe('when flushing to TPDS fails', function() {
- it('should log an error but not fail', async function() {
+ describe('when flushing to TPDS fails', function () {
+ it('should log an error but not fail', async function () {
this.TpdsProjectFlusher.promises.flushProjectToTpds.rejects(
new Error('oops')
)
@@ -459,8 +459,8 @@ describe('CollaboratorsHandler', function() {
})
})
- describe('setCollaboratorPrivilegeLevel', function() {
- it('sets a collaborator to read-only', async function() {
+ describe('setCollaboratorPrivilegeLevel', function () {
+ it('sets a collaborator to read-only', async function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{
@@ -484,7 +484,7 @@ describe('CollaboratorsHandler', function() {
)
})
- it('sets a collaborator to read-write', async function() {
+ it('sets a collaborator to read-write', async function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{
@@ -508,10 +508,8 @@ describe('CollaboratorsHandler', function() {
)
})
- it('throws a NotFoundError if the project or collaborator does not exist', async function() {
- this.ProjectMock.expects('updateOne')
- .chain('exec')
- .resolves({ n: 0 })
+ it('throws a NotFoundError if the project or collaborator does not exist', async function () {
+ this.ProjectMock.expects('updateOne').chain('exec').resolves({ n: 0 })
await expect(
this.CollaboratorsHandler.promises.setCollaboratorPrivilegeLevel(
this.projectId,
diff --git a/services/web/test/unit/src/Collaborators/CollaboratorsInviteControllerTests.js b/services/web/test/unit/src/Collaborators/CollaboratorsInviteControllerTests.js
index c81bd3693d..b39cb21a39 100644
--- a/services/web/test/unit/src/Collaborators/CollaboratorsInviteControllerTests.js
+++ b/services/web/test/unit/src/Collaborators/CollaboratorsInviteControllerTests.js
@@ -21,8 +21,8 @@ const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
const { ObjectId } = require('mongodb')
-describe('CollaboratorsInviteController', function() {
- beforeEach(function() {
+describe('CollaboratorsInviteController', function () {
+ beforeEach(function () {
this.user = { _id: 'id' }
this.AnalyticsManger = { recordEvent: sinon.stub() }
this.sendingUser = null
@@ -65,8 +65,8 @@ describe('CollaboratorsInviteController', function() {
return (this.callback = sinon.stub())
})
- describe('getAllInvites', function() {
- beforeEach(function() {
+ describe('getAllInvites', function () {
+ beforeEach(function () {
this.fakeInvites = [
{ _id: ObjectId(), one: 1 },
{ _id: ObjectId(), two: 2 }
@@ -76,8 +76,8 @@ describe('CollaboratorsInviteController', function() {
return (this.next = sinon.stub())
})
- describe('when all goes well', function() {
- beforeEach(function() {
+ describe('when all goes well', function () {
+ beforeEach(function () {
this.CollaboratorsInviteHandler.getAllInvites = sinon
.stub()
.callsArgWith(1, null, this.fakeInvites)
@@ -88,18 +88,18 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should not produce an error', function() {
+ it('should not produce an error', function () {
return this.next.callCount.should.equal(0)
})
- it('should produce a list of invite objects', function() {
+ it('should produce a list of invite objects', function () {
this.res.json.callCount.should.equal(1)
return this.res.json
.calledWith({ invites: this.fakeInvites })
.should.equal(true)
})
- it('should have called CollaboratorsInviteHandler.getAllInvites', function() {
+ it('should have called CollaboratorsInviteHandler.getAllInvites', function () {
this.CollaboratorsInviteHandler.getAllInvites.callCount.should.equal(1)
return this.CollaboratorsInviteHandler.getAllInvites
.calledWith(this.project_id)
@@ -107,8 +107,8 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('when CollaboratorsInviteHandler.getAllInvites produces an error', function() {
- beforeEach(function() {
+ describe('when CollaboratorsInviteHandler.getAllInvites produces an error', function () {
+ beforeEach(function () {
this.CollaboratorsInviteHandler.getAllInvites = sinon
.stub()
.callsArgWith(1, new Error('woops'))
@@ -119,15 +119,15 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should produce an error', function() {
+ it('should produce an error', function () {
this.next.callCount.should.equal(1)
return this.next.firstCall.args[0].should.be.instanceof(Error)
})
})
})
- describe('inviteToProject', function() {
- beforeEach(function() {
+ describe('inviteToProject', function () {
+ beforeEach(function () {
this.targetEmail = 'user@example.com'
this.req.params = { Project_id: this.project_id }
this.current_user = { _id: (this.current_user_id = 'current-user-id') }
@@ -156,8 +156,8 @@ describe('CollaboratorsInviteController', function() {
return (this.next = sinon.stub())
})
- describe('when all goes well', function() {
- beforeEach(function() {
+ describe('when all goes well', function () {
+ beforeEach(function () {
this.CollaboratorsInviteController._checkShouldInviteEmail = sinon
.stub()
.callsArgWith(1, null, true)
@@ -174,21 +174,21 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should produce json response', function() {
+ it('should produce json response', function () {
this.res.json.callCount.should.equal(1)
return { invite: this.invite }.should.deep.equal(
this.res.json.firstCall.args[0]
)
})
- it('should have called canAddXCollaborators', function() {
+ it('should have called canAddXCollaborators', function () {
this.LimitationsManager.canAddXCollaborators.callCount.should.equal(1)
return this.LimitationsManager.canAddXCollaborators
.calledWith(this.project_id)
.should.equal(true)
})
- it('should have called _checkShouldInviteEmail', function() {
+ it('should have called _checkShouldInviteEmail', function () {
this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal(
1
)
@@ -197,7 +197,7 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should have called inviteToProject', function() {
+ it('should have called inviteToProject', function () {
this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal(
1
)
@@ -211,7 +211,7 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should have called emitToRoom', function() {
+ it('should have called emitToRoom', function () {
this.EditorRealTimeController.emitToRoom.callCount.should.equal(1)
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'project:membership:changed')
@@ -219,8 +219,8 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('when the user is not allowed to add more collaborators', function() {
- beforeEach(function() {
+ describe('when the user is not allowed to add more collaborators', function () {
+ beforeEach(function () {
this.CollaboratorsInviteController._checkShouldInviteEmail = sinon
.stub()
.callsArgWith(1, null, true)
@@ -237,14 +237,14 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should produce json response without an invite', function() {
+ it('should produce json response without an invite', function () {
this.res.json.callCount.should.equal(1)
return { invite: null }.should.deep.equal(
this.res.json.firstCall.args[0]
)
})
- it('should not have called _checkShouldInviteEmail', function() {
+ it('should not have called _checkShouldInviteEmail', function () {
this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal(
0
)
@@ -253,15 +253,15 @@ describe('CollaboratorsInviteController', function() {
.should.equal(false)
})
- it('should not have called inviteToProject', function() {
+ it('should not have called inviteToProject', function () {
return this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal(
0
)
})
})
- describe('when canAddXCollaborators produces an error', function() {
- beforeEach(function() {
+ describe('when canAddXCollaborators produces an error', function () {
+ beforeEach(function () {
this.CollaboratorsInviteController._checkShouldInviteEmail = sinon
.stub()
.callsArgWith(1, null, true)
@@ -278,14 +278,14 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.next.callCount.should.equal(1)
return this.next
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
- it('should not have called _checkShouldInviteEmail', function() {
+ it('should not have called _checkShouldInviteEmail', function () {
this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal(
0
)
@@ -294,15 +294,15 @@ describe('CollaboratorsInviteController', function() {
.should.equal(false)
})
- it('should not have called inviteToProject', function() {
+ it('should not have called inviteToProject', function () {
return this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal(
0
)
})
})
- describe('when inviteToProject produces an error', function() {
- beforeEach(function() {
+ describe('when inviteToProject produces an error', function () {
+ beforeEach(function () {
this.CollaboratorsInviteController._checkShouldInviteEmail = sinon
.stub()
.callsArgWith(1, null, true)
@@ -319,19 +319,19 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.next.callCount.should.equal(1)
expect(this.next).to.have.been.calledWith(sinon.match.instanceOf(Error))
})
- it('should have called canAddXCollaborators', function() {
+ it('should have called canAddXCollaborators', function () {
this.LimitationsManager.canAddXCollaborators.callCount.should.equal(1)
return this.LimitationsManager.canAddXCollaborators
.calledWith(this.project_id)
.should.equal(true)
})
- it('should have called _checkShouldInviteEmail', function() {
+ it('should have called _checkShouldInviteEmail', function () {
this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal(
1
)
@@ -340,7 +340,7 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should have called inviteToProject', function() {
+ it('should have called inviteToProject', function () {
this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal(
1
)
@@ -355,8 +355,8 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('when _checkShouldInviteEmail disallows the invite', function() {
- beforeEach(function() {
+ describe('when _checkShouldInviteEmail disallows the invite', function () {
+ beforeEach(function () {
this.CollaboratorsInviteController._checkShouldInviteEmail = sinon
.stub()
.callsArgWith(1, null, false)
@@ -373,7 +373,7 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should produce json response with no invite, and an error property', function() {
+ it('should produce json response with no invite, and an error property', function () {
this.res.json.callCount.should.equal(1)
return {
invite: null,
@@ -381,7 +381,7 @@ describe('CollaboratorsInviteController', function() {
}.should.deep.equal(this.res.json.firstCall.args[0])
})
- it('should have called _checkShouldInviteEmail', function() {
+ it('should have called _checkShouldInviteEmail', function () {
this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal(
1
)
@@ -390,15 +390,15 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should not have called inviteToProject', function() {
+ it('should not have called inviteToProject', function () {
return this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal(
0
)
})
})
- describe('when _checkShouldInviteEmail produces an error', function() {
- beforeEach(function() {
+ describe('when _checkShouldInviteEmail produces an error', function () {
+ beforeEach(function () {
this.CollaboratorsInviteController._checkShouldInviteEmail = sinon
.stub()
.callsArgWith(1, new Error('woops'))
@@ -415,14 +415,14 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.next.callCount.should.equal(1)
return this.next
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
- it('should have called _checkShouldInviteEmail', function() {
+ it('should have called _checkShouldInviteEmail', function () {
this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal(
1
)
@@ -431,15 +431,15 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should not have called inviteToProject', function() {
+ it('should not have called inviteToProject', function () {
return this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal(
0
)
})
})
- describe('when the user invites themselves to the project', function() {
- beforeEach(function() {
+ describe('when the user invites themselves to the project', function () {
+ beforeEach(function () {
this.req.session.user = { _id: 'abc', email: 'me@example.com' }
this.req.body.email = 'me@example.com'
this.CollaboratorsInviteController._checkShouldInviteEmail = sinon
@@ -458,40 +458,40 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should reject action, return json response with error code', function() {
+ it('should reject action, return json response with error code', function () {
this.res.json.callCount.should.equal(1)
return { invite: null, error: 'cannot_invite_self' }.should.deep.equal(
this.res.json.firstCall.args[0]
)
})
- it('should not have called canAddXCollaborators', function() {
+ it('should not have called canAddXCollaborators', function () {
return this.LimitationsManager.canAddXCollaborators.callCount.should.equal(
0
)
})
- it('should not have called _checkShouldInviteEmail', function() {
+ it('should not have called _checkShouldInviteEmail', function () {
return this.CollaboratorsInviteController._checkShouldInviteEmail.callCount.should.equal(
0
)
})
- it('should not have called inviteToProject', function() {
+ it('should not have called inviteToProject', function () {
return this.CollaboratorsInviteHandler.inviteToProject.callCount.should.equal(
0
)
})
- it('should not have called emitToRoom', function() {
+ it('should not have called emitToRoom', function () {
return this.EditorRealTimeController.emitToRoom.callCount.should.equal(
0
)
})
})
- describe('when _checkRateLimit returns false', function() {
- beforeEach(function() {
+ describe('when _checkRateLimit returns false', function () {
+ beforeEach(function () {
this.CollaboratorsInviteController._checkShouldInviteEmail = sinon
.stub()
.callsArgWith(1, null, true)
@@ -508,17 +508,17 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should send a 429 response', function() {
+ it('should send a 429 response', function () {
return this.res.sendStatus.calledWith(429).should.equal(true)
})
- it('should not call inviteToProject', function() {
+ it('should not call inviteToProject', function () {
return this.CollaboratorsInviteHandler.inviteToProject.called.should.equal(
false
)
})
- it('should not call emitToRoom', function() {
+ it('should not call emitToRoom', function () {
return this.EditorRealTimeController.emitToRoom.called.should.equal(
false
)
@@ -526,8 +526,8 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('viewInvite', function() {
- beforeEach(function() {
+ describe('viewInvite', function () {
+ beforeEach(function () {
this.token = 'some-opaque-token'
this.req.params = {
Project_id: this.project_id,
@@ -576,8 +576,8 @@ describe('CollaboratorsInviteController', function() {
return (this.next = sinon.stub())
})
- describe('when the token is valid', function() {
- beforeEach(function() {
+ describe('when the token is valid', function () {
+ beforeEach(function () {
return this.CollaboratorsInviteController.viewInvite(
this.req,
this.res,
@@ -585,18 +585,18 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should render the view template', function() {
+ it('should render the view template', function () {
this.res.render.callCount.should.equal(1)
return this.res.render
.calledWith('project/invite/show')
.should.equal(true)
})
- it('should not call next', function() {
+ it('should not call next', function () {
return this.next.callCount.should.equal(0)
})
- it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function() {
+ it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal(
1
)
@@ -605,7 +605,7 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should call getInviteByToken', function() {
+ it('should call getInviteByToken', function () {
this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal(
1
)
@@ -614,14 +614,14 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should call User.getUser', function() {
+ it('should call User.getUser', function () {
this.UserGetter.getUser.callCount.should.equal(1)
return this.UserGetter.getUser
.calledWith({ _id: this.fakeProject.owner_ref })
.should.equal(true)
})
- it('should call ProjectGetter.getProject', function() {
+ it('should call ProjectGetter.getProject', function () {
this.ProjectGetter.getProject.callCount.should.equal(1)
return this.ProjectGetter.getProject
.calledWith(this.project_id)
@@ -629,8 +629,8 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('when user is already a member of the project', function() {
- beforeEach(function() {
+ describe('when user is already a member of the project', function () {
+ beforeEach(function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject = sinon
.stub()
.callsArgWith(2, null, true)
@@ -641,18 +641,18 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should redirect to the project page', function() {
+ it('should redirect to the project page', function () {
this.res.redirect.callCount.should.equal(1)
return this.res.redirect
.calledWith(`/project/${this.project_id}`)
.should.equal(true)
})
- it('should not call next with an error', function() {
+ it('should not call next with an error', function () {
return this.next.callCount.should.equal(0)
})
- it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function() {
+ it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal(
1
)
@@ -661,23 +661,23 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should not call getInviteByToken', function() {
+ it('should not call getInviteByToken', function () {
return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal(
0
)
})
- it('should not call User.getUser', function() {
+ it('should not call User.getUser', function () {
return this.UserGetter.getUser.callCount.should.equal(0)
})
- it('should not call ProjectGetter.getProject', function() {
+ it('should not call ProjectGetter.getProject', function () {
return this.ProjectGetter.getProject.callCount.should.equal(0)
})
})
- describe('when isUserInvitedMemberOfProject produces an error', function() {
- beforeEach(function() {
+ describe('when isUserInvitedMemberOfProject produces an error', function () {
+ beforeEach(function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject = sinon
.stub()
.callsArgWith(2, new Error('woops'))
@@ -688,12 +688,12 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.next.callCount.should.equal(1)
return expect(this.next.firstCall.args[0]).to.be.instanceof(Error)
})
- it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function() {
+ it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal(
1
)
@@ -702,23 +702,23 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should not call getInviteByToken', function() {
+ it('should not call getInviteByToken', function () {
return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal(
0
)
})
- it('should not call User.getUser', function() {
+ it('should not call User.getUser', function () {
return this.UserGetter.getUser.callCount.should.equal(0)
})
- it('should not call ProjectGetter.getProject', function() {
+ it('should not call ProjectGetter.getProject', function () {
return this.ProjectGetter.getProject.callCount.should.equal(0)
})
})
- describe('when the getInviteByToken produces an error', function() {
- beforeEach(function() {
+ describe('when the getInviteByToken produces an error', function () {
+ beforeEach(function () {
this.CollaboratorsInviteHandler.getInviteByToken.callsArgWith(
2,
new Error('woops')
@@ -730,14 +730,14 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should call next with the error', function() {
+ it('should call next with the error', function () {
this.next.callCount.should.equal(1)
return this.next
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
- it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function() {
+ it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal(
1
)
@@ -746,7 +746,7 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should call getInviteByToken', function() {
+ it('should call getInviteByToken', function () {
this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal(
1
)
@@ -755,17 +755,17 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should not call User.getUser', function() {
+ it('should not call User.getUser', function () {
return this.UserGetter.getUser.callCount.should.equal(0)
})
- it('should not call ProjectGetter.getProject', function() {
+ it('should not call ProjectGetter.getProject', function () {
return this.ProjectGetter.getProject.callCount.should.equal(0)
})
})
- describe('when the getInviteByToken does not produce an invite', function() {
- beforeEach(function() {
+ describe('when the getInviteByToken does not produce an invite', function () {
+ beforeEach(function () {
this.CollaboratorsInviteHandler.getInviteByToken.callsArgWith(
2,
null,
@@ -778,18 +778,18 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should render the not-valid view template', function() {
+ it('should render the not-valid view template', function () {
this.res.render.callCount.should.equal(1)
return this.res.render
.calledWith('project/invite/not-valid')
.should.equal(true)
})
- it('should not call next', function() {
+ it('should not call next', function () {
return this.next.callCount.should.equal(0)
})
- it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function() {
+ it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal(
1
)
@@ -798,7 +798,7 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should call getInviteByToken', function() {
+ it('should call getInviteByToken', function () {
this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal(
1
)
@@ -807,17 +807,17 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should not call User.getUser', function() {
+ it('should not call User.getUser', function () {
return this.UserGetter.getUser.callCount.should.equal(0)
})
- it('should not call ProjectGetter.getProject', function() {
+ it('should not call ProjectGetter.getProject', function () {
return this.ProjectGetter.getProject.callCount.should.equal(0)
})
})
- describe('when User.getUser produces an error', function() {
- beforeEach(function() {
+ describe('when User.getUser produces an error', function () {
+ beforeEach(function () {
this.UserGetter.getUser.callsArgWith(2, new Error('woops'))
return this.CollaboratorsInviteController.viewInvite(
this.req,
@@ -826,12 +826,12 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should produce an error', function() {
+ it('should produce an error', function () {
this.next.callCount.should.equal(1)
return expect(this.next.firstCall.args[0]).to.be.instanceof(Error)
})
- it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function() {
+ it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal(
1
)
@@ -840,26 +840,26 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should call getInviteByToken', function() {
+ it('should call getInviteByToken', function () {
return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal(
1
)
})
- it('should call User.getUser', function() {
+ it('should call User.getUser', function () {
this.UserGetter.getUser.callCount.should.equal(1)
return this.UserGetter.getUser
.calledWith({ _id: this.fakeProject.owner_ref })
.should.equal(true)
})
- it('should not call ProjectGetter.getProject', function() {
+ it('should not call ProjectGetter.getProject', function () {
return this.ProjectGetter.getProject.callCount.should.equal(0)
})
})
- describe('when User.getUser does not find a user', function() {
- beforeEach(function() {
+ describe('when User.getUser does not find a user', function () {
+ beforeEach(function () {
this.UserGetter.getUser.callsArgWith(2, null, null)
return this.CollaboratorsInviteController.viewInvite(
this.req,
@@ -868,18 +868,18 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should render the not-valid view template', function() {
+ it('should render the not-valid view template', function () {
this.res.render.callCount.should.equal(1)
return this.res.render
.calledWith('project/invite/not-valid')
.should.equal(true)
})
- it('should not call next', function() {
+ it('should not call next', function () {
return this.next.callCount.should.equal(0)
})
- it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function() {
+ it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal(
1
)
@@ -888,26 +888,26 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should call getInviteByToken', function() {
+ it('should call getInviteByToken', function () {
return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal(
1
)
})
- it('should call User.getUser', function() {
+ it('should call User.getUser', function () {
this.UserGetter.getUser.callCount.should.equal(1)
return this.UserGetter.getUser
.calledWith({ _id: this.fakeProject.owner_ref })
.should.equal(true)
})
- it('should not call ProjectGetter.getProject', function() {
+ it('should not call ProjectGetter.getProject', function () {
return this.ProjectGetter.getProject.callCount.should.equal(0)
})
})
- describe('when getProject produces an error', function() {
- beforeEach(function() {
+ describe('when getProject produces an error', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.callsArgWith(2, new Error('woops'))
return this.CollaboratorsInviteController.viewInvite(
this.req,
@@ -916,12 +916,12 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should produce an error', function() {
+ it('should produce an error', function () {
this.next.callCount.should.equal(1)
return expect(this.next.firstCall.args[0]).to.be.instanceof(Error)
})
- it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function() {
+ it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal(
1
)
@@ -930,26 +930,26 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should call getInviteByToken', function() {
+ it('should call getInviteByToken', function () {
return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal(
1
)
})
- it('should call User.getUser', function() {
+ it('should call User.getUser', function () {
this.UserGetter.getUser.callCount.should.equal(1)
return this.UserGetter.getUser
.calledWith({ _id: this.fakeProject.owner_ref })
.should.equal(true)
})
- it('should call ProjectGetter.getProject', function() {
+ it('should call ProjectGetter.getProject', function () {
return this.ProjectGetter.getProject.callCount.should.equal(1)
})
})
- describe('when Project.getUser does not find a user', function() {
- beforeEach(function() {
+ describe('when Project.getUser does not find a user', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.callsArgWith(2, null, null)
return this.CollaboratorsInviteController.viewInvite(
this.req,
@@ -958,18 +958,18 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should render the not-valid view template', function() {
+ it('should render the not-valid view template', function () {
this.res.render.callCount.should.equal(1)
return this.res.render
.calledWith('project/invite/not-valid')
.should.equal(true)
})
- it('should not call next', function() {
+ it('should not call next', function () {
return this.next.callCount.should.equal(0)
})
- it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function() {
+ it('should call CollaboratorsGetter.isUserInvitedMemberOfProject', function () {
this.CollaboratorsGetter.isUserInvitedMemberOfProject.callCount.should.equal(
1
)
@@ -978,27 +978,27 @@ describe('CollaboratorsInviteController', function() {
.should.equal(true)
})
- it('should call getInviteByToken', function() {
+ it('should call getInviteByToken', function () {
return this.CollaboratorsInviteHandler.getInviteByToken.callCount.should.equal(
1
)
})
- it('should call getUser', function() {
+ it('should call getUser', function () {
this.UserGetter.getUser.callCount.should.equal(1)
return this.UserGetter.getUser
.calledWith({ _id: this.fakeProject.owner_ref })
.should.equal(true)
})
- it('should call ProjectGetter.getProject', function() {
+ it('should call ProjectGetter.getProject', function () {
return this.ProjectGetter.getProject.callCount.should.equal(1)
})
})
})
- describe('resendInvite', function() {
- beforeEach(function() {
+ describe('resendInvite', function () {
+ beforeEach(function () {
this.req.params = {
Project_id: this.project_id,
invite_id: (this.invite_id = 'thuseoautoh')
@@ -1018,8 +1018,8 @@ describe('CollaboratorsInviteController', function() {
return (this.next = sinon.stub())
})
- describe('when resendInvite does not produce an error', function() {
- beforeEach(function() {
+ describe('when resendInvite does not produce an error', function () {
+ beforeEach(function () {
return this.CollaboratorsInviteController.resendInvite(
this.req,
this.res,
@@ -1027,26 +1027,26 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should produce a 201 response', function() {
+ it('should produce a 201 response', function () {
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(201).should.equal(true)
})
- it('should have called resendInvite', function() {
+ it('should have called resendInvite', function () {
return this.CollaboratorsInviteHandler.resendInvite.callCount.should.equal(
1
)
})
- it('should check the rate limit', function() {
+ it('should check the rate limit', function () {
return this.CollaboratorsInviteController._checkRateLimit.callCount.should.equal(
1
)
})
})
- describe('when resendInvite produces an error', function() {
- beforeEach(function() {
+ describe('when resendInvite produces an error', function () {
+ beforeEach(function () {
this.CollaboratorsInviteHandler.resendInvite = sinon
.stub()
.callsArgWith(3, new Error('woops'))
@@ -1057,18 +1057,18 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should not produce a 201 response', function() {
+ it('should not produce a 201 response', function () {
return this.res.sendStatus.callCount.should.equal(0)
})
- it('should call next with the error', function() {
+ it('should call next with the error', function () {
this.next.callCount.should.equal(1)
return this.next
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
- it('should have called resendInvite', function() {
+ it('should have called resendInvite', function () {
return this.CollaboratorsInviteHandler.resendInvite.callCount.should.equal(
1
)
@@ -1076,8 +1076,8 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('revokeInvite', function() {
- beforeEach(function() {
+ describe('revokeInvite', function () {
+ beforeEach(function () {
this.req.params = {
Project_id: this.project_id,
invite_id: (this.invite_id = 'thuseoautoh')
@@ -1093,8 +1093,8 @@ describe('CollaboratorsInviteController', function() {
return (this.next = sinon.stub())
})
- describe('when revokeInvite does not produce an error', function() {
- beforeEach(function() {
+ describe('when revokeInvite does not produce an error', function () {
+ beforeEach(function () {
return this.CollaboratorsInviteController.revokeInvite(
this.req,
this.res,
@@ -1102,18 +1102,18 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should produce a 201 response', function() {
+ it('should produce a 201 response', function () {
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(201).should.equal(true)
})
- it('should have called revokeInvite', function() {
+ it('should have called revokeInvite', function () {
return this.CollaboratorsInviteHandler.revokeInvite.callCount.should.equal(
1
)
})
- it('should have called emitToRoom', function() {
+ it('should have called emitToRoom', function () {
this.EditorRealTimeController.emitToRoom.callCount.should.equal(1)
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'project:membership:changed')
@@ -1121,8 +1121,8 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('when revokeInvite produces an error', function() {
- beforeEach(function() {
+ describe('when revokeInvite produces an error', function () {
+ beforeEach(function () {
this.CollaboratorsInviteHandler.revokeInvite = sinon
.stub()
.callsArgWith(2, new Error('woops'))
@@ -1133,18 +1133,18 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should not produce a 201 response', function() {
+ it('should not produce a 201 response', function () {
return this.res.sendStatus.callCount.should.equal(0)
})
- it('should call next with the error', function() {
+ it('should call next with the error', function () {
this.next.callCount.should.equal(1)
return this.next
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
- it('should have called revokeInvite', function() {
+ it('should have called revokeInvite', function () {
return this.CollaboratorsInviteHandler.revokeInvite.callCount.should.equal(
1
)
@@ -1152,8 +1152,8 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('acceptInvite', function() {
- beforeEach(function() {
+ describe('acceptInvite', function () {
+ beforeEach(function () {
this.req.params = {
Project_id: this.project_id,
token: (this.token = 'mock-token')
@@ -1170,8 +1170,8 @@ describe('CollaboratorsInviteController', function() {
return (this.next = sinon.stub())
})
- describe('when acceptInvite does not produce an error', function() {
- beforeEach(function() {
+ describe('when acceptInvite does not produce an error', function () {
+ beforeEach(function () {
return this.CollaboratorsInviteController.acceptInvite(
this.req,
this.res,
@@ -1179,20 +1179,20 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should redirect to project page', function() {
+ it('should redirect to project page', function () {
this.res.redirect.callCount.should.equal(1)
return this.res.redirect
.calledWith(`/project/${this.project_id}`)
.should.equal(true)
})
- it('should have called acceptInvite', function() {
+ it('should have called acceptInvite', function () {
return this.CollaboratorsInviteHandler.acceptInvite
.calledWith(this.project_id, this.token)
.should.equal(true)
})
- it('should have called emitToRoom', function() {
+ it('should have called emitToRoom', function () {
this.EditorRealTimeController.emitToRoom.callCount.should.equal(1)
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'project:membership:changed')
@@ -1200,8 +1200,8 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('when revokeInvite produces an error', function() {
- beforeEach(function() {
+ describe('when revokeInvite produces an error', function () {
+ beforeEach(function () {
this.CollaboratorsInviteHandler.acceptInvite = sinon
.stub()
.callsArgWith(3, new Error('woops'))
@@ -1212,18 +1212,18 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should not redirect to project page', function() {
+ it('should not redirect to project page', function () {
return this.res.redirect.callCount.should.equal(0)
})
- it('should call next with the error', function() {
+ it('should call next with the error', function () {
this.next.callCount.should.equal(1)
return this.next
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
- it('should have called acceptInvite', function() {
+ it('should have called acceptInvite', function () {
return this.CollaboratorsInviteHandler.acceptInvite.callCount.should.equal(
1
)
@@ -1231,13 +1231,13 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('_checkShouldInviteEmail', function() {
- beforeEach(function() {
+ describe('_checkShouldInviteEmail', function () {
+ beforeEach(function () {
return (this.email = 'user@example.com')
})
- describe('when we should be restricting to existing accounts', function() {
- beforeEach(function() {
+ describe('when we should be restricting to existing accounts', function () {
+ beforeEach(function () {
this.settings.restrictInvitesToExistingAccounts = true
return (this.call = callback => {
return this.CollaboratorsInviteController._checkShouldInviteEmail(
@@ -1247,15 +1247,15 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('when user account is present', function() {
- beforeEach(function() {
+ describe('when user account is present', function () {
+ beforeEach(function () {
this.user = { _id: ObjectId().toString() }
return (this.UserGetter.getUserByAnyEmail = sinon
.stub()
.callsArgWith(2, null, this.user))
})
- it('should callback with `true`', function(done) {
+ it('should callback with `true`', function (done) {
return this.call((err, shouldAllow) => {
expect(err).to.equal(null)
expect(shouldAllow).to.equal(true)
@@ -1264,15 +1264,15 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('when user account is absent', function() {
- beforeEach(function() {
+ describe('when user account is absent', function () {
+ beforeEach(function () {
this.user = null
return (this.UserGetter.getUserByAnyEmail = sinon
.stub()
.callsArgWith(2, null, this.user))
})
- it('should callback with `false`', function(done) {
+ it('should callback with `false`', function (done) {
return this.call((err, shouldAllow) => {
expect(err).to.equal(null)
expect(shouldAllow).to.equal(false)
@@ -1280,7 +1280,7 @@ describe('CollaboratorsInviteController', function() {
})
})
- it('should have called getUser', function(done) {
+ it('should have called getUser', function (done) {
return this.call((err, shouldAllow) => {
this.UserGetter.getUserByAnyEmail.callCount.should.equal(1)
this.UserGetter.getUserByAnyEmail
@@ -1291,15 +1291,15 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('when getUser produces an error', function() {
- beforeEach(function() {
+ describe('when getUser produces an error', function () {
+ beforeEach(function () {
this.user = null
return (this.UserGetter.getUserByAnyEmail = sinon
.stub()
.callsArgWith(2, new Error('woops')))
})
- it('should callback with an error', function(done) {
+ it('should callback with an error', function (done) {
return this.call((err, shouldAllow) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -1311,8 +1311,8 @@ describe('CollaboratorsInviteController', function() {
})
})
- describe('_checkRateLimit', function() {
- beforeEach(function() {
+ describe('_checkRateLimit', function () {
+ beforeEach(function () {
this.settings.restrictInvitesToExistingAccounts = false
this.sendingUserId = '32312313'
this.LimitationsManager.allowedNumberOfCollaboratorsForUser = sinon.stub()
@@ -1321,7 +1321,7 @@ describe('CollaboratorsInviteController', function() {
.yields(null, 17)
})
- it('should callback with `true` when rate limit under', function(done) {
+ it('should callback with `true` when rate limit under', function (done) {
this.RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true)
return this.CollaboratorsInviteController._checkRateLimit(
this.sendingUserId,
@@ -1333,7 +1333,7 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should callback with `false` when rate limit hit', function(done) {
+ it('should callback with `false` when rate limit hit', function (done) {
this.RateLimiter.addCount = sinon.stub().callsArgWith(1, null, false)
return this.CollaboratorsInviteController._checkRateLimit(
this.sendingUserId,
@@ -1345,7 +1345,7 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should call rate limiter with 10x the collaborators', function(done) {
+ it('should call rate limiter with 10x the collaborators', function (done) {
this.RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true)
return this.CollaboratorsInviteController._checkRateLimit(
this.sendingUserId,
@@ -1356,7 +1356,7 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should call rate limiter with 200 when collaborators is -1', function(done) {
+ it('should call rate limiter with 200 when collaborators is -1', function (done) {
this.LimitationsManager.allowedNumberOfCollaboratorsForUser
.withArgs(this.sendingUserId)
.yields(null, -1)
@@ -1370,7 +1370,7 @@ describe('CollaboratorsInviteController', function() {
)
})
- it('should call rate limiter with 10 when user has no collaborators set', function(done) {
+ it('should call rate limiter with 10 when user has no collaborators set', function (done) {
this.LimitationsManager.allowedNumberOfCollaboratorsForUser
.withArgs(this.sendingUserId)
.yields(null)
diff --git a/services/web/test/unit/src/Collaborators/CollaboratorsInviteHandlerTests.js b/services/web/test/unit/src/Collaborators/CollaboratorsInviteHandlerTests.js
index 1c658ca93b..99aba4c37f 100644
--- a/services/web/test/unit/src/Collaborators/CollaboratorsInviteHandlerTests.js
+++ b/services/web/test/unit/src/Collaborators/CollaboratorsInviteHandlerTests.js
@@ -23,10 +23,10 @@ const events = require('events')
const { ObjectId } = require('mongodb')
const Crypto = require('crypto')
-describe('CollaboratorsInviteHandler', function() {
- beforeEach(function() {
+describe('CollaboratorsInviteHandler', function () {
+ beforeEach(function () {
let ProjectInvite
- this.ProjectInvite = ProjectInvite = (function() {
+ this.ProjectInvite = ProjectInvite = (function () {
ProjectInvite = class ProjectInvite {
static initClass() {
this.prototype.save = sinon.stub()
@@ -93,8 +93,8 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('getInviteCount', function() {
- beforeEach(function() {
+ describe('getInviteCount', function () {
+ beforeEach(function () {
this.ProjectInvite.countDocuments.callsArgWith(1, null, 2)
return (this.call = callback => {
return this.CollaboratorsInviteHandler.getInviteCount(
@@ -104,7 +104,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, invites) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -112,22 +112,22 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should produce the count of documents', function(done) {
+ it('should produce the count of documents', function (done) {
return this.call((err, count) => {
expect(count).to.equal(2)
return done()
})
})
- describe('when model.countDocuments produces an error', function() {
- beforeEach(function() {
+ describe('when model.countDocuments produces an error', function () {
+ beforeEach(function () {
return this.ProjectInvite.countDocuments.callsArgWith(
1,
new Error('woops')
)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, count) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -136,8 +136,8 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('getAllInvites', function() {
- beforeEach(function() {
+ describe('getAllInvites', function () {
+ beforeEach(function () {
this.fakeInvites = [
{ _id: ObjectId(), one: 1 },
{ _id: ObjectId(), two: 2 }
@@ -151,10 +151,10 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when all goes well', function() {
- beforeEach(function() {})
+ describe('when all goes well', function () {
+ beforeEach(function () {})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, invites) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -162,7 +162,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should produce a list of invite objects', function(done) {
+ it('should produce a list of invite objects', function (done) {
return this.call((err, invites) => {
expect(invites).to.not.be.oneOf([null, undefined])
expect(invites).to.deep.equal(this.fakeInvites)
@@ -170,7 +170,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have called ProjectInvite.find', function(done) {
+ it('should have called ProjectInvite.find', function (done) {
return this.call((err, invites) => {
this.ProjectInvite.find.callCount.should.equal(1)
this.ProjectInvite.find
@@ -181,12 +181,12 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when ProjectInvite.find produces an error', function() {
- beforeEach(function() {
+ describe('when ProjectInvite.find produces an error', function () {
+ beforeEach(function () {
return this.ProjectInvite.find.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, invites) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -195,9 +195,9 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('inviteToProject', function() {
- beforeEach(function() {
- this.ProjectInvite.prototype.save = sinon.spy(function(cb) {
+ describe('inviteToProject', function () {
+ beforeEach(function () {
+ this.ProjectInvite.prototype.save = sinon.spy(function (cb) {
return cb(null, this)
})
this.randomBytesSpy = sinon.spy(this.Crypto, 'randomBytes')
@@ -215,14 +215,14 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
return this.randomBytesSpy.restore()
})
- describe('when all goes well', function() {
- beforeEach(function() {})
+ describe('when all goes well', function () {
+ beforeEach(function () {})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -230,7 +230,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should produce the invite object', function(done) {
+ it('should produce the invite object', function (done) {
return this.call((err, invite) => {
expect(invite).to.not.equal(null)
expect(invite).to.not.equal(undefined)
@@ -247,21 +247,21 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have generated a random token', function(done) {
+ it('should have generated a random token', function (done) {
return this.call((err, invite) => {
this.randomBytesSpy.callCount.should.equal(1)
return done()
})
})
- it('should have called ProjectInvite.save', function(done) {
+ it('should have called ProjectInvite.save', function (done) {
return this.call((err, invite) => {
this.ProjectInvite.prototype.save.callCount.should.equal(1)
return done()
})
})
- it('should have called _sendMessages', function(done) {
+ it('should have called _sendMessages', function (done) {
return this.call((err, invite) => {
this.CollaboratorsInviteHandler._sendMessages.callCount.should.equal(
1
@@ -274,14 +274,14 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when saving model produces an error', function() {
- beforeEach(function() {
- return (this.ProjectInvite.prototype.save = sinon.spy(function(cb) {
+ describe('when saving model produces an error', function () {
+ beforeEach(function () {
+ return (this.ProjectInvite.prototype.save = sinon.spy(function (cb) {
return cb(new Error('woops'), this)
}))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -290,8 +290,8 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('_sendMessages', function() {
- beforeEach(function() {
+ describe('_sendMessages', function () {
+ beforeEach(function () {
this.CollaboratorsEmailHandler.notifyUserOfProjectInvite = sinon
.stub()
.callsArgWith(4, null)
@@ -308,8 +308,8 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when all goes well', function() {
- it('should not produce an error', function(done) {
+ describe('when all goes well', function () {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -317,7 +317,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should call CollaboratorsEmailHandler.notifyUserOfProjectInvite', function(done) {
+ it('should call CollaboratorsEmailHandler.notifyUserOfProjectInvite', function (done) {
return this.call(err => {
this.CollaboratorsEmailHandler.notifyUserOfProjectInvite.callCount.should.equal(
1
@@ -329,7 +329,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should call _trySendInviteNotification', function(done) {
+ it('should call _trySendInviteNotification', function (done) {
return this.call(err => {
this.CollaboratorsInviteHandler._trySendInviteNotification.callCount.should.equal(
1
@@ -342,21 +342,21 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when CollaboratorsEmailHandler.notifyUserOfProjectInvite produces an error', function() {
- beforeEach(function() {
+ describe('when CollaboratorsEmailHandler.notifyUserOfProjectInvite produces an error', function () {
+ beforeEach(function () {
return (this.CollaboratorsEmailHandler.notifyUserOfProjectInvite = sinon
.stub()
.callsArgWith(4, new Error('woops')))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should not call _trySendInviteNotification', function(done) {
+ it('should not call _trySendInviteNotification', function (done) {
return this.call(err => {
this.CollaboratorsInviteHandler._trySendInviteNotification.callCount.should.equal(
0
@@ -366,14 +366,14 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when _trySendInviteNotification produces an error', function() {
- beforeEach(function() {
+ describe('when _trySendInviteNotification produces an error', function () {
+ beforeEach(function () {
return (this.CollaboratorsInviteHandler._trySendInviteNotification = sinon
.stub()
.callsArgWith(3, new Error('woops')))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -382,8 +382,8 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('revokeInvite', function() {
- beforeEach(function() {
+ describe('revokeInvite', function () {
+ beforeEach(function () {
this.ProjectInvite.deleteOne.callsArgWith(1, null)
this.CollaboratorsInviteHandler._tryCancelInviteNotification = sinon
.stub()
@@ -397,10 +397,10 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when all goes well', function() {
- beforeEach(function() {})
+ describe('when all goes well', function () {
+ beforeEach(function () {})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -408,7 +408,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should call ProjectInvite.deleteOne', function(done) {
+ it('should call ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(1)
this.ProjectInvite.deleteOne
@@ -418,7 +418,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should call _tryCancelInviteNotification', function(done) {
+ it('should call _tryCancelInviteNotification', function (done) {
return this.call(err => {
this.CollaboratorsInviteHandler._tryCancelInviteNotification.callCount.should.equal(
1
@@ -431,12 +431,12 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when remove produces an error', function() {
- beforeEach(function() {
+ describe('when remove produces an error', function () {
+ beforeEach(function () {
return this.ProjectInvite.deleteOne.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
@@ -445,8 +445,8 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('resendInvite', function() {
- beforeEach(function() {
+ describe('resendInvite', function () {
+ beforeEach(function () {
this.ProjectInvite.findOne.callsArgWith(1, null, this.fakeInvite)
this.CollaboratorsInviteHandler._sendMessages = sinon
.stub()
@@ -461,10 +461,10 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when all goes well', function() {
- beforeEach(function() {})
+ describe('when all goes well', function () {
+ beforeEach(function () {})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -472,7 +472,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should call ProjectInvite.findOne', function(done) {
+ it('should call ProjectInvite.findOne', function (done) {
return this.call((err, invite) => {
this.ProjectInvite.findOne.callCount.should.equal(1)
this.ProjectInvite.findOne
@@ -482,7 +482,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have called _sendMessages', function(done) {
+ it('should have called _sendMessages', function (done) {
return this.call((err, invite) => {
this.CollaboratorsInviteHandler._sendMessages.callCount.should.equal(
1
@@ -495,19 +495,19 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when findOne produces an error', function() {
- beforeEach(function() {
+ describe('when findOne produces an error', function () {
+ beforeEach(function () {
return this.ProjectInvite.findOne.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should not have called _sendMessages', function(done) {
+ it('should not have called _sendMessages', function (done) {
return this.call((err, invite) => {
this.CollaboratorsInviteHandler._sendMessages.callCount.should.equal(
0
@@ -517,12 +517,12 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when findOne does not find an invite', function() {
- beforeEach(function() {
+ describe('when findOne does not find an invite', function () {
+ beforeEach(function () {
return this.ProjectInvite.findOne.callsArgWith(1, null, null)
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -530,7 +530,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should not have called _sendMessages', function(done) {
+ it('should not have called _sendMessages', function (done) {
return this.call((err, invite) => {
this.CollaboratorsInviteHandler._sendMessages.callCount.should.equal(
0
@@ -541,8 +541,8 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('getInviteByToken', function() {
- beforeEach(function() {
+ describe('getInviteByToken', function () {
+ beforeEach(function () {
this.ProjectInvite.findOne.callsArgWith(1, null, this.fakeInvite)
return (this.call = callback => {
return this.CollaboratorsInviteHandler.getInviteByToken(
@@ -553,10 +553,10 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when all goes well', function() {
- beforeEach(function() {})
+ describe('when all goes well', function () {
+ beforeEach(function () {})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -564,14 +564,14 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should produce the invite object', function(done) {
+ it('should produce the invite object', function (done) {
return this.call((err, invite) => {
expect(invite).to.deep.equal(this.fakeInvite)
return done()
})
})
- it('should call ProjectInvite.findOne', function(done) {
+ it('should call ProjectInvite.findOne', function (done) {
return this.call((err, invite) => {
this.ProjectInvite.findOne.callCount.should.equal(1)
this.ProjectInvite.findOne
@@ -582,12 +582,12 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when findOne produces an error', function() {
- beforeEach(function() {
+ describe('when findOne produces an error', function () {
+ beforeEach(function () {
return this.ProjectInvite.findOne.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -595,12 +595,12 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when findOne does not find an invite', function() {
- beforeEach(function() {
+ describe('when findOne does not find an invite', function () {
+ beforeEach(function () {
return this.ProjectInvite.findOne.callsArgWith(1, null, null)
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -608,7 +608,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should not produce an invite object', function(done) {
+ it('should not produce an invite object', function (done) {
return this.call((err, invite) => {
expect(invite).to.not.be.instanceof(Error)
expect(invite).to.be.oneOf([null, undefined])
@@ -618,8 +618,8 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('acceptInvite', function() {
- beforeEach(function() {
+ describe('acceptInvite', function () {
+ beforeEach(function () {
this.fakeProject = {
_id: this.projectId,
collaberator_refs: [],
@@ -645,14 +645,14 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
return this._getInviteByToken.restore()
})
- describe('when all goes well', function() {
- beforeEach(function() {})
+ describe('when all goes well', function () {
+ beforeEach(function () {})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -660,7 +660,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have called getInviteByToken', function(done) {
+ it('should have called getInviteByToken', function (done) {
return this.call(err => {
this._getInviteByToken.callCount.should.equal(1)
this._getInviteByToken
@@ -670,7 +670,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have called CollaboratorsHandler.addUserIdToProject', function(done) {
+ it('should have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(1)
this.CollaboratorsHandler.addUserIdToProject
@@ -685,7 +685,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have called ProjectInvite.deleteOne', function(done) {
+ it('should have called ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(1)
this.ProjectInvite.deleteOne
@@ -696,13 +696,13 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when the invite is for readOnly access', function() {
- beforeEach(function() {
+ describe('when the invite is for readOnly access', function () {
+ beforeEach(function () {
this.fakeInvite.privileges = 'readOnly'
return this._getInviteByToken.callsArgWith(2, null, this.fakeInvite)
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
@@ -710,7 +710,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have called CollaboratorsHandler.addUserIdToProject', function(done) {
+ it('should have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(1)
this.CollaboratorsHandler.addUserIdToProject
@@ -726,12 +726,12 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when getInviteByToken does not find an invite', function() {
- beforeEach(function() {
+ describe('when getInviteByToken does not find an invite', function () {
+ beforeEach(function () {
return this._getInviteByToken.callsArgWith(2, null, null)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
expect(err.name).to.equal('NotFoundError')
@@ -739,7 +739,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have called getInviteByToken', function(done) {
+ it('should have called getInviteByToken', function (done) {
return this.call(err => {
this._getInviteByToken.callCount.should.equal(1)
this._getInviteByToken
@@ -749,14 +749,14 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should not have called CollaboratorsHandler.addUserIdToProject', function(done) {
+ it('should not have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(0)
return done()
})
})
- it('should not have called ProjectInvite.deleteOne', function(done) {
+ it('should not have called ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(0)
return done()
@@ -764,19 +764,19 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when getInviteByToken produces an error', function() {
- beforeEach(function() {
+ describe('when getInviteByToken produces an error', function () {
+ beforeEach(function () {
return this._getInviteByToken.callsArgWith(2, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should have called getInviteByToken', function(done) {
+ it('should have called getInviteByToken', function (done) {
return this.call(err => {
this._getInviteByToken.callCount.should.equal(1)
this._getInviteByToken
@@ -786,14 +786,14 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should not have called CollaboratorsHandler.addUserIdToProject', function(done) {
+ it('should not have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(0)
return done()
})
})
- it('should not have called ProjectInvite.deleteOne', function(done) {
+ it('should not have called ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(0)
return done()
@@ -801,22 +801,22 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when addUserIdToProject produces an error', function() {
- beforeEach(function() {
+ describe('when addUserIdToProject produces an error', function () {
+ beforeEach(function () {
return this.CollaboratorsHandler.addUserIdToProject.callsArgWith(
4,
new Error('woops')
)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should have called getInviteByToken', function(done) {
+ it('should have called getInviteByToken', function (done) {
return this.call(err => {
this._getInviteByToken.callCount.should.equal(1)
this._getInviteByToken
@@ -826,7 +826,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have called CollaboratorsHandler.addUserIdToProject', function(done) {
+ it('should have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(1)
this.CollaboratorsHandler.addUserIdToProject
@@ -841,7 +841,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should not have called ProjectInvite.deleteOne', function(done) {
+ it('should not have called ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(0)
return done()
@@ -849,19 +849,19 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when ProjectInvite.deleteOne produces an error', function() {
- beforeEach(function() {
+ describe('when ProjectInvite.deleteOne produces an error', function () {
+ beforeEach(function () {
return this.ProjectInvite.deleteOne.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should have called getInviteByToken', function(done) {
+ it('should have called getInviteByToken', function (done) {
return this.call(err => {
this._getInviteByToken.callCount.should.equal(1)
this._getInviteByToken
@@ -871,7 +871,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have called CollaboratorsHandler.addUserIdToProject', function(done) {
+ it('should have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(1)
this.CollaboratorsHandler.addUserIdToProject
@@ -886,7 +886,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should have called ProjectInvite.deleteOne', function(done) {
+ it('should have called ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(1)
return done()
@@ -895,8 +895,8 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('_tryCancelInviteNotification', function() {
- beforeEach(function() {
+ describe('_tryCancelInviteNotification', function () {
+ beforeEach(function () {
this.inviteId = ObjectId()
this.currentUser = { _id: ObjectId() }
this.notification = { read: sinon.stub().callsArgWith(0, null) }
@@ -911,22 +911,22 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
- it('should call notification.read', function(done) {
+ it('should call notification.read', function (done) {
return this.call(err => {
this.notification.read.callCount.should.equal(1)
return done()
})
})
- describe('when notification.read produces an error', function() {
- beforeEach(function() {
+ describe('when notification.read produces an error', function () {
+ beforeEach(function () {
this.notification = {
read: sinon.stub().callsArgWith(0, new Error('woops'))
}
@@ -935,7 +935,7 @@ describe('CollaboratorsInviteHandler', function() {
.returns(this.notification))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
@@ -944,8 +944,8 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('_trySendInviteNotification', function() {
- beforeEach(function() {
+ describe('_trySendInviteNotification', function () {
+ beforeEach(function () {
this.invite = {
_id: ObjectId(),
token: 'some_token',
@@ -983,17 +983,17 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when the user exists', function() {
- beforeEach(function() {})
+ describe('when the user exists', function () {
+ beforeEach(function () {})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
- it('should call getUser', function(done) {
+ it('should call getUser', function (done) {
return this.call(err => {
this.UserGetter.getUserByAnyEmail.callCount.should.equal(1)
this.UserGetter.getUserByAnyEmail
@@ -1003,7 +1003,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should call getProject', function(done) {
+ it('should call getProject', function (done) {
return this.call(err => {
this.ProjectGetter.getProject.callCount.should.equal(1)
this.ProjectGetter.getProject
@@ -1013,7 +1013,7 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should call NotificationsBuilder.projectInvite.create', function(done) {
+ it('should call NotificationsBuilder.projectInvite.create', function (done) {
return this.call(err => {
this.NotificationsBuilder.projectInvite.callCount.should.equal(1)
this.notification.create.callCount.should.equal(1)
@@ -1021,22 +1021,22 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when getProject produces an error', function() {
- beforeEach(function() {
+ describe('when getProject produces an error', function () {
+ beforeEach(function () {
return this.ProjectGetter.getProject.callsArgWith(
2,
new Error('woops')
)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should not call NotificationsBuilder.projectInvite.create', function(done) {
+ it('should not call NotificationsBuilder.projectInvite.create', function (done) {
return this.call(err => {
this.NotificationsBuilder.projectInvite.callCount.should.equal(0)
this.notification.create.callCount.should.equal(0)
@@ -1045,12 +1045,12 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when projectInvite.create produces an error', function() {
- beforeEach(function() {
+ describe('when projectInvite.create produces an error', function () {
+ beforeEach(function () {
return this.notification.create.callsArgWith(0, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
@@ -1059,21 +1059,21 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when the user does not exist', function() {
- beforeEach(function() {
+ describe('when the user does not exist', function () {
+ beforeEach(function () {
return (this.UserGetter.getUserByAnyEmail = sinon
.stub()
.callsArgWith(2, null, null))
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
- it('should call getUser', function(done) {
+ it('should call getUser', function (done) {
return this.call(err => {
this.UserGetter.getUserByAnyEmail.callCount.should.equal(1)
this.UserGetter.getUserByAnyEmail
@@ -1083,14 +1083,14 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should not call getProject', function(done) {
+ it('should not call getProject', function (done) {
return this.call(err => {
this.ProjectGetter.getProject.callCount.should.equal(0)
return done()
})
})
- it('should not call NotificationsBuilder.projectInvite.create', function(done) {
+ it('should not call NotificationsBuilder.projectInvite.create', function (done) {
return this.call(err => {
this.NotificationsBuilder.projectInvite.callCount.should.equal(0)
this.notification.create.callCount.should.equal(0)
@@ -1099,21 +1099,21 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- describe('when the getUser produces an error', function() {
- beforeEach(function() {
+ describe('when the getUser produces an error', function () {
+ beforeEach(function () {
return (this.UserGetter.getUserByAnyEmail = sinon
.stub()
.callsArgWith(2, new Error('woops')))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should call getUser', function(done) {
+ it('should call getUser', function (done) {
return this.call(err => {
this.UserGetter.getUserByAnyEmail.callCount.should.equal(1)
this.UserGetter.getUserByAnyEmail
@@ -1123,14 +1123,14 @@ describe('CollaboratorsInviteHandler', function() {
})
})
- it('should not call getProject', function(done) {
+ it('should not call getProject', function (done) {
return this.call(err => {
this.ProjectGetter.getProject.callCount.should.equal(0)
return done()
})
})
- it('should not call NotificationsBuilder.projectInvite.create', function(done) {
+ it('should not call NotificationsBuilder.projectInvite.create', function (done) {
return this.call(err => {
this.NotificationsBuilder.projectInvite.callCount.should.equal(0)
this.notification.create.callCount.should.equal(0)
diff --git a/services/web/test/unit/src/Collaborators/OwnershipTransferHandlerTests.js b/services/web/test/unit/src/Collaborators/OwnershipTransferHandlerTests.js
index 67ef08ec98..220e30760d 100644
--- a/services/web/test/unit/src/Collaborators/OwnershipTransferHandlerTests.js
+++ b/services/web/test/unit/src/Collaborators/OwnershipTransferHandlerTests.js
@@ -8,8 +8,8 @@ const { ObjectId } = require('mongodb')
const MODULE_PATH =
'../../../../app/src/Features/Collaborators/OwnershipTransferHandler'
-describe('OwnershipTransferHandler', function() {
- beforeEach(function() {
+describe('OwnershipTransferHandler', function () {
+ beforeEach(function () {
this.user = { _id: ObjectId(), email: 'owner@example.com' }
this.collaborator = { _id: ObjectId(), email: 'collaborator@example.com' }
this.project = {
@@ -74,8 +74,8 @@ describe('OwnershipTransferHandler', function() {
})
})
- describe('transferOwnership', function() {
- beforeEach(function() {
+ describe('transferOwnership', function () {
+ beforeEach(function () {
this.UserGetter.promises.getUser
.withArgs(this.user._id)
.resolves(this.user)
@@ -84,14 +84,14 @@ describe('OwnershipTransferHandler', function() {
.resolves(this.collaborator)
})
- it("should return a not found error if the project can't be found", async function() {
+ it("should return a not found error if the project can't be found", async function () {
this.ProjectGetter.promises.getProject.resolves(null)
await expect(
this.handler.promises.transferOwnership('abc', this.collaborator._id)
).to.be.rejectedWith(Errors.ProjectNotFoundError)
})
- it("should return a not found error if the user can't be found", async function() {
+ it("should return a not found error if the user can't be found", async function () {
this.UserGetter.promises.getUser
.withArgs(this.collaborator._id)
.resolves(null)
@@ -103,7 +103,7 @@ describe('OwnershipTransferHandler', function() {
).to.be.rejectedWith(Errors.UserNotFoundError)
})
- it('should return an error if user cannot be removed as collaborator ', async function() {
+ it('should return an error if user cannot be removed as collaborator ', async function () {
this.CollaboratorsHandler.promises.removeUserFromProject.rejects(
new Error('user-cannot-be-removed')
)
@@ -115,7 +115,7 @@ describe('OwnershipTransferHandler', function() {
).to.be.rejected
})
- it('should transfer ownership of the project', async function() {
+ it('should transfer ownership of the project', async function () {
await this.handler.promises.transferOwnership(
this.project._id,
this.collaborator._id
@@ -126,7 +126,7 @@ describe('OwnershipTransferHandler', function() {
)
})
- it('should do nothing if transferring back to the owner', async function() {
+ it('should do nothing if transferring back to the owner', async function () {
await this.handler.promises.transferOwnership(
this.project._id,
this.user._id
@@ -134,7 +134,7 @@ describe('OwnershipTransferHandler', function() {
expect(this.ProjectModel.updateOne).not.to.have.been.called
})
- it("should remove the user from the project's collaborators", async function() {
+ it("should remove the user from the project's collaborators", async function () {
await this.handler.promises.transferOwnership(
this.project._id,
this.collaborator._id
@@ -144,7 +144,7 @@ describe('OwnershipTransferHandler', function() {
).to.have.been.calledWith(this.project._id, this.collaborator._id)
})
- it('should add the former project owner as a read/write collaborator', async function() {
+ it('should add the former project owner as a read/write collaborator', async function () {
await this.handler.promises.transferOwnership(
this.project._id,
this.collaborator._id
@@ -159,7 +159,7 @@ describe('OwnershipTransferHandler', function() {
)
})
- it('should flush the project to tpds', async function() {
+ it('should flush the project to tpds', async function () {
await this.handler.promises.transferOwnership(
this.project._id,
this.collaborator._id
@@ -169,7 +169,7 @@ describe('OwnershipTransferHandler', function() {
).to.have.been.calledWith(this.project._id)
})
- it('should send an email notification', async function() {
+ it('should send an email notification', async function () {
await this.handler.promises.transferOwnership(
this.project._id,
this.collaborator._id
@@ -192,7 +192,7 @@ describe('OwnershipTransferHandler', function() {
)
})
- it('should write an entry in the audit log', async function() {
+ it('should write an entry in the audit log', async function () {
const sessionUserId = ObjectId()
await this.handler.promises.transferOwnership(
this.project._id,
@@ -212,7 +212,7 @@ describe('OwnershipTransferHandler', function() {
)
})
- it('should decline to transfer ownership to a non-collaborator', async function() {
+ it('should decline to transfer ownership to a non-collaborator', async function () {
this.project.collaberator_refs = []
await expect(
this.handler.promises.transferOwnership(
diff --git a/services/web/test/unit/src/Compile/ClsiCookieManagerTests.js b/services/web/test/unit/src/Compile/ClsiCookieManagerTests.js
index 87b734da7f..4418d3befc 100644
--- a/services/web/test/unit/src/Compile/ClsiCookieManagerTests.js
+++ b/services/web/test/unit/src/Compile/ClsiCookieManagerTests.js
@@ -17,8 +17,8 @@ const modulePath = '../../../../app/src/Features/Compile/ClsiCookieManager.js'
const SandboxedModule = require('sandboxed-module')
const realRequst = require('request')
-describe('ClsiCookieManager', function() {
- beforeEach(function() {
+describe('ClsiCookieManager', function () {
+ beforeEach(function () {
const self = this
this.redis = {
auth() {},
@@ -60,8 +60,8 @@ describe('ClsiCookieManager', function() {
})())
})
- describe('getServerId', function() {
- it('should call get for the key', function(done) {
+ describe('getServerId', function () {
+ it('should call get for the key', function (done) {
this.redis.get.callsArgWith(1, null, 'clsi-7')
return this.ClsiCookieManager._getServerId(
this.project_id,
@@ -75,7 +75,7 @@ describe('ClsiCookieManager', function() {
)
})
- it('should _populateServerIdViaRequest if no key is found', function(done) {
+ it('should _populateServerIdViaRequest if no key is found', function (done) {
this.ClsiCookieManager._populateServerIdViaRequest = sinon
.stub()
.callsArgWith(1)
@@ -91,7 +91,7 @@ describe('ClsiCookieManager', function() {
)
})
- it('should _populateServerIdViaRequest if no key is blank', function(done) {
+ it('should _populateServerIdViaRequest if no key is blank', function (done) {
this.ClsiCookieManager._populateServerIdViaRequest = sinon
.stub()
.callsArgWith(1)
@@ -108,8 +108,8 @@ describe('ClsiCookieManager', function() {
})
})
- describe('_populateServerIdViaRequest', function() {
- beforeEach(function() {
+ describe('_populateServerIdViaRequest', function () {
+ beforeEach(function () {
this.response = 'some data'
this.request.post.callsArgWith(1, null, this.response)
return (this.ClsiCookieManager.setServerId = sinon
@@ -117,7 +117,7 @@ describe('ClsiCookieManager', function() {
.callsArgWith(2, null, 'clsi-9'))
})
- it('should make a request to the clsi', function(done) {
+ it('should make a request to the clsi', function (done) {
return this.ClsiCookieManager._populateServerIdViaRequest(
this.project_id,
(err, serverId) => {
@@ -129,7 +129,7 @@ describe('ClsiCookieManager', function() {
)
})
- it('should return the server id', function(done) {
+ it('should return the server id', function (done) {
return this.ClsiCookieManager._populateServerIdViaRequest(
this.project_id,
(err, serverId) => {
@@ -140,15 +140,15 @@ describe('ClsiCookieManager', function() {
})
})
- describe('setServerId', function() {
- beforeEach(function() {
+ describe('setServerId', function () {
+ beforeEach(function () {
this.response = 'dsadsakj'
this.ClsiCookieManager._parseServerIdFromResponse = sinon
.stub()
.returns('clsi-8')
})
- it('should set the server id with a ttl', function(done) {
+ it('should set the server id with a ttl', function (done) {
return this.ClsiCookieManager.setServerId(
this.project_id,
this.response,
@@ -165,7 +165,7 @@ describe('ClsiCookieManager', function() {
)
})
- it('should return the server id', function(done) {
+ it('should return the server id', function (done) {
return this.ClsiCookieManager.setServerId(
this.project_id,
this.response,
@@ -176,7 +176,7 @@ describe('ClsiCookieManager', function() {
)
})
- it('should not set the server id if clsiCookies are not enabled', function(done) {
+ it('should not set the server id if clsiCookies are not enabled', function (done) {
delete this.settings.clsiCookie.key
this.ClsiCookieManager = SandboxedModule.require(modulePath, {
globals: {
@@ -194,7 +194,7 @@ describe('ClsiCookieManager', function() {
)
})
- it('should not set the server id there is no server id in the response', function(done) {
+ it('should not set the server id there is no server id in the response', function (done) {
this.ClsiCookieManager._parseServerIdFromResponse = sinon
.stub()
.returns(null)
@@ -208,7 +208,7 @@ describe('ClsiCookieManager', function() {
)
})
- it('should also set in the secondary if secondary redis is enabled', function(done) {
+ it('should also set in the secondary if secondary redis is enabled', function (done) {
this.redis_secondary = { setex: sinon.stub().callsArg(3) }
this.settings.redis.clsi_cookie_secondary = {}
this.RedisWrapper.client = sinon.stub()
@@ -242,14 +242,14 @@ describe('ClsiCookieManager', function() {
})
})
- describe('getCookieJar', function() {
- beforeEach(function() {
+ describe('getCookieJar', function () {
+ beforeEach(function () {
return (this.ClsiCookieManager._getServerId = sinon
.stub()
.callsArgWith(1, null, 'clsi-11'))
})
- it('should return a jar with the cookie set populated from redis', function(done) {
+ it('should return a jar with the cookie set populated from redis', function (done) {
return this.ClsiCookieManager.getCookieJar(
this.project_id,
(err, jar) => {
@@ -264,7 +264,7 @@ describe('ClsiCookieManager', function() {
)
})
- it('should return empty cookie jar if clsiCookies are not enabled', function(done) {
+ it('should return empty cookie jar if clsiCookies are not enabled', function (done) {
delete this.settings.clsiCookie.key
this.ClsiCookieManager = SandboxedModule.require(modulePath, {
globals: {
diff --git a/services/web/test/unit/src/Compile/ClsiFormatCheckerTests.js b/services/web/test/unit/src/Compile/ClsiFormatCheckerTests.js
index ce6e06480e..391a8fceaf 100644
--- a/services/web/test/unit/src/Compile/ClsiFormatCheckerTests.js
+++ b/services/web/test/unit/src/Compile/ClsiFormatCheckerTests.js
@@ -16,8 +16,8 @@ const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/Compile/ClsiFormatChecker.js'
const SandboxedModule = require('sandboxed-module')
-describe('ClsiFormatChecker', function() {
- beforeEach(function() {
+describe('ClsiFormatChecker', function () {
+ beforeEach(function () {
this.ClsiFormatChecker = SandboxedModule.require(modulePath, {
requires: {
'settings-sharelatex': (this.settings = { compileBodySizeLimitMb: 5 })
@@ -26,8 +26,8 @@ describe('ClsiFormatChecker', function() {
return (this.project_id = 'project-id')
})
- describe('checkRecoursesForProblems', function() {
- beforeEach(function() {
+ describe('checkRecoursesForProblems', function () {
+ beforeEach(function () {
return (this.resources = [
{
path: 'main.tex',
@@ -45,7 +45,7 @@ describe('ClsiFormatChecker', function() {
])
})
- it('should call _checkDocsAreUnderSizeLimit and _checkForConflictingPaths', function(done) {
+ it('should call _checkDocsAreUnderSizeLimit and _checkForConflictingPaths', function (done) {
this.ClsiFormatChecker._checkForConflictingPaths = sinon
.stub()
.callsArgWith(1, null)
@@ -66,7 +66,7 @@ describe('ClsiFormatChecker', function() {
)
})
- it('should remove undefined errors', function(done) {
+ it('should remove undefined errors', function (done) {
this.ClsiFormatChecker._checkForConflictingPaths = sinon
.stub()
.callsArgWith(1, null, [])
@@ -83,7 +83,7 @@ describe('ClsiFormatChecker', function() {
)
})
- it('should keep populated arrays', function(done) {
+ it('should keep populated arrays', function (done) {
this.ClsiFormatChecker._checkForConflictingPaths = sinon
.stub()
.callsArgWith(1, null, [{ path: 'somewhere/main.tex' }])
@@ -100,7 +100,7 @@ describe('ClsiFormatChecker', function() {
)
})
- it('should keep populated object', function(done) {
+ it('should keep populated object', function (done) {
this.ClsiFormatChecker._checkForConflictingPaths = sinon
.stub()
.callsArgWith(1, null, [])
@@ -121,8 +121,8 @@ describe('ClsiFormatChecker', function() {
)
})
- describe('_checkForConflictingPaths', function() {
- beforeEach(function() {
+ describe('_checkForConflictingPaths', function () {
+ beforeEach(function () {
this.resources.push({
path: 'chapters/chapter1.tex',
content: 'other stuff'
@@ -134,7 +134,7 @@ describe('ClsiFormatChecker', function() {
})
})
- it('should flag up when a nested file has folder with same subpath as file elsewhere', function(done) {
+ it('should flag up when a nested file has folder with same subpath as file elsewhere', function (done) {
this.resources.push({
path: 'stuff/image',
url: 'http://somwhere.com'
@@ -150,7 +150,7 @@ describe('ClsiFormatChecker', function() {
)
})
- it('should flag up when a root level file has folder with same subpath as file elsewhere', function(done) {
+ it('should flag up when a root level file has folder with same subpath as file elsewhere', function (done) {
this.resources.push({
path: 'stuff',
content: 'other stuff'
@@ -166,7 +166,7 @@ describe('ClsiFormatChecker', function() {
)
})
- it('should not flag up when the file is a substring of a path', function(done) {
+ it('should not flag up when the file is a substring of a path', function (done) {
this.resources.push({
path: 'stuf',
content: 'other stuff'
@@ -182,8 +182,8 @@ describe('ClsiFormatChecker', function() {
})
})
- describe('_checkDocsAreUnderSizeLimit', function() {
- it('should error when there is more than 5mb of data', function(done) {
+ describe('_checkDocsAreUnderSizeLimit', function () {
+ it('should error when there is more than 5mb of data', function (done) {
this.resources.push({
path: 'massive.tex',
content: 'hello world'.repeat(833333) // over 5mb limit
@@ -208,7 +208,7 @@ describe('ClsiFormatChecker', function() {
)
})
- it('should return nothing when project is correct size', function(done) {
+ it('should return nothing when project is correct size', function (done) {
this.resources.push({
path: 'massive.tex',
content: 'x'.repeat(2 * 1000 * 1000)
diff --git a/services/web/test/unit/src/Compile/ClsiManagerTests.js b/services/web/test/unit/src/Compile/ClsiManagerTests.js
index 39bdf35ca1..0ff98df914 100644
--- a/services/web/test/unit/src/Compile/ClsiManagerTests.js
+++ b/services/web/test/unit/src/Compile/ClsiManagerTests.js
@@ -3,8 +3,8 @@ const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/Compile/ClsiManager.js'
const SandboxedModule = require('sandboxed-module')
-describe('ClsiManager', function() {
- beforeEach(function() {
+describe('ClsiManager', function () {
+ beforeEach(function () {
this.jar = { cookie: 'stuff' }
this.ClsiCookieManager = {
clearServerId: sinon.stub().yields(),
@@ -68,16 +68,16 @@ describe('ClsiManager', function() {
this.callback = sinon.stub()
})
- describe('sendRequest', function() {
- beforeEach(function() {
+ describe('sendRequest', function () {
+ beforeEach(function () {
this.ClsiManager._buildRequest = sinon
.stub()
.callsArgWith(2, null, (this.request = 'mock-request'))
this.ClsiCookieManager._getServerId.callsArgWith(1, null, 'clsi3')
})
- describe('with a successful compile', function() {
- beforeEach(function() {
+ describe('with a successful compile', function () {
+ beforeEach(function () {
this.ClsiManager._postToClsi = sinon.stub().callsArgWith(4, null, {
compile: {
status: (this.status = 'success'),
@@ -105,19 +105,19 @@ describe('ClsiManager', function() {
)
})
- it('should build the request', function() {
+ it('should build the request', function () {
this.ClsiManager._buildRequest
.calledWith(this.project_id)
.should.equal(true)
})
- it('should send the request to the CLSI', function() {
+ it('should send the request to the CLSI', function () {
this.ClsiManager._postToClsi
.calledWith(this.project_id, this.user_id, this.request, 'standard')
.should.equal(true)
})
- it('should call the callback with the status and output files', function() {
+ it('should call the callback with the status and output files', function () {
const outputFiles = [
{
url: `/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.pdf`,
@@ -138,8 +138,8 @@ describe('ClsiManager', function() {
})
})
- describe('with a failed compile', function() {
- beforeEach(function() {
+ describe('with a failed compile', function () {
+ beforeEach(function () {
this.ClsiManager._postToClsi = sinon.stub().callsArgWith(4, null, {
compile: {
status: (this.status = 'failure')
@@ -153,13 +153,13 @@ describe('ClsiManager', function() {
)
})
- it('should call the callback with a failure status', function() {
+ it('should call the callback with a failure status', function () {
this.callback.calledWith(null, this.status).should.equal(true)
})
})
- describe('with a sync conflict', function() {
- beforeEach(function() {
+ describe('with a sync conflict', function () {
+ beforeEach(function () {
this.ClsiManager.sendRequestOnce = sinon.stub()
this.ClsiManager.sendRequestOnce
.withArgs(this.project_id, this.user_id, { syncType: 'full' })
@@ -175,29 +175,29 @@ describe('ClsiManager', function() {
)
})
- it('should call the sendRequestOnce method twice', function() {
+ it('should call the sendRequestOnce method twice', function () {
this.ClsiManager.sendRequestOnce.calledTwice.should.equal(true)
})
- it('should call the sendRequestOnce method with syncType:full', function() {
+ it('should call the sendRequestOnce method with syncType:full', function () {
this.ClsiManager.sendRequestOnce
.calledWith(this.project_id, this.user_id, { syncType: 'full' })
.should.equal(true)
})
- it('should call the sendRequestOnce method without syncType:full', function() {
+ it('should call the sendRequestOnce method without syncType:full', function () {
this.ClsiManager.sendRequestOnce
.calledWith(this.project_id, this.user_id, {})
.should.equal(true)
})
- it('should call the callback with a success status', function() {
+ it('should call the callback with a success status', function () {
this.callback.calledWith(null, this.status).should.equal(true)
})
})
- describe('with an unavailable response', function() {
- beforeEach(function() {
+ describe('with an unavailable response', function () {
+ beforeEach(function () {
this.ClsiManager.sendRequestOnce = sinon.stub()
this.ClsiManager.sendRequestOnce
.withArgs(this.project_id, this.user_id, {
@@ -216,11 +216,11 @@ describe('ClsiManager', function() {
)
})
- it('should call the sendRequestOnce method twice', function() {
+ it('should call the sendRequestOnce method twice', function () {
this.ClsiManager.sendRequestOnce.calledTwice.should.equal(true)
})
- it('should call the sendRequestOnce method with forceNewClsiServer:true', function() {
+ it('should call the sendRequestOnce method with forceNewClsiServer:true', function () {
this.ClsiManager.sendRequestOnce
.calledWith(this.project_id, this.user_id, {
forceNewClsiServer: true,
@@ -229,19 +229,19 @@ describe('ClsiManager', function() {
.should.equal(true)
})
- it('should call the sendRequestOnce method without forceNewClsiServer:true', function() {
+ it('should call the sendRequestOnce method without forceNewClsiServer:true', function () {
this.ClsiManager.sendRequestOnce
.calledWith(this.project_id, this.user_id, {})
.should.equal(true)
})
- it('should call the callback with a success status', function() {
+ it('should call the callback with a success status', function () {
this.callback.calledWith(null, this.status).should.equal(true)
})
})
- describe('when the resources fail the precompile check', function() {
- beforeEach(function() {
+ describe('when the resources fail the precompile check', function () {
+ beforeEach(function () {
this.ClsiFormatChecker.checkRecoursesForProblems = sinon
.stub()
.callsArgWith(1, new Error('failed'))
@@ -258,25 +258,25 @@ describe('ClsiManager', function() {
)
})
- it('should call the callback only once', function() {
+ it('should call the callback only once', function () {
this.callback.calledOnce.should.equal(true)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
this.callback.should.have.been.calledWith(sinon.match.instanceOf(Error))
})
})
})
- describe('sendExternalRequest', function() {
- beforeEach(function() {
+ describe('sendExternalRequest', function () {
+ beforeEach(function () {
this.submission_id = 'submission-id'
this.clsi_request = 'mock-request'
this.ClsiCookieManager._getServerId.callsArgWith(1, null, 'clsi3')
})
- describe('with a successful compile', function() {
- beforeEach(function() {
+ describe('with a successful compile', function () {
+ beforeEach(function () {
this.ClsiManager._postToClsi = sinon.stub().callsArgWith(4, null, {
compile: {
status: (this.status = 'success'),
@@ -304,13 +304,13 @@ describe('ClsiManager', function() {
)
})
- it('should send the request to the CLSI', function() {
+ it('should send the request to the CLSI', function () {
this.ClsiManager._postToClsi
.calledWith(this.submission_id, null, this.clsi_request, 'standard')
.should.equal(true)
})
- it('should call the callback with the status and output files', function() {
+ it('should call the callback with the status and output files', function () {
const outputFiles = [
{
url: `/project/${this.submission_id}/build/1234/output/output.pdf`,
@@ -331,8 +331,8 @@ describe('ClsiManager', function() {
})
})
- describe('with a failed compile', function() {
- beforeEach(function() {
+ describe('with a failed compile', function () {
+ beforeEach(function () {
this.ClsiManager._postToClsi = sinon.stub().callsArgWith(4, null, {
compile: {
status: (this.status = 'failure')
@@ -346,13 +346,13 @@ describe('ClsiManager', function() {
)
})
- it('should call the callback with a failure status', function() {
+ it('should call the callback with a failure status', function () {
this.callback.calledWith(null, this.status).should.equal(true)
})
})
- describe('when the resources fail the precompile check', function() {
- beforeEach(function() {
+ describe('when the resources fail the precompile check', function () {
+ beforeEach(function () {
this.ClsiFormatChecker.checkRecoursesForProblems = sinon
.stub()
.callsArgWith(1, new Error('failed'))
@@ -369,24 +369,24 @@ describe('ClsiManager', function() {
)
})
- it('should call the callback only once', function() {
+ it('should call the callback only once', function () {
this.callback.calledOnce.should.equal(true)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
this.callback.should.have.been.calledWith(sinon.match.instanceOf(Error))
})
})
})
- describe('deleteAuxFiles', function() {
- beforeEach(function() {
+ describe('deleteAuxFiles', function () {
+ beforeEach(function () {
this.ClsiManager._makeRequestWithClsiServerId = sinon.stub().yields(null)
this.DocumentUpdaterHandler.clearProjectState = sinon.stub().callsArg(1)
})
- describe('with the standard compileGroup', function() {
- beforeEach(function() {
+ describe('with the standard compileGroup', function () {
+ beforeEach(function () {
this.ClsiManager.deleteAuxFiles(
this.project_id,
this.user_id,
@@ -396,7 +396,7 @@ describe('ClsiManager', function() {
)
})
- it('should call the delete method in the standard CLSI', function() {
+ it('should call the delete method in the standard CLSI', function () {
this.ClsiManager._makeRequestWithClsiServerId
.calledWith(
this.project_id,
@@ -409,26 +409,26 @@ describe('ClsiManager', function() {
.should.equal(true)
})
- it('should clear the project state from the docupdater', function() {
+ it('should clear the project state from the docupdater', function () {
this.DocumentUpdaterHandler.clearProjectState
.calledWith(this.project_id)
.should.equal(true)
})
- it('should clear the clsi persistance', function() {
+ it('should clear the clsi persistance', function () {
this.ClsiCookieManager.clearServerId
.calledWith(this.project_id)
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
})
- describe('_buildRequest', function() {
- beforeEach(function() {
+ describe('_buildRequest', function () {
+ beforeEach(function () {
this.project = {
_id: this.project_id,
compiler: (this.compiler = 'latex'),
@@ -472,8 +472,8 @@ describe('ClsiManager', function() {
.callsArgWith(1, null)
})
- describe('with a valid project', function() {
- beforeEach(function(done) {
+ describe('with a valid project', function () {
+ beforeEach(function (done) {
this.ClsiManager._buildRequest(
this.project_id,
{ timeout: 100, compileGroup: 'standard' },
@@ -487,7 +487,7 @@ describe('ClsiManager', function() {
)
})
- it('should get the project with the required fields', function() {
+ it('should get the project with the required fields', function () {
this.ProjectGetter.getProject
.calledWith(this.project_id, {
compiler: 1,
@@ -498,25 +498,25 @@ describe('ClsiManager', function() {
.should.equal(true)
})
- it('should flush the project to the database', function() {
+ it('should flush the project to the database', function () {
this.DocumentUpdaterHandler.flushProjectToMongo
.calledWith(this.project_id)
.should.equal(true)
})
- it('should get all the docs', function() {
+ it('should get all the docs', function () {
this.ProjectEntityHandler.getAllDocs
.calledWith(this.project_id)
.should.equal(true)
})
- it('should get all the files', function() {
+ it('should get all the files', function () {
this.ProjectEntityHandler.getAllFiles
.calledWith(this.project_id)
.should.equal(true)
})
- it('should build up the CLSI request', function() {
+ it('should build up the CLSI request', function () {
expect(this.request).to.deep.equal({
compile: {
options: {
@@ -550,8 +550,8 @@ describe('ClsiManager', function() {
})
})
- describe('with the incremental compile option', function() {
- beforeEach(function(done) {
+ describe('with the incremental compile option', function () {
+ beforeEach(function (done) {
this.ClsiStateManager.computeHash = sinon
.stub()
.callsArgWith(
@@ -584,7 +584,7 @@ describe('ClsiManager', function() {
)
})
- it('should get the project with the required fields', function() {
+ it('should get the project with the required fields', function () {
this.ProjectGetter.getProject
.calledWith(this.project_id, {
compiler: 1,
@@ -595,23 +595,23 @@ describe('ClsiManager', function() {
.should.equal(true)
})
- it('should not explicitly flush the project to the database', function() {
+ it('should not explicitly flush the project to the database', function () {
this.DocumentUpdaterHandler.flushProjectToMongo
.calledWith(this.project_id)
.should.equal(false)
})
- it('should get only the live docs from the docupdater with a background flush in docupdater', function() {
+ it('should get only the live docs from the docupdater with a background flush in docupdater', function () {
this.DocumentUpdaterHandler.getProjectDocsIfMatch
.calledWith(this.project_id)
.should.equal(true)
})
- it('should not get any of the files', function() {
+ it('should not get any of the files', function () {
this.ProjectEntityHandler.getAllFiles.called.should.equal(false)
})
- it('should build up the CLSI request', function() {
+ it('should build up the CLSI request', function () {
expect(this.request).to.deep.equal({
compile: {
options: {
@@ -635,8 +635,8 @@ describe('ClsiManager', function() {
})
})
- describe('when the root doc is set and not in the docupdater', function() {
- beforeEach(function(done) {
+ describe('when the root doc is set and not in the docupdater', function () {
+ beforeEach(function (done) {
this.ClsiStateManager.computeHash = sinon
.stub()
.callsArgWith(
@@ -672,7 +672,7 @@ describe('ClsiManager', function() {
)
})
- it('should still change the root path', function() {
+ it('should still change the root path', function () {
this.request.compile.rootResourcePath.should.equal(
'chapters/chapter1.tex'
)
@@ -680,8 +680,8 @@ describe('ClsiManager', function() {
})
})
- describe('when root doc override is valid', function() {
- beforeEach(function(done) {
+ describe('when root doc override is valid', function () {
+ beforeEach(function (done) {
this.ClsiManager._buildRequest(
this.project_id,
{ rootDoc_id: 'mock-doc-id-2' },
@@ -695,15 +695,15 @@ describe('ClsiManager', function() {
)
})
- it('should change root path', function() {
+ it('should change root path', function () {
this.request.compile.rootResourcePath.should.equal(
'chapters/chapter1.tex'
)
})
})
- describe('when root doc override is invalid', function() {
- beforeEach(function(done) {
+ describe('when root doc override is invalid', function () {
+ beforeEach(function (done) {
this.ClsiManager._buildRequest(
this.project_id,
{ rootDoc_id: 'invalid-id' },
@@ -717,13 +717,13 @@ describe('ClsiManager', function() {
)
})
- it('should fallback to default root doc', function() {
+ it('should fallback to default root doc', function () {
this.request.compile.rootResourcePath.should.equal('main.tex')
})
})
- describe('when the project has an invalid compiler', function() {
- beforeEach(function(done) {
+ describe('when the project has an invalid compiler', function () {
+ beforeEach(function (done) {
this.project.compiler = 'context'
this.ClsiManager._buildRequest(this.project, null, (err, request) => {
if (err != null) {
@@ -734,13 +734,13 @@ describe('ClsiManager', function() {
})
})
- it('should set the compiler to pdflatex', function() {
+ it('should set the compiler to pdflatex', function () {
this.request.compile.options.compiler.should.equal('pdflatex')
})
})
- describe('when there is no valid root document', function() {
- beforeEach(function(done) {
+ describe('when there is no valid root document', function () {
+ beforeEach(function (done) {
this.project.rootDoc_id = 'not-valid'
this.ClsiManager._buildRequest(this.project, null, (error, request) => {
this.error = error
@@ -749,13 +749,13 @@ describe('ClsiManager', function() {
})
})
- it('should set to main.tex', function() {
+ it('should set to main.tex', function () {
this.request.compile.rootResourcePath.should.equal('main.tex')
})
})
- describe('when there is no valid root document and no main.tex document', function() {
- beforeEach(function() {
+ describe('when there is no valid root document and no main.tex document', function () {
+ beforeEach(function () {
this.project.rootDoc_id = 'not-valid'
this.docs = {
'/other.tex': (this.doc_1 = {
@@ -775,13 +775,13 @@ describe('ClsiManager', function() {
this.ClsiManager._buildRequest(this.project, null, this.callback)
})
- it('should report an error', function() {
+ it('should report an error', function () {
this.callback.should.have.been.calledWith(sinon.match.instanceOf(Error))
})
})
- describe('when there is no valid root document and a single document which is not main.tex', function() {
- beforeEach(function(done) {
+ describe('when there is no valid root document and a single document which is not main.tex', function () {
+ beforeEach(function (done) {
this.project.rootDoc_id = 'not-valid'
this.docs = {
'/other.tex': (this.doc_1 = {
@@ -800,13 +800,13 @@ describe('ClsiManager', function() {
})
})
- it('should set io to the only file', function() {
+ it('should set io to the only file', function () {
this.request.compile.rootResourcePath.should.equal('other.tex')
})
})
- describe('with the draft option', function() {
- it('should add the draft option into the request', function(done) {
+ describe('with the draft option', function () {
+ it('should add the draft option into the request', function (done) {
this.ClsiManager._buildRequest(
this.project_id,
{ timeout: 100, draft: true },
@@ -822,13 +822,13 @@ describe('ClsiManager', function() {
})
})
- describe('_postToClsi', function() {
- beforeEach(function() {
+ describe('_postToClsi', function () {
+ beforeEach(function () {
this.req = { mock: 'req', compile: {} }
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
this.ClsiManager._makeRequest = sinon
.stub()
.callsArgWith(
@@ -846,7 +846,7 @@ describe('ClsiManager', function() {
)
})
- it('should send the request to the CLSI', function() {
+ it('should send the request to the CLSI', function () {
const url = `${this.settings.apis.clsi.url}/project/${this.project_id}/user/${this.user_id}/compile`
this.ClsiManager._makeRequest
.calledWith(this.project_id, {
@@ -857,13 +857,13 @@ describe('ClsiManager', function() {
.should.equal(true)
})
- it('should call the callback with the body and no error', function() {
+ it('should call the callback with the body and no error', function () {
this.callback.calledWith(null, this.body).should.equal(true)
})
})
- describe('when the CLSI returns an error', function() {
- beforeEach(function() {
+ describe('when the CLSI returns an error', function () {
+ beforeEach(function () {
this.ClsiManager._makeRequest = sinon
.stub()
.callsArgWith(
@@ -881,14 +881,14 @@ describe('ClsiManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
this.callback.should.have.been.calledWith(sinon.match.instanceOf(Error))
})
})
})
- describe('wordCount', function() {
- beforeEach(function() {
+ describe('wordCount', function () {
+ beforeEach(function () {
this.ClsiManager._makeRequestWithClsiServerId = sinon
.stub()
.yields(null, { statusCode: 200 }, (this.body = { mock: 'foo' }))
@@ -901,8 +901,8 @@ describe('ClsiManager', function() {
)
})
- describe('with root file', function() {
- beforeEach(function() {
+ describe('with root file', function () {
+ beforeEach(function () {
this.ClsiManager.wordCount(
this.project_id,
this.user_id,
@@ -913,7 +913,7 @@ describe('ClsiManager', function() {
)
})
- it('should call wordCount with root file', function() {
+ it('should call wordCount with root file', function () {
this.ClsiManager._makeRequestWithClsiServerId
.calledWith(
this.project_id,
@@ -930,13 +930,13 @@ describe('ClsiManager', function() {
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('with param file', function() {
- beforeEach(function() {
+ describe('with param file', function () {
+ beforeEach(function () {
this.ClsiManager.wordCount(
this.project_id,
this.user_id,
@@ -947,7 +947,7 @@ describe('ClsiManager', function() {
)
})
- it('should call wordCount with param file', function() {
+ it('should call wordCount with param file', function () {
this.ClsiManager._makeRequestWithClsiServerId
.calledWith(
this.project_id,
@@ -962,8 +962,8 @@ describe('ClsiManager', function() {
})
})
- describe('with image', function() {
- beforeEach(function() {
+ describe('with image', function () {
+ beforeEach(function () {
this.req.compile.options.imageName = this.image =
'example.com/mock/image'
this.ClsiManager.wordCount(
@@ -976,7 +976,7 @@ describe('ClsiManager', function() {
)
})
- it('should call wordCount with file and image', function() {
+ it('should call wordCount with file and image', function () {
this.ClsiManager._makeRequestWithClsiServerId
.calledWith(
this.project_id,
@@ -992,8 +992,8 @@ describe('ClsiManager', function() {
})
})
- describe('_makeRequest', function() {
- beforeEach(function() {
+ describe('_makeRequest', function () {
+ beforeEach(function () {
this.response = { there: 'something' }
this.request.callsArgWith(1, null, this.response)
this.opts = {
@@ -1002,7 +1002,7 @@ describe('ClsiManager', function() {
}
})
- it('should process a request with a cookie jar', function(done) {
+ it('should process a request with a cookie jar', function (done) {
this.ClsiManager._makeRequest(this.project_id, this.opts, () => {
const args = this.request.args[0]
args[0].method.should.equal(this.opts.method)
@@ -1012,7 +1012,7 @@ describe('ClsiManager', function() {
})
})
- it('should set the cookie again on response as it might have changed', function(done) {
+ it('should set the cookie again on response as it might have changed', function (done) {
this.ClsiManager._makeRequest(this.project_id, this.opts, () => {
this.ClsiCookieManager.setServerId
.calledWith(this.project_id, this.response)
@@ -1022,8 +1022,8 @@ describe('ClsiManager', function() {
})
})
- describe('_makeRequestWithClsiServerId', function() {
- beforeEach(function() {
+ describe('_makeRequestWithClsiServerId', function () {
+ beforeEach(function () {
this.response = { statusCode: 200 }
this.request.yields(null, this.response)
this.opts = {
@@ -1032,8 +1032,8 @@ describe('ClsiManager', function() {
}
})
- describe('with a regular request', function() {
- it('should process a request with a cookie jar', function(done) {
+ describe('with a regular request', function () {
+ it('should process a request with a cookie jar', function (done) {
this.ClsiManager._makeRequestWithClsiServerId(
this.project_id,
this.opts,
@@ -1050,7 +1050,7 @@ describe('ClsiManager', function() {
)
})
- it('should persist the cookie from the response', function(done) {
+ it('should persist the cookie from the response', function (done) {
this.ClsiManager._makeRequestWithClsiServerId(
this.project_id,
this.opts,
@@ -1066,8 +1066,8 @@ describe('ClsiManager', function() {
})
})
- describe('with a persistent request', function() {
- it('should not add a cookie jar', function(done) {
+ describe('with a persistent request', function () {
+ it('should not add a cookie jar', function (done) {
this.ClsiManager._makeRequestWithClsiServerId(
this.project_id,
this.opts,
@@ -1084,7 +1084,7 @@ describe('ClsiManager', function() {
)
})
- it('should not persist a cookie on response', function(done) {
+ it('should not persist a cookie on response', function (done) {
this.ClsiManager._makeRequestWithClsiServerId(
this.project_id,
this.opts,
@@ -1099,8 +1099,8 @@ describe('ClsiManager', function() {
})
})
- describe('_makeGoogleCloudRequest', function() {
- beforeEach(function() {
+ describe('_makeGoogleCloudRequest', function () {
+ beforeEach(function () {
this.settings.apis.clsi_new = { url: 'https://compiles.somewhere.test' }
this.response = { there: 'something' }
this.request.callsArgWith(1, null, this.response)
@@ -1109,7 +1109,7 @@ describe('ClsiManager', function() {
}
})
- it('should change the domain on the url', function(done) {
+ it('should change the domain on the url', function (done) {
this.ClsiManager._makeNewBackendRequest(
this.project_id,
this.opts,
@@ -1123,7 +1123,7 @@ describe('ClsiManager', function() {
)
})
- it('should not make a request if there is not clsi_new url', function(done) {
+ it('should not make a request if there is not clsi_new url', function (done) {
this.settings.apis.clsi_new = undefined
this.ClsiManager._makeNewBackendRequest(
this.project_id,
diff --git a/services/web/test/unit/src/Compile/ClsiStateManagerTests.js b/services/web/test/unit/src/Compile/ClsiStateManagerTests.js
index b69247fa2d..c00e2b2e0d 100644
--- a/services/web/test/unit/src/Compile/ClsiStateManagerTests.js
+++ b/services/web/test/unit/src/Compile/ClsiStateManagerTests.js
@@ -17,8 +17,8 @@ const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/Compile/ClsiStateManager.js'
const SandboxedModule = require('sandboxed-module')
-describe('ClsiStateManager', function() {
- beforeEach(function() {
+describe('ClsiStateManager', function () {
+ beforeEach(function () {
this.ClsiStateManager = SandboxedModule.require(modulePath, {
requires: {
'settings-sharelatex': (this.settings = {}),
@@ -30,8 +30,8 @@ describe('ClsiStateManager', function() {
return (this.callback = sinon.stub())
})
- describe('computeHash', function() {
- beforeEach(function(done) {
+ describe('computeHash', function () {
+ beforeEach(function (done) {
this.docs = [
{ path: '/main.tex', doc: { _id: 'doc-id-1' } },
{ path: '/folder/sub.tex', doc: { _id: 'doc-id-2' } }
@@ -59,8 +59,8 @@ describe('ClsiStateManager', function() {
)
})
- describe('with a sample project', function() {
- beforeEach(function() {
+ describe('with a sample project', function () {
+ beforeEach(function () {
return this.ClsiStateManager.computeHash(
this.project,
this.options,
@@ -68,15 +68,15 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with a hash value', function() {
+ it('should call the callback with a hash value', function () {
return this.callback
.calledWith(null, '21b1ab73aa3892bec452baf8ffa0956179e1880f')
.should.equal(true)
})
})
- describe('when the files and docs are in a different order', function() {
- beforeEach(function() {
+ describe('when the files and docs are in a different order', function () {
+ beforeEach(function () {
;[this.docs[0], this.docs[1]] = Array.from([this.docs[1], this.docs[0]])
;[this.files[0], this.files[1]] = Array.from([
this.files[1],
@@ -89,13 +89,13 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with the same hash value', function() {
+ it('should call the callback with the same hash value', function () {
return this.callback.calledWith(null, this.hash0).should.equal(true)
})
})
- describe('when a doc is renamed', function() {
- beforeEach(function(done) {
+ describe('when a doc is renamed', function () {
+ beforeEach(function (done) {
this.docs[0].path = '/new.tex'
return this.ClsiStateManager.computeHash(
this.project,
@@ -107,15 +107,15 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with a different hash value', function() {
+ it('should call the callback with a different hash value', function () {
return this.callback
.neverCalledWith(null, this.hash0)
.should.equal(true)
})
})
- describe('when a file is renamed', function() {
- beforeEach(function(done) {
+ describe('when a file is renamed', function () {
+ beforeEach(function (done) {
this.files[0].path = '/newfigure.pdf'
return this.ClsiStateManager.computeHash(
this.project,
@@ -127,15 +127,15 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with a different hash value', function() {
+ it('should call the callback with a different hash value', function () {
return this.callback
.neverCalledWith(null, this.hash0)
.should.equal(true)
})
})
- describe('when a doc is added', function() {
- beforeEach(function(done) {
+ describe('when a doc is added', function () {
+ beforeEach(function (done) {
this.docs.push({ path: '/newdoc.tex', doc: { _id: 'newdoc-id' } })
return this.ClsiStateManager.computeHash(
this.project,
@@ -147,15 +147,15 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with a different hash value', function() {
+ it('should call the callback with a different hash value', function () {
return this.callback
.neverCalledWith(null, this.hash0)
.should.equal(true)
})
})
- describe('when a file is added', function() {
- beforeEach(function(done) {
+ describe('when a file is added', function () {
+ beforeEach(function (done) {
this.files.push({
path: '/newfile.tex',
file: { _id: 'newfile-id', rev: 123 }
@@ -170,15 +170,15 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with a different hash value', function() {
+ it('should call the callback with a different hash value', function () {
return this.callback
.neverCalledWith(null, this.hash0)
.should.equal(true)
})
})
- describe('when a doc is removed', function() {
- beforeEach(function(done) {
+ describe('when a doc is removed', function () {
+ beforeEach(function (done) {
this.docs.pop()
return this.ClsiStateManager.computeHash(
this.project,
@@ -190,15 +190,15 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with a different hash value', function() {
+ it('should call the callback with a different hash value', function () {
return this.callback
.neverCalledWith(null, this.hash0)
.should.equal(true)
})
})
- describe('when a file is removed', function() {
- beforeEach(function(done) {
+ describe('when a file is removed', function () {
+ beforeEach(function (done) {
this.files.pop()
return this.ClsiStateManager.computeHash(
this.project,
@@ -210,15 +210,15 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with a different hash value', function() {
+ it('should call the callback with a different hash value', function () {
return this.callback
.neverCalledWith(null, this.hash0)
.should.equal(true)
})
})
- describe("when a file's revision is updated", function() {
- beforeEach(function(done) {
+ describe("when a file's revision is updated", function () {
+ beforeEach(function (done) {
this.files[0].file.rev++
return this.ClsiStateManager.computeHash(
this.project,
@@ -230,15 +230,15 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with a different hash value', function() {
+ it('should call the callback with a different hash value', function () {
return this.callback
.neverCalledWith(null, this.hash0)
.should.equal(true)
})
})
- describe("when a file's date is updated", function() {
- beforeEach(function(done) {
+ describe("when a file's date is updated", function () {
+ beforeEach(function (done) {
this.files[0].file.created = 'zzzzzz'
return this.ClsiStateManager.computeHash(
this.project,
@@ -250,15 +250,15 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with a different hash value', function() {
+ it('should call the callback with a different hash value', function () {
return this.callback
.neverCalledWith(null, this.hash0)
.should.equal(true)
})
})
- describe('when the compile options are changed', function() {
- beforeEach(function(done) {
+ describe('when the compile options are changed', function () {
+ beforeEach(function (done) {
this.options.draft = !this.options.draft
return this.ClsiStateManager.computeHash(
this.project,
@@ -270,15 +270,15 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with a different hash value', function() {
+ it('should call the callback with a different hash value', function () {
return this.callback
.neverCalledWith(null, this.hash0)
.should.equal(true)
})
})
- describe('when the isAutoCompile option is changed', function() {
- beforeEach(function() {
+ describe('when the isAutoCompile option is changed', function () {
+ beforeEach(function () {
this.options.isAutoCompile = !this.options.isAutoCompile
return this.ClsiStateManager.computeHash(
this.project,
@@ -287,7 +287,7 @@ describe('ClsiStateManager', function() {
)
})
- it('should call the callback with the same hash value', function() {
+ it('should call the callback with the same hash value', function () {
return this.callback.calledWith(null, this.hash0).should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Compile/CompileControllerTests.js b/services/web/test/unit/src/Compile/CompileControllerTests.js
index 042a7160a9..363a5d197d 100644
--- a/services/web/test/unit/src/Compile/CompileControllerTests.js
+++ b/services/web/test/unit/src/Compile/CompileControllerTests.js
@@ -18,8 +18,8 @@ const SandboxedModule = require('sandboxed-module')
const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
-describe('CompileController', function() {
- beforeEach(function() {
+describe('CompileController', function () {
+ beforeEach(function () {
this.user_id = 'wat'
this.user = {
_id: this.user_id,
@@ -78,8 +78,8 @@ describe('CompileController', function() {
return (this.res = new MockResponse())
})
- describe('compile', function() {
- beforeEach(function() {
+ describe('compile', function () {
+ beforeEach(function () {
this.req.params = { Project_id: this.project_id }
this.req.session = {}
return (this.CompileManager.compile = sinon
@@ -92,28 +92,28 @@ describe('CompileController', function() {
))
})
- describe('when not an auto compile', function() {
- beforeEach(function() {
+ describe('when not an auto compile', function () {
+ beforeEach(function () {
return this.CompileController.compile(this.req, this.res, this.next)
})
- it('should look up the user id', function() {
+ it('should look up the user id', function () {
return this.AuthenticationController.getLoggedInUserId
.calledWith(this.req)
.should.equal(true)
})
- it('should do the compile without the auto compile flag', function() {
+ it('should do the compile without the auto compile flag', function () {
return this.CompileManager.compile
.calledWith(this.project_id, this.user_id, { isAutoCompile: false })
.should.equal(true)
})
- it('should set the content-type of the response to application/json', function() {
+ it('should set the content-type of the response to application/json', function () {
this.res.type.should.equal('application/json')
})
- it('should send a successful response reporting the status and files', function() {
+ it('should send a successful response reporting the status and files', function () {
this.res.statusCode.should.equal(200)
this.res.body.should.equal(
JSON.stringify({
@@ -124,26 +124,26 @@ describe('CompileController', function() {
})
})
- describe('when an auto compile', function() {
- beforeEach(function() {
+ describe('when an auto compile', function () {
+ beforeEach(function () {
this.req.query = { auto_compile: 'true' }
return this.CompileController.compile(this.req, this.res, this.next)
})
- it('should do the compile with the auto compile flag', function() {
+ it('should do the compile with the auto compile flag', function () {
return this.CompileManager.compile
.calledWith(this.project_id, this.user_id, { isAutoCompile: true })
.should.equal(true)
})
})
- describe('with the draft attribute', function() {
- beforeEach(function() {
+ describe('with the draft attribute', function () {
+ beforeEach(function () {
this.req.body = { draft: true }
return this.CompileController.compile(this.req, this.res, this.next)
})
- it('should do the compile without the draft compile flag', function() {
+ it('should do the compile without the draft compile flag', function () {
return this.CompileManager.compile
.calledWith(this.project_id, this.user_id, {
isAutoCompile: false,
@@ -154,8 +154,8 @@ describe('CompileController', function() {
})
})
- describe('compileSubmission', function() {
- beforeEach(function() {
+ describe('compileSubmission', function () {
+ beforeEach(function () {
this.submission_id = 'sub-1234'
this.req.params = { submission_id: this.submission_id }
this.req.body = {}
@@ -171,14 +171,14 @@ describe('CompileController', function() {
))
})
- it('should set the content-type of the response to application/json', function() {
+ it('should set the content-type of the response to application/json', function () {
this.CompileController.compileSubmission(this.req, this.res, this.next)
return this.res.contentType
.calledWith('application/json')
.should.equal(true)
})
- it('should send a successful response reporting the status and files', function() {
+ it('should send a successful response reporting the status and files', function () {
this.CompileController.compileSubmission(this.req, this.res, this.next)
this.res.statusCode.should.equal(200)
return this.res.body.should.equal(
@@ -191,8 +191,8 @@ describe('CompileController', function() {
)
})
- describe('with compileGroup and timeout', function() {
- beforeEach(function() {
+ describe('with compileGroup and timeout', function () {
+ beforeEach(function () {
this.req.body = {
compileGroup: 'special',
timeout: 600
@@ -204,7 +204,7 @@ describe('CompileController', function() {
)
})
- it('should use the supplied values', function() {
+ it('should use the supplied values', function () {
return this.ClsiManager.sendExternalRequest
.calledWith(
this.submission_id,
@@ -215,8 +215,8 @@ describe('CompileController', function() {
})
})
- describe('with other supported options but not compileGroup and timeout', function() {
- beforeEach(function() {
+ describe('with other supported options but not compileGroup and timeout', function () {
+ beforeEach(function () {
this.req.body = {
rootResourcePath: 'main.tex',
compiler: 'lualatex',
@@ -230,7 +230,7 @@ describe('CompileController', function() {
)
})
- it('should use the other options but default values for compileGroup and timeout', function() {
+ it('should use the other options but default values for compileGroup and timeout', function () {
return this.ClsiManager.sendExternalRequest
.calledWith(
this.submission_id,
@@ -254,8 +254,8 @@ describe('CompileController', function() {
})
})
- describe('downloadPdf', function() {
- beforeEach(function() {
+ describe('downloadPdf', function () {
+ beforeEach(function () {
this.req.params = { Project_id: this.project_id }
this.req.query = { pdfng: true }
@@ -265,36 +265,36 @@ describe('CompileController', function() {
.callsArgWith(2, null, this.project))
})
- describe('when downloading for embedding', function() {
- beforeEach(function() {
+ describe('when downloading for embedding', function () {
+ beforeEach(function () {
this.CompileController.proxyToClsi = sinon.stub()
this.RateLimiter.addCount.callsArgWith(1, null, true)
return this.CompileController.downloadPdf(this.req, this.res, this.next)
})
- it('should look up the project', function() {
+ it('should look up the project', function () {
return this.ProjectGetter.getProject
.calledWith(this.project_id, { name: 1 })
.should.equal(true)
})
- it('should set the content-type of the response to application/pdf', function() {
+ it('should set the content-type of the response to application/pdf', function () {
return this.res.contentType
.calledWith('application/pdf')
.should.equal(true)
})
- it('should set the content-disposition header with a safe version of the project name', function() {
+ it('should set the content-disposition header with a safe version of the project name', function () {
return this.res.setContentDisposition
.calledWith('', { filename: 'test_nam_.pdf' })
.should.equal(true)
})
- it('should increment the pdf-downloads metric', function() {
+ it('should increment the pdf-downloads metric', function () {
return this.Metrics.inc.calledWith('pdf-downloads').should.equal(true)
})
- it('should proxy the PDF from the CLSI', function() {
+ it('should proxy the PDF from the CLSI', function () {
return this.CompileController.proxyToClsi
.calledWith(
this.project_id,
@@ -307,15 +307,15 @@ describe('CompileController', function() {
})
})
- describe('when the a build-id is provided', function() {
- beforeEach(function() {
+ describe('when the a build-id is provided', function () {
+ beforeEach(function () {
this.req.params.build_id = this.buildId = '1234-5678'
this.CompileController.proxyToClsi = sinon.stub()
this.RateLimiter.addCount.callsArgWith(1, null, true)
return this.CompileController.downloadPdf(this.req, this.res, this.next)
})
- it('should proxy the PDF from the CLSI, with a build-id', function() {
+ it('should proxy the PDF from the CLSI, with a build-id', function () {
return this.CompileController.proxyToClsi
.calledWith(
this.project_id,
@@ -328,8 +328,8 @@ describe('CompileController', function() {
})
})
- describe('when the pdf is not going to be used in pdfjs viewer', function() {
- it('should check the rate limiter when pdfng is not set', function(done) {
+ describe('when the pdf is not going to be used in pdfjs viewer', function () {
+ it('should check the rate limiter when pdfng is not set', function (done) {
this.req.query = {}
this.RateLimiter.addCount.callsArgWith(1, null, true)
this.CompileController.proxyToClsi = (project_id, url) => {
@@ -339,7 +339,7 @@ describe('CompileController', function() {
return this.CompileController.downloadPdf(this.req, this.res)
})
- it('should check the rate limiter when pdfng is false', function(done) {
+ it('should check the rate limiter when pdfng is false', function (done) {
this.req.query = { pdfng: false }
this.RateLimiter.addCount.callsArgWith(1, null, true)
this.CompileController.proxyToClsi = (project_id, url) => {
@@ -351,8 +351,8 @@ describe('CompileController', function() {
})
})
- describe('getFileFromClsiWithoutUser', function() {
- beforeEach(function() {
+ describe('getFileFromClsiWithoutUser', function () {
+ beforeEach(function () {
this.submission_id = 'sub-1234'
this.build_id = 123456
this.file = 'project.pdf'
@@ -366,8 +366,8 @@ describe('CompileController', function() {
return (this.CompileController.proxyToClsiWithLimits = sinon.stub())
})
- describe('without limits specified', function() {
- beforeEach(function() {
+ describe('without limits specified', function () {
+ beforeEach(function () {
return this.CompileController.getFileFromClsiWithoutUser(
this.req,
this.res,
@@ -375,7 +375,7 @@ describe('CompileController', function() {
)
})
- it('should proxy to CLSI with correct URL and default limits', function() {
+ it('should proxy to CLSI with correct URL and default limits', function () {
return this.CompileController.proxyToClsiWithLimits
.calledWith(this.submission_id, this.expected_url, {
compileGroup: 'standard'
@@ -384,8 +384,8 @@ describe('CompileController', function() {
})
})
- describe('with limits specified', function() {
- beforeEach(function() {
+ describe('with limits specified', function () {
+ beforeEach(function () {
this.req.body = { compileTimeout: 600, compileGroup: 'special' }
return this.CompileController.getFileFromClsiWithoutUser(
this.req,
@@ -394,7 +394,7 @@ describe('CompileController', function() {
)
})
- it('should proxy to CLSI with correct URL and specified limits', function() {
+ it('should proxy to CLSI with correct URL and specified limits', function () {
return this.CompileController.proxyToClsiWithLimits
.calledWith(this.submission_id, this.expected_url, {
compileGroup: 'special'
@@ -403,10 +403,10 @@ describe('CompileController', function() {
})
})
})
- describe('proxySyncCode', function() {
+ describe('proxySyncCode', function () {
let file, line, column, imageName
- beforeEach(function(done) {
+ beforeEach(function (done) {
this.req.params = { Project_id: this.project_id }
file = 'main.tex'
line = String(Date.now())
@@ -423,7 +423,7 @@ describe('CompileController', function() {
this.CompileController.proxySyncCode(this.req, this.res, this.next)
})
- it('should proxy the request with an imageName', function() {
+ it('should proxy the request with an imageName', function () {
expect(this.CompileController.proxyToClsi).to.have.been.calledWith(
this.project_id,
{
@@ -437,10 +437,10 @@ describe('CompileController', function() {
})
})
- describe('proxySyncPdf', function() {
+ describe('proxySyncPdf', function () {
let page, h, v, imageName
- beforeEach(function(done) {
+ beforeEach(function (done) {
this.req.params = { Project_id: this.project_id }
page = String(Date.now())
h = String(Math.random())
@@ -457,7 +457,7 @@ describe('CompileController', function() {
this.CompileController.proxySyncPdf(this.req, this.res, this.next)
})
- it('should proxy the request with an imageName', function() {
+ it('should proxy the request with an imageName', function () {
expect(this.CompileController.proxyToClsi).to.have.been.calledWith(
this.project_id,
{
@@ -471,8 +471,8 @@ describe('CompileController', function() {
})
})
- describe('proxyToClsi', function() {
- beforeEach(function() {
+ describe('proxyToClsi', function () {
+ beforeEach(function () {
this.request.returns(
(this.proxy = {
pipe: sinon.stub(),
@@ -492,9 +492,9 @@ describe('CompileController', function() {
})
})
- describe('old pdf viewer', function() {
- describe('user with standard priority', function() {
- beforeEach(function() {
+ describe('old pdf viewer', function () {
+ describe('user with standard priority', function () {
+ beforeEach(function () {
this.CompileManager.getProjectCompileLimits = sinon
.stub()
.callsArgWith(1, null, { compileGroup: 'standard' })
@@ -507,7 +507,7 @@ describe('CompileController', function() {
)
})
- it('should open a request to the CLSI', function() {
+ it('should open a request to the CLSI', function () {
return this.request
.calledWith({
jar: this.jar,
@@ -518,17 +518,17 @@ describe('CompileController', function() {
.should.equal(true)
})
- it('should pass the request on to the client', function() {
+ it('should pass the request on to the client', function () {
return this.proxy.pipe.calledWith(this.res).should.equal(true)
})
- it('should bind an error handle to the request proxy', function() {
+ it('should bind an error handle to the request proxy', function () {
return this.proxy.on.calledWith('error').should.equal(true)
})
})
- describe('user with priority compile', function() {
- beforeEach(function() {
+ describe('user with priority compile', function () {
+ beforeEach(function () {
this.CompileManager.getProjectCompileLimits = sinon
.stub()
.callsArgWith(1, null, { compileGroup: 'priority' })
@@ -542,8 +542,8 @@ describe('CompileController', function() {
})
})
- describe('user with standard priority via query string', function() {
- beforeEach(function() {
+ describe('user with standard priority via query string', function () {
+ beforeEach(function () {
this.req.query = { compileGroup: 'standard' }
return this.CompileController.proxyToClsi(
this.project_id,
@@ -554,7 +554,7 @@ describe('CompileController', function() {
)
})
- it('should open a request to the CLSI', function() {
+ it('should open a request to the CLSI', function () {
return this.request
.calledWith({
jar: this.jar,
@@ -565,17 +565,17 @@ describe('CompileController', function() {
.should.equal(true)
})
- it('should pass the request on to the client', function() {
+ it('should pass the request on to the client', function () {
return this.proxy.pipe.calledWith(this.res).should.equal(true)
})
- it('should bind an error handle to the request proxy', function() {
+ it('should bind an error handle to the request proxy', function () {
return this.proxy.on.calledWith('error').should.equal(true)
})
})
- describe('user with non-existent priority via query string', function() {
- beforeEach(function() {
+ describe('user with non-existent priority via query string', function () {
+ beforeEach(function () {
this.req.query = { compileGroup: 'foobar' }
return this.CompileController.proxyToClsi(
this.project_id,
@@ -586,7 +586,7 @@ describe('CompileController', function() {
)
})
- it('should proxy to the standard url', function() {
+ it('should proxy to the standard url', function () {
return this.request
.calledWith({
jar: this.jar,
@@ -598,8 +598,8 @@ describe('CompileController', function() {
})
})
- describe('user with build parameter via query string', function() {
- beforeEach(function() {
+ describe('user with build parameter via query string', function () {
+ beforeEach(function () {
this.CompileManager.getProjectCompileLimits = sinon
.stub()
.callsArgWith(1, null, { compileGroup: 'standard' })
@@ -613,7 +613,7 @@ describe('CompileController', function() {
)
})
- it('should proxy to the standard url without the build parameter', function() {
+ it('should proxy to the standard url without the build parameter', function () {
return this.request
.calledWith({
jar: this.jar,
@@ -626,12 +626,12 @@ describe('CompileController', function() {
})
})
- describe('new pdf viewer', function() {
- beforeEach(function() {
+ describe('new pdf viewer', function () {
+ beforeEach(function () {
return (this.req.query = { pdfng: true })
})
- describe('user with standard priority', function() {
- beforeEach(function() {
+ describe('user with standard priority', function () {
+ beforeEach(function () {
this.CompileManager.getProjectCompileLimits = sinon
.stub()
.callsArgWith(1, null, { compileGroup: 'standard' })
@@ -644,7 +644,7 @@ describe('CompileController', function() {
)
})
- it('should open a request to the CLSI', function() {
+ it('should open a request to the CLSI', function () {
return this.request
.calledWith({
jar: this.jar,
@@ -660,17 +660,17 @@ describe('CompileController', function() {
.should.equal(true)
})
- it('should pass the request on to the client', function() {
+ it('should pass the request on to the client', function () {
return this.proxy.pipe.calledWith(this.res).should.equal(true)
})
- it('should bind an error handle to the request proxy', function() {
+ it('should bind an error handle to the request proxy', function () {
return this.proxy.on.calledWith('error').should.equal(true)
})
})
- describe('user with build parameter via query string', function() {
- beforeEach(function() {
+ describe('user with build parameter via query string', function () {
+ beforeEach(function () {
this.CompileManager.getProjectCompileLimits = sinon
.stub()
.callsArgWith(1, null, { compileGroup: 'standard' })
@@ -684,7 +684,7 @@ describe('CompileController', function() {
)
})
- it('should proxy to the standard url with the build parameter', function() {
+ it('should proxy to the standard url with the build parameter', function () {
return this.request
.calledWith({
jar: this.jar,
@@ -704,8 +704,8 @@ describe('CompileController', function() {
})
})
- describe('deleteAuxFiles', function() {
- beforeEach(function() {
+ describe('deleteAuxFiles', function () {
+ beforeEach(function () {
this.CompileManager.deleteAuxFiles = sinon.stub().yields()
this.req.params = { Project_id: this.project_id }
this.req.query = { clsiserverid: 'node-1' }
@@ -717,19 +717,19 @@ describe('CompileController', function() {
)
})
- it('should proxy to the CLSI', function() {
+ it('should proxy to the CLSI', function () {
return this.CompileManager.deleteAuxFiles
.calledWith(this.project_id, this.user_id, 'node-1')
.should.equal(true)
})
- it('should return a 200', function() {
+ it('should return a 200', function () {
return this.res.sendStatus.calledWith(200).should.equal(true)
})
})
- describe('compileAndDownloadPdf', function() {
- beforeEach(function() {
+ describe('compileAndDownloadPdf', function () {
+ beforeEach(function () {
this.req = {
params: {
project_id: this.project_id
@@ -740,13 +740,13 @@ describe('CompileController', function() {
return (this.res = { send: () => {} })
})
- it('should call compile in the compile manager', function(done) {
+ it('should call compile in the compile manager', function (done) {
this.CompileController.compileAndDownloadPdf(this.req, this.res)
this.CompileManager.compile.calledWith(this.project_id).should.equal(true)
return done()
})
- it('should proxy the res to the clsi with correct url', function(done) {
+ it('should proxy the res to the clsi with correct url', function (done) {
this.CompileController.compileAndDownloadPdf(this.req, this.res)
sinon.assert.calledWith(
this.CompileController.proxyToClsi,
@@ -768,8 +768,8 @@ describe('CompileController', function() {
})
})
- describe('wordCount', function() {
- beforeEach(function() {
+ describe('wordCount', function () {
+ beforeEach(function () {
this.CompileManager.wordCount = sinon
.stub()
.yields(null, { content: 'body' })
@@ -780,13 +780,13 @@ describe('CompileController', function() {
return this.CompileController.wordCount(this.req, this.res, this.next)
})
- it('should proxy to the CLSI', function() {
+ it('should proxy to the CLSI', function () {
return this.CompileManager.wordCount
.calledWith(this.project_id, this.user_id, false, 'node-42')
.should.equal(true)
})
- it('should return a 200 and body', function() {
+ it('should return a 200 and body', function () {
return this.res.send.calledWith({ content: 'body' }).should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Compile/CompileManagerTests.js b/services/web/test/unit/src/Compile/CompileManagerTests.js
index 284c2dd7c7..2d880e0096 100644
--- a/services/web/test/unit/src/Compile/CompileManagerTests.js
+++ b/services/web/test/unit/src/Compile/CompileManagerTests.js
@@ -17,8 +17,8 @@ const { assert, expect } = require('chai')
const modulePath = '../../../../app/src/Features/Compile/CompileManager.js'
const SandboxedModule = require('sandboxed-module')
-describe('CompileManager', function() {
- beforeEach(function() {
+describe('CompileManager', function () {
+ beforeEach(function () {
let Timer
this.rateLimitGetStub = sinon.stub()
const { rateLimitGetStub } = this
@@ -40,7 +40,7 @@ describe('CompileManager', function() {
'./ClsiManager': (this.ClsiManager = {}),
'../../infrastructure/RateLimiter': this.ratelimiter,
'@overleaf/metrics': (this.Metrics = {
- Timer: (Timer = (function() {
+ Timer: (Timer = (function () {
Timer = class Timer {
static initClass() {
this.prototype.done = sinon.stub()
@@ -61,8 +61,8 @@ describe('CompileManager', function() {
})
})
- describe('compile', function() {
- beforeEach(function() {
+ describe('compile', function () {
+ beforeEach(function () {
this.CompileManager._checkIfRecentlyCompiled = sinon
.stub()
.callsArgWith(2, null, false)
@@ -83,8 +83,8 @@ describe('CompileManager', function() {
))
})
- describe('succesfully', function() {
- beforeEach(function() {
+ describe('succesfully', function () {
+ beforeEach(function () {
this.CompileManager._checkIfAutoCompileLimitHasBeenHit = (
isAutoCompile,
compileGroup,
@@ -98,25 +98,25 @@ describe('CompileManager', function() {
)
})
- it('should check the project has not been recently compiled', function() {
+ it('should check the project has not been recently compiled', function () {
return this.CompileManager._checkIfRecentlyCompiled
.calledWith(this.project_id, this.user_id)
.should.equal(true)
})
- it('should ensure that the root document is set', function() {
+ it('should ensure that the root document is set', function () {
return this.ProjectRootDocManager.ensureRootDocumentIsSet
.calledWith(this.project_id)
.should.equal(true)
})
- it('should get the project compile limits', function() {
+ it('should get the project compile limits', function () {
return this.CompileManager.getProjectCompileLimits
.calledWith(this.project_id)
.should.equal(true)
})
- it('should run the compile with the compile limits', function() {
+ it('should run the compile with the compile limits', function () {
return this.ClsiManager.sendRequest
.calledWith(this.project_id, this.user_id, {
timeout: this.limits.timeout
@@ -124,19 +124,19 @@ describe('CompileManager', function() {
.should.equal(true)
})
- it('should call the callback with the output', function() {
+ it('should call the callback with the output', function () {
return this.callback
.calledWith(null, this.status, this.outputFiles, this.output)
.should.equal(true)
})
- it('should time the compile', function() {
+ it('should time the compile', function () {
return this.Metrics.Timer.prototype.done.called.should.equal(true)
})
})
- describe('when the project has been recently compiled', function() {
- it('should return', function(done) {
+ describe('when the project has been recently compiled', function () {
+ it('should return', function (done) {
this.CompileManager._checkIfAutoCompileLimitHasBeenHit = (
isAutoCompile,
compileGroup,
@@ -157,8 +157,8 @@ describe('CompileManager', function() {
})
})
- describe('should check the rate limit', function() {
- it('should return', function(done) {
+ describe('should check the rate limit', function () {
+ it('should return', function (done) {
this.CompileManager._checkIfAutoCompileLimitHasBeenHit = sinon
.stub()
.callsArgWith(2, null, false)
@@ -175,8 +175,8 @@ describe('CompileManager', function() {
})
})
- describe('getProjectCompileLimits', function() {
- beforeEach(function() {
+ describe('getProjectCompileLimits', function () {
+ beforeEach(function () {
this.features = {
compileTimeout: (this.timeout = 42),
compileGroup: (this.group = 'priority')
@@ -197,13 +197,13 @@ describe('CompileManager', function() {
)
})
- it('should look up the owner of the project', function() {
+ it('should look up the owner of the project', function () {
return this.ProjectGetter.getProject
.calledWith(this.project_id, { owner_ref: 1 })
.should.equal(true)
})
- it("should look up the owner's features", function() {
+ it("should look up the owner's features", function () {
return this.UserGetter.getUser
.calledWith(this.project.owner_ref, {
alphaProgram: 1,
@@ -213,7 +213,7 @@ describe('CompileManager', function() {
.should.equal(true)
})
- it('should return the limits', function() {
+ it('should return the limits', function () {
return this.callback
.calledWith(null, {
timeout: this.timeout,
@@ -223,8 +223,8 @@ describe('CompileManager', function() {
})
})
- describe('deleteAuxFiles', function() {
- beforeEach(function() {
+ describe('deleteAuxFiles', function () {
+ beforeEach(function () {
this.CompileManager.getProjectCompileLimits = sinon
.stub()
.callsArgWith(
@@ -240,26 +240,26 @@ describe('CompileManager', function() {
)
})
- it('should look up the compile group to use', function() {
+ it('should look up the compile group to use', function () {
return this.CompileManager.getProjectCompileLimits
.calledWith(this.project_id)
.should.equal(true)
})
- it('should delete the aux files', function() {
+ it('should delete the aux files', function () {
return this.ClsiManager.deleteAuxFiles
.calledWith(this.project_id, this.user_id, this.limits)
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('_checkIfRecentlyCompiled', function() {
- describe('when the key exists in redis', function() {
- beforeEach(function() {
+ describe('_checkIfRecentlyCompiled', function () {
+ describe('when the key exists in redis', function () {
+ beforeEach(function () {
this.rclient.set = sinon.stub().callsArgWith(5, null, null)
return this.CompileManager._checkIfRecentlyCompiled(
this.project_id,
@@ -268,7 +268,7 @@ describe('CompileManager', function() {
)
})
- it('should try to set the key', function() {
+ it('should try to set the key', function () {
return this.rclient.set
.calledWith(
`compile:${this.project_id}:${this.user_id}`,
@@ -280,13 +280,13 @@ describe('CompileManager', function() {
.should.equal(true)
})
- it('should call the callback with true', function() {
+ it('should call the callback with true', function () {
return this.callback.calledWith(null, true).should.equal(true)
})
})
- describe('when the key does not exist in redis', function() {
- beforeEach(function() {
+ describe('when the key does not exist in redis', function () {
+ beforeEach(function () {
this.rclient.set = sinon.stub().callsArgWith(5, null, 'OK')
return this.CompileManager._checkIfRecentlyCompiled(
this.project_id,
@@ -295,7 +295,7 @@ describe('CompileManager', function() {
)
})
- it('should try to set the key', function() {
+ it('should try to set the key', function () {
return this.rclient.set
.calledWith(
`compile:${this.project_id}:${this.user_id}`,
@@ -307,14 +307,14 @@ describe('CompileManager', function() {
.should.equal(true)
})
- it('should call the callback with false', function() {
+ it('should call the callback with false', function () {
return this.callback.calledWith(null, false).should.equal(true)
})
})
})
- describe('_checkIfAutoCompileLimitHasBeenHit', function() {
- it('should be able to compile if it is not an autocompile', function(done) {
+ describe('_checkIfAutoCompileLimitHasBeenHit', function () {
+ it('should be able to compile if it is not an autocompile', function (done) {
this.ratelimiter.addCount.callsArgWith(2, null, true)
return this.CompileManager._checkIfAutoCompileLimitHasBeenHit(
false,
@@ -326,7 +326,7 @@ describe('CompileManager', function() {
)
})
- it('should be able to compile if rate limit has remianing', function(done) {
+ it('should be able to compile if rate limit has remianing', function (done) {
this.ratelimiter.addCount.callsArgWith(1, null, true)
return this.CompileManager._checkIfAutoCompileLimitHasBeenHit(
true,
@@ -343,7 +343,7 @@ describe('CompileManager', function() {
)
})
- it('should be not able to compile if rate limit has no remianing', function(done) {
+ it('should be not able to compile if rate limit has no remianing', function (done) {
this.ratelimiter.addCount.callsArgWith(1, null, false)
return this.CompileManager._checkIfAutoCompileLimitHasBeenHit(
true,
@@ -355,7 +355,7 @@ describe('CompileManager', function() {
)
})
- it('should return false if there is an error in the rate limit', function(done) {
+ it('should return false if there is an error in the rate limit', function (done) {
this.ratelimiter.addCount.callsArgWith(1, 'error')
return this.CompileManager._checkIfAutoCompileLimitHasBeenHit(
true,
@@ -368,8 +368,8 @@ describe('CompileManager', function() {
})
})
- describe('wordCount', function() {
- beforeEach(function() {
+ describe('wordCount', function () {
+ beforeEach(function () {
this.CompileManager.getProjectCompileLimits = sinon
.stub()
.callsArgWith(
@@ -386,19 +386,19 @@ describe('CompileManager', function() {
)
})
- it('should look up the compile group to use', function() {
+ it('should look up the compile group to use', function () {
return this.CompileManager.getProjectCompileLimits
.calledWith(this.project_id)
.should.equal(true)
})
- it('should call wordCount for project', function() {
+ it('should call wordCount for project', function () {
return this.ClsiManager.wordCount
.calledWith(this.project_id, this.user_id, false, this.limits)
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Contact/ContactControllerTests.js b/services/web/test/unit/src/Contact/ContactControllerTests.js
index 1837b15711..e595e46773 100644
--- a/services/web/test/unit/src/Contact/ContactControllerTests.js
+++ b/services/web/test/unit/src/Contact/ContactControllerTests.js
@@ -16,8 +16,8 @@ const { assert, expect } = require('chai')
const modulePath = '../../../../app/src/Features/Contacts/ContactController.js'
const SandboxedModule = require('sandboxed-module')
-describe('ContactController', function() {
- beforeEach(function() {
+describe('ContactController', function () {
+ beforeEach(function () {
this.AuthenticationController = { getLoggedInUserId: sinon.stub() }
this.ContactController = SandboxedModule.require(modulePath, {
requires: {
@@ -37,8 +37,8 @@ describe('ContactController', function() {
return (this.res.send = sinon.stub())
})
- describe('getContacts', function() {
- beforeEach(function() {
+ describe('getContacts', function () {
+ beforeEach(function () {
this.user_id = 'mock-user-id'
this.contact_ids = ['contact-1', 'contact-2', 'contact-3']
this.contacts = [
@@ -79,19 +79,19 @@ describe('ContactController', function() {
return this.ContactController.getContacts(this.req, this.res, this.next)
})
- it('should look up the logged in user id', function() {
+ it('should look up the logged in user id', function () {
return this.AuthenticationController.getLoggedInUserId
.calledWith(this.req)
.should.equal(true)
})
- it('should get the users contact ids', function() {
+ it('should get the users contact ids', function () {
return this.ContactManager.getContactIds
.calledWith(this.user_id, { limit: 50 })
.should.equal(true)
})
- it('should populate the users contacts ids', function() {
+ it('should populate the users contacts ids', function () {
return this.UserGetter.getUsers
.calledWith(this.contact_ids, {
email: 1,
@@ -102,13 +102,13 @@ describe('ContactController', function() {
.should.equal(true)
})
- it('should fire the getContact module hook', function() {
+ it('should fire the getContact module hook', function () {
return this.Modules.hooks.fire
.calledWith('getContacts', this.user_id)
.should.equal(true)
})
- it('should return a formatted list of contacts in contact list order, without holding accounts', function() {
+ it('should return a formatted list of contacts in contact list order, without holding accounts', function () {
return this.res.send.args[0][0].contacts.should.deep.equal([
{
id: 'contact-1',
diff --git a/services/web/test/unit/src/Contact/ContactManagerTests.js b/services/web/test/unit/src/Contact/ContactManagerTests.js
index f3b9a51dea..a7d04ff35e 100644
--- a/services/web/test/unit/src/Contact/ContactManagerTests.js
+++ b/services/web/test/unit/src/Contact/ContactManagerTests.js
@@ -13,8 +13,8 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/Contacts/ContactManager'
const SandboxedModule = require('sandboxed-module')
-describe('ContactManager', function() {
- beforeEach(function() {
+describe('ContactManager', function () {
+ beforeEach(function () {
this.ContactManager = SandboxedModule.require(modulePath, {
requires: {
request: (this.request = sinon.stub()),
@@ -33,9 +33,9 @@ describe('ContactManager', function() {
return (this.callback = sinon.stub())
})
- describe('getContacts', function() {
- describe('with a successful response code', function() {
- beforeEach(function() {
+ describe('getContacts', function () {
+ describe('with a successful response code', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(
@@ -51,7 +51,7 @@ describe('ContactManager', function() {
)
})
- it('should get the contacts from the contacts api', function() {
+ it('should get the contacts from the contacts api', function () {
return this.request.get
.calledWith({
url: `${this.settings.apis.contacts.url}/user/${this.user_id}/contacts`,
@@ -62,15 +62,15 @@ describe('ContactManager', function() {
.should.equal(true)
})
- it('should call the callback with the contatcs', function() {
+ it('should call the callback with the contatcs', function () {
return this.callback
.calledWith(null, this.contact_ids)
.should.equal(true)
})
})
- describe('with a failed response code', function() {
- beforeEach(function() {
+ describe('with a failed response code', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, null)
@@ -81,7 +81,7 @@ describe('ContactManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
@@ -98,9 +98,9 @@ describe('ContactManager', function() {
})
})
- describe('addContact', function() {
- describe('with a successful response code', function() {
- beforeEach(function() {
+ describe('addContact', function () {
+ describe('with a successful response code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 200 }, null)
@@ -111,7 +111,7 @@ describe('ContactManager', function() {
)
})
- it('should add the contacts for the user in the contacts api', function() {
+ it('should add the contacts for the user in the contacts api', function () {
return this.request.post
.calledWith({
url: `${this.settings.apis.contacts.url}/user/${this.user_id}/contacts`,
@@ -123,13 +123,13 @@ describe('ContactManager', function() {
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('with a failed response code', function() {
- beforeEach(function() {
+ describe('with a failed response code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, null)
@@ -140,7 +140,7 @@ describe('ContactManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
diff --git a/services/web/test/unit/src/Cooldown/CooldownManagerTests.js b/services/web/test/unit/src/Cooldown/CooldownManagerTests.js
index eeba93e4db..8e73e30c3c 100644
--- a/services/web/test/unit/src/Cooldown/CooldownManagerTests.js
+++ b/services/web/test/unit/src/Cooldown/CooldownManagerTests.js
@@ -18,8 +18,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Cooldown/CooldownManager'
)
-describe('CooldownManager', function() {
- beforeEach(function() {
+describe('CooldownManager', function () {
+ beforeEach(function () {
this.projectId = 'abcdefg'
this.rclient = { set: sinon.stub(), get: sinon.stub() }
this.RedisWrapper = { client: () => this.rclient }
@@ -30,27 +30,27 @@ describe('CooldownManager', function() {
}))
})
- describe('_buildKey', function() {
- it('should build a properly formatted redis key', function() {
+ describe('_buildKey', function () {
+ it('should build a properly formatted redis key', function () {
return expect(this.CooldownManager._buildKey('ABC')).to.equal(
'Cooldown:{ABC}'
)
})
})
- describe('isProjectOnCooldown', function() {
- beforeEach(function() {
+ describe('isProjectOnCooldown', function () {
+ beforeEach(function () {
return (this.call = cb => {
return this.CooldownManager.isProjectOnCooldown(this.projectId, cb)
})
})
- describe('when project is on cooldown', function() {
- beforeEach(function() {
+ describe('when project is on cooldown', function () {
+ beforeEach(function () {
return (this.rclient.get = sinon.stub().callsArgWith(1, null, '1'))
})
- it('should fetch key from redis', function(done) {
+ it('should fetch key from redis', function (done) {
return this.call((err, result) => {
this.rclient.get.callCount.should.equal(1)
this.rclient.get.calledWith('Cooldown:{abcdefg}').should.equal(true)
@@ -58,14 +58,14 @@ describe('CooldownManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.equal(null)
return done()
})
})
- it('should produce a true result', function(done) {
+ it('should produce a true result', function (done) {
return this.call((err, result) => {
expect(result).to.equal(true)
return done()
@@ -73,12 +73,12 @@ describe('CooldownManager', function() {
})
})
- describe('when project is not on cooldown', function() {
- beforeEach(function() {
+ describe('when project is not on cooldown', function () {
+ beforeEach(function () {
return (this.rclient.get = sinon.stub().callsArgWith(1, null, null))
})
- it('should fetch key from redis', function(done) {
+ it('should fetch key from redis', function (done) {
return this.call((err, result) => {
this.rclient.get.callCount.should.equal(1)
this.rclient.get.calledWith('Cooldown:{abcdefg}').should.equal(true)
@@ -86,14 +86,14 @@ describe('CooldownManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.equal(null)
return done()
})
})
- it('should produce a false result', function(done) {
+ it('should produce a false result', function (done) {
return this.call((err, result) => {
expect(result).to.equal(false)
return done()
@@ -101,14 +101,14 @@ describe('CooldownManager', function() {
})
})
- describe('when rclient.get produces an error', function() {
- beforeEach(function() {
+ describe('when rclient.get produces an error', function () {
+ beforeEach(function () {
return (this.rclient.get = sinon
.stub()
.callsArgWith(1, new Error('woops')))
})
- it('should fetch key from redis', function(done) {
+ it('should fetch key from redis', function (done) {
return this.call((err, result) => {
this.rclient.get.callCount.should.equal(1)
this.rclient.get.calledWith('Cooldown:{abcdefg}').should.equal(true)
@@ -116,7 +116,7 @@ describe('CooldownManager', function() {
})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -126,19 +126,19 @@ describe('CooldownManager', function() {
})
})
- describe('putProjectOnCooldown', function() {
- beforeEach(function() {
+ describe('putProjectOnCooldown', function () {
+ beforeEach(function () {
return (this.call = cb => {
return this.CooldownManager.putProjectOnCooldown(this.projectId, cb)
})
})
- describe('when rclient.set does not produce an error', function() {
- beforeEach(function() {
+ describe('when rclient.set does not produce an error', function () {
+ beforeEach(function () {
return (this.rclient.set = sinon.stub().callsArgWith(4, null))
})
- it('should set a key in redis', function(done) {
+ it('should set a key in redis', function (done) {
return this.call(err => {
this.rclient.set.callCount.should.equal(1)
this.rclient.set.calledWith('Cooldown:{abcdefg}').should.equal(true)
@@ -146,7 +146,7 @@ describe('CooldownManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.equal(null)
return done()
@@ -154,14 +154,14 @@ describe('CooldownManager', function() {
})
})
- describe('when rclient.set produces an error', function() {
- beforeEach(function() {
+ describe('when rclient.set produces an error', function () {
+ beforeEach(function () {
return (this.rclient.set = sinon
.stub()
.callsArgWith(4, new Error('woops')))
})
- it('should set a key in redis', function(done) {
+ it('should set a key in redis', function (done) {
return this.call(err => {
this.rclient.set.callCount.should.equal(1)
this.rclient.set.calledWith('Cooldown:{abcdefg}').should.equal(true)
@@ -169,7 +169,7 @@ describe('CooldownManager', function() {
})
})
- it('produce an error', function(done) {
+ it('produce an error', function (done) {
return this.call(err => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
diff --git a/services/web/test/unit/src/Cooldown/CooldownMiddlewareTests.js b/services/web/test/unit/src/Cooldown/CooldownMiddlewareTests.js
index 433196fbda..2564c0bf44 100644
--- a/services/web/test/unit/src/Cooldown/CooldownMiddlewareTests.js
+++ b/services/web/test/unit/src/Cooldown/CooldownMiddlewareTests.js
@@ -17,8 +17,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Cooldown/CooldownMiddleware'
)
-describe('CooldownMiddleware', function() {
- beforeEach(function() {
+describe('CooldownMiddleware', function () {
+ beforeEach(function () {
this.CooldownManager = { isProjectOnCooldown: sinon.stub() }
return (this.CooldownMiddleware = SandboxedModule.require(modulePath, {
requires: {
@@ -27,9 +27,9 @@ describe('CooldownMiddleware', function() {
}))
})
- describe('freezeProject', function() {
- describe('when project is on cooldown', function() {
- beforeEach(function() {
+ describe('freezeProject', function () {
+ describe('when project is on cooldown', function () {
+ beforeEach(function () {
this.CooldownManager.isProjectOnCooldown = sinon
.stub()
.callsArgWith(1, null, true)
@@ -38,7 +38,7 @@ describe('CooldownMiddleware', function() {
return (this.next = sinon.stub())
})
- it('should call CooldownManager.isProjectOnCooldown', function() {
+ it('should call CooldownManager.isProjectOnCooldown', function () {
this.CooldownMiddleware.freezeProject(this.req, this.res, this.next)
this.CooldownManager.isProjectOnCooldown.callCount.should.equal(1)
return this.CooldownManager.isProjectOnCooldown
@@ -46,20 +46,20 @@ describe('CooldownMiddleware', function() {
.should.equal(true)
})
- it('should not produce an error', function() {
+ it('should not produce an error', function () {
this.CooldownMiddleware.freezeProject(this.req, this.res, this.next)
return this.next.callCount.should.equal(0)
})
- it('should send a 429 status', function() {
+ it('should send a 429 status', function () {
this.CooldownMiddleware.freezeProject(this.req, this.res, this.next)
this.res.sendStatus.callCount.should.equal(1)
return this.res.sendStatus.calledWith(429).should.equal(true)
})
})
- describe('when project is not on cooldown', function() {
- beforeEach(function() {
+ describe('when project is not on cooldown', function () {
+ beforeEach(function () {
this.CooldownManager.isProjectOnCooldown = sinon
.stub()
.callsArgWith(1, null, false)
@@ -68,7 +68,7 @@ describe('CooldownMiddleware', function() {
return (this.next = sinon.stub())
})
- it('should call CooldownManager.isProjectOnCooldown', function() {
+ it('should call CooldownManager.isProjectOnCooldown', function () {
this.CooldownMiddleware.freezeProject(this.req, this.res, this.next)
this.CooldownManager.isProjectOnCooldown.callCount.should.equal(1)
return this.CooldownManager.isProjectOnCooldown
@@ -76,15 +76,15 @@ describe('CooldownMiddleware', function() {
.should.equal(true)
})
- it('call next with no arguments', function() {
+ it('call next with no arguments', function () {
this.CooldownMiddleware.freezeProject(this.req, this.res, this.next)
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args.length).to.equal(0)
})
})
- describe('when isProjectOnCooldown produces an error', function() {
- beforeEach(function() {
+ describe('when isProjectOnCooldown produces an error', function () {
+ beforeEach(function () {
this.CooldownManager.isProjectOnCooldown = sinon
.stub()
.callsArgWith(1, new Error('woops'))
@@ -93,7 +93,7 @@ describe('CooldownMiddleware', function() {
return (this.next = sinon.stub())
})
- it('should call CooldownManager.isProjectOnCooldown', function() {
+ it('should call CooldownManager.isProjectOnCooldown', function () {
this.CooldownMiddleware.freezeProject(this.req, this.res, this.next)
this.CooldownManager.isProjectOnCooldown.callCount.should.equal(1)
return this.CooldownManager.isProjectOnCooldown
@@ -101,15 +101,15 @@ describe('CooldownMiddleware', function() {
.should.equal(true)
})
- it('call next with an error', function() {
+ it('call next with an error', function () {
this.CooldownMiddleware.freezeProject(this.req, this.res, this.next)
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
})
- describe('when projectId is not part of route', function() {
- beforeEach(function() {
+ describe('when projectId is not part of route', function () {
+ beforeEach(function () {
this.CooldownManager.isProjectOnCooldown = sinon
.stub()
.callsArgWith(1, null, true)
@@ -118,13 +118,13 @@ describe('CooldownMiddleware', function() {
return (this.next = sinon.stub())
})
- it('call next with an error', function() {
+ it('call next with an error', function () {
this.CooldownMiddleware.freezeProject(this.req, this.res, this.next)
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
- it('should not call CooldownManager.isProjectOnCooldown', function() {
+ it('should not call CooldownManager.isProjectOnCooldown', function () {
this.CooldownMiddleware.freezeProject(this.req, this.res, this.next)
return this.CooldownManager.isProjectOnCooldown.callCount.should.equal(
0
diff --git a/services/web/test/unit/src/Docstore/DocstoreManagerTests.js b/services/web/test/unit/src/Docstore/DocstoreManagerTests.js
index c432bf7d35..d3f2731aa1 100644
--- a/services/web/test/unit/src/Docstore/DocstoreManagerTests.js
+++ b/services/web/test/unit/src/Docstore/DocstoreManagerTests.js
@@ -15,8 +15,8 @@ const SandboxedModule = require('sandboxed-module')
const Errors = require('../../../../app/src/Features/Errors/Errors.js')
const tk = require('timekeeper')
-describe('DocstoreManager', function() {
- beforeEach(function() {
+describe('DocstoreManager', function () {
+ beforeEach(function () {
this.requestDefaults = sinon.stub().returns((this.request = sinon.stub()))
this.DocstoreManager = SandboxedModule.require(modulePath, {
requires: {
@@ -40,17 +40,17 @@ describe('DocstoreManager', function() {
return (this.callback = sinon.stub())
})
- describe('deleteDoc', function() {
- describe('with a successful response code', function() {
+ describe('deleteDoc', function () {
+ describe('with a successful response code', function () {
// for assertions on the deletedAt timestamp, we need to freeze the clock.
- before(function() {
+ before(function () {
tk.freeze(Date.now())
})
- after(function() {
+ after(function () {
tk.reset()
})
- beforeEach(function() {
+ beforeEach(function () {
this.request.patch = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 }, '')
@@ -63,7 +63,7 @@ describe('DocstoreManager', function() {
)
})
- it('should delete the doc in the docstore api', function() {
+ it('should delete the doc in the docstore api', function () {
return this.request.patch
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc/${this.doc_id}`,
@@ -73,13 +73,13 @@ describe('DocstoreManager', function() {
.should.equal(true)
})
- it('should call the callback without an error', function() {
+ it('should call the callback without an error', function () {
return this.callback.calledWith(null).should.equal(true)
})
})
- describe('with a failed response code', function() {
- beforeEach(function() {
+ describe('with a failed response code', function () {
+ beforeEach(function () {
this.request.patch = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, '')
@@ -92,7 +92,7 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
@@ -108,8 +108,8 @@ describe('DocstoreManager', function() {
})
})
- describe('with a missing (404) response code', function() {
- beforeEach(function() {
+ describe('with a missing (404) response code', function () {
+ beforeEach(function () {
this.request.patch = sinon
.stub()
.callsArgWith(1, null, { statusCode: 404 }, '')
@@ -122,7 +122,7 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
this.callback
.calledWith(
sinon.match
@@ -139,8 +139,8 @@ describe('DocstoreManager', function() {
})
})
- describe('updateDoc', function() {
- beforeEach(function() {
+ describe('updateDoc', function () {
+ beforeEach(function () {
this.lines = ['mock', 'doc', 'lines']
this.rev = 5
this.version = 42
@@ -148,8 +148,8 @@ describe('DocstoreManager', function() {
return (this.modified = true)
})
- describe('with a successful response code', function() {
- beforeEach(function() {
+ describe('with a successful response code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(
@@ -168,7 +168,7 @@ describe('DocstoreManager', function() {
)
})
- it('should update the doc in the docstore api', function() {
+ it('should update the doc in the docstore api', function () {
return this.request.post
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc/${this.doc_id}`,
@@ -182,15 +182,15 @@ describe('DocstoreManager', function() {
.should.equal(true)
})
- it('should call the callback with the modified status and revision', function() {
+ it('should call the callback with the modified status and revision', function () {
return this.callback
.calledWith(null, this.modified, this.rev)
.should.equal(true)
})
})
- describe('with a failed response code', function() {
- beforeEach(function() {
+ describe('with a failed response code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, '')
@@ -204,7 +204,7 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
@@ -221,8 +221,8 @@ describe('DocstoreManager', function() {
})
})
- describe('getDoc', function() {
- beforeEach(function() {
+ describe('getDoc', function () {
+ beforeEach(function () {
return (this.doc = {
lines: (this.lines = ['mock', 'doc', 'lines']),
rev: (this.rev = 5),
@@ -231,8 +231,8 @@ describe('DocstoreManager', function() {
})
})
- describe('with a successful response code', function() {
- beforeEach(function() {
+ describe('with a successful response code', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 }, this.doc)
@@ -243,7 +243,7 @@ describe('DocstoreManager', function() {
)
})
- it('should get the doc from the docstore api', function() {
+ it('should get the doc from the docstore api', function () {
return this.request.get
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc/${this.doc_id}`,
@@ -253,15 +253,15 @@ describe('DocstoreManager', function() {
.should.equal(true)
})
- it('should call the callback with the lines, version and rev', function() {
+ it('should call the callback with the lines, version and rev', function () {
return this.callback
.calledWith(null, this.lines, this.rev, this.version, this.ranges)
.should.equal(true)
})
})
- describe('with a failed response code', function() {
- beforeEach(function() {
+ describe('with a failed response code', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, '')
@@ -272,7 +272,7 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
@@ -288,8 +288,8 @@ describe('DocstoreManager', function() {
})
})
- describe('with include_deleted=true', function() {
- beforeEach(function() {
+ describe('with include_deleted=true', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 }, this.doc)
@@ -301,7 +301,7 @@ describe('DocstoreManager', function() {
)
})
- it('should get the doc from the docstore api (including deleted)', function() {
+ it('should get the doc from the docstore api (including deleted)', function () {
return this.request.get
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc/${this.doc_id}?include_deleted=true`,
@@ -311,15 +311,15 @@ describe('DocstoreManager', function() {
.should.equal(true)
})
- it('should call the callback with the lines, version and rev', function() {
+ it('should call the callback with the lines, version and rev', function () {
return this.callback
.calledWith(null, this.lines, this.rev, this.version, this.ranges)
.should.equal(true)
})
})
- describe('with a missing (404) response code', function() {
- beforeEach(function() {
+ describe('with a missing (404) response code', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 404 }, '')
@@ -330,7 +330,7 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
@@ -342,9 +342,9 @@ describe('DocstoreManager', function() {
})
})
- describe('getAllDocs', function() {
- describe('with a successful response code', function() {
- beforeEach(function() {
+ describe('getAllDocs', function () {
+ describe('with a successful response code', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(
@@ -356,7 +356,7 @@ describe('DocstoreManager', function() {
return this.DocstoreManager.getAllDocs(this.project_id, this.callback)
})
- it('should get all the project docs in the docstore api', function() {
+ it('should get all the project docs in the docstore api', function () {
return this.request.get
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc`,
@@ -366,20 +366,20 @@ describe('DocstoreManager', function() {
.should.equal(true)
})
- it('should call the callback with the docs', function() {
+ it('should call the callback with the docs', function () {
return this.callback.calledWith(null, this.docs).should.equal(true)
})
})
- describe('with a failed response code', function() {
- beforeEach(function() {
+ describe('with a failed response code', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, '')
return this.DocstoreManager.getAllDocs(this.project_id, this.callback)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
@@ -396,9 +396,9 @@ describe('DocstoreManager', function() {
})
})
- describe('getAllDeletedDocs', function() {
- describe('with a successful response code', function() {
- beforeEach(function(done) {
+ describe('getAllDeletedDocs', function () {
+ describe('with a successful response code', function () {
+ beforeEach(function (done) {
this.callback.callsFake(done)
this.docs = [{ _id: 'mock-doc-id', name: 'foo.tex' }]
this.request.get = sinon
@@ -407,7 +407,7 @@ describe('DocstoreManager', function() {
this.DocstoreManager.getAllDeletedDocs(this.project_id, this.callback)
})
- it('should get all the project docs in the docstore api', function() {
+ it('should get all the project docs in the docstore api', function () {
this.request.get.should.have.been.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/doc-deleted`,
timeout: 30 * 1000,
@@ -415,13 +415,13 @@ describe('DocstoreManager', function() {
})
})
- it('should call the callback with the docs', function() {
+ it('should call the callback with the docs', function () {
this.callback.should.have.been.calledWith(null, this.docs)
})
})
- describe('with an error', function() {
- beforeEach(function(done) {
+ describe('with an error', function () {
+ beforeEach(function (done) {
this.callback.callsFake(() => done())
this.request.get = sinon
.stub()
@@ -429,7 +429,7 @@ describe('DocstoreManager', function() {
this.DocstoreManager.getAllDocs(this.project_id, this.callback)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
this.callback.should.have.been.calledWith(
sinon.match
.instanceOf(Error)
@@ -438,8 +438,8 @@ describe('DocstoreManager', function() {
})
})
- describe('with a failed response code', function() {
- beforeEach(function(done) {
+ describe('with a failed response code', function () {
+ beforeEach(function (done) {
this.callback.callsFake(() => done())
this.request.get = sinon
.stub()
@@ -447,7 +447,7 @@ describe('DocstoreManager', function() {
this.DocstoreManager.getAllDocs(this.project_id, this.callback)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
this.callback.should.have.been.calledWith(
sinon.match
.instanceOf(Error)
@@ -462,9 +462,9 @@ describe('DocstoreManager', function() {
})
})
- describe('getAllRanges', function() {
- describe('with a successful response code', function() {
- beforeEach(function() {
+ describe('getAllRanges', function () {
+ describe('with a successful response code', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(
@@ -476,7 +476,7 @@ describe('DocstoreManager', function() {
return this.DocstoreManager.getAllRanges(this.project_id, this.callback)
})
- it('should get all the project doc ranges in the docstore api', function() {
+ it('should get all the project doc ranges in the docstore api', function () {
return this.request.get
.calledWith({
url: `${this.settings.apis.docstore.url}/project/${this.project_id}/ranges`,
@@ -486,20 +486,20 @@ describe('DocstoreManager', function() {
.should.equal(true)
})
- it('should call the callback with the docs', function() {
+ it('should call the callback with the docs', function () {
return this.callback.calledWith(null, this.docs).should.equal(true)
})
})
- describe('with a failed response code', function() {
- beforeEach(function() {
+ describe('with a failed response code', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 }, '')
return this.DocstoreManager.getAllRanges(this.project_id, this.callback)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
@@ -516,9 +516,9 @@ describe('DocstoreManager', function() {
})
})
- describe('archiveProject', function() {
- describe('with a successful response code', function() {
- beforeEach(function() {
+ describe('archiveProject', function () {
+ describe('with a successful response code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 })
@@ -528,13 +528,13 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('with a failed response code', function() {
- beforeEach(function() {
+ describe('with a failed response code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 })
@@ -544,7 +544,7 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
@@ -561,9 +561,9 @@ describe('DocstoreManager', function() {
})
})
- describe('unarchiveProject', function() {
- describe('with a successful response code', function() {
- beforeEach(function() {
+ describe('unarchiveProject', function () {
+ describe('with a successful response code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 })
@@ -573,13 +573,13 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('with a failed response code', function() {
- beforeEach(function() {
+ describe('with a failed response code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 })
@@ -589,7 +589,7 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
@@ -606,9 +606,9 @@ describe('DocstoreManager', function() {
})
})
- describe('destroyProject', function() {
- describe('with a successful response code', function() {
- beforeEach(function() {
+ describe('destroyProject', function () {
+ describe('with a successful response code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 204 })
@@ -618,13 +618,13 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('with a failed response code', function() {
- beforeEach(function() {
+ describe('with a failed response code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 500 })
@@ -634,7 +634,7 @@ describe('DocstoreManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
diff --git a/services/web/test/unit/src/DocumentUpdater/DocumentUpdaterHandlerTests.js b/services/web/test/unit/src/DocumentUpdater/DocumentUpdaterHandlerTests.js
index a817dc76d3..035009f1aa 100644
--- a/services/web/test/unit/src/DocumentUpdater/DocumentUpdaterHandlerTests.js
+++ b/services/web/test/unit/src/DocumentUpdater/DocumentUpdaterHandlerTests.js
@@ -7,8 +7,8 @@ const modulePath = path.join(
'../../../../app/src/Features/DocumentUpdater/DocumentUpdaterHandler'
)
-describe('DocumentUpdaterHandler', function() {
- beforeEach(function() {
+describe('DocumentUpdaterHandler', function () {
+ beforeEach(function () {
this.project_id = 'project-id-923'
this.projectHistoryId = 'ol-project-id-1'
this.doc_id = 'doc-id-394'
@@ -53,14 +53,14 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('flushProjectToMongo', function() {
- describe('successfully', function() {
- beforeEach(function() {
+ describe('flushProjectToMongo', function () {
+ describe('successfully', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 204 }, '')
this.handler.flushProjectToMongo(this.project_id, this.callback)
})
- it('should flush the document from the document updater', function() {
+ it('should flush the document from the document updater', function () {
this.request
.calledWithMatch({
url: `${this.settings.apis.documentupdater.url}/project/${this.project_id}/flush`,
@@ -69,13 +69,13 @@ describe('DocumentUpdaterHandler', function() {
.should.equal(true)
})
- it('should call the callback with no error', function() {
+ it('should call the callback with no error', function () {
this.callback.calledWith(null).should.equal(true)
})
})
- describe('when the document updater API returns an error', function() {
- beforeEach(function() {
+ describe('when the document updater API returns an error', function () {
+ beforeEach(function () {
this.request.callsArgWith(
1,
new Error('something went wrong'),
@@ -85,20 +85,20 @@ describe('DocumentUpdaterHandler', function() {
this.handler.flushProjectToMongo(this.project_id, this.callback)
})
- it('should return an error to the callback', function() {
+ it('should return an error to the callback', function () {
this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('when the document updater returns a failure error code', function() {
- beforeEach(function() {
+ describe('when the document updater returns a failure error code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 }, '')
this.handler.flushProjectToMongo(this.project_id, this.callback)
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
this.callback
.calledWith(
sinon.match
@@ -115,9 +115,9 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('flushProjectToMongoAndDelete', function() {
- describe('successfully', function() {
- beforeEach(function() {
+ describe('flushProjectToMongoAndDelete', function () {
+ describe('successfully', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 204 }, '')
this.handler.flushProjectToMongoAndDelete(
this.project_id,
@@ -125,7 +125,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should delete the project from the document updater', function() {
+ it('should delete the project from the document updater', function () {
this.request
.calledWithMatch({
url: `${this.settings.apis.documentupdater.url}/project/${this.project_id}`,
@@ -134,13 +134,13 @@ describe('DocumentUpdaterHandler', function() {
.should.equal(true)
})
- it('should call the callback with no error', function() {
+ it('should call the callback with no error', function () {
this.callback.calledWith(null).should.equal(true)
})
})
- describe('when the document updater API returns an error', function() {
- beforeEach(function() {
+ describe('when the document updater API returns an error', function () {
+ beforeEach(function () {
this.request.callsArgWith(
1,
new Error('something went wrong'),
@@ -153,15 +153,15 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return an error to the callback', function() {
+ it('should return an error to the callback', function () {
this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('when the document updater returns a failure error code', function() {
- beforeEach(function() {
+ describe('when the document updater returns a failure error code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 }, '')
this.handler.flushProjectToMongoAndDelete(
this.project_id,
@@ -169,7 +169,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
this.callback
.calledWith(
sinon.match
@@ -186,9 +186,9 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('flushDocToMongo', function() {
- describe('successfully', function() {
- beforeEach(function() {
+ describe('flushDocToMongo', function () {
+ describe('successfully', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 204 }, '')
this.handler.flushDocToMongo(
this.project_id,
@@ -197,7 +197,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should flush the document from the document updater', function() {
+ it('should flush the document from the document updater', function () {
this.request
.calledWithMatch({
url: `${this.settings.apis.documentupdater.url}/project/${this.project_id}/doc/${this.doc_id}/flush`,
@@ -206,13 +206,13 @@ describe('DocumentUpdaterHandler', function() {
.should.equal(true)
})
- it('should call the callback with no error', function() {
+ it('should call the callback with no error', function () {
this.callback.calledWith(null).should.equal(true)
})
})
- describe('when the document updater API returns an error', function() {
- beforeEach(function() {
+ describe('when the document updater API returns an error', function () {
+ beforeEach(function () {
this.request.callsArgWith(
1,
new Error('something went wrong'),
@@ -226,15 +226,15 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return an error to the callback', function() {
+ it('should return an error to the callback', function () {
this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('when the document updater returns a failure error code', function() {
- beforeEach(function() {
+ describe('when the document updater returns a failure error code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 }, '')
this.handler.flushDocToMongo(
this.project_id,
@@ -243,7 +243,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
this.callback
.calledWith(
sinon.match
@@ -260,14 +260,14 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('deleteDoc', function() {
- describe('successfully', function() {
- beforeEach(function() {
+ describe('deleteDoc', function () {
+ describe('successfully', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 204 }, '')
this.handler.deleteDoc(this.project_id, this.doc_id, this.callback)
})
- it('should delete the document from the document updater', function() {
+ it('should delete the document from the document updater', function () {
this.request
.calledWithMatch({
url: `${this.settings.apis.documentupdater.url}/project/${this.project_id}/doc/${this.doc_id}`,
@@ -276,13 +276,13 @@ describe('DocumentUpdaterHandler', function() {
.should.equal(true)
})
- it('should call the callback with no error', function() {
+ it('should call the callback with no error', function () {
this.callback.calledWith(null).should.equal(true)
})
})
- describe('when the document updater API returns an error', function() {
- beforeEach(function() {
+ describe('when the document updater API returns an error', function () {
+ beforeEach(function () {
this.request.callsArgWith(
1,
new Error('something went wrong'),
@@ -292,20 +292,20 @@ describe('DocumentUpdaterHandler', function() {
this.handler.deleteDoc(this.project_id, this.doc_id, this.callback)
})
- it('should return an error to the callback', function() {
+ it('should return an error to the callback', function () {
this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('when the document updater returns a failure error code', function() {
- beforeEach(function() {
+ describe('when the document updater returns a failure error code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 }, '')
this.handler.deleteDoc(this.project_id, this.doc_id, this.callback)
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
this.callback
.calledWith(
sinon.match
@@ -322,13 +322,13 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('setDocument', function() {
- beforeEach(function() {
+ describe('setDocument', function () {
+ beforeEach(function () {
this.source = 'dropbox'
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 204 }, '')
this.handler.setDocument(
this.project_id,
@@ -340,7 +340,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should set the document in the document updater', function() {
+ it('should set the document in the document updater', function () {
this.request
.calledWith({
url: `${this.settings.apis.documentupdater.url}/project/${this.project_id}/doc/${this.doc_id}`,
@@ -354,13 +354,13 @@ describe('DocumentUpdaterHandler', function() {
.should.equal(true)
})
- it('should call the callback with no error', function() {
+ it('should call the callback with no error', function () {
this.callback.calledWith(null).should.equal(true)
})
})
- describe('when the document updater API returns an error', function() {
- beforeEach(function() {
+ describe('when the document updater API returns an error', function () {
+ beforeEach(function () {
this.request.callsArgWith(
1,
new Error('something went wrong'),
@@ -377,15 +377,15 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return an error to the callback', function() {
+ it('should return an error to the callback', function () {
this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('when the document updater returns a failure error code', function() {
- beforeEach(function() {
+ describe('when the document updater returns a failure error code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 }, '')
this.handler.setDocument(
this.project_id,
@@ -397,7 +397,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
this.callback
.calledWith(
sinon.match
@@ -414,9 +414,9 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('getDocument', function() {
- describe('successfully', function() {
- beforeEach(function() {
+ describe('getDocument', function () {
+ describe('successfully', function () {
+ beforeEach(function () {
this.body = {
lines: this.lines,
version: this.version,
@@ -433,7 +433,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should get the document from the document updater', function() {
+ it('should get the document from the document updater', function () {
this.request
.calledWith({
url: `${this.settings.apis.documentupdater.url}/project/${this.project_id}/doc/${this.doc_id}?fromVersion=${this.fromVersion}`,
@@ -443,15 +443,15 @@ describe('DocumentUpdaterHandler', function() {
.should.equal(true)
})
- it('should call the callback with the lines and version', function() {
+ it('should call the callback with the lines and version', function () {
this.callback
.calledWith(null, this.lines, this.version, this.ranges, this.ops)
.should.equal(true)
})
})
- describe('when the document updater API returns an error', function() {
- beforeEach(function() {
+ describe('when the document updater API returns an error', function () {
+ beforeEach(function () {
this.request.callsArgWith(
1,
new Error('something went wrong'),
@@ -466,15 +466,15 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return an error to the callback', function() {
+ it('should return an error to the callback', function () {
this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('when the document updater returns a failure error code', function() {
- beforeEach(function() {
+ describe('when the document updater returns a failure error code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 }, '')
this.handler.getDocument(
this.project_id,
@@ -484,7 +484,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
this.callback
.calledWith(
sinon.match
@@ -501,13 +501,13 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('getProjectDocsIfMatch', function() {
- beforeEach(function() {
+ describe('getProjectDocsIfMatch', function () {
+ beforeEach(function () {
this.project_state_hash = '1234567890abcdef'
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
this.doc0 = {
_id: this.doc_id,
lines: this.lines,
@@ -525,18 +525,18 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should get the documents from the document updater', function() {
+ it('should get the documents from the document updater', function () {
const url = `${this.settings.apis.documentupdater.url}/project/${this.project_id}/get_and_flush_if_old?state=${this.project_state_hash}`
this.request.post.calledWith(url).should.equal(true)
})
- it('should call the callback with the documents', function() {
+ it('should call the callback with the documents', function () {
this.callback.calledWithExactly(null, this.docs).should.equal(true)
})
})
- describe('when the document updater API returns an error', function() {
- beforeEach(function() {
+ describe('when the document updater API returns an error', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, new Error('something went wrong'), null, null)
@@ -547,15 +547,15 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return an error to the callback', function() {
+ it('should return an error to the callback', function () {
this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('when the document updater returns a conflict error code', function() {
- beforeEach(function() {
+ describe('when the document updater returns a conflict error code', function () {
+ beforeEach(function () {
this.request.post = sinon
.stub()
.callsArgWith(1, null, { statusCode: 409 }, 'Conflict')
@@ -566,20 +566,20 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return the callback with no documents', function() {
+ it('should return the callback with no documents', function () {
this.callback.alwaysCalledWithExactly().should.equal(true)
})
})
})
- describe('clearProjectState', function() {
- describe('successfully', function() {
- beforeEach(function() {
+ describe('clearProjectState', function () {
+ describe('successfully', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 200 })
this.handler.clearProjectState(this.project_id, this.callback)
})
- it('should clear the project state from the document updater', function() {
+ it('should clear the project state from the document updater', function () {
this.request
.calledWithMatch({
url: `${this.settings.apis.documentupdater.url}/project/${this.project_id}/clearState`,
@@ -588,13 +588,13 @@ describe('DocumentUpdaterHandler', function() {
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.calledWith(null).should.equal(true)
})
})
- describe('when the document updater API returns an error', function() {
- beforeEach(function() {
+ describe('when the document updater API returns an error', function () {
+ beforeEach(function () {
this.request.callsArgWith(
1,
new Error('something went wrong'),
@@ -604,20 +604,20 @@ describe('DocumentUpdaterHandler', function() {
this.handler.clearProjectState(this.project_id, this.callback)
})
- it('should return an error to the callback', function() {
+ it('should return an error to the callback', function () {
this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('when the document updater returns an error code', function() {
- beforeEach(function() {
+ describe('when the document updater returns an error code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 }, null)
this.handler.clearProjectState(this.project_id, this.callback)
})
- it('should return the callback with no documents', function() {
+ it('should return the callback with no documents', function () {
this.callback
.calledWith(
sinon.match
@@ -634,13 +634,13 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('acceptChanges', function() {
- beforeEach(function() {
+ describe('acceptChanges', function () {
+ beforeEach(function () {
this.change_id = 'mock-change-id-1'
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 200 }, this.body)
this.handler.acceptChanges(
this.project_id,
@@ -650,7 +650,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should accept the change in the document updater', function() {
+ it('should accept the change in the document updater', function () {
this.request
.calledWith({
url: `${this.settings.apis.documentupdater.url}/project/${this.project_id}/doc/${this.doc_id}/change/accept`,
@@ -662,13 +662,13 @@ describe('DocumentUpdaterHandler', function() {
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.calledWith(null).should.equal(true)
})
})
- describe('when the document updater API returns an error', function() {
- beforeEach(function() {
+ describe('when the document updater API returns an error', function () {
+ beforeEach(function () {
this.request.callsArgWith(
1,
new Error('something went wrong'),
@@ -683,15 +683,15 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return an error to the callback', function() {
+ it('should return an error to the callback', function () {
this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('when the document updater returns a failure error code', function() {
- beforeEach(function() {
+ describe('when the document updater returns a failure error code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 }, '')
this.handler.acceptChanges(
this.project_id,
@@ -701,7 +701,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
this.callback
.calledWith(
sinon.match
@@ -718,13 +718,13 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('deleteThread', function() {
- beforeEach(function() {
+ describe('deleteThread', function () {
+ beforeEach(function () {
this.thread_id = 'mock-thread-id-1'
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 200 }, this.body)
this.handler.deleteThread(
this.project_id,
@@ -734,7 +734,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should delete the thread in the document updater', function() {
+ it('should delete the thread in the document updater', function () {
this.request
.calledWithMatch({
url: `${this.settings.apis.documentupdater.url}/project/${this.project_id}/doc/${this.doc_id}/comment/${this.thread_id}`,
@@ -743,13 +743,13 @@ describe('DocumentUpdaterHandler', function() {
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.calledWith(null).should.equal(true)
})
})
- describe('when the document updater API returns an error', function() {
- beforeEach(function() {
+ describe('when the document updater API returns an error', function () {
+ beforeEach(function () {
this.request.callsArgWith(
1,
new Error('something went wrong'),
@@ -764,15 +764,15 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return an error to the callback', function() {
+ it('should return an error to the callback', function () {
this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('when the document updater returns a failure error code', function() {
- beforeEach(function() {
+ describe('when the document updater returns a failure error code', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 500 }, '')
this.handler.deleteThread(
this.project_id,
@@ -782,7 +782,7 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
this.callback
.calledWith(
sinon.match
@@ -799,14 +799,14 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('updateProjectStructure ', function() {
- beforeEach(function() {
+ describe('updateProjectStructure ', function () {
+ beforeEach(function () {
this.user_id = 1234
this.version = 999
})
- describe('with project history disabled', function() {
- beforeEach(function() {
+ describe('with project history disabled', function () {
+ beforeEach(function () {
this.settings.apis.project_history.sendProjectStructureOps = false
this.handler.updateProjectStructure(
this.project_id,
@@ -817,24 +817,24 @@ describe('DocumentUpdaterHandler', function() {
)
})
- it('does not make a web request', function() {
+ it('does not make a web request', function () {
this.request.called.should.equal(false)
})
- it('calls the callback', function() {
+ it('calls the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('with project history enabled', function() {
- beforeEach(function() {
+ describe('with project history enabled', function () {
+ beforeEach(function () {
this.settings.apis.project_history.sendProjectStructureOps = true
this.url = `${this.settings.apis.documentupdater.url}/project/${this.project_id}`
this.request.callsArgWith(1, null, { statusCode: 204 }, '')
})
- describe('when an entity has changed name', function() {
- it('should send the structure update to the document updater', function(done) {
+ describe('when an entity has changed name', function () {
+ it('should send the structure update to the document updater', function (done) {
this.docIdA = new ObjectId()
this.docIdB = new ObjectId()
this.changes = {
@@ -889,8 +889,8 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('when a doc has been added', function() {
- it('should send the structure update to the document updater', function(done) {
+ describe('when a doc has been added', function () {
+ it('should send the structure update to the document updater', function (done) {
this.docId = new ObjectId()
this.changes = {
newDocs: [
@@ -934,8 +934,8 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('when a file has been added', function() {
- it('should send the structure update to the document updater', function(done) {
+ describe('when a file has been added', function () {
+ it('should send the structure update to the document updater', function (done) {
this.fileId = new ObjectId()
this.changes = {
newFiles: [
@@ -983,8 +983,8 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('when an entity has been deleted', function() {
- it('should end the structure update to the document updater', function(done) {
+ describe('when an entity has been deleted', function () {
+ it('should end the structure update to the document updater', function (done) {
this.docId = new ObjectId()
this.changes = {
oldDocs: [
@@ -1026,8 +1026,8 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('when a file is converted to a doc', function() {
- it('should send the delete first', function(done) {
+ describe('when a file is converted to a doc', function () {
+ it('should send the delete first', function (done) {
this.docId = new ObjectId()
this.fileId = new ObjectId()
this.changes = {
@@ -1087,8 +1087,8 @@ describe('DocumentUpdaterHandler', function() {
})
})
- describe('when the project version is missing', function() {
- it('should call the callback with an error', function() {
+ describe('when the project version is missing', function () {
+ it('should call the callback with an error', function () {
this.docId = new ObjectId()
this.changes = {
oldDocs: [
diff --git a/services/web/test/unit/src/Documents/DocumentControllerTests.js b/services/web/test/unit/src/Documents/DocumentControllerTests.js
index 57ce31ee3a..90d2917082 100644
--- a/services/web/test/unit/src/Documents/DocumentControllerTests.js
+++ b/services/web/test/unit/src/Documents/DocumentControllerTests.js
@@ -20,8 +20,8 @@ const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
const Errors = require('../../../../app/src/Features/Errors/Errors')
-describe('DocumentController', function() {
- beforeEach(function() {
+describe('DocumentController', function () {
+ beforeEach(function () {
this.DocumentController = SandboxedModule.require(modulePath, {
requires: {
'../Project/ProjectGetter': (this.ProjectGetter = {}),
@@ -44,24 +44,24 @@ describe('DocumentController', function() {
return (this.rev = 5)
})
- describe('getDocument', function() {
- beforeEach(function() {
+ describe('getDocument', function () {
+ beforeEach(function () {
return (this.req.params = {
Project_id: this.project_id,
doc_id: this.doc_id
})
})
- describe('when the project exists without project history enabled', function() {
- beforeEach(function() {
+ describe('when the project exists without project history enabled', function () {
+ beforeEach(function () {
this.project = { _id: this.project_id }
return (this.ProjectGetter.getProject = sinon
.stub()
.callsArgWith(2, null, this.project))
})
- describe('when the document exists', function() {
- beforeEach(function() {
+ describe('when the document exists', function () {
+ beforeEach(function () {
this.doc = { _id: this.doc_id }
this.ProjectLocator.findElement = sinon
.stub()
@@ -83,13 +83,13 @@ describe('DocumentController', function() {
)
})
- it('should get the project', function() {
+ it('should get the project', function () {
return this.ProjectGetter.getProject
.calledWith(this.project_id, { rootFolder: true, overleaf: true })
.should.equal(true)
})
- it('should get the pathname of the document', function() {
+ it('should get the pathname of the document', function () {
return this.ProjectLocator.findElement
.calledWith({
project: this.project,
@@ -99,13 +99,13 @@ describe('DocumentController', function() {
.should.equal(true)
})
- it('should get the document content', function() {
+ it('should get the document content', function () {
return this.ProjectEntityHandler.getDoc
.calledWith(this.project_id, this.doc_id)
.should.equal(true)
})
- it('should return the document data to the client as JSON', function() {
+ it('should return the document data to the client as JSON', function () {
this.res.type.should.equal('application/json')
return this.res.body.should.equal(
JSON.stringify({
@@ -118,8 +118,8 @@ describe('DocumentController', function() {
})
})
- describe("when the document doesn't exist", function() {
- beforeEach(function() {
+ describe("when the document doesn't exist", function () {
+ beforeEach(function () {
this.ProjectLocator.findElement = sinon
.stub()
.callsArgWith(1, new Errors.NotFoundError('not found'))
@@ -130,7 +130,7 @@ describe('DocumentController', function() {
)
})
- it('should call next with the NotFoundError', function() {
+ it('should call next with the NotFoundError', function () {
return this.next
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
@@ -138,8 +138,8 @@ describe('DocumentController', function() {
})
})
- describe('when project exists with project history enabled', function() {
- beforeEach(function() {
+ describe('when project exists with project history enabled', function () {
+ beforeEach(function () {
this.doc = { _id: this.doc_id }
this.projectHistoryId = 1234
this.projectHistoryDisplay = true
@@ -176,7 +176,7 @@ describe('DocumentController', function() {
)
})
- it('should return the history id and display setting to the client as JSON', function() {
+ it('should return the history id and display setting to the client as JSON', function () {
this.res.type.should.equal('application/json')
return this.res.body.should.equal(
JSON.stringify({
@@ -191,8 +191,8 @@ describe('DocumentController', function() {
})
})
- describe('when the project does not exist', function() {
- beforeEach(function() {
+ describe('when the project does not exist', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, null)
return this.DocumentController.getDocument(
this.req,
@@ -201,22 +201,22 @@ describe('DocumentController', function() {
)
})
- it('returns a 404', function() {
+ it('returns a 404', function () {
return this.res.statusCode.should.equal(404)
})
})
})
- describe('setDocument', function() {
- beforeEach(function() {
+ describe('setDocument', function () {
+ beforeEach(function () {
return (this.req.params = {
Project_id: this.project_id,
doc_id: this.doc_id
})
})
- describe('when the document exists', function() {
- beforeEach(function() {
+ describe('when the document exists', function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.updateDocLines = sinon.stub().yields()
this.req.body = {
lines: this.doc_lines,
@@ -232,7 +232,7 @@ describe('DocumentController', function() {
)
})
- it('should update the document in Mongo', function() {
+ it('should update the document in Mongo', function () {
return sinon.assert.calledWith(
this.ProjectEntityUpdateHandler.updateDocLines,
this.project_id,
@@ -245,13 +245,13 @@ describe('DocumentController', function() {
)
})
- it('should return a successful response', function() {
+ it('should return a successful response', function () {
return this.res.success.should.equal(true)
})
})
- describe("when the document doesn't exist", function() {
- beforeEach(function() {
+ describe("when the document doesn't exist", function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.updateDocLines = sinon
.stub()
.yields(new Errors.NotFoundError('document does not exist'))
@@ -263,7 +263,7 @@ describe('DocumentController', function() {
)
})
- it('should call next with the NotFoundError', function() {
+ it('should call next with the NotFoundError', function () {
return this.next
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
diff --git a/services/web/test/unit/src/Documents/DocumentHelperTests.js b/services/web/test/unit/src/Documents/DocumentHelperTests.js
index f2ad88bdf9..268c78edb3 100644
--- a/services/web/test/unit/src/Documents/DocumentHelperTests.js
+++ b/services/web/test/unit/src/Documents/DocumentHelperTests.js
@@ -15,55 +15,55 @@ const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/Documents/DocumentHelper.js'
const SandboxedModule = require('sandboxed-module')
-describe('DocumentHelper', function() {
- beforeEach(function() {
+describe('DocumentHelper', function () {
+ beforeEach(function () {
return (this.DocumentHelper = SandboxedModule.require(modulePath))
})
- describe('getTitleFromTexContent', function() {
- it('should return the title', function() {
+ describe('getTitleFromTexContent', function () {
+ it('should return the title', function () {
const document = '\\begin{document}\n\\title{foo}\n\\end{document}'
return expect(
this.DocumentHelper.getTitleFromTexContent(document)
).to.equal('foo')
})
- it('should return the title if surrounded by space', function() {
+ it('should return the title if surrounded by space', function () {
const document = '\\begin{document}\n \\title{foo} \n\\end{document}'
return expect(
this.DocumentHelper.getTitleFromTexContent(document)
).to.equal('foo')
})
- it('should return null if there is no title', function() {
+ it('should return null if there is no title', function () {
const document = '\\begin{document}\n\\end{document}'
return expect(
this.DocumentHelper.getTitleFromTexContent(document)
).to.eql(null)
})
- it('should accept an array', function() {
+ it('should accept an array', function () {
const document = ['\\begin{document}', '\\title{foo}', '\\end{document}']
return expect(
this.DocumentHelper.getTitleFromTexContent(document)
).to.equal('foo')
})
- it('should parse out formatting elements from the title', function() {
+ it('should parse out formatting elements from the title', function () {
const document = '\\title{\\textbf{\\large{Second Year LaTeX Exercise}}}'
return expect(
this.DocumentHelper.getTitleFromTexContent(document)
).to.equal('Second Year LaTeX Exercise')
})
- it('should ignore junk after the title', function() {
+ it('should ignore junk after the title', function () {
const document = '\\title{wombat} potato'
return expect(
this.DocumentHelper.getTitleFromTexContent(document)
).to.equal('wombat')
})
- it('should ignore junk before the title', function() {
+ it('should ignore junk before the title', function () {
const document =
'% this is something that v1 relied on, even though it seems odd \\title{wombat}'
return expect(
@@ -76,7 +76,7 @@ describe('DocumentHelper', function() {
// document = "\\title{Second Year \\large{LaTeX} Exercise}"
// expect(@DocumentHelper.getTitleFromTexContent(document)).to.equal "Second Year LaTeX Exercise"
- it('should collapse whitespace', function() {
+ it('should collapse whitespace', function () {
const document = '\\title{Second Year LaTeX Exercise}'
return expect(
this.DocumentHelper.getTitleFromTexContent(document)
@@ -84,27 +84,27 @@ describe('DocumentHelper', function() {
})
})
- describe('detex', function() {
+ describe('detex', function () {
// note, there are a number of tests for getTitleFromTexContent that also test cases here
- it('leaves a non-TeX string unchanged', function() {
+ it('leaves a non-TeX string unchanged', function () {
expect(this.DocumentHelper.detex('')).to.equal('')
expect(this.DocumentHelper.detex('a')).to.equal('a')
return expect(this.DocumentHelper.detex('a a')).to.equal('a a')
})
- it('collapses spaces', function() {
+ it('collapses spaces', function () {
expect(this.DocumentHelper.detex('a a')).to.equal('a a')
return expect(this.DocumentHelper.detex('a \n a')).to.equal('a \n a')
})
- it('replaces named commands', function() {
+ it('replaces named commands', function () {
expect(this.DocumentHelper.detex('\\LaTeX')).to.equal('LaTeX')
expect(this.DocumentHelper.detex('\\TikZ')).to.equal('TikZ')
expect(this.DocumentHelper.detex('\\TeX')).to.equal('TeX')
return expect(this.DocumentHelper.detex('\\BibTeX')).to.equal('BibTeX')
})
- it('removes general commands', function() {
+ it('removes general commands', function () {
expect(this.DocumentHelper.detex('\\foo')).to.equal('')
expect(this.DocumentHelper.detex('\\foo{}')).to.equal('')
expect(this.DocumentHelper.detex('\\foo~Test')).to.equal('Test')
@@ -112,35 +112,35 @@ describe('DocumentHelper', function() {
return expect(this.DocumentHelper.detex('\\textit{e}')).to.equal('e')
})
- it('leaves basic math', function() {
+ it('leaves basic math', function () {
return expect(this.DocumentHelper.detex('$\\cal{O}(n^2)$')).to.equal(
'O(n^2)'
)
})
- it('removes line spacing commands', function() {
+ it('removes line spacing commands', function () {
return expect(this.DocumentHelper.detex('a \\\\[1.50cm] b')).to.equal(
'a b'
)
})
})
- describe('contentHasDocumentclass', function() {
- it('should return true if the content has a documentclass', function() {
+ describe('contentHasDocumentclass', function () {
+ it('should return true if the content has a documentclass', function () {
const document = ['% line', '% line', '% line', '\\documentclass']
return expect(
this.DocumentHelper.contentHasDocumentclass(document)
).to.equal(true)
})
- it('should allow whitespace before the documentclass', function() {
+ it('should allow whitespace before the documentclass', function () {
const document = ['% line', '% line', '% line', ' \\documentclass']
return expect(
this.DocumentHelper.contentHasDocumentclass(document)
).to.equal(true)
})
- it('should not allow non-whitespace before the documentclass', function() {
+ it('should not allow non-whitespace before the documentclass', function () {
const document = [
'% line',
'% line',
@@ -152,7 +152,7 @@ describe('DocumentHelper', function() {
).to.equal(false)
})
- it('should return false when there is no documentclass', function() {
+ it('should return false when there is no documentclass', function () {
const document = ['% line', '% line', '% line']
return expect(
this.DocumentHelper.contentHasDocumentclass(document)
diff --git a/services/web/test/unit/src/Downloads/ProjectDownloadsControllerTests.js b/services/web/test/unit/src/Downloads/ProjectDownloadsControllerTests.js
index d14da27ab1..13863b156e 100644
--- a/services/web/test/unit/src/Downloads/ProjectDownloadsControllerTests.js
+++ b/services/web/test/unit/src/Downloads/ProjectDownloadsControllerTests.js
@@ -18,8 +18,8 @@ const SandboxedModule = require('sandboxed-module')
const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
-describe('ProjectDownloadsController', function() {
- beforeEach(function() {
+describe('ProjectDownloadsController', function () {
+ beforeEach(function () {
this.project_id = 'project-id-123'
this.req = new MockRequest()
this.res = new MockResponse()
@@ -39,8 +39,8 @@ describe('ProjectDownloadsController', function() {
))
})
- describe('downloadProject', function() {
- beforeEach(function() {
+ describe('downloadProject', function () {
+ beforeEach(function () {
this.stream = { pipe: sinon.stub() }
this.ProjectZipStreamManager.createZipStreamForProject = sinon
.stub()
@@ -63,47 +63,47 @@ describe('ProjectDownloadsController', function() {
)
})
- it('should create a zip from the project', function() {
+ it('should create a zip from the project', function () {
return this.ProjectZipStreamManager.createZipStreamForProject
.calledWith(this.project_id)
.should.equal(true)
})
- it('should stream the zip to the request', function() {
+ it('should stream the zip to the request', function () {
return this.stream.pipe.calledWith(this.res).should.equal(true)
})
- it('should set the correct content type on the request', function() {
+ it('should set the correct content type on the request', function () {
return this.res.contentType
.calledWith('application/zip')
.should.equal(true)
})
- it('should flush the project to mongo', function() {
+ it('should flush the project to mongo', function () {
return this.DocumentUpdaterHandler.flushProjectToMongo
.calledWith(this.project_id)
.should.equal(true)
})
- it("should look up the project's name", function() {
+ it("should look up the project's name", function () {
return this.ProjectGetter.getProject
.calledWith(this.project_id, { name: true })
.should.equal(true)
})
- it('should name the downloaded file after the project', function() {
+ it('should name the downloaded file after the project', function () {
return this.res.setContentDisposition
.calledWith('attachment', { filename: `${this.project_name}.zip` })
.should.equal(true)
})
- it('should record the action via Metrics', function() {
+ it('should record the action via Metrics', function () {
return this.metrics.inc.calledWith('zip-downloads').should.equal(true)
})
})
- describe('downloadMultipleProjects', function() {
- beforeEach(function() {
+ describe('downloadMultipleProjects', function () {
+ beforeEach(function () {
this.stream = { pipe: sinon.stub() }
this.ProjectZipStreamManager.createZipStreamForMultipleProjects = sinon
.stub()
@@ -123,29 +123,29 @@ describe('ProjectDownloadsController', function() {
)
})
- it('should create a zip from the project', function() {
+ it('should create a zip from the project', function () {
return this.ProjectZipStreamManager.createZipStreamForMultipleProjects
.calledWith(this.project_ids)
.should.equal(true)
})
- it('should stream the zip to the request', function() {
+ it('should stream the zip to the request', function () {
return this.stream.pipe.calledWith(this.res).should.equal(true)
})
- it('should set the correct content type on the request', function() {
+ it('should set the correct content type on the request', function () {
return this.res.contentType
.calledWith('application/zip')
.should.equal(true)
})
- it('should flush the projects to mongo', function() {
+ it('should flush the projects to mongo', function () {
return this.DocumentUpdaterHandler.flushMultipleProjectsToMongo
.calledWith(this.project_ids)
.should.equal(true)
})
- it('should name the downloaded file after the project', function() {
+ it('should name the downloaded file after the project', function () {
return this.res.setContentDisposition
.calledWith('attachment', {
filename: 'Overleaf Projects (2 items).zip'
@@ -153,7 +153,7 @@ describe('ProjectDownloadsController', function() {
.should.equal(true)
})
- it('should record the action via Metrics', function() {
+ it('should record the action via Metrics', function () {
return this.metrics.inc
.calledWith('zip-downloads-multiple')
.should.equal(true)
diff --git a/services/web/test/unit/src/Downloads/ProjectZipStreamManagerTests.js b/services/web/test/unit/src/Downloads/ProjectZipStreamManagerTests.js
index e99f02b0f2..acb072d50f 100644
--- a/services/web/test/unit/src/Downloads/ProjectZipStreamManagerTests.js
+++ b/services/web/test/unit/src/Downloads/ProjectZipStreamManagerTests.js
@@ -22,8 +22,8 @@ const modulePath =
const SandboxedModule = require('sandboxed-module')
const { EventEmitter } = require('events')
-describe('ProjectZipStreamManager', function() {
- beforeEach(function() {
+describe('ProjectZipStreamManager', function () {
+ beforeEach(function () {
this.project_id = 'project-id-123'
this.callback = sinon.stub()
this.archive = {
@@ -40,9 +40,9 @@ describe('ProjectZipStreamManager', function() {
}))
})
- describe('createZipStreamForMultipleProjects', function() {
- describe('successfully', function() {
- beforeEach(function(done) {
+ describe('createZipStreamForMultipleProjects', function () {
+ describe('successfully', function () {
+ beforeEach(function (done) {
this.project_ids = ['project-1', 'project-2']
this.zip_streams = {
'project-1': new EventEmitter(),
@@ -81,11 +81,11 @@ describe('ProjectZipStreamManager', function() {
return (this.archive.finalize = () => done())
})
- it('should create a zip archive', function() {
+ it('should create a zip archive', function () {
return this.archiver.calledWith('zip').should.equal(true)
})
- it('should return a stream before any processing is done', function() {
+ it('should return a stream before any processing is done', function () {
this.callback
.calledWith(sinon.match.falsy, this.archive)
.should.equal(true)
@@ -94,7 +94,7 @@ describe('ProjectZipStreamManager', function() {
.should.equal(true)
})
- it('should get a zip stream for all of the projects', function() {
+ it('should get a zip stream for all of the projects', function () {
return Array.from(this.project_ids).map(project_id =>
this.ProjectZipStreamManager.createZipStreamForProject
.calledWith(project_id)
@@ -102,7 +102,7 @@ describe('ProjectZipStreamManager', function() {
)
})
- it('should get the names of each project', function() {
+ it('should get the names of each project', function () {
return Array.from(this.project_ids).map(project_id =>
this.ProjectGetter.getProject
.calledWith(project_id, { name: true })
@@ -110,7 +110,7 @@ describe('ProjectZipStreamManager', function() {
)
})
- it('should add all of the projects to the zip', function() {
+ it('should add all of the projects to the zip', function () {
return Array.from(this.project_ids).map(project_id =>
this.archive.append
.calledWith(this.zip_streams[project_id], {
@@ -122,9 +122,9 @@ describe('ProjectZipStreamManager', function() {
})
})
- describe('createZipStreamForProject', function() {
- describe('successfully', function() {
- beforeEach(function() {
+ describe('createZipStreamForProject', function () {
+ describe('successfully', function () {
+ beforeEach(function () {
this.ProjectZipStreamManager.addAllDocsToArchive = sinon
.stub()
.callsArg(2)
@@ -138,11 +138,11 @@ describe('ProjectZipStreamManager', function() {
)
})
- it('should create a zip archive', function() {
+ it('should create a zip archive', function () {
return this.archiver.calledWith('zip').should.equal(true)
})
- it('should return a stream before any processing is done', function() {
+ it('should return a stream before any processing is done', function () {
this.callback
.calledWith(sinon.match.falsy, this.archive)
.should.equal(true)
@@ -154,25 +154,25 @@ describe('ProjectZipStreamManager', function() {
.should.equal(true)
})
- it('should add all of the project docs to the zip', function() {
+ it('should add all of the project docs to the zip', function () {
return this.ProjectZipStreamManager.addAllDocsToArchive
.calledWith(this.project_id, this.archive)
.should.equal(true)
})
- it('should add all of the project files to the zip', function() {
+ it('should add all of the project files to the zip', function () {
return this.ProjectZipStreamManager.addAllFilesToArchive
.calledWith(this.project_id, this.archive)
.should.equal(true)
})
- it('should finalise the stream', function() {
+ it('should finalise the stream', function () {
return this.archive.finalize.called.should.equal(true)
})
})
- describe('with an error adding docs', function() {
- beforeEach(function() {
+ describe('with an error adding docs', function () {
+ beforeEach(function () {
this.ProjectZipStreamManager.addAllDocsToArchive = sinon
.stub()
.callsArgWith(2, new Error('something went wrong'))
@@ -186,13 +186,13 @@ describe('ProjectZipStreamManager', function() {
)
})
- it('should log out an error', function() {
+ it('should log out an error', function () {
return this.logger.error
.calledWith(sinon.match.any, 'error adding docs to zip stream')
.should.equal(true)
})
- it('should continue with the process', function() {
+ it('should continue with the process', function () {
this.ProjectZipStreamManager.addAllDocsToArchive.called.should.equal(
true
)
@@ -203,8 +203,8 @@ describe('ProjectZipStreamManager', function() {
})
})
- describe('with an error adding files', function() {
- beforeEach(function() {
+ describe('with an error adding files', function () {
+ beforeEach(function () {
this.ProjectZipStreamManager.addAllDocsToArchive = sinon
.stub()
.callsArg(2)
@@ -218,13 +218,13 @@ describe('ProjectZipStreamManager', function() {
)
})
- it('should log out an error', function() {
+ it('should log out an error', function () {
return this.logger.error
.calledWith(sinon.match.any, 'error adding files to zip stream')
.should.equal(true)
})
- it('should continue with the process', function() {
+ it('should continue with the process', function () {
this.ProjectZipStreamManager.addAllDocsToArchive.called.should.equal(
true
)
@@ -236,8 +236,8 @@ describe('ProjectZipStreamManager', function() {
})
})
- describe('addAllDocsToArchive', function() {
- beforeEach(function(done) {
+ describe('addAllDocsToArchive', function () {
+ beforeEach(function (done) {
this.docs = {
'/main.tex': {
lines: [
@@ -264,13 +264,13 @@ describe('ProjectZipStreamManager', function() {
)
})
- it('should get the docs for the project', function() {
+ it('should get the docs for the project', function () {
return this.ProjectEntityHandler.getAllDocs
.calledWith(this.project_id)
.should.equal(true)
})
- it('should add each doc to the archive', function() {
+ it('should add each doc to the archive', function () {
return (() => {
const result = []
for (let path in this.docs) {
@@ -287,8 +287,8 @@ describe('ProjectZipStreamManager', function() {
})
})
- describe('addAllFilesToArchive', function() {
- beforeEach(function() {
+ describe('addAllFilesToArchive', function () {
+ beforeEach(function () {
this.files = {
'/image.png': {
_id: 'file-id-1'
@@ -325,13 +325,13 @@ describe('ProjectZipStreamManager', function() {
})()
})
- it('should get the files for the project', function() {
+ it('should get the files for the project', function () {
return this.ProjectEntityHandler.getAllFiles
.calledWith(this.project_id)
.should.equal(true)
})
- it('should get a stream for each file', function() {
+ it('should get a stream for each file', function () {
return (() => {
const result = []
for (let path in this.files) {
@@ -346,7 +346,7 @@ describe('ProjectZipStreamManager', function() {
})()
})
- it('should add each file to the archive', function() {
+ it('should add each file to the archive', function () {
return (() => {
const result = []
for (let path in this.files) {
diff --git a/services/web/test/unit/src/Editor/EditorControllerTests.js b/services/web/test/unit/src/Editor/EditorControllerTests.js
index 228f98e4fc..aca5be3623 100644
--- a/services/web/test/unit/src/Editor/EditorControllerTests.js
+++ b/services/web/test/unit/src/Editor/EditorControllerTests.js
@@ -23,8 +23,8 @@ const MockClient = require('../helpers/MockClient')
const assert = require('assert')
const { ObjectId } = require('mongodb')
-describe('EditorController', function() {
- beforeEach(function() {
+describe('EditorController', function () {
+ beforeEach(function () {
this.project_id = 'test-project-id'
this.source = 'dropbox'
this.user_id = new ObjectId()
@@ -71,8 +71,8 @@ describe('EditorController', function() {
}))
})
- describe('addDoc', function() {
- beforeEach(function() {
+ describe('addDoc', function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.addDocWithRanges = sinon
.stub()
.yields(null, this.doc, this.folder_id)
@@ -87,7 +87,7 @@ describe('EditorController', function() {
)
})
- it('should add the doc using the project entity handler', function() {
+ it('should add the doc using the project entity handler', function () {
return this.ProjectEntityUpdateHandler.addDocWithRanges
.calledWith(
this.project_id,
@@ -99,7 +99,7 @@ describe('EditorController', function() {
.should.equal(true)
})
- it('should send the update out to the users in the project', function() {
+ it('should send the update out to the users in the project', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -112,13 +112,13 @@ describe('EditorController', function() {
.should.equal(true)
})
- it('calls the callback', function() {
+ it('calls the callback', function () {
return this.callback.calledWith(null, this.doc).should.equal(true)
})
})
- describe('addFile', function() {
- beforeEach(function() {
+ describe('addFile', function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.addFile = sinon
.stub()
.yields(null, this.file, this.folder_id)
@@ -134,7 +134,7 @@ describe('EditorController', function() {
)
})
- it('should add the folder using the project entity handler', function() {
+ it('should add the folder using the project entity handler', function () {
return this.ProjectEntityUpdateHandler.addFile
.calledWith(
this.project_id,
@@ -147,7 +147,7 @@ describe('EditorController', function() {
.should.equal(true)
})
- it('should send the update of a new folder out to the users in the project', function() {
+ it('should send the update of a new folder out to the users in the project', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -161,13 +161,13 @@ describe('EditorController', function() {
.should.equal(true)
})
- it('calls the callback', function() {
+ it('calls the callback', function () {
return this.callback.calledWith(null, this.file).should.equal(true)
})
})
- describe('upsertDoc', function() {
- beforeEach(function() {
+ describe('upsertDoc', function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.upsertDoc = sinon
.stub()
.yields(null, this.doc, false)
@@ -182,7 +182,7 @@ describe('EditorController', function() {
)
})
- it('upserts the doc using the project entity handler', function() {
+ it('upserts the doc using the project entity handler', function () {
return this.ProjectEntityUpdateHandler.upsertDoc
.calledWith(
this.project_id,
@@ -194,12 +194,12 @@ describe('EditorController', function() {
.should.equal(true)
})
- it('returns the doc', function() {
+ it('returns the doc', function () {
return this.callback.calledWith(null, this.doc).should.equal(true)
})
- describe('doc does not exist', function() {
- beforeEach(function() {
+ describe('doc does not exist', function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.upsertDoc = sinon
.stub()
.yields(null, this.doc, true)
@@ -214,7 +214,7 @@ describe('EditorController', function() {
)
})
- it('sends an update out to users in the project', function() {
+ it('sends an update out to users in the project', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -229,8 +229,8 @@ describe('EditorController', function() {
})
})
- describe('upsertFile', function() {
- beforeEach(function() {
+ describe('upsertFile', function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.upsertFile = sinon
.stub()
.yields(null, this.newFile, false, this.file)
@@ -246,7 +246,7 @@ describe('EditorController', function() {
)
})
- it('upserts the file using the project entity handler', function() {
+ it('upserts the file using the project entity handler', function () {
return this.ProjectEntityUpdateHandler.upsertFile
.calledWith(
this.project_id,
@@ -259,12 +259,12 @@ describe('EditorController', function() {
.should.equal(true)
})
- it('returns the file', function() {
+ it('returns the file', function () {
return this.callback.calledWith(null, this.newFile).should.equal(true)
})
- describe('file does not exist', function() {
- beforeEach(function() {
+ describe('file does not exist', function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.upsertFile = sinon
.stub()
.yields(null, this.file, true)
@@ -280,7 +280,7 @@ describe('EditorController', function() {
)
})
- it('should send the update out to users in the project', function() {
+ it('should send the update out to users in the project', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -296,8 +296,8 @@ describe('EditorController', function() {
})
})
- describe('upsertDocWithPath', function() {
- beforeEach(function() {
+ describe('upsertDocWithPath', function () {
+ beforeEach(function () {
this.docPath = '/folder/doc'
this.ProjectEntityUpdateHandler.upsertDocWithPath = sinon
@@ -313,14 +313,14 @@ describe('EditorController', function() {
)
})
- it('upserts the doc using the project entity handler', function() {
+ it('upserts the doc using the project entity handler', function () {
return this.ProjectEntityUpdateHandler.upsertDocWithPath
.calledWith(this.project_id, this.docPath, this.docLines, this.source)
.should.equal(true)
})
- describe('doc does not exist', function() {
- beforeEach(function() {
+ describe('doc does not exist', function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.upsertDocWithPath = sinon
.stub()
.yields(null, this.doc, true, [], this.folder)
@@ -334,7 +334,7 @@ describe('EditorController', function() {
)
})
- it('should send the update for the doc out to users in the project', function() {
+ it('should send the update for the doc out to users in the project', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -348,8 +348,8 @@ describe('EditorController', function() {
})
})
- describe('folders required for doc do not exist', function() {
- beforeEach(function() {
+ describe('folders required for doc do not exist', function () {
+ beforeEach(function () {
const folders = [
(this.folderA = { _id: 2, parentFolder_id: 1 }),
(this.folderB = { _id: 3, parentFolder_id: 2 })
@@ -367,7 +367,7 @@ describe('EditorController', function() {
)
})
- it('should send the update for each folder to users in the project', function() {
+ it('should send the update for each folder to users in the project', function () {
this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -388,8 +388,8 @@ describe('EditorController', function() {
})
})
- describe('upsertFileWithPath', function() {
- beforeEach(function() {
+ describe('upsertFileWithPath', function () {
+ beforeEach(function () {
this.filePath = '/folder/file'
this.ProjectEntityUpdateHandler.upsertFileWithPath = sinon
@@ -406,7 +406,7 @@ describe('EditorController', function() {
)
})
- it('upserts the file using the project entity handler', function() {
+ it('upserts the file using the project entity handler', function () {
return this.ProjectEntityUpdateHandler.upsertFileWithPath
.calledWith(
this.project_id,
@@ -417,8 +417,8 @@ describe('EditorController', function() {
.should.equal(true)
})
- describe('file does not exist', function() {
- beforeEach(function() {
+ describe('file does not exist', function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.upsertFileWithPath = sinon
.stub()
.yields(null, this.file, true, undefined, [], this.folder)
@@ -433,7 +433,7 @@ describe('EditorController', function() {
)
})
- it('should send the update for the file out to users in the project', function() {
+ it('should send the update for the file out to users in the project', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -448,8 +448,8 @@ describe('EditorController', function() {
})
})
- describe('folders required for file do not exist', function() {
- beforeEach(function() {
+ describe('folders required for file do not exist', function () {
+ beforeEach(function () {
const folders = [
(this.folderA = { _id: 2, parentFolder_id: 1 }),
(this.folderB = { _id: 3, parentFolder_id: 2 })
@@ -468,7 +468,7 @@ describe('EditorController', function() {
)
})
- it('should send the update for each folder to users in the project', function() {
+ it('should send the update for each folder to users in the project', function () {
this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -489,8 +489,8 @@ describe('EditorController', function() {
})
})
- describe('addFolder', function() {
- beforeEach(function() {
+ describe('addFolder', function () {
+ beforeEach(function () {
this.EditorController._notifyProjectUsersOfNewFolder = sinon
.stub()
.yields()
@@ -507,25 +507,25 @@ describe('EditorController', function() {
)
})
- it('should add the folder using the project entity handler', function() {
+ it('should add the folder using the project entity handler', function () {
return this.ProjectEntityUpdateHandler.addFolder
.calledWith(this.project_id, this.folder_id, this.folderName)
.should.equal(true)
})
- it('should notifyProjectUsersOfNewFolder', function() {
+ it('should notifyProjectUsersOfNewFolder', function () {
return this.EditorController._notifyProjectUsersOfNewFolder
.calledWith(this.project_id, this.folder_id, this.folder, this.user_id)
.should.equal(true)
})
- it('should return the folder in the callback', function() {
+ it('should return the folder in the callback', function () {
return this.callback.calledWith(null, this.folder).should.equal(true)
})
})
- describe('mkdirp', function() {
- beforeEach(function() {
+ describe('mkdirp', function () {
+ beforeEach(function () {
this.path = 'folder1/folder2'
this.folders = [
(this.folderA = { _id: 2, parentFolder_id: 1 }),
@@ -544,28 +544,28 @@ describe('EditorController', function() {
)
})
- it('should create the folder using the project entity handler', function() {
+ it('should create the folder using the project entity handler', function () {
return this.ProjectEntityUpdateHandler.mkdirp
.calledWith(this.project_id, this.path)
.should.equal(true)
})
- it('should notifyProjectUsersOfNewFolder', function() {
+ it('should notifyProjectUsersOfNewFolder', function () {
return this.EditorController._notifyProjectUsersOfNewFolders.calledWith(
this.project_id,
this.folders
)
})
- it('should return the folder in the callback', function() {
+ it('should return the folder in the callback', function () {
return this.callback
.calledWith(null, this.folders, this.folder)
.should.equal(true)
})
})
- describe('deleteEntity', function() {
- beforeEach(function() {
+ describe('deleteEntity', function () {
+ beforeEach(function () {
this.entity_id = 'entity_id_here'
this.type = 'doc'
this.ProjectEntityUpdateHandler.deleteEntity = sinon.stub().yields()
@@ -579,13 +579,13 @@ describe('EditorController', function() {
)
})
- it('should delete the folder using the project entity handler', function() {
+ it('should delete the folder using the project entity handler', function () {
return this.ProjectEntityUpdateHandler.deleteEntity
.calledWith(this.project_id, this.entity_id, this.type, this.user_id)
.should.equal(true)
})
- it('notify users an entity has been deleted', function() {
+ it('notify users an entity has been deleted', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -597,8 +597,8 @@ describe('EditorController', function() {
})
})
- describe('deleteEntityWithPath', function() {
- beforeEach(function() {
+ describe('deleteEntityWithPath', function () {
+ beforeEach(function () {
this.entity_id = 'entity_id_here'
this.ProjectEntityUpdateHandler.deleteEntityWithPath = sinon
.stub()
@@ -613,13 +613,13 @@ describe('EditorController', function() {
)
})
- it('should delete the folder using the project entity handler', function() {
+ it('should delete the folder using the project entity handler', function () {
return this.ProjectEntityUpdateHandler.deleteEntityWithPath
.calledWith(this.project_id, this.path, this.user_id)
.should.equal(true)
})
- it('notify users an entity has been deleted', function() {
+ it('notify users an entity has been deleted', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -631,8 +631,8 @@ describe('EditorController', function() {
})
})
- describe('updateProjectDescription', function() {
- beforeEach(function() {
+ describe('updateProjectDescription', function () {
+ beforeEach(function () {
this.description = 'new description'
return this.EditorController.updateProjectDescription(
this.project_id,
@@ -641,13 +641,13 @@ describe('EditorController', function() {
)
})
- it('should send the new description to the project details handler', function() {
+ it('should send the new description to the project details handler', function () {
return this.ProjectDetailsHandler.setProjectDescription
.calledWith(this.project_id, this.description)
.should.equal(true)
})
- it('should notify the other clients about the updated description', function() {
+ it('should notify the other clients about the updated description', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -658,15 +658,15 @@ describe('EditorController', function() {
})
})
- describe('deleteProject', function() {
- beforeEach(function() {
+ describe('deleteProject', function () {
+ beforeEach(function () {
this.err = 'errro'
return (this.ProjectDeleter.deleteProject = sinon
.stub()
.callsArgWith(1, this.err))
})
- it('should call the project handler', function(done) {
+ it('should call the project handler', function (done) {
return this.EditorController.deleteProject(this.project_id, err => {
err.should.equal(this.err)
this.ProjectDeleter.deleteProject
@@ -677,8 +677,8 @@ describe('EditorController', function() {
})
})
- describe('renameEntity', function() {
- beforeEach(function(done) {
+ describe('renameEntity', function () {
+ beforeEach(function (done) {
this.entity_id = 'entity_id_here'
this.entityType = 'doc'
this.newName = 'bobsfile.tex'
@@ -694,7 +694,7 @@ describe('EditorController', function() {
)
})
- it('should call the project handler', function() {
+ it('should call the project handler', function () {
return this.ProjectEntityUpdateHandler.renameEntity
.calledWith(
this.project_id,
@@ -706,7 +706,7 @@ describe('EditorController', function() {
.should.equal(true)
})
- it('should emit the update to the room', function() {
+ it('should emit the update to the room', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -718,8 +718,8 @@ describe('EditorController', function() {
})
})
- describe('moveEntity', function() {
- beforeEach(function() {
+ describe('moveEntity', function () {
+ beforeEach(function () {
this.entity_id = 'entity_id_here'
this.entityType = 'doc'
this.ProjectEntityUpdateHandler.moveEntity = sinon.stub().yields()
@@ -733,7 +733,7 @@ describe('EditorController', function() {
)
})
- it('should call the ProjectEntityUpdateHandler', function() {
+ it('should call the ProjectEntityUpdateHandler', function () {
return this.ProjectEntityUpdateHandler.moveEntity
.calledWith(
this.project_id,
@@ -745,7 +745,7 @@ describe('EditorController', function() {
.should.equal(true)
})
- it('should emit the update to the room', function() {
+ it('should emit the update to the room', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(
this.project_id,
@@ -756,13 +756,13 @@ describe('EditorController', function() {
.should.equal(true)
})
- it('calls the callback', function() {
+ it('calls the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('renameProject', function() {
- beforeEach(function() {
+ describe('renameProject', function () {
+ beforeEach(function () {
this.err = 'errro'
this.newName = 'new name here'
return this.EditorController.renameProject(
@@ -772,21 +772,21 @@ describe('EditorController', function() {
)
})
- it('should call the EditorController', function() {
+ it('should call the EditorController', function () {
return this.ProjectDetailsHandler.renameProject
.calledWith(this.project_id, this.newName)
.should.equal(true)
})
- it('should emit the update to the room', function() {
+ it('should emit the update to the room', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'projectNameUpdated', this.newName)
.should.equal(true)
})
})
- describe('setCompiler', function() {
- beforeEach(function() {
+ describe('setCompiler', function () {
+ beforeEach(function () {
this.compiler = 'latex'
return this.EditorController.setCompiler(
this.project_id,
@@ -795,7 +795,7 @@ describe('EditorController', function() {
)
})
- it('should send the new compiler and project id to the project options handler', function() {
+ it('should send the new compiler and project id to the project options handler', function () {
this.ProjectOptionsHandler.setCompiler
.calledWith(this.project_id, this.compiler)
.should.equal(true)
@@ -805,8 +805,8 @@ describe('EditorController', function() {
})
})
- describe('setImageName', function() {
- beforeEach(function() {
+ describe('setImageName', function () {
+ beforeEach(function () {
this.imageName = 'texlive-1234.5'
return this.EditorController.setImageName(
this.project_id,
@@ -815,7 +815,7 @@ describe('EditorController', function() {
)
})
- it('should send the new imageName and project id to the project options handler', function() {
+ it('should send the new imageName and project id to the project options handler', function () {
this.ProjectOptionsHandler.setImageName
.calledWith(this.project_id, this.imageName)
.should.equal(true)
@@ -825,8 +825,8 @@ describe('EditorController', function() {
})
})
- describe('setSpellCheckLanguage', function() {
- beforeEach(function() {
+ describe('setSpellCheckLanguage', function () {
+ beforeEach(function () {
this.languageCode = 'fr'
return this.EditorController.setSpellCheckLanguage(
this.project_id,
@@ -835,7 +835,7 @@ describe('EditorController', function() {
)
})
- it('should send the new languageCode and project id to the project options handler', function() {
+ it('should send the new languageCode and project id to the project options handler', function () {
this.ProjectOptionsHandler.setSpellCheckLanguage
.calledWith(this.project_id, this.languageCode)
.should.equal(true)
@@ -849,9 +849,9 @@ describe('EditorController', function() {
})
})
- describe('setPublicAccessLevel', function() {
- describe('when setting to private', function() {
- beforeEach(function() {
+ describe('setPublicAccessLevel', function () {
+ describe('when setting to private', function () {
+ beforeEach(function () {
this.newAccessLevel = 'private'
this.ProjectDetailsHandler.ensureTokensArePresent = sinon
.stub()
@@ -863,25 +863,25 @@ describe('EditorController', function() {
)
})
- it('should set the access level', function() {
+ it('should set the access level', function () {
return this.ProjectDetailsHandler.setPublicAccessLevel
.calledWith(this.project_id, this.newAccessLevel)
.should.equal(true)
})
- it('should broadcast the access level change', function() {
+ it('should broadcast the access level change', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'project:publicAccessLevel:changed')
.should.equal(true)
})
- it('should not ensure tokens are present for project', function() {
+ it('should not ensure tokens are present for project', function () {
return this.ProjectDetailsHandler.ensureTokensArePresent
.calledWith(this.project_id)
.should.equal(false)
})
- it('should not broadcast a token change', function() {
+ it('should not broadcast a token change', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'project:tokens:changed', {
tokens: this.tokens
@@ -890,8 +890,8 @@ describe('EditorController', function() {
})
})
- describe('when setting to tokenBased', function() {
- beforeEach(function() {
+ describe('when setting to tokenBased', function () {
+ beforeEach(function () {
this.newAccessLevel = 'tokenBased'
this.tokens = { readOnly: 'aaa', readAndWrite: '42bbb' }
this.ProjectDetailsHandler.ensureTokensArePresent = sinon
@@ -904,25 +904,25 @@ describe('EditorController', function() {
)
})
- it('should set the access level', function() {
+ it('should set the access level', function () {
return this.ProjectDetailsHandler.setPublicAccessLevel
.calledWith(this.project_id, this.newAccessLevel)
.should.equal(true)
})
- it('should broadcast the access level change', function() {
+ it('should broadcast the access level change', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'project:publicAccessLevel:changed')
.should.equal(true)
})
- it('should ensure tokens are present for project', function() {
+ it('should ensure tokens are present for project', function () {
return this.ProjectDetailsHandler.ensureTokensArePresent
.calledWith(this.project_id)
.should.equal(true)
})
- it('should broadcast the token change too', function() {
+ it('should broadcast the token change too', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'project:tokens:changed', {
tokens: this.tokens
@@ -932,8 +932,8 @@ describe('EditorController', function() {
})
})
- describe('setRootDoc', function() {
- beforeEach(function() {
+ describe('setRootDoc', function () {
+ beforeEach(function () {
this.newRootDocID = '21312321321'
this.ProjectEntityUpdateHandler.setRootDoc = sinon.stub().yields()
return this.EditorController.setRootDoc(
@@ -943,13 +943,13 @@ describe('EditorController', function() {
)
})
- it('should call the ProjectEntityUpdateHandler', function() {
+ it('should call the ProjectEntityUpdateHandler', function () {
return this.ProjectEntityUpdateHandler.setRootDoc
.calledWith(this.project_id, this.newRootDocID)
.should.equal(true)
})
- it('should emit the update to the room', function() {
+ it('should emit the update to the room', function () {
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'rootDocUpdated', this.newRootDocID)
.should.equal(true)
diff --git a/services/web/test/unit/src/Editor/EditorHttpControllerTests.js b/services/web/test/unit/src/Editor/EditorHttpControllerTests.js
index b0de1f2535..8673282249 100644
--- a/services/web/test/unit/src/Editor/EditorHttpControllerTests.js
+++ b/services/web/test/unit/src/Editor/EditorHttpControllerTests.js
@@ -6,8 +6,8 @@ const Errors = require('../../../../app/src/Features/Errors/Errors')
const MODULE_PATH = '../../../../app/src/Features/Editor/EditorHttpController'
-describe('EditorHttpController', function() {
- beforeEach(function() {
+describe('EditorHttpController', function () {
+ beforeEach(function () {
this.ownerId = new ObjectId()
this.project = {
_id: new ObjectId(),
@@ -152,19 +152,19 @@ describe('EditorHttpController', function() {
})
})
- describe('joinProject', function() {
- beforeEach(function() {
+ describe('joinProject', function () {
+ beforeEach(function () {
this.req.params = { Project_id: this.project._id }
this.req.query = { user_id: this.user._id }
})
- describe('successfully', function() {
- beforeEach(function(done) {
+ describe('successfully', function () {
+ beforeEach(function (done) {
this.res.json.callsFake(() => done())
this.EditorHttpController.joinProject(this.req, this.res)
})
- it('should return the project and privilege level', function() {
+ it('should return the project and privilege level', function () {
expect(this.res.json).to.have.been.calledWith({
project: this.projectView,
privilegeLevel: 'owner',
@@ -172,32 +172,32 @@ describe('EditorHttpController', function() {
})
})
- it('should not try to unmark the project as deleted', function() {
+ it('should not try to unmark the project as deleted', function () {
expect(this.ProjectDeleter.promises.unmarkAsDeletedByExternalSource).not
.to.have.been.called
})
- it('should send an inc metric', function() {
+ it('should send an inc metric', function () {
expect(this.Metrics.inc).to.have.been.calledWith('editor.join-project')
})
})
- describe('when the project is marked as deleted', function() {
- beforeEach(function(done) {
+ describe('when the project is marked as deleted', function () {
+ beforeEach(function (done) {
this.projectView.deletedByExternalDataSource = true
this.res.json.callsFake(() => done())
this.EditorHttpController.joinProject(this.req, this.res)
})
- it('should unmark the project as deleted', function() {
+ it('should unmark the project as deleted', function () {
expect(
this.ProjectDeleter.promises.unmarkAsDeletedByExternalSource
).to.have.been.calledWith(this.project._id)
})
})
- describe('with a restricted user', function() {
- beforeEach(function(done) {
+ describe('with a restricted user', function () {
+ beforeEach(function (done) {
this.AuthorizationManager.isRestrictedUser.returns(true)
this.AuthorizationManager.promises.getPrivilegeLevelForProject.resolves(
'readOnly'
@@ -206,7 +206,7 @@ describe('EditorHttpController', function() {
this.EditorHttpController.joinProject(this.req, this.res)
})
- it('should mark the user as restricted, and hide details of owner', function() {
+ it('should mark the user as restricted, and hide details of owner', function () {
expect(this.res.json).to.have.been.calledWith({
project: this.reducedProjectView,
privilegeLevel: 'readOnly',
@@ -215,8 +215,8 @@ describe('EditorHttpController', function() {
})
})
- describe('when not authorized', function() {
- beforeEach(function(done) {
+ describe('when not authorized', function () {
+ beforeEach(function (done) {
this.AuthorizationManager.promises.getPrivilegeLevelForProject.resolves(
null
)
@@ -224,13 +224,13 @@ describe('EditorHttpController', function() {
this.EditorHttpController.joinProject(this.req, this.res)
})
- it('should send a 403 response', function() {
+ it('should send a 403 response', function () {
expect(this.res.sendStatus).to.have.been.calledWith(403)
})
})
- describe('with an anonymous user', function() {
- beforeEach(function(done) {
+ describe('with an anonymous user', function () {
+ beforeEach(function (done) {
this.req.query = { user_id: 'anonymous-user' }
this.res.json.callsFake(() => done())
this.AuthorizationManager.isRestrictedUser
@@ -242,7 +242,7 @@ describe('EditorHttpController', function() {
this.EditorHttpController.joinProject(this.req, this.res)
})
- it('should mark the user as restricted', function() {
+ it('should mark the user as restricted', function () {
expect(this.res.json).to.have.been.calledWith({
project: this.reducedProjectView,
privilegeLevel: 'readOnly',
@@ -251,14 +251,14 @@ describe('EditorHttpController', function() {
})
})
- describe('when project is not found', function() {
- beforeEach(function(done) {
+ describe('when project is not found', function () {
+ beforeEach(function (done) {
this.ProjectGetter.promises.getProjectWithoutDocLines.resolves(null)
this.next.callsFake(() => done())
this.EditorHttpController.joinProject(this.req, this.res, this.next)
})
- it('should handle return not found error', function() {
+ it('should handle return not found error', function () {
expect(this.next).to.have.been.calledWith(
sinon.match.instanceOf(Errors.NotFoundError)
)
@@ -266,8 +266,8 @@ describe('EditorHttpController', function() {
})
})
- describe('addDoc', function() {
- beforeEach(function() {
+ describe('addDoc', function () {
+ beforeEach(function () {
this.req.params = { Project_id: this.project._id }
this.req.body = {
name: (this.name = 'doc-name'),
@@ -275,13 +275,13 @@ describe('EditorHttpController', function() {
}
})
- describe('successfully', function() {
- beforeEach(function(done) {
+ describe('successfully', function () {
+ beforeEach(function (done) {
this.res.json.callsFake(() => done())
this.EditorHttpController.addDoc(this.req, this.res)
})
- it('should call EditorController.addDoc', function() {
+ it('should call EditorController.addDoc', function () {
expect(this.EditorController.promises.addDoc).to.have.been.calledWith(
this.project._id,
this.parentFolderId,
@@ -292,13 +292,13 @@ describe('EditorHttpController', function() {
)
})
- it('should send the doc back as JSON', function() {
+ it('should send the doc back as JSON', function () {
expect(this.res.json).to.have.been.calledWith(this.doc)
})
})
- describe('unsuccesfully', function() {
- it('handle name too short', function(done) {
+ describe('unsuccesfully', function () {
+ it('handle name too short', function (done) {
this.req.body.name = ''
this.res.sendStatus.callsFake(status => {
expect(status).to.equal(400)
@@ -307,7 +307,7 @@ describe('EditorHttpController', function() {
this.EditorHttpController.addDoc(this.req, this.res)
})
- it('handle too many files', function(done) {
+ it('handle too many files', function (done) {
this.EditorController.promises.addDoc.rejects(
new Error('project_has_too_many_files')
)
@@ -322,8 +322,8 @@ describe('EditorHttpController', function() {
})
})
- describe('addFolder', function() {
- beforeEach(function() {
+ describe('addFolder', function () {
+ beforeEach(function () {
this.folderName = 'folder-name'
this.req.params = { Project_id: this.project._id }
this.req.body = {
@@ -332,13 +332,13 @@ describe('EditorHttpController', function() {
}
})
- describe('successfully', function() {
- beforeEach(function(done) {
+ describe('successfully', function () {
+ beforeEach(function (done) {
this.res.json.callsFake(() => done())
this.EditorHttpController.addFolder(this.req, this.res)
})
- it('should call EditorController.addFolder', function() {
+ it('should call EditorController.addFolder', function () {
expect(
this.EditorController.promises.addFolder
).to.have.been.calledWith(
@@ -349,13 +349,13 @@ describe('EditorHttpController', function() {
)
})
- it('should send the folder back as JSON', function() {
+ it('should send the folder back as JSON', function () {
expect(this.res.json).to.have.been.calledWith(this.folder)
})
})
- describe('unsuccesfully', function() {
- it('handle name too short', function(done) {
+ describe('unsuccesfully', function () {
+ it('handle name too short', function (done) {
this.req.body.name = ''
this.res.sendStatus.callsFake(status => {
expect(status).to.equal(400)
@@ -364,7 +364,7 @@ describe('EditorHttpController', function() {
this.EditorHttpController.addFolder(this.req, this.res)
})
- it('handle too many files', function(done) {
+ it('handle too many files', function (done) {
this.EditorController.promises.addFolder.rejects(
new Error('project_has_too_many_files')
)
@@ -377,7 +377,7 @@ describe('EditorHttpController', function() {
this.EditorHttpController.addFolder(this.req, this.res)
})
- it('handle invalid element name', function(done) {
+ it('handle invalid element name', function (done) {
this.EditorController.promises.addFolder.rejects(
new Error('invalid element name')
)
@@ -392,8 +392,8 @@ describe('EditorHttpController', function() {
})
})
- describe('renameEntity', function() {
- beforeEach(function() {
+ describe('renameEntity', function () {
+ beforeEach(function () {
this.entityId = 'entity-id-123'
this.entityType = 'entity-type'
this.req.params = {
@@ -403,15 +403,15 @@ describe('EditorHttpController', function() {
}
})
- describe('successfully', function() {
- beforeEach(function(done) {
+ describe('successfully', function () {
+ beforeEach(function (done) {
this.newName = 'new-name'
this.req.body = { name: this.newName }
this.res.sendStatus.callsFake(() => done())
this.EditorHttpController.renameEntity(this.req, this.res)
})
- it('should call EditorController.renameEntity', function() {
+ it('should call EditorController.renameEntity', function () {
expect(
this.EditorController.promises.renameEntity
).to.have.been.calledWith(
@@ -423,37 +423,37 @@ describe('EditorHttpController', function() {
)
})
- it('should send back a success response', function() {
+ it('should send back a success response', function () {
expect(this.res.sendStatus).to.have.been.calledWith(204)
})
})
- describe('with long name', function() {
- beforeEach(function() {
+ describe('with long name', function () {
+ beforeEach(function () {
this.newName = 'long'.repeat(100)
this.req.body = { name: this.newName }
this.EditorHttpController.renameEntity(this.req, this.res)
})
- it('should send back a bad request status code', function() {
+ it('should send back a bad request status code', function () {
expect(this.res.sendStatus).to.have.been.calledWith(400)
})
})
- describe('with 0 length name', function() {
- beforeEach(function() {
+ describe('with 0 length name', function () {
+ beforeEach(function () {
this.newName = ''
this.req.body = { name: this.newName }
this.EditorHttpController.renameEntity(this.req, this.res)
})
- it('should send back a bad request status code', function() {
+ it('should send back a bad request status code', function () {
expect(this.res.sendStatus).to.have.been.calledWith(400)
})
})
})
- describe('moveEntity', function() {
- beforeEach(function(done) {
+ describe('moveEntity', function () {
+ beforeEach(function (done) {
this.entityId = 'entity-id-123'
this.entityType = 'entity-type'
this.folderId = 'folder-id-123'
@@ -467,7 +467,7 @@ describe('EditorHttpController', function() {
this.EditorHttpController.moveEntity(this.req, this.res)
})
- it('should call EditorController.moveEntity', function() {
+ it('should call EditorController.moveEntity', function () {
expect(this.EditorController.promises.moveEntity).to.have.been.calledWith(
this.project._id,
this.entityId,
@@ -477,13 +477,13 @@ describe('EditorHttpController', function() {
)
})
- it('should send back a success response', function() {
+ it('should send back a success response', function () {
expect(this.res.sendStatus).to.have.been.calledWith(204)
})
})
- describe('deleteEntity', function() {
- beforeEach(function(done) {
+ describe('deleteEntity', function () {
+ beforeEach(function (done) {
this.entityId = 'entity-id-123'
this.entityType = 'entity-type'
this.req.params = {
@@ -495,7 +495,7 @@ describe('EditorHttpController', function() {
this.EditorHttpController.deleteEntity(this.req, this.res)
})
- it('should call EditorController.deleteEntity', function() {
+ it('should call EditorController.deleteEntity', function () {
expect(
this.EditorController.promises.deleteEntity
).to.have.been.calledWith(
@@ -507,13 +507,13 @@ describe('EditorHttpController', function() {
)
})
- it('should send back a success response', function() {
+ it('should send back a success response', function () {
expect(this.res.sendStatus).to.have.been.calledWith(204)
})
})
- describe('convertDocToFile', function() {
- beforeEach(function(done) {
+ describe('convertDocToFile', function () {
+ beforeEach(function (done) {
this.req.params = {
Project_id: this.project._id.toString(),
entity_id: this.doc._id.toString()
@@ -523,8 +523,8 @@ describe('EditorHttpController', function() {
this.EditorHttpController.convertDocToFile(this.req, this.res)
})
- describe('when successful', function() {
- it('should convert the doc to a file', function() {
+ describe('when successful', function () {
+ it('should convert the doc to a file', function () {
expect(
this.ProjectEntityUpdateHandler.promises.convertDocToFile
).to.have.been.calledWith(
@@ -534,15 +534,15 @@ describe('EditorHttpController', function() {
)
})
- it('should return the file id in the response', function() {
+ it('should return the file id in the response', function () {
expect(this.res.json).to.have.been.calledWith({
fileId: this.file._id.toString()
})
})
})
- describe('when the doc has ranges', function() {
- it('should return a 422 - Unprocessable Entity', function(done) {
+ describe('when the doc has ranges', function () {
+ it('should return a 422 - Unprocessable Entity', function (done) {
this.ProjectEntityUpdateHandler.promises.convertDocToFile.rejects(
new Errors.DocHasRangesError({})
)
@@ -558,8 +558,8 @@ describe('EditorHttpController', function() {
})
})
- describe("when the doc does't exist", function() {
- it('should return a 404 - not found', function(done) {
+ describe("when the doc does't exist", function () {
+ it('should return a 404 - not found', function (done) {
this.ProjectEntityUpdateHandler.promises.convertDocToFile.rejects(
new Errors.NotFoundError({})
)
diff --git a/services/web/test/unit/src/Editor/EditorRealTimeControllerTests.js b/services/web/test/unit/src/Editor/EditorRealTimeControllerTests.js
index 551b964b14..79abe87c14 100644
--- a/services/web/test/unit/src/Editor/EditorRealTimeControllerTests.js
+++ b/services/web/test/unit/src/Editor/EditorRealTimeControllerTests.js
@@ -17,8 +17,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Editor/EditorRealTimeController'
)
-describe('EditorRealTimeController', function() {
- beforeEach(function() {
+describe('EditorRealTimeController', function () {
+ beforeEach(function () {
this.rclient = { publish: sinon.stub() }
this.Metrics = { summary: sinon.stub() }
this.EditorRealTimeController = SandboxedModule.require(modulePath, {
@@ -46,8 +46,8 @@ describe('EditorRealTimeController', function() {
return (this.payload = ['argument one', 42])
})
- describe('emitToRoom', function() {
- beforeEach(function() {
+ describe('emitToRoom', function () {
+ beforeEach(function () {
this.message_id = 'web:somehost:01020304-0'
return this.EditorRealTimeController.emitToRoom(
this.room_id,
@@ -56,7 +56,7 @@ describe('EditorRealTimeController', function() {
)
})
- it('should publish the message to redis', function() {
+ it('should publish the message to redis', function () {
return this.rclient.publish
.calledWith(
'editor-events',
@@ -70,7 +70,7 @@ describe('EditorRealTimeController', function() {
.should.equal(true)
})
- it('should track the payload size', function() {
+ it('should track the payload size', function () {
this.Metrics.summary
.calledWith(
'redis.publish.editor-events',
@@ -85,8 +85,8 @@ describe('EditorRealTimeController', function() {
})
})
- describe('emitToAll', function() {
- beforeEach(function() {
+ describe('emitToAll', function () {
+ beforeEach(function () {
this.EditorRealTimeController.emitToRoom = sinon.stub()
return this.EditorRealTimeController.emitToAll(
this.message,
@@ -94,7 +94,7 @@ describe('EditorRealTimeController', function() {
)
})
- it("should emit to the room 'all'", function() {
+ it("should emit to the room 'all'", function () {
return this.EditorRealTimeController.emitToRoom
.calledWith('all', this.message, ...Array.from(this.payload))
.should.equal(true)
diff --git a/services/web/test/unit/src/Email/EmailBuilderTests.js b/services/web/test/unit/src/Email/EmailBuilderTests.js
index 750105ccd7..5c4a547da2 100644
--- a/services/web/test/unit/src/Email/EmailBuilderTests.js
+++ b/services/web/test/unit/src/Email/EmailBuilderTests.js
@@ -13,8 +13,8 @@ const ctaEmailBody = require('../../../../app/src/Features/Email/Bodies/cta-emai
const NoCTAEmailBody = require('../../../../app/src/Features/Email/Bodies/NoCTAEmailBody')
const BaseWithHeaderEmailLayout = require('../../../../app/src/Features/Email/Layouts/BaseWithHeaderEmailLayout')
-describe('EmailBuilder', function() {
- before(function() {
+describe('EmailBuilder', function () {
+ before(function () {
this.settings = {
appName: 'testApp',
siteUrl: 'https://www.overleaf.com'
@@ -30,8 +30,8 @@ describe('EmailBuilder', function() {
})
})
- describe('projectInvite', function() {
- beforeEach(function() {
+ describe('projectInvite', function () {
+ beforeEach(function () {
this.opts = {
to: 'bob@bob.com',
first_name: 'bob',
@@ -46,41 +46,41 @@ describe('EmailBuilder', function() {
}
})
- describe('when sending a normal email', function() {
- beforeEach(function() {
+ describe('when sending a normal email', function () {
+ beforeEach(function () {
this.email = this.EmailBuilder.buildEmail('projectInvite', this.opts)
})
- it('should have html and text properties', function() {
+ it('should have html and text properties', function () {
expect(this.email.html != null).to.equal(true)
expect(this.email.text != null).to.equal(true)
})
- it('should not have undefined in it', function() {
+ it('should not have undefined in it', function () {
this.email.html.indexOf('undefined').should.equal(-1)
this.email.subject.indexOf('undefined').should.equal(-1)
})
})
- describe('when someone is up to no good', function() {
- beforeEach(function() {
+ describe('when someone is up to no good', function () {
+ beforeEach(function () {
this.opts.project.name = "
"
this.email = this.EmailBuilder.buildEmail('projectInvite', this.opts)
})
- it('should not contain unescaped html in the html part', function() {
+ it('should not contain unescaped html in the html part', function () {
expect(this.email.html).to.contain('New Project')
})
- it('should not have undefined in it', function() {
+ it('should not have undefined in it', function () {
this.email.html.indexOf('undefined').should.equal(-1)
this.email.subject.indexOf('undefined').should.equal(-1)
})
})
})
- describe('SpamSafe', function() {
- beforeEach(function() {
+ describe('SpamSafe', function () {
+ beforeEach(function () {
this.opts = {
to: 'bob@joe.com',
first_name: 'bob',
@@ -96,14 +96,14 @@ describe('EmailBuilder', function() {
this.email = this.EmailBuilder.buildEmail('projectInvite', this.opts)
})
- it('should replace spammy project name', function() {
+ it('should replace spammy project name', function () {
this.email.html.indexOf('a new project').should.not.equal(-1)
this.email.subject.indexOf('New Project').should.not.equal(-1)
})
})
- describe('ctaTemplate', function() {
- describe('missing required content', function() {
+ describe('ctaTemplate', function () {
+ describe('missing required content', function () {
const content = {
title: () => {},
greeting: () => {},
@@ -113,25 +113,25 @@ describe('EmailBuilder', function() {
ctaURL: () => {},
gmailGoToAction: () => {}
}
- it('should throw an error when missing title', function() {
+ it('should throw an error when missing title', function () {
let { title, ...missing } = content
expect(() => {
this.EmailBuilder.ctaTemplate(missing)
}).to.throw(Error)
})
- it('should throw an error when missing message', function() {
+ it('should throw an error when missing message', function () {
let { message, ...missing } = content
expect(() => {
this.EmailBuilder.ctaTemplate(missing)
}).to.throw(Error)
})
- it('should throw an error when missing ctaText', function() {
+ it('should throw an error when missing ctaText', function () {
let { ctaText, ...missing } = content
expect(() => {
this.EmailBuilder.ctaTemplate(missing)
}).to.throw(Error)
})
- it('should throw an error when missing ctaURL', function() {
+ it('should throw an error when missing ctaURL', function () {
let { ctaURL, ...missing } = content
expect(() => {
this.EmailBuilder.ctaTemplate(missing)
@@ -140,10 +140,10 @@ describe('EmailBuilder', function() {
})
})
- describe('templates', function() {
- describe('CTA', function() {
- describe('canceledSubscription', function() {
- beforeEach(function() {
+ describe('templates', function () {
+ describe('CTA', function () {
+ describe('canceledSubscription', function () {
+ beforeEach(function () {
this.emailAddress = 'example@overleaf.com'
this.opts = {
to: this.emailAddress
@@ -156,13 +156,13 @@ describe('EmailBuilder', function() {
'https://docs.google.com/forms/d/e/1FAIpQLSfa7z_s-cucRRXm70N4jEcSbFsZeb0yuKThHGQL8ySEaQzF0Q/viewform?usp=sf_link'
})
- it('should build the email', function() {
+ it('should build the email', function () {
expect(this.email.html).to.exist
expect(this.email.text).to.exist
})
- describe('HTML email', function() {
- it('should include a CTA button and a fallback CTA link', function() {
+ describe('HTML email', function () {
+ it('should include a CTA button and a fallback CTA link', function () {
const dom = cheerio.load(this.email.html)
const buttonLink = dom('a:contains("Leave Feedback")')
expect(buttonLink.length).to.equal(1)
@@ -174,15 +174,15 @@ describe('EmailBuilder', function() {
})
})
- describe('plain text email', function() {
- it('should contain the CTA link', function() {
+ describe('plain text email', function () {
+ it('should contain the CTA link', function () {
expect(this.email.text).to.contain(this.expectedUrl)
})
})
})
- describe('confirmEmail', function() {
- before(function() {
+ describe('confirmEmail', function () {
+ before(function () {
this.emailAddress = 'example@overleaf.com'
this.userId = 'abc123'
this.opts = {
@@ -193,13 +193,13 @@ describe('EmailBuilder', function() {
this.email = this.EmailBuilder.buildEmail('confirmEmail', this.opts)
})
- it('should build the email', function() {
+ it('should build the email', function () {
expect(this.email.html).to.exist
expect(this.email.text).to.exist
})
- describe('HTML email', function() {
- it('should include a CTA button and a fallback CTA link', function() {
+ describe('HTML email', function () {
+ it('should include a CTA button and a fallback CTA link', function () {
const dom = cheerio.load(this.email.html)
const buttonLink = dom('a:contains("Confirm Email")')
expect(buttonLink.length).to.equal(1)
@@ -211,15 +211,15 @@ describe('EmailBuilder', function() {
})
})
- describe('plain text email', function() {
- it('should contain the CTA link', function() {
+ describe('plain text email', function () {
+ it('should contain the CTA link', function () {
expect(this.email.text).to.contain(this.opts.confirmEmailUrl)
})
})
})
- describe('ownershipTransferConfirmationNewOwner', function() {
- before(function() {
+ describe('ownershipTransferConfirmationNewOwner', function () {
+ before(function () {
this.emailAddress = 'example@overleaf.com'
this.opts = {
to: this.emailAddress,
@@ -238,13 +238,13 @@ describe('EmailBuilder', function() {
}/project/${this.opts.project._id.toString()}`
})
- it('should build the email', function() {
+ it('should build the email', function () {
expect(this.email.html).to.exist
expect(this.email.text).to.exist
})
- describe('HTML email', function() {
- it('should include a CTA button and a fallback CTA link', function() {
+ describe('HTML email', function () {
+ it('should include a CTA button and a fallback CTA link', function () {
const dom = cheerio.load(this.email.html)
const buttonLink = dom('td a')
expect(buttonLink).to.exist
@@ -256,15 +256,15 @@ describe('EmailBuilder', function() {
})
})
- describe('plain text email', function() {
- it('should contain the CTA link', function() {
+ describe('plain text email', function () {
+ it('should contain the CTA link', function () {
expect(this.email.text).to.contain(this.expectedUrl)
})
})
})
- describe('passwordResetRequested', function() {
- before(function() {
+ describe('passwordResetRequested', function () {
+ before(function () {
this.emailAddress = 'example@overleaf.com'
this.opts = {
to: this.emailAddress,
@@ -280,13 +280,13 @@ describe('EmailBuilder', function() {
)
})
- it('should build the email', function() {
+ it('should build the email', function () {
expect(this.email.html).to.exist
expect(this.email.text).to.exist
})
- describe('HTML email', function() {
- it('should include a CTA button and a fallback CTA link', function() {
+ describe('HTML email', function () {
+ it('should include a CTA button and a fallback CTA link', function () {
const dom = cheerio.load(this.email.html)
const buttonLink = dom('td a')
expect(buttonLink).to.exist
@@ -300,15 +300,15 @@ describe('EmailBuilder', function() {
})
})
- describe('plain text email', function() {
- it('should contain the CTA link', function() {
+ describe('plain text email', function () {
+ it('should contain the CTA link', function () {
expect(this.email.text).to.contain(this.opts.setNewPasswordUrl)
})
})
})
- describe('verifyEmailToJoinTeam', function() {
- before(function() {
+ describe('verifyEmailToJoinTeam', function () {
+ before(function () {
this.emailAddress = 'example@overleaf.com'
this.opts = {
to: this.emailAddress,
@@ -325,13 +325,13 @@ describe('EmailBuilder', function() {
)
})
- it('should build the email', function() {
+ it('should build the email', function () {
expect(this.email.html).to.exist
expect(this.email.text).to.exist
})
- describe('HTML email', function() {
- it('should include a CTA button and a fallback CTA link', function() {
+ describe('HTML email', function () {
+ it('should include a CTA button and a fallback CTA link', function () {
const dom = cheerio.load(this.email.html)
const buttonLink = dom('a:contains("Join now")')
expect(buttonLink.length).to.equal(1)
@@ -343,15 +343,15 @@ describe('EmailBuilder', function() {
})
})
- describe('plain text email', function() {
- it('should contain the CTA link', function() {
+ describe('plain text email', function () {
+ it('should contain the CTA link', function () {
expect(this.email.text).to.contain(this.opts.acceptInviteUrl)
})
})
})
- describe('reactivatedSubscription', function() {
- before(function() {
+ describe('reactivatedSubscription', function () {
+ before(function () {
this.emailAddress = 'example@overleaf.com'
this.opts = {
to: this.emailAddress
@@ -363,13 +363,13 @@ describe('EmailBuilder', function() {
this.expectedUrl = `${this.settings.siteUrl}/user/subscription`
})
- it('should build the email', function() {
+ it('should build the email', function () {
expect(this.email.html).to.exist
expect(this.email.text).to.exist
})
- describe('HTML email', function() {
- it('should include a CTA button and a fallback CTA link', function() {
+ describe('HTML email', function () {
+ it('should include a CTA button and a fallback CTA link', function () {
const dom = cheerio.load(this.email.html)
const buttonLink = dom('a:contains("View Subscription Dashboard")')
expect(buttonLink.length).to.equal(1)
@@ -381,15 +381,15 @@ describe('EmailBuilder', function() {
})
})
- describe('plain text email', function() {
- it('should contain the CTA link', function() {
+ describe('plain text email', function () {
+ it('should contain the CTA link', function () {
expect(this.email.text).to.contain(this.expectedUrl)
})
})
})
- describe('testEmail', function() {
- before(function() {
+ describe('testEmail', function () {
+ before(function () {
this.emailAddress = 'example@overleaf.com'
this.opts = {
to: this.emailAddress
@@ -397,13 +397,13 @@ describe('EmailBuilder', function() {
this.email = this.EmailBuilder.buildEmail('testEmail', this.opts)
})
- it('should build the email', function() {
+ it('should build the email', function () {
expect(this.email.html).to.exist
expect(this.email.text).to.exist
})
- describe('HTML email', function() {
- it('should include a CTA button and a fallback CTA link', function() {
+ describe('HTML email', function () {
+ it('should include a CTA button and a fallback CTA link', function () {
const dom = cheerio.load(this.email.html)
const buttonLink = dom(
`a:contains("Open ${this.settings.appName}")`
@@ -417,8 +417,8 @@ describe('EmailBuilder', function() {
})
})
- describe('plain text email', function() {
- it('should contain the CTA link', function() {
+ describe('plain text email', function () {
+ it('should contain the CTA link', function () {
expect(this.email.text).to.contain(
`Open ${this.settings.appName}: ${this.settings.siteUrl}`
)
@@ -426,8 +426,8 @@ describe('EmailBuilder', function() {
})
})
- describe('registered', function() {
- before(function() {
+ describe('registered', function () {
+ before(function () {
this.emailAddress = 'example@overleaf.com'
this.opts = {
to: this.emailAddress,
@@ -436,13 +436,13 @@ describe('EmailBuilder', function() {
this.email = this.EmailBuilder.buildEmail('registered', this.opts)
})
- it('should build the email', function() {
+ it('should build the email', function () {
expect(this.email.html).to.exist
expect(this.email.text).to.exist
})
- describe('HTML email', function() {
- it('should include a CTA button and a fallback CTA link', function() {
+ describe('HTML email', function () {
+ it('should include a CTA button and a fallback CTA link', function () {
const dom = cheerio.load(this.email.html)
const buttonLink = dom('a:contains("Set password")')
expect(buttonLink.length).to.equal(1)
@@ -456,15 +456,15 @@ describe('EmailBuilder', function() {
})
})
- describe('plain text email', function() {
- it('should contain the CTA link', function() {
+ describe('plain text email', function () {
+ it('should contain the CTA link', function () {
expect(this.email.text).to.contain(this.opts.setNewPasswordUrl)
})
})
})
- describe('projectInvite', function() {
- before(function() {
+ describe('projectInvite', function () {
+ before(function () {
this.emailAddress = 'example@overleaf.com'
this.owner = {
email: 'owner@example.com',
@@ -489,13 +489,13 @@ describe('EmailBuilder', function() {
this.email = this.EmailBuilder.buildEmail('projectInvite', this.opts)
})
- it('should build the email', function() {
+ it('should build the email', function () {
expect(this.email.html).to.exist
expect(this.email.text).to.exist
})
- describe('HTML email', function() {
- it('should include a CTA button and a fallback CTA link', function() {
+ describe('HTML email', function () {
+ it('should include a CTA button and a fallback CTA link', function () {
const dom = cheerio.load(this.email.html)
const buttonLink = dom('a:contains("View project")')
expect(buttonLink.length).to.equal(1)
@@ -507,16 +507,16 @@ describe('EmailBuilder', function() {
})
})
- describe('plain text email', function() {
- it('should contain the CTA link', function() {
+ describe('plain text email', function () {
+ it('should contain the CTA link', function () {
expect(this.email.text).to.contain(this.opts.inviteUrl)
})
})
})
})
- describe('no CTA', function() {
- describe('securityAlert', function() {
- before(function() {
+ describe('no CTA', function () {
+ describe('securityAlert', function () {
+ before(function () {
this.message = 'more details about the action'
this.messageHTML = `
${this.message}`
this.messageNotAllowedHTML = `${this.messageHTML}`
@@ -534,30 +534,30 @@ describe('EmailBuilder', function() {
this.email = this.EmailBuilder.buildEmail('securityAlert', this.opts)
})
- it('should build the email', function() {
+ it('should build the email', function () {
expect(this.email.html != null).to.equal(true)
expect(this.email.text != null).to.equal(true)
})
- describe('HTML email', function() {
- it('should clean HTML in opts.actionDescribed', function() {
+ describe('HTML email', function () {
+ it('should clean HTML in opts.actionDescribed', function () {
expect(this.email.html).to.not.contain(
this.actionDescribedNotAllowedHTML
)
expect(this.email.html).to.contain(this.actionDescribedHTML)
})
- it('should clean HTML in opts.message', function() {
+ it('should clean HTML in opts.message', function () {
expect(this.email.html).to.not.contain(this.messageNotAllowedHTML)
expect(this.email.html).to.contain(this.messageHTML)
})
})
- describe('plain text email', function() {
- it('should remove all HTML in opts.actionDescribed', function() {
+ describe('plain text email', function () {
+ it('should remove all HTML in opts.actionDescribed', function () {
expect(this.email.text).to.not.contain(this.actionDescribedHTML)
expect(this.email.text).to.contain(this.actionDescribed)
})
- it('should remove all HTML in opts.message', function() {
+ it('should remove all HTML in opts.message', function () {
expect(this.email.text).to.not.contain(this.messageHTML)
expect(this.email.text).to.contain(this.message)
})
diff --git a/services/web/test/unit/src/Email/EmailHandlerTests.js b/services/web/test/unit/src/Email/EmailHandlerTests.js
index 7708727e4c..6ea65b7106 100644
--- a/services/web/test/unit/src/Email/EmailHandlerTests.js
+++ b/services/web/test/unit/src/Email/EmailHandlerTests.js
@@ -8,8 +8,8 @@ const MODULE_PATH = path.join(
'../../../../app/src/Features/Email/EmailHandler'
)
-describe('EmailHandler', function() {
- beforeEach(function() {
+describe('EmailHandler', function () {
+ beforeEach(function () {
this.html = 'hello'
this.Settings = { email: {} }
this.EmailBuilder = {
@@ -29,8 +29,8 @@ describe('EmailHandler', function() {
})
})
- describe('send email', function() {
- it('should use the correct options', async function() {
+ describe('send email', function () {
+ it('should use the correct options', async function () {
const opts = { to: 'bob@bob.com' }
await this.EmailHandler.promises.sendEmail('welcome', opts)
expect(this.EmailSender.promises.sendEmail).to.have.been.calledWithMatch({
@@ -38,7 +38,7 @@ describe('EmailHandler', function() {
})
})
- it('should return the error', async function() {
+ it('should return the error', async function () {
this.EmailSender.promises.sendEmail.rejects(new Error('boom'))
const opts = {
to: 'bob@bob.com',
@@ -48,14 +48,14 @@ describe('EmailHandler', function() {
.rejected
})
- it('should not send an email if lifecycle is not enabled', async function() {
+ it('should not send an email if lifecycle is not enabled', async function () {
this.Settings.email.lifecycle = false
this.EmailBuilder.buildEmail.returns({ type: 'lifecycle' })
await this.EmailHandler.promises.sendEmail('welcome', {})
expect(this.EmailSender.promises.sendEmail).not.to.have.been.called
})
- it('should send an email if lifecycle is not enabled but the type is notification', async function() {
+ it('should send an email if lifecycle is not enabled but the type is notification', async function () {
this.Settings.email.lifecycle = false
this.EmailBuilder.buildEmail.returns({ type: 'notification' })
const opts = { to: 'bob@bob.com' }
@@ -63,7 +63,7 @@ describe('EmailHandler', function() {
expect(this.EmailSender.promises.sendEmail).to.have.been.called
})
- it('should send lifecycle email if it is enabled', async function() {
+ it('should send lifecycle email if it is enabled', async function () {
this.Settings.email.lifecycle = true
this.EmailBuilder.buildEmail.returns({ type: 'lifecycle' })
const opts = { to: 'bob@bob.com' }
@@ -71,12 +71,12 @@ describe('EmailHandler', function() {
expect(this.EmailSender.promises.sendEmail).to.have.been.called
})
- describe('with plain-text email content', function() {
- beforeEach(function() {
+ describe('with plain-text email content', function () {
+ beforeEach(function () {
this.text = 'hello there'
})
- it('should pass along the text field', async function() {
+ it('should pass along the text field', async function () {
this.EmailBuilder.buildEmail.returns({
html: this.html,
text: this.text
diff --git a/services/web/test/unit/src/Email/EmailMessageHelperTests.js b/services/web/test/unit/src/Email/EmailMessageHelperTests.js
index 4200082bd4..563c51acf6 100644
--- a/services/web/test/unit/src/Email/EmailMessageHelperTests.js
+++ b/services/web/test/unit/src/Email/EmailMessageHelperTests.js
@@ -7,24 +7,24 @@ const MODULE_PATH = path.join(
'../../../../app/src/Features/Email/EmailMessageHelper'
)
-describe('EmailMessageHelper', function() {
- beforeEach(function() {
+describe('EmailMessageHelper', function () {
+ beforeEach(function () {
this.EmailMessageHelper = SandboxedModule.require(MODULE_PATH, {})
})
- describe('cleanHTML', function() {
- beforeEach(function() {
+ describe('cleanHTML', function () {
+ beforeEach(function () {
this.text = 'a message'
this.span = `${this.text}`
this.fullMessage = `${this.span}`
})
- it('should remove HTML for plainText version', function() {
+ it('should remove HTML for plainText version', function () {
const processed = this.EmailMessageHelper.cleanHTML(
this.fullMessage,
true
)
expect(processed).to.equal(this.text)
})
- it('should keep HTML for HTML version but remove tags not allowed', function() {
+ it('should keep HTML for HTML version but remove tags not allowed', function () {
const processed = this.EmailMessageHelper.cleanHTML(
this.fullMessage,
false
diff --git a/services/web/test/unit/src/Email/EmailSenderTests.js b/services/web/test/unit/src/Email/EmailSenderTests.js
index bbc8de50f8..b4fbfbdd54 100644
--- a/services/web/test/unit/src/Email/EmailSenderTests.js
+++ b/services/web/test/unit/src/Email/EmailSenderTests.js
@@ -8,8 +8,8 @@ const MODULE_PATH = path.join(
'../../../../app/src/Features/Email/EmailSender.js'
)
-describe('EmailSender', function() {
- beforeEach(function() {
+describe('EmailSender', function () {
+ beforeEach(function () {
this.RateLimiter = {
promises: {
addCount: sinon.stub()
@@ -52,8 +52,8 @@ describe('EmailSender', function() {
}
})
- describe('sendEmail', function() {
- it('should set the properties on the email to send', async function() {
+ describe('sendEmail', function () {
+ it('should set the properties on the email to send', async function () {
await this.EmailSender.promises.sendEmail(this.opts)
expect(this.sesClient.sendMail).to.have.been.calledWithMatch({
html: this.opts.html,
@@ -62,28 +62,28 @@ describe('EmailSender', function() {
})
})
- it('should return a non-specific error', async function() {
+ it('should return a non-specific error', async function () {
this.sesClient.sendMail.rejects(new Error('boom'))
await expect(this.EmailSender.promises.sendEmail({})).to.be.rejectedWith(
'error sending message'
)
})
- it('should use the from address from settings', async function() {
+ it('should use the from address from settings', async function () {
await this.EmailSender.promises.sendEmail(this.opts)
expect(this.sesClient.sendMail).to.have.been.calledWithMatch({
from: this.Settings.email.fromAddress
})
})
- it('should use the reply to address from settings', async function() {
+ it('should use the reply to address from settings', async function () {
await this.EmailSender.promises.sendEmail(this.opts)
expect(this.sesClient.sendMail).to.have.been.calledWithMatch({
replyTo: this.Settings.email.replyToAddress
})
})
- it('should use the reply to address in options as an override', async function() {
+ it('should use the reply to address in options as an override', async function () {
this.opts.replyTo = 'someone@else.com'
await this.EmailSender.promises.sendEmail(this.opts)
expect(this.sesClient.sendMail).to.have.been.calledWithMatch({
@@ -91,7 +91,7 @@ describe('EmailSender', function() {
})
})
- it('should not send an email when the rate limiter says no', async function() {
+ it('should not send an email when the rate limiter says no', async function () {
this.opts.sendingUser_id = '12321312321'
this.RateLimiter.promises.addCount.resolves(false)
await expect(this.EmailSender.promises.sendEmail(this.opts)).to.be
@@ -99,26 +99,26 @@ describe('EmailSender', function() {
expect(this.sesClient.sendMail).not.to.have.been.called
})
- it('should send the email when the rate limtier says continue', async function() {
+ it('should send the email when the rate limtier says continue', async function () {
this.opts.sendingUser_id = '12321312321'
this.RateLimiter.promises.addCount.resolves(true)
await this.EmailSender.promises.sendEmail(this.opts)
expect(this.sesClient.sendMail).to.have.been.called
})
- it('should not check the rate limiter when there is no sendingUser_id', async function() {
+ it('should not check the rate limiter when there is no sendingUser_id', async function () {
this.EmailSender.sendEmail(this.opts, () => {
expect(this.sesClient.sendMail).to.have.been.called
expect(this.RateLimiter.promises.addCount).not.to.have.been.called
})
})
- describe('with plain-text email content', function() {
- beforeEach(function() {
+ describe('with plain-text email content', function () {
+ beforeEach(function () {
this.opts.text = 'hello there'
})
- it('should set the text property on the email to send', async function() {
+ it('should set the text property on the email to send', async function () {
await this.EmailSender.promises.sendEmail(this.opts)
expect(this.sesClient.sendMail).to.have.been.calledWithMatch({
html: this.opts.html,
diff --git a/services/web/test/unit/src/Email/SpamSafeTests.js b/services/web/test/unit/src/Email/SpamSafeTests.js
index f1ddf58261..0af623b3fa 100644
--- a/services/web/test/unit/src/Email/SpamSafeTests.js
+++ b/services/web/test/unit/src/Email/SpamSafeTests.js
@@ -6,8 +6,8 @@ const modulePath = path.join(
const SpamSafe = require(modulePath)
const { expect } = require('chai')
-describe('SpamSafe', function() {
- it('should reject spammy names', function() {
+describe('SpamSafe', function () {
+ it('should reject spammy names', function () {
expect(SpamSafe.isSafeUserName('Charline Wałęsa')).to.equal(true)
expect(
SpamSafe.isSafeUserName(
diff --git a/services/web/test/unit/src/Errors/HttpErrorHandlerTests.js b/services/web/test/unit/src/Errors/HttpErrorHandlerTests.js
index d902e16743..6d335fbf21 100644
--- a/services/web/test/unit/src/Errors/HttpErrorHandlerTests.js
+++ b/services/web/test/unit/src/Errors/HttpErrorHandlerTests.js
@@ -4,8 +4,8 @@ const MockRequest = require('../helpers/MockRequest')
const SandboxedModule = require('sandboxed-module')
const modulePath = '../../../../app/src/Features/Errors/HttpErrorHandler.js'
-describe('HttpErrorHandler', function() {
- beforeEach(function() {
+describe('HttpErrorHandler', function () {
+ beforeEach(function () {
this.req = new MockRequest()
this.res = new MockResponse()
@@ -19,8 +19,8 @@ describe('HttpErrorHandler', function() {
})
})
- describe('handleErrorByStatusCode', function() {
- it('returns the http status code of 400 errors', function() {
+ describe('handleErrorByStatusCode', function () {
+ it('returns the http status code of 400 errors', function () {
const err = new Error()
this.HttpErrorHandler.handleErrorByStatusCode(
this.req,
@@ -31,7 +31,7 @@ describe('HttpErrorHandler', function() {
expect(this.res.statusCode).to.equal(400)
})
- it('returns the http status code of 500 errors', function() {
+ it('returns the http status code of 500 errors', function () {
const err = new Error()
this.HttpErrorHandler.handleErrorByStatusCode(
this.req,
@@ -42,7 +42,7 @@ describe('HttpErrorHandler', function() {
expect(this.res.statusCode).to.equal(500)
})
- it('returns the http status code of any 5xx error', function() {
+ it('returns the http status code of any 5xx error', function () {
const err = new Error()
this.HttpErrorHandler.handleErrorByStatusCode(
this.req,
@@ -53,7 +53,7 @@ describe('HttpErrorHandler', function() {
expect(this.res.statusCode).to.equal(588)
})
- it('returns the http status code of any 4xx error', function() {
+ it('returns the http status code of any 4xx error', function () {
const err = new Error()
this.HttpErrorHandler.handleErrorByStatusCode(
this.req,
@@ -64,7 +64,7 @@ describe('HttpErrorHandler', function() {
expect(this.res.statusCode).to.equal(488)
})
- it('returns 500 for http status codes smaller than 400', function() {
+ it('returns 500 for http status codes smaller than 400', function () {
const err = new Error()
this.HttpErrorHandler.handleErrorByStatusCode(
this.req,
@@ -75,7 +75,7 @@ describe('HttpErrorHandler', function() {
expect(this.res.statusCode).to.equal(500)
})
- it('returns 500 for http status codes larger than 600', function() {
+ it('returns 500 for http status codes larger than 600', function () {
const err = new Error()
this.HttpErrorHandler.handleErrorByStatusCode(
this.req,
@@ -86,13 +86,13 @@ describe('HttpErrorHandler', function() {
expect(this.res.statusCode).to.equal(500)
})
- it('returns 500 when the error has no http status code', function() {
+ it('returns 500 when the error has no http status code', function () {
const err = new Error()
this.HttpErrorHandler.handleErrorByStatusCode(this.req, this.res, err)
expect(this.res.statusCode).to.equal(500)
})
- it('uses the conflict() error handler', function() {
+ it('uses the conflict() error handler', function () {
const err = new Error()
this.HttpErrorHandler.handleErrorByStatusCode(
this.req,
@@ -103,7 +103,7 @@ describe('HttpErrorHandler', function() {
expect(this.res.body).to.equal('conflict')
})
- it('uses the forbidden() error handler', function() {
+ it('uses the forbidden() error handler', function () {
const err = new Error()
this.HttpErrorHandler.handleErrorByStatusCode(
this.req,
@@ -114,7 +114,7 @@ describe('HttpErrorHandler', function() {
expect(this.res.body).to.equal('restricted')
})
- it('uses the notFound() error handler', function() {
+ it('uses the notFound() error handler', function () {
const err = new Error()
this.HttpErrorHandler.handleErrorByStatusCode(
this.req,
@@ -125,7 +125,7 @@ describe('HttpErrorHandler', function() {
expect(this.res.body).to.equal('not found')
})
- it('uses the unprocessableEntity() error handler', function() {
+ it('uses the unprocessableEntity() error handler', function () {
const err = new Error()
err.httpStatusCode = 422
this.HttpErrorHandler.handleErrorByStatusCode(
@@ -138,18 +138,18 @@ describe('HttpErrorHandler', function() {
})
})
- describe('badRequest', function() {
- it('returns 400', function() {
+ describe('badRequest', function () {
+ it('returns 400', function () {
this.HttpErrorHandler.badRequest(this.req, this.res)
expect(this.res.statusCode).to.equal(400)
})
- it('should print a message when no content-type is included', function() {
+ it('should print a message when no content-type is included', function () {
this.HttpErrorHandler.badRequest(this.req, this.res)
expect(this.res.body).to.equal('client error')
})
- it("should render a template including the error message when content-type is 'html'", function() {
+ it("should render a template including the error message when content-type is 'html'", function () {
this.req.accepts = () => 'html'
this.HttpErrorHandler.badRequest(this.req, this.res, 'an error')
expect(this.res.renderedTemplate).to.equal('general/400')
@@ -159,7 +159,7 @@ describe('HttpErrorHandler', function() {
})
})
- it("should render a default template when content-type is 'html' and no message is provided", function() {
+ it("should render a default template when content-type is 'html' and no message is provided", function () {
this.req.accepts = () => 'html'
this.HttpErrorHandler.badRequest(this.req, this.res)
expect(this.res.renderedTemplate).to.equal('general/400')
@@ -169,7 +169,7 @@ describe('HttpErrorHandler', function() {
})
})
- it("should return a json object when content-type is 'json'", function() {
+ it("should return a json object when content-type is 'json'", function () {
this.req.accepts = () => 'json'
this.HttpErrorHandler.badRequest(this.req, this.res, 'an error', {
foo: 'bar'
@@ -180,25 +180,25 @@ describe('HttpErrorHandler', function() {
})
})
- it("should return an empty json object when content-type is 'json' and no message and info are provided", function() {
+ it("should return an empty json object when content-type is 'json' and no message and info are provided", function () {
this.req.accepts = () => 'json'
this.HttpErrorHandler.badRequest(this.req, this.res)
expect(JSON.parse(this.res.body)).to.deep.equal({})
})
})
- describe('conflict', function() {
- it('returns 409', function() {
+ describe('conflict', function () {
+ it('returns 409', function () {
this.HttpErrorHandler.conflict(this.req, this.res)
expect(this.res.statusCode).to.equal(409)
})
- it('should print a message when no content-type is included', function() {
+ it('should print a message when no content-type is included', function () {
this.HttpErrorHandler.conflict(this.req, this.res)
expect(this.res.body).to.equal('conflict')
})
- it("should render a template including the error message when content-type is 'html'", function() {
+ it("should render a template including the error message when content-type is 'html'", function () {
this.req.accepts = () => 'html'
this.HttpErrorHandler.unprocessableEntity(this.req, this.res, 'an error')
expect(this.res.renderedTemplate).to.equal('general/400')
@@ -208,7 +208,7 @@ describe('HttpErrorHandler', function() {
})
})
- it("should return a json object when content-type is 'json'", function() {
+ it("should return a json object when content-type is 'json'", function () {
this.req.accepts = () => 'json'
this.HttpErrorHandler.unprocessableEntity(
this.req,
@@ -225,18 +225,18 @@ describe('HttpErrorHandler', function() {
})
})
- describe('forbidden', function() {
- it('returns 403', function() {
+ describe('forbidden', function () {
+ it('returns 403', function () {
this.HttpErrorHandler.forbidden(this.req, this.res)
expect(this.res.statusCode).to.equal(403)
})
- it('should print a message when no content-type is included', function() {
+ it('should print a message when no content-type is included', function () {
this.HttpErrorHandler.forbidden(this.req, this.res)
expect(this.res.body).to.equal('restricted')
})
- it("should render a template when content-type is 'html'", function() {
+ it("should render a template when content-type is 'html'", function () {
this.req.accepts = () => 'html'
this.HttpErrorHandler.forbidden(this.req, this.res)
expect(this.res.renderedTemplate).to.equal('user/restricted')
@@ -245,7 +245,7 @@ describe('HttpErrorHandler', function() {
})
})
- it("should return a json object when content-type is 'json'", function() {
+ it("should return a json object when content-type is 'json'", function () {
this.req.accepts = () => 'json'
this.HttpErrorHandler.forbidden(this.req, this.res, 'an error', {
foo: 'bar'
@@ -257,18 +257,18 @@ describe('HttpErrorHandler', function() {
})
})
- describe('notFound', function() {
- it('returns 404', function() {
+ describe('notFound', function () {
+ it('returns 404', function () {
this.HttpErrorHandler.notFound(this.req, this.res)
expect(this.res.statusCode).to.equal(404)
})
- it('should print a message when no content-type is included', function() {
+ it('should print a message when no content-type is included', function () {
this.HttpErrorHandler.notFound(this.req, this.res)
expect(this.res.body).to.equal('not found')
})
- it("should render a template when content-type is 'html'", function() {
+ it("should render a template when content-type is 'html'", function () {
this.req.accepts = () => 'html'
this.HttpErrorHandler.notFound(this.req, this.res)
expect(this.res.renderedTemplate).to.equal('general/404')
@@ -277,7 +277,7 @@ describe('HttpErrorHandler', function() {
})
})
- it("should return a json object when content-type is 'json'", function() {
+ it("should return a json object when content-type is 'json'", function () {
this.req.accepts = () => 'json'
this.HttpErrorHandler.notFound(this.req, this.res, 'an error', {
foo: 'bar'
@@ -289,18 +289,18 @@ describe('HttpErrorHandler', function() {
})
})
- describe('unprocessableEntity', function() {
- it('returns 422', function() {
+ describe('unprocessableEntity', function () {
+ it('returns 422', function () {
this.HttpErrorHandler.unprocessableEntity(this.req, this.res)
expect(this.res.statusCode).to.equal(422)
})
- it('should print a message when no content-type is included', function() {
+ it('should print a message when no content-type is included', function () {
this.HttpErrorHandler.unprocessableEntity(this.req, this.res)
expect(this.res.body).to.equal('unprocessable entity')
})
- it("should render a template including the error message when content-type is 'html'", function() {
+ it("should render a template including the error message when content-type is 'html'", function () {
this.req.accepts = () => 'html'
this.HttpErrorHandler.unprocessableEntity(this.req, this.res, 'an error')
expect(this.res.renderedTemplate).to.equal('general/400')
@@ -310,7 +310,7 @@ describe('HttpErrorHandler', function() {
})
})
- it("should return a json object when content-type is 'json'", function() {
+ it("should return a json object when content-type is 'json'", function () {
this.req.accepts = () => 'json'
this.HttpErrorHandler.unprocessableEntity(
this.req,
@@ -326,13 +326,13 @@ describe('HttpErrorHandler', function() {
})
})
- describe('legacyInternal', function() {
- it('returns 500', function() {
+ describe('legacyInternal', function () {
+ it('returns 500', function () {
this.HttpErrorHandler.legacyInternal(this.req, this.res, new Error())
expect(this.res.statusCode).to.equal(500)
})
- it('should send the error to the logger', function() {
+ it('should send the error to the logger', function () {
const error = new Error('message')
this.HttpErrorHandler.legacyInternal(
this.req,
@@ -343,12 +343,12 @@ describe('HttpErrorHandler', function() {
expect(this.logger.error).to.have.been.calledWith(error)
})
- it('should print a message when no content-type is included', function() {
+ it('should print a message when no content-type is included', function () {
this.HttpErrorHandler.legacyInternal(this.req, this.res, new Error())
expect(this.res.body).to.equal('internal server error')
})
- it("should render a template when content-type is 'html'", function() {
+ it("should render a template when content-type is 'html'", function () {
this.req.accepts = () => 'html'
this.HttpErrorHandler.legacyInternal(this.req, this.res, new Error())
expect(this.res.renderedTemplate).to.equal('general/500')
@@ -357,7 +357,7 @@ describe('HttpErrorHandler', function() {
})
})
- it("should return a json object with a static message when content-type is 'json'", function() {
+ it("should return a json object with a static message when content-type is 'json'", function () {
this.req.accepts = () => 'json'
this.HttpErrorHandler.legacyInternal(
this.req,
diff --git a/services/web/test/unit/src/Exports/ExportsControllerTests.js b/services/web/test/unit/src/Exports/ExportsControllerTests.js
index b30b9226cd..b071228e01 100644
--- a/services/web/test/unit/src/Exports/ExportsControllerTests.js
+++ b/services/web/test/unit/src/Exports/ExportsControllerTests.js
@@ -21,7 +21,7 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Exports/ExportsController.js'
)
-describe('ExportsController', function() {
+describe('ExportsController', function () {
const project_id = '123njdskj9jlk'
const user_id = '123nd3ijdks'
const brand_variation_id = 22
@@ -33,7 +33,7 @@ describe('ExportsController', function() {
const license = 'other'
const show_source = true
- beforeEach(function() {
+ beforeEach(function () {
this.handler = { getUserNotifications: sinon.stub().callsArgWith(1) }
this.req = {
params: {
@@ -71,8 +71,8 @@ describe('ExportsController', function() {
}))
})
- describe('without gallery fields', function() {
- it('should ask the handler to perform the export', function(done) {
+ describe('without gallery fields', function () {
+ it('should ask the handler to perform the export', function (done) {
this.handler.exportProject = sinon
.stub()
.yields(null, { iAmAnExport: true, v1_id: 897 })
@@ -93,8 +93,8 @@ describe('ExportsController', function() {
})
})
- describe('with a message from v1', function() {
- it('should ask the handler to perform the export', function(done) {
+ describe('with a message from v1', function () {
+ it('should ask the handler to perform the export', function (done) {
this.handler.exportProject = sinon.stub().yields(null, {
iAmAnExport: true,
v1_id: 897,
@@ -120,8 +120,8 @@ describe('ExportsController', function() {
})
})
- describe('with gallery fields', function() {
- beforeEach(function() {
+ describe('with gallery fields', function () {
+ beforeEach(function () {
this.req.body.title = title
this.req.body.description = description
this.req.body.author = author
@@ -129,7 +129,7 @@ describe('ExportsController', function() {
return (this.req.body.showSource = true)
})
- it('should ask the handler to perform the export', function(done) {
+ it('should ask the handler to perform the export', function (done) {
this.handler.exportProject = sinon
.stub()
.yields(null, { iAmAnExport: true, v1_id: 897 })
@@ -155,8 +155,8 @@ describe('ExportsController', function() {
})
})
- describe('with an error return from v1 to forward to the publish modal', function() {
- it('should forward the response onward', function(done) {
+ describe('with an error return from v1 to forward to the publish modal', function () {
+ it('should forward the response onward', function (done) {
this.error_json = { status: 422, message: 'nope' }
this.handler.exportProject = sinon
.stub()
@@ -168,7 +168,7 @@ describe('ExportsController', function() {
})
})
- it('should ask the handler to return the status of an export', function(done) {
+ it('should ask the handler to return the status of an export', function (done) {
this.handler.fetchExport = sinon.stub().yields(
null,
`{ \
diff --git a/services/web/test/unit/src/Exports/ExportsHandlerTests.js b/services/web/test/unit/src/Exports/ExportsHandlerTests.js
index ebe0d5fb28..873881c9ac 100644
--- a/services/web/test/unit/src/Exports/ExportsHandlerTests.js
+++ b/services/web/test/unit/src/Exports/ExportsHandlerTests.js
@@ -16,8 +16,8 @@ const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/Exports/ExportsHandler.js'
const SandboxedModule = require('sandboxed-module')
-describe('ExportsHandler', function() {
- beforeEach(function() {
+describe('ExportsHandler', function () {
+ beforeEach(function () {
this.stubRequest = {}
this.request = {
defaults: () => {
@@ -57,8 +57,8 @@ describe('ExportsHandler', function() {
return (this.callback = sinon.stub())
})
- describe('exportProject', function() {
- beforeEach(function() {
+ describe('exportProject', function () {
+ beforeEach(function () {
this.export_data = { iAmAnExport: true }
this.response_body = { iAmAResponseBody: true }
this.ExportsHandler._buildExport = sinon
@@ -69,8 +69,8 @@ describe('ExportsHandler', function() {
.yields(null, this.response_body))
})
- describe('when all goes well', function() {
- beforeEach(function(done) {
+ describe('when all goes well', function () {
+ beforeEach(function (done) {
return this.ExportsHandler.exportProject(
this.export_params,
(error, export_data) => {
@@ -80,27 +80,27 @@ describe('ExportsHandler', function() {
)
})
- it('should build the export', function() {
+ it('should build the export', function () {
return this.ExportsHandler._buildExport
.calledWith(this.export_params)
.should.equal(true)
})
- it('should request the export', function() {
+ it('should request the export', function () {
return this.ExportsHandler._requestExport
.calledWith(this.export_data)
.should.equal(true)
})
- it('should return the export', function() {
+ it('should return the export', function () {
return this.callback
.calledWith(null, this.export_data)
.should.equal(true)
})
})
- describe("when request can't be built", function() {
- beforeEach(function(done) {
+ describe("when request can't be built", function () {
+ beforeEach(function (done) {
this.ExportsHandler._buildExport = sinon
.stub()
.yields(new Error('cannot export project without root doc'))
@@ -113,13 +113,13 @@ describe('ExportsHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
- describe('when export request returns an error to forward to the user', function() {
- beforeEach(function(done) {
+ describe('when export request returns an error to forward to the user', function () {
+ beforeEach(function (done) {
this.error_json = { status: 422, message: 'nope' }
this.ExportsHandler._requestExport = sinon
.stub()
@@ -133,7 +133,7 @@ describe('ExportsHandler', function() {
)
})
- it('should return success and the response to forward', function() {
+ it('should return success and the response to forward', function () {
;(this.callback.args[0][0] instanceof Error).should.equal(false)
return this.callback.calledWith(null, {
forwardResponse: this.error_json
@@ -142,8 +142,8 @@ describe('ExportsHandler', function() {
})
})
- describe('_buildExport', function() {
- beforeEach(function(done) {
+ describe('_buildExport', function () {
+ beforeEach(function (done) {
this.project = {
id: this.project_id,
rootDoc_id: 'doc1_id',
@@ -184,8 +184,8 @@ describe('ExportsHandler', function() {
return done()
})
- describe('when all goes well', function() {
- beforeEach(function(done) {
+ describe('when all goes well', function () {
+ beforeEach(function (done) {
return this.ExportsHandler._buildExport(
this.export_params,
(error, export_data) => {
@@ -195,17 +195,17 @@ describe('ExportsHandler', function() {
)
})
- it('should ensure the project has history', function() {
+ it('should ensure the project has history', function () {
return this.ProjectHistoryHandler.ensureHistoryExistsForProject.called.should.equal(
true
)
})
- it('should request the project history version', function() {
+ it('should request the project history version', function () {
return this.ExportsHandler._requestVersion.called.should.equal(true)
})
- it('should return export data', function() {
+ it('should return export data', function () {
const expected_export_data = {
project: {
id: this.project_id,
@@ -244,8 +244,8 @@ describe('ExportsHandler', function() {
})
})
- describe('when we send replacement user first and last name', function() {
- beforeEach(function(done) {
+ describe('when we send replacement user first and last name', function () {
+ beforeEach(function (done) {
this.custom_first_name = 'FIRST'
this.custom_last_name = 'LAST'
this.export_params.first_name = this.custom_first_name
@@ -259,7 +259,7 @@ describe('ExportsHandler', function() {
)
})
- it('should send the data from the user input', function() {
+ it('should send the data from the user input', function () {
const expected_export_data = {
project: {
id: this.project_id,
@@ -298,8 +298,8 @@ describe('ExportsHandler', function() {
})
})
- describe('when project is not found', function() {
- beforeEach(function(done) {
+ describe('when project is not found', function () {
+ beforeEach(function (done) {
this.ProjectGetter.getProject = sinon
.stub()
.yields(new Error('project not found'))
@@ -312,14 +312,14 @@ describe('ExportsHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
- describe('when project has no root doc', function() {
- describe('when a root doc can be set automatically', function() {
- beforeEach(function(done) {
+ describe('when project has no root doc', function () {
+ describe('when a root doc can be set automatically', function () {
+ beforeEach(function (done) {
this.project.rootDoc_id = null
this.ProjectLocator.findRootDoc = sinon
.stub()
@@ -333,13 +333,13 @@ describe('ExportsHandler', function() {
)
})
- it('should set a root doc', function() {
+ it('should set a root doc', function () {
return this.ProjectRootDocManager.ensureRootDocumentIsValid.called.should.equal(
true
)
})
- it('should return export data', function() {
+ it('should return export data', function () {
const expected_export_data = {
project: {
id: this.project_id,
@@ -379,9 +379,9 @@ describe('ExportsHandler', function() {
})
})
- describe('when project has an invalid root doc', function() {
- describe('when a new root doc can be set automatically', function() {
- beforeEach(function(done) {
+ describe('when project has an invalid root doc', function () {
+ describe('when a new root doc can be set automatically', function () {
+ beforeEach(function (done) {
this.fakeDoc_id = '1a2b3c4d5e6f'
this.project.rootDoc_id = this.fakeDoc_id
this.ProjectLocator.findRootDoc = sinon
@@ -396,13 +396,13 @@ describe('ExportsHandler', function() {
)
})
- it('should set a valid root doc', function() {
+ it('should set a valid root doc', function () {
return this.ProjectRootDocManager.ensureRootDocumentIsValid.called.should.equal(
true
)
})
- it('should return export data', function() {
+ it('should return export data', function () {
const expected_export_data = {
project: {
id: this.project_id,
@@ -441,8 +441,8 @@ describe('ExportsHandler', function() {
})
})
- describe('when no root doc can be identified', function() {
- beforeEach(function(done) {
+ describe('when no root doc can be identified', function () {
+ beforeEach(function (done) {
this.ProjectLocator.findRootDoc = sinon
.stub()
.yields(null, [null, null])
@@ -455,14 +455,14 @@ describe('ExportsHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
})
- describe('when user is not found', function() {
- beforeEach(function(done) {
+ describe('when user is not found', function () {
+ beforeEach(function (done) {
this.UserGetter.getUser = sinon
.stub()
.yields(new Error('user not found'))
@@ -475,13 +475,13 @@ describe('ExportsHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
- describe('when project history request fails', function() {
- beforeEach(function(done) {
+ describe('when project history request fails', function () {
+ beforeEach(function (done) {
this.ExportsHandler._requestVersion = sinon
.stub()
.yields(new Error('project history call failed'))
@@ -494,14 +494,14 @@ describe('ExportsHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
})
- describe('_requestExport', function() {
- beforeEach(function(done) {
+ describe('_requestExport', function () {
+ beforeEach(function (done) {
this.settings.apis = {
v1: {
url: 'http://localhost:5000',
@@ -517,8 +517,8 @@ describe('ExportsHandler', function() {
return done()
})
- describe('when all goes well', function() {
- beforeEach(function(done) {
+ describe('when all goes well', function () {
+ beforeEach(function (done) {
this.stubRequest.post = this.stubPost
return this.ExportsHandler._requestExport(
this.export_data,
@@ -529,7 +529,7 @@ describe('ExportsHandler', function() {
)
})
- it('should issue the request', function() {
+ it('should issue the request', function () {
return expect(this.stubPost.getCall(0).args[0]).to.deep.equal({
url: this.settings.apis.v1.url + '/api/v1/sharelatex/exports',
auth: {
@@ -540,15 +540,15 @@ describe('ExportsHandler', function() {
})
})
- it('should return the body with v1 export id', function() {
+ it('should return the body with v1 export id', function () {
return this.callback
.calledWith(null, { exportId: this.export_id })
.should.equal(true)
})
})
- describe('when the request fails', function() {
- beforeEach(function(done) {
+ describe('when the request fails', function () {
+ beforeEach(function (done) {
this.stubRequest.post = sinon
.stub()
.yields(new Error('export request failed'))
@@ -561,13 +561,13 @@ describe('ExportsHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
return (this.callback.args[0][0] instanceof Error).should.equal(true)
})
})
- describe('when the request returns an error response to forward', function() {
- beforeEach(function(done) {
+ describe('when the request returns an error response to forward', function () {
+ beforeEach(function (done) {
this.error_code = 422
this.error_json = { status: this.error_code, message: 'nope' }
this.stubRequest.post = sinon
@@ -582,7 +582,7 @@ describe('ExportsHandler', function() {
)
})
- it('should return success and the response to forward', function() {
+ it('should return success and the response to forward', function () {
;(this.callback.args[0][0] instanceof Error).should.equal(false)
return this.callback.calledWith(null, {
forwardResponse: this.error_json
@@ -591,8 +591,8 @@ describe('ExportsHandler', function() {
})
})
- describe('fetchExport', function() {
- beforeEach(function(done) {
+ describe('fetchExport', function () {
+ beforeEach(function (done) {
this.settings.apis = {
v1: {
url: 'http://localhost:5000',
@@ -608,8 +608,8 @@ describe('ExportsHandler', function() {
return done()
})
- describe('when all goes well', function() {
- beforeEach(function(done) {
+ describe('when all goes well', function () {
+ beforeEach(function (done) {
this.stubRequest.get = this.stubGet
return this.ExportsHandler.fetchExport(
this.export_id,
@@ -620,7 +620,7 @@ describe('ExportsHandler', function() {
)
})
- it('should issue the request', function() {
+ it('should issue the request', function () {
return expect(this.stubGet.getCall(0).args[0]).to.deep.equal({
url:
this.settings.apis.v1.url +
@@ -633,7 +633,7 @@ describe('ExportsHandler', function() {
})
})
- it('should return the v1 export id', function() {
+ it('should return the v1 export id', function () {
return this.callback
.calledWith(null, { body: this.body })
.should.equal(true)
@@ -641,8 +641,8 @@ describe('ExportsHandler', function() {
})
})
- describe('fetchDownload', function() {
- beforeEach(function(done) {
+ describe('fetchDownload', function () {
+ beforeEach(function (done) {
this.settings.apis = {
v1: {
url: 'http://localhost:5000',
@@ -659,8 +659,8 @@ describe('ExportsHandler', function() {
return done()
})
- describe('when all goes well', function() {
- beforeEach(function(done) {
+ describe('when all goes well', function () {
+ beforeEach(function (done) {
this.stubRequest.get = this.stubGet
return this.ExportsHandler.fetchDownload(
this.export_id,
@@ -672,7 +672,7 @@ describe('ExportsHandler', function() {
)
})
- it('should issue the request', function() {
+ it('should issue the request', function () {
return expect(this.stubGet.getCall(0).args[0]).to.deep.equal({
url:
this.settings.apis.v1.url +
@@ -686,7 +686,7 @@ describe('ExportsHandler', function() {
})
})
- it('should return the v1 export id', function() {
+ it('should return the v1 export id', function () {
return this.callback
.calledWith(null, { body: this.body })
.should.equal(true)
diff --git a/services/web/test/unit/src/FileStore/FileStoreControllerTests.js b/services/web/test/unit/src/FileStore/FileStoreControllerTests.js
index 4a18557a29..7162417879 100644
--- a/services/web/test/unit/src/FileStore/FileStoreControllerTests.js
+++ b/services/web/test/unit/src/FileStore/FileStoreControllerTests.js
@@ -6,8 +6,8 @@ const Errors = require('../../../../app/src/Features/Errors/Errors')
const MODULE_PATH =
'../../../../app/src/Features/FileStore/FileStoreController.js'
-describe('FileStoreController', function() {
- beforeEach(function() {
+describe('FileStoreController', function () {
+ beforeEach(function () {
this.FileStoreHandler = {
getFileStream: sinon.stub(),
getFileSize: sinon.stub()
@@ -42,13 +42,13 @@ describe('FileStoreController', function() {
this.file = { name: 'myfile.png' }
})
- describe('getFile', function() {
- beforeEach(function() {
+ describe('getFile', function () {
+ beforeEach(function () {
this.FileStoreHandler.getFileStream.callsArgWith(3, null, this.stream)
this.ProjectLocator.findElement.callsArgWith(1, null, this.file)
})
- it('should call the file store handler with the project_id file_id and any query string', function(done) {
+ it('should call the file store handler with the project_id file_id and any query string', function (done) {
this.stream.pipe = des => {
this.FileStoreHandler.getFileStream
.calledWith(
@@ -62,7 +62,7 @@ describe('FileStoreController', function() {
this.controller.getFile(this.req, this.res)
})
- it('should pipe to res', function(done) {
+ it('should pipe to res', function (done) {
this.stream.pipe = des => {
des.should.equal(this.res)
done()
@@ -70,7 +70,7 @@ describe('FileStoreController', function() {
this.controller.getFile(this.req, this.res)
})
- it('should get the file from the db', function(done) {
+ it('should get the file from the db', function (done) {
this.stream.pipe = des => {
const opts = {
project_id: this.projectId,
@@ -83,7 +83,7 @@ describe('FileStoreController', function() {
this.controller.getFile(this.req, this.res)
})
- it('should set the Content-Disposition header', function(done) {
+ it('should set the Content-Disposition header', function (done) {
this.stream.pipe = des => {
this.res.setContentDisposition
.calledWith('attachment', { filename: this.file.name })
@@ -95,8 +95,8 @@ describe('FileStoreController', function() {
// Test behaviour around handling html files
;['.html', '.htm', '.xhtml'].forEach(extension => {
- describe(`with a '${extension}' file extension`, function() {
- beforeEach(function() {
+ describe(`with a '${extension}' file extension`, function () {
+ beforeEach(function () {
this.file.name = `bad${extension}`
this.req.get = key => {
if (key === 'User-Agent') {
@@ -105,8 +105,8 @@ describe('FileStoreController', function() {
}
})
- describe('from a non-ios browser', function() {
- it('should not set Content-Type', function(done) {
+ describe('from a non-ios browser', function () {
+ it('should not set Content-Type', function (done) {
this.stream.pipe = des => {
this.res.setHeader
.calledWith('Content-Type', 'text/plain')
@@ -117,8 +117,8 @@ describe('FileStoreController', function() {
})
})
- describe('from an iPhone', function() {
- beforeEach(function() {
+ describe('from an iPhone', function () {
+ beforeEach(function () {
this.req.get = key => {
if (key === 'User-Agent') {
return 'An iPhone browser'
@@ -126,7 +126,7 @@ describe('FileStoreController', function() {
}
})
- it("should set Content-Type to 'text/plain'", function(done) {
+ it("should set Content-Type to 'text/plain'", function (done) {
this.stream.pipe = des => {
this.res.setHeader
.calledWith('Content-Type', 'text/plain')
@@ -137,8 +137,8 @@ describe('FileStoreController', function() {
})
})
- describe('from an iPad', function() {
- beforeEach(function() {
+ describe('from an iPad', function () {
+ beforeEach(function () {
this.req.get = key => {
if (key === 'User-Agent') {
return 'An iPad browser'
@@ -146,7 +146,7 @@ describe('FileStoreController', function() {
}
})
- it("should set Content-Type to 'text/plain'", function(done) {
+ it("should set Content-Type to 'text/plain'", function (done) {
this.stream.pipe = des => {
this.res.setHeader
.calledWith('Content-Type', 'text/plain')
@@ -165,8 +165,8 @@ describe('FileStoreController', function() {
'.html-is-good-for-hidden-files',
'somefile')
].forEach(filename => {
- describe(`with filename as '${filename}'`, function() {
- beforeEach(function() {
+ describe(`with filename as '${filename}'`, function () {
+ beforeEach(function () {
this.user_agent = 'A generic browser'
this.file.name = filename
this.req.get = key => {
@@ -176,12 +176,12 @@ describe('FileStoreController', function() {
}
})
;[('iPhone', 'iPad', 'Firefox', 'Chrome')].forEach(browser => {
- describe(`downloaded from ${browser}`, function() {
- beforeEach(function() {
+ describe(`downloaded from ${browser}`, function () {
+ beforeEach(function () {
this.user_agent = `Some ${browser} thing`
})
- it('Should not set the Content-type', function(done) {
+ it('Should not set the Content-type', function (done) {
this.stream.pipe = des => {
this.res.setHeader
.calledWith('Content-Type', 'text/plain')
@@ -196,8 +196,8 @@ describe('FileStoreController', function() {
})
})
- describe('getFileHead', function() {
- it('reports the file size', function(done) {
+ describe('getFileHead', function () {
+ it('reports the file size', function (done) {
const expectedFileSize = 99393
this.FileStoreHandler.getFileSize.yields(
new Error('getFileSize: unexpected arguments')
@@ -218,7 +218,7 @@ describe('FileStoreController', function() {
this.controller.getFileHead(this.req, this.res)
})
- it('returns 404 on NotFoundError', function(done) {
+ it('returns 404 on NotFoundError', function (done) {
this.FileStoreHandler.getFileSize.yields(new Errors.NotFoundError())
this.res.end = () => {
@@ -229,7 +229,7 @@ describe('FileStoreController', function() {
this.controller.getFileHead(this.req, this.res)
})
- it('returns 500 on error', function(done) {
+ it('returns 500 on error', function (done) {
this.FileStoreHandler.getFileSize.yields(new Error('boom!'))
this.res.end = () => {
diff --git a/services/web/test/unit/src/FileStore/FileStoreHandlerTests.js b/services/web/test/unit/src/FileStore/FileStoreHandlerTests.js
index fe356a3c86..8ffbde73c2 100644
--- a/services/web/test/unit/src/FileStore/FileStoreHandlerTests.js
+++ b/services/web/test/unit/src/FileStore/FileStoreHandlerTests.js
@@ -6,8 +6,8 @@ const OError = require('@overleaf/o-error')
const MODULE_PATH = '../../../../app/src/Features/FileStore/FileStoreHandler.js'
-describe('FileStoreHandler', function() {
- beforeEach(function() {
+describe('FileStoreHandler', function () {
+ beforeEach(function () {
this.fs = {
createReadStream: sinon.stub(),
lstat: sinon.stub().callsArgWith(1, null, {
@@ -70,12 +70,12 @@ describe('FileStoreHandler', function() {
})
})
- describe('uploadFileFromDisk', function() {
- beforeEach(function() {
+ describe('uploadFileFromDisk', function () {
+ beforeEach(function () {
this.request.returns(this.writeStream)
})
- it('should create read stream', function(done) {
+ it('should create read stream', function (done) {
this.fs.createReadStream.returns({
pipe() {},
on(type, cb) {
@@ -95,7 +95,7 @@ describe('FileStoreHandler', function() {
)
})
- it('should pipe the read stream to request', function(done) {
+ it('should pipe the read stream to request', function (done) {
this.request.returns(this.writeStream)
this.fs.createReadStream.returns({
on(type, cb) {
@@ -116,7 +116,7 @@ describe('FileStoreHandler', function() {
)
})
- it('should pass the correct options to request', function(done) {
+ it('should pass the correct options to request', function (done) {
const fileUrl = this.getFileUrl(this.projectId, this.fileId)
this.fs.createReadStream.returns({
pipe() {},
@@ -138,7 +138,7 @@ describe('FileStoreHandler', function() {
)
})
- it('should callback with the url and fileRef', function(done) {
+ it('should callback with the url and fileRef', function (done) {
const fileUrl = this.getFileUrl(this.projectId, this.fileId)
this.fs.createReadStream.returns({
pipe() {},
@@ -162,8 +162,8 @@ describe('FileStoreHandler', function() {
)
})
- describe('symlink', function() {
- it('should not read file if it is symlink', function(done) {
+ describe('symlink', function () {
+ it('should not read file if it is symlink', function (done) {
this.fs.lstat = sinon.stub().callsArgWith(1, null, {
isFile() {
return false
@@ -184,7 +184,7 @@ describe('FileStoreHandler', function() {
)
})
- it('should not read file stat returns nothing', function(done) {
+ it('should not read file stat returns nothing', function (done) {
this.fs.lstat = sinon.stub().callsArgWith(1, null, null)
this.handler.uploadFileFromDisk(
this.projectId,
@@ -198,16 +198,16 @@ describe('FileStoreHandler', function() {
})
})
- describe('when upload fails', function() {
- beforeEach(function() {
- this.writeStream.on = function(type, cb) {
+ describe('when upload fails', function () {
+ beforeEach(function () {
+ this.writeStream.on = function (type, cb) {
if (type === 'response') {
cb({ statusCode: 500 })
}
}
})
- it('should callback with an error', function(done) {
+ it('should callback with an error', function (done) {
this.fs.createReadStream.callCount = 0
this.fs.createReadStream.returns({
pipe() {},
@@ -234,8 +234,8 @@ describe('FileStoreHandler', function() {
})
})
- describe('deleteFile', function() {
- it('should send a delete request to filestore api', function(done) {
+ describe('deleteFile', function () {
+ it('should send a delete request to filestore api', function (done) {
const fileUrl = this.getFileUrl(this.projectId, this.fileId)
this.request.callsArgWith(1, null)
@@ -247,7 +247,7 @@ describe('FileStoreHandler', function() {
})
})
- it('should return the error if there is one', function(done) {
+ it('should return the error if there is one', function (done) {
const error = 'my error'
this.request.callsArgWith(1, error)
this.handler.deleteFile(this.projectId, this.fileId, err => {
@@ -257,8 +257,8 @@ describe('FileStoreHandler', function() {
})
})
- describe('deleteProject', function() {
- it('should send a delete request to filestore api', function(done) {
+ describe('deleteProject', function () {
+ it('should send a delete request to filestore api', function (done) {
const projectUrl = this.getProjectUrl(this.projectId)
this.request.callsArgWith(1, null)
@@ -270,7 +270,7 @@ describe('FileStoreHandler', function() {
})
})
- it('should wrap the error if there is one', function(done) {
+ it('should wrap the error if there is one', function (done) {
const error = new Error('my error')
this.request.callsArgWith(1, error)
this.handler.deleteProject(this.projectId, err => {
@@ -283,13 +283,13 @@ describe('FileStoreHandler', function() {
})
})
- describe('getFileStream', function() {
- beforeEach(function() {
+ describe('getFileStream', function () {
+ beforeEach(function () {
this.query = {}
this.request.returns(this.readStream)
})
- it('should get the stream with the correct params', function(done) {
+ it('should get the stream with the correct params', function (done) {
const fileUrl = this.getFileUrl(this.projectId, this.fileId)
this.handler.getFileStream(
this.projectId,
@@ -306,7 +306,7 @@ describe('FileStoreHandler', function() {
)
})
- it('should get stream from request', function(done) {
+ it('should get stream from request', function (done) {
this.handler.getFileStream(
this.projectId,
this.fileId,
@@ -321,7 +321,7 @@ describe('FileStoreHandler', function() {
)
})
- it('should add an error handler', function(done) {
+ it('should add an error handler', function (done) {
this.handler.getFileStream(
this.projectId,
this.fileId,
@@ -336,12 +336,12 @@ describe('FileStoreHandler', function() {
)
})
- describe('when range is specified in query', function() {
- beforeEach(function() {
+ describe('when range is specified in query', function () {
+ beforeEach(function () {
this.query = { range: '0-10' }
})
- it('should add a range header', function(done) {
+ it('should add a range header', function (done) {
this.handler.getFileStream(
this.projectId,
this.fileId,
@@ -359,13 +359,13 @@ describe('FileStoreHandler', function() {
)
})
- describe('when range is invalid', function() {
+ describe('when range is invalid', function () {
;['0-', '-100', 'one-two', 'nonsense'].forEach(r => {
- beforeEach(function() {
+ beforeEach(function () {
this.query = { range: `${r}` }
})
- it(`should not add a range header for '${r}'`, function(done) {
+ it(`should not add a range header for '${r}'`, function (done) {
this.handler.getFileStream(
this.projectId,
this.fileId,
@@ -386,8 +386,8 @@ describe('FileStoreHandler', function() {
})
})
- describe('getFileSize', function() {
- it('returns the file size reported by filestore', function(done) {
+ describe('getFileSize', function () {
+ it('returns the file size reported by filestore', function (done) {
const expectedFileSize = 32432
const fileUrl = this.getFileUrl(this.projectId, this.fileId)
this.request.head.yields(
@@ -409,7 +409,7 @@ describe('FileStoreHandler', function() {
})
})
- it('throws a NotFoundError on a 404 from filestore', function(done) {
+ it('throws a NotFoundError on a 404 from filestore', function (done) {
this.request.head.yields(null, { statusCode: 404 })
this.handler.getFileSize(this.projectId, this.fileId, err => {
@@ -418,7 +418,7 @@ describe('FileStoreHandler', function() {
})
})
- it('throws an error on a non-200 from filestore', function(done) {
+ it('throws an error on a non-200 from filestore', function (done) {
this.request.head.yields(null, { statusCode: 500 })
this.handler.getFileSize(this.projectId, this.fileId, err => {
@@ -427,7 +427,7 @@ describe('FileStoreHandler', function() {
})
})
- it('rethrows errors from filestore', function(done) {
+ it('rethrows errors from filestore', function (done) {
this.request.head.yields(new Error())
this.handler.getFileSize(this.projectId, this.fileId, err => {
@@ -437,13 +437,13 @@ describe('FileStoreHandler', function() {
})
})
- describe('copyFile', function() {
- beforeEach(function() {
+ describe('copyFile', function () {
+ beforeEach(function () {
this.newProjectId = 'new project'
this.newFileId = 'new file id'
})
- it('should post json', function(done) {
+ it('should post json', function (done) {
const newFileUrl = this.getFileUrl(this.newProjectId, this.newFileId)
this.request.callsArgWith(1, null, { statusCode: 200 })
@@ -464,7 +464,7 @@ describe('FileStoreHandler', function() {
)
})
- it('returns the url', function(done) {
+ it('returns the url', function (done) {
const expectedUrl = this.getFileUrl(this.newProjectId, this.newFileId)
this.request.callsArgWith(1, null, { statusCode: 200 })
this.handler.copyFile(
@@ -482,7 +482,7 @@ describe('FileStoreHandler', function() {
)
})
- it('should return the err', function(done) {
+ it('should return the err', function (done) {
const error = new Error('error')
this.request.callsArgWith(1, error)
this.handler.copyFile(
@@ -497,7 +497,7 @@ describe('FileStoreHandler', function() {
)
})
- it('should return an error for a non-success statusCode', function(done) {
+ it('should return an error for a non-success statusCode', function (done) {
this.request.callsArgWith(1, null, { statusCode: 500 })
this.handler.copyFile(
this.projectId,
diff --git a/services/web/test/unit/src/HelperFiles/AuthorizationHelperTests.js b/services/web/test/unit/src/HelperFiles/AuthorizationHelperTests.js
index d90227f7dc..a956e27c30 100644
--- a/services/web/test/unit/src/HelperFiles/AuthorizationHelperTests.js
+++ b/services/web/test/unit/src/HelperFiles/AuthorizationHelperTests.js
@@ -2,8 +2,8 @@ const SandboxedModule = require('sandboxed-module')
const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/Helpers/AuthorizationHelper'
-describe('AuthorizationHelper', function() {
- beforeEach(function() {
+describe('AuthorizationHelper', function () {
+ beforeEach(function () {
this.AuthorizationHelper = SandboxedModule.require(modulePath, {
requires: {
'../../models/User': {
@@ -25,28 +25,28 @@ describe('AuthorizationHelper', function() {
})
})
- describe('hasAnyStaffAccess', function() {
- it('with empty user', function() {
+ describe('hasAnyStaffAccess', function () {
+ it('with empty user', function () {
const user = {}
expect(this.AuthorizationHelper.hasAnyStaffAccess(user)).to.be.false
})
- it('with no access user', function() {
+ it('with no access user', function () {
const user = { isAdmin: false, staffAccess: { adminMetrics: false } }
expect(this.AuthorizationHelper.hasAnyStaffAccess(user)).to.be.false
})
- it('with admin user', function() {
+ it('with admin user', function () {
const user = { isAdmin: true }
expect(this.AuthorizationHelper.hasAnyStaffAccess(user)).to.be.true
})
- it('with staff user', function() {
+ it('with staff user', function () {
const user = { staffAccess: { adminMetrics: true, somethingElse: false } }
expect(this.AuthorizationHelper.hasAnyStaffAccess(user)).to.be.true
})
- it('with non-staff user with extra attributes', function() {
+ it('with non-staff user with extra attributes', function () {
// make sure that staffAccess attributes not declared on the model don't
// give user access
const user = { staffAccess: { adminMetrics: false, somethingElse: true } }
diff --git a/services/web/test/unit/src/HelperFiles/NewLogsUITests.js b/services/web/test/unit/src/HelperFiles/NewLogsUITests.js
index 7c5fea9c69..fc1aa10219 100644
--- a/services/web/test/unit/src/HelperFiles/NewLogsUITests.js
+++ b/services/web/test/unit/src/HelperFiles/NewLogsUITests.js
@@ -6,7 +6,7 @@ const MODULE_PATH = require('path').join(
'../../../../app/src/Features/Helpers/NewLogsUI.js'
)
-describe('NewLogsUI helper', function() {
+describe('NewLogsUI helper', function () {
let NewLogsUI
function userIdFromTime(time) {
@@ -27,7 +27,7 @@ describe('NewLogsUI helper', function() {
)
}
- beforeEach(function() {
+ beforeEach(function () {
this.user = {
alphaProgram: false,
betaProgram: false,
@@ -47,7 +47,7 @@ describe('NewLogsUI helper', function() {
})
})
- it('should always show the new UI with popup for alpha users', function() {
+ it('should always show the new UI with popup for alpha users', function () {
this.user.alphaProgram = true
for (const percentile of [0, 20, 40, 60, 80]) {
this.user._id = userIdFromTime(percentile)
@@ -56,13 +56,13 @@ describe('NewLogsUI helper', function() {
}
})
- describe('for beta users', function() {
- beforeEach(function() {
+ describe('for beta users', function () {
+ beforeEach(function () {
this.user.betaProgram = true
})
- describe('with a 0% rollout', function() {
- it('should always show the existing UI', function() {
+ describe('with a 0% rollout', function () {
+ it('should always show the existing UI', function () {
for (const percentile of [0, 20, 40, 60, 80]) {
this.user._id = userIdFromTime(percentile)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
@@ -71,7 +71,7 @@ describe('NewLogsUI helper', function() {
})
})
- describe('with a new UI rollout', function() {
+ describe('with a new UI rollout', function () {
const newUIWithPopupPercentage = 33
const newUIWithoutPopupPercentage = 33
@@ -79,31 +79,31 @@ describe('NewLogsUI helper', function() {
const newUIWithoutPopupThreshold =
newUIWithPopupPercentage + newUIWithoutPopupPercentage
- beforeEach(function() {
+ beforeEach(function () {
this.settings.logsUIPercentageBeta = newUIWithPopupPercentage
this.settings.logsUIPercentageWithoutPopupBeta = newUIWithoutPopupPercentage
})
- it('should show the new UI with popup when the id is below the new UI with popup upper threshold (exc)', function() {
+ it('should show the new UI with popup when the id is below the new UI with popup upper threshold (exc)', function () {
this.user._id = userIdFromTime(newUIWithPopupThreshold - 1)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
expect(isNewUIWithPopup(variant)).to.be.true
})
- it('should show the new UI without popup when the id is at the new UI with popup upper threshold (exc)', function() {
+ it('should show the new UI without popup when the id is at the new UI with popup upper threshold (exc)', function () {
this.user._id = userIdFromTime(newUIWithPopupThreshold)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
expect(isNewUIWithoutPopup(variant)).to.be.true
})
- it('should show the new UI without popup when the id is above the new UI with popup upper threshold (inc) and below the new UI without popup upper threshold (exc)', function() {
+ it('should show the new UI without popup when the id is above the new UI with popup upper threshold (inc) and below the new UI without popup upper threshold (exc)', function () {
this.user._id = userIdFromTime(newUIWithoutPopupThreshold - 1)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
expect(isNewUIWithoutPopup(variant)).to.be.true
})
- it('should show the existing UI when the id is at the new UI without popup upper threshold (exc)', function() {
+ it('should show the existing UI when the id is at the new UI without popup upper threshold (exc)', function () {
this.user._id = userIdFromTime(newUIWithoutPopupThreshold)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
expect(isExistingUI(variant)).to.be.true
})
- it('should show the existing UI when the id is above the new UI without popup upper threshold (exc)', function() {
+ it('should show the existing UI when the id is above the new UI without popup upper threshold (exc)', function () {
this.user._id = userIdFromTime(newUIWithoutPopupThreshold + 1)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
expect(isExistingUI(variant)).to.be.true
@@ -111,9 +111,9 @@ describe('NewLogsUI helper', function() {
})
})
- describe('for regular users', function() {
- describe('with a 0% rollout', function() {
- it('should always show the existing UI', function() {
+ describe('for regular users', function () {
+ describe('with a 0% rollout', function () {
+ it('should always show the existing UI', function () {
for (const percentile of [0, 20, 40, 60, 80]) {
this.user._id = userIdFromTime(percentile)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
@@ -122,7 +122,7 @@ describe('NewLogsUI helper', function() {
})
})
- describe('with a new UI rollout', function() {
+ describe('with a new UI rollout', function () {
const newUIWithPopupPercentage = 33
const newUIWithoutPopupPercentage = 33
@@ -130,31 +130,31 @@ describe('NewLogsUI helper', function() {
const newUIWithoutPopupThreshold =
newUIWithPopupPercentage + newUIWithoutPopupPercentage
- beforeEach(function() {
+ beforeEach(function () {
this.settings.logsUIPercentage = newUIWithPopupPercentage
this.settings.logsUIPercentageWithoutPopup = newUIWithoutPopupPercentage
})
- it('should show the new UI with popup when the id is below the new UI with popup upper threshold (exc)', function() {
+ it('should show the new UI with popup when the id is below the new UI with popup upper threshold (exc)', function () {
this.user._id = userIdFromTime(newUIWithPopupThreshold - 1)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
expect(isNewUIWithPopup(variant)).to.be.true
})
- it('should show the new UI without popup when the id is at the new UI with popup upper threshold (exc)', function() {
+ it('should show the new UI without popup when the id is at the new UI with popup upper threshold (exc)', function () {
this.user._id = userIdFromTime(newUIWithPopupThreshold)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
expect(isNewUIWithoutPopup(variant)).to.be.true
})
- it('should show the new UI without popup when the id is above the new UI with popup upper threshold (inc) and below the new UI without popup upper threshold (exc)', function() {
+ it('should show the new UI without popup when the id is above the new UI with popup upper threshold (inc) and below the new UI without popup upper threshold (exc)', function () {
this.user._id = userIdFromTime(newUIWithoutPopupThreshold - 1)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
expect(isNewUIWithoutPopup(variant)).to.be.true
})
- it('should show the existing UI when the id is at the new UI without popup upper threshold (exc)', function() {
+ it('should show the existing UI when the id is at the new UI without popup upper threshold (exc)', function () {
this.user._id = userIdFromTime(newUIWithoutPopupThreshold)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
expect(isExistingUI(variant)).to.be.true
})
- it('should show the existing UI when the id is above the new UI without popup upper threshold (exc)', function() {
+ it('should show the existing UI when the id is above the new UI without popup upper threshold (exc)', function () {
this.user._id = userIdFromTime(newUIWithoutPopupThreshold + 1)
const variant = NewLogsUI.getNewLogsUIVariantForUser(this.user)
expect(isExistingUI(variant)).to.be.true
diff --git a/services/web/test/unit/src/HelperFiles/SafeHTMLSubstituteTests.js b/services/web/test/unit/src/HelperFiles/SafeHTMLSubstituteTests.js
index 87d8d0aff8..94a09d06b1 100644
--- a/services/web/test/unit/src/HelperFiles/SafeHTMLSubstituteTests.js
+++ b/services/web/test/unit/src/HelperFiles/SafeHTMLSubstituteTests.js
@@ -5,13 +5,13 @@ const MODULE_PATH = require('path').join(
'../../../../app/src/Features/Helpers/SafeHTMLSubstitution.js'
)
-describe('SafeHTMLSubstitution', function() {
+describe('SafeHTMLSubstitution', function () {
let SafeHTMLSubstitution
- before(function() {
+ before(function () {
SafeHTMLSubstitution = SandboxedModule.require(MODULE_PATH)
})
- describe('SPLIT_REGEX', function() {
+ describe('SPLIT_REGEX', function () {
const CASES = {
'PRE<0>INNER0>POST': ['PRE', '0', 'INNER', 'POST'],
'<0>INNER0>': ['', '0', 'INNER', ''],
@@ -21,7 +21,7 @@ describe('SafeHTMLSubstitution', function() {
'PLAIN TEXT': ['PLAIN TEXT']
}
Object.entries(CASES).forEach(([input, output]) => {
- it(`should parse "${input}" as expected`, function() {
+ it(`should parse "${input}" as expected`, function () {
expect(input.split(SafeHTMLSubstitution.SPLIT_REGEX)).to.deep.equal(
output
)
@@ -29,27 +29,27 @@ describe('SafeHTMLSubstitution', function() {
})
})
- describe('render', function() {
- describe('substitution', function() {
- it('should substitute a single component', function() {
+ describe('render', function () {
+ describe('substitution', function () {
+ it('should substitute a single component', function () {
expect(
SafeHTMLSubstitution.render('<0>good0>', [{ name: 'b' }])
).to.equal('good')
})
- it('should substitute a single component as string', function() {
+ it('should substitute a single component as string', function () {
expect(SafeHTMLSubstitution.render('<0>good0>', ['b'])).to.equal(
'good'
)
})
- it('should substitute a single component twice', function() {
+ it('should substitute a single component twice', function () {
expect(
SafeHTMLSubstitution.render('<0>one0><0>two0>', [{ name: 'b' }])
).to.equal('onetwo')
})
- it('should substitute two components', function() {
+ it('should substitute two components', function () {
expect(
SafeHTMLSubstitution.render('<0>one0><1>two1>', [
{ name: 'b' },
@@ -58,7 +58,7 @@ describe('SafeHTMLSubstitution', function() {
).to.equal('onetwo')
})
- it('should substitute a single component with a class', function() {
+ it('should substitute a single component with a class', function () {
expect(
SafeHTMLSubstitution.render('<0>text0>', [
{
@@ -71,7 +71,7 @@ describe('SafeHTMLSubstitution', function() {
).to.equal('text')
})
- it('should substitute two nested components', function() {
+ it('should substitute two nested components', function () {
expect(
SafeHTMLSubstitution.render('<0><1>nested1>0>', [
{ name: 'b' },
@@ -80,7 +80,7 @@ describe('SafeHTMLSubstitution', function() {
).to.equal('nested')
})
- it('should handle links', function() {
+ it('should handle links', function () {
expect(
SafeHTMLSubstitution.render('<0>Go to Login0>', [
{ name: 'a', attrs: { href: 'https://www.overleaf.com/login' } }
@@ -88,7 +88,7 @@ describe('SafeHTMLSubstitution', function() {
).to.equal('Go to Login')
})
- it('should not complain about too many components', function() {
+ it('should not complain about too many components', function () {
expect(
SafeHTMLSubstitution.render('<0>good0>', [
{ name: 'b' },
@@ -99,52 +99,52 @@ describe('SafeHTMLSubstitution', function() {
})
})
- describe('pug.escape', function() {
- it('should handle plain text', function() {
+ describe('pug.escape', function () {
+ it('should handle plain text', function () {
expect(SafeHTMLSubstitution.render('plain text')).to.equal('plain text')
})
- it('should keep a simple string delimiter', function() {
+ it('should keep a simple string delimiter', function () {
expect(SafeHTMLSubstitution.render("'")).to.equal(`'`)
})
- it('should escape double quotes', function() {
+ it('should escape double quotes', function () {
expect(SafeHTMLSubstitution.render('"')).to.equal(`"`)
})
- it('should escape &', function() {
+ it('should escape &', function () {
expect(SafeHTMLSubstitution.render('&')).to.equal(`&`)
})
- it('should escape <', function() {
+ it('should escape <', function () {
expect(SafeHTMLSubstitution.render('<')).to.equal(`<`)
})
- it('should escape >', function() {
+ it('should escape >', function () {
expect(SafeHTMLSubstitution.render('>')).to.equal(`>`)
})
- it('should escape html', function() {
+ it('should escape html', function () {
expect(SafeHTMLSubstitution.render('bad')).to.equal(
'<b>bad</b>'
)
})
})
- describe('escape around substitutions', function() {
- it('should escape text inside a component', function() {
+ describe('escape around substitutions', function () {
+ it('should escape text inside a component', function () {
expect(
SafeHTMLSubstitution.render('<0>inner0>', [{ name: 'b' }])
).to.equal('<i>inner</i>')
})
- it('should escape text in front of a component', function() {
+ it('should escape text in front of a component', function () {
expect(
SafeHTMLSubstitution.render('PRE<0>inner0>', [{ name: 'b' }])
).to.equal('<i>PRE</i>inner')
})
- it('should escape text after of a component', function() {
+ it('should escape text after of a component', function () {
expect(
SafeHTMLSubstitution.render('<0>inner0>POST', [
{ name: 'b' }
diff --git a/services/web/test/unit/src/HelperFiles/UrlHelperTests.js b/services/web/test/unit/src/HelperFiles/UrlHelperTests.js
index b0a8d00a1f..d397014375 100644
--- a/services/web/test/unit/src/HelperFiles/UrlHelperTests.js
+++ b/services/web/test/unit/src/HelperFiles/UrlHelperTests.js
@@ -5,8 +5,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Helpers/UrlHelper.js'
)
-describe('UrlHelper', function() {
- beforeEach(function() {
+describe('UrlHelper', function () {
+ beforeEach(function () {
this.settings = {
apis: { linkedUrlProxy: { url: undefined } },
siteUrl: 'http://localhost:3000'
@@ -15,8 +15,8 @@ describe('UrlHelper', function() {
requires: { 'settings-sharelatex': this.settings }
})
})
- describe('getSafeRedirectPath', function() {
- it('sanitize redirect path to prevent open redirects', function() {
+ describe('getSafeRedirectPath', function () {
+ it('sanitize redirect path to prevent open redirects', function () {
expect(this.UrlHelper.getSafeRedirectPath('https://evil.com')).to.be
.undefined
diff --git a/services/web/test/unit/src/History/HistoryControllerTests.js b/services/web/test/unit/src/History/HistoryControllerTests.js
index a5be813c49..34258d9c83 100644
--- a/services/web/test/unit/src/History/HistoryControllerTests.js
+++ b/services/web/test/unit/src/History/HistoryControllerTests.js
@@ -16,8 +16,8 @@ const Errors = require('../../../../app/src/Features/Errors/Errors')
const modulePath = '../../../../app/src/Features/History/HistoryController'
const SandboxedModule = require('sandboxed-module')
-describe('HistoryController', function() {
- beforeEach(function() {
+describe('HistoryController', function () {
+ beforeEach(function () {
this.callback = sinon.stub()
this.user_id = 'user-id-123'
this.AuthenticationController = {
@@ -47,15 +47,15 @@ describe('HistoryController', function() {
})
})
- describe('selectHistoryApi', function() {
- beforeEach(function() {
+ describe('selectHistoryApi', function () {
+ beforeEach(function () {
this.req = { url: '/mock/url', method: 'POST', params: {} }
this.res = 'mock-res'
return (this.next = sinon.stub())
})
- describe('for a project with project history', function() {
- beforeEach(function() {
+ describe('for a project with project history', function () {
+ beforeEach(function () {
this.ProjectDetailsHandler.getDetails = sinon
.stub()
.callsArgWith(1, null, {
@@ -68,13 +68,13 @@ describe('HistoryController', function() {
)
})
- it('should set the flag for project history to true', function() {
+ it('should set the flag for project history to true', function () {
return this.req.useProjectHistory.should.equal(true)
})
})
- describe('for any other project ', function() {
- beforeEach(function() {
+ describe('for any other project ', function () {
+ beforeEach(function () {
this.ProjectDetailsHandler.getDetails = sinon
.stub()
.callsArgWith(1, null, {})
@@ -85,14 +85,14 @@ describe('HistoryController', function() {
)
})
- it('should not set the flag for project history to false', function() {
+ it('should not set the flag for project history to false', function () {
return this.req.useProjectHistory.should.equal(false)
})
})
})
- describe('proxyToHistoryApi', function() {
- beforeEach(function() {
+ describe('proxyToHistoryApi', function () {
+ beforeEach(function () {
this.req = { url: '/mock/url', method: 'POST' }
this.res = 'mock-res'
this.next = sinon.stub()
@@ -106,8 +106,8 @@ describe('HistoryController', function() {
return this.request.returns(this.proxy)
})
- describe('for a project with the project history flag', function() {
- beforeEach(function() {
+ describe('for a project with the project history flag', function () {
+ beforeEach(function () {
this.req.useProjectHistory = true
return this.HistoryController.proxyToHistoryApi(
this.req,
@@ -116,13 +116,13 @@ describe('HistoryController', function() {
)
})
- it('should get the user id', function() {
+ it('should get the user id', function () {
return this.AuthenticationController.getLoggedInUserId
.calledWith(this.req)
.should.equal(true)
})
- it('should call the project history api', function() {
+ it('should call the project history api', function () {
return this.request
.calledWith({
url: `${this.settings.apis.project_history.url}${this.req.url}`,
@@ -134,13 +134,13 @@ describe('HistoryController', function() {
.should.equal(true)
})
- it('should pipe the response to the client', function() {
+ it('should pipe the response to the client', function () {
return this.proxy.pipe.calledWith(this.res).should.equal(true)
})
})
- describe('for a project without the project history flag', function() {
- beforeEach(function() {
+ describe('for a project without the project history flag', function () {
+ beforeEach(function () {
this.req.useProjectHistory = false
return this.HistoryController.proxyToHistoryApi(
this.req,
@@ -149,13 +149,13 @@ describe('HistoryController', function() {
)
})
- it('should get the user id', function() {
+ it('should get the user id', function () {
return this.AuthenticationController.getLoggedInUserId
.calledWith(this.req)
.should.equal(true)
})
- it('should call the track changes api', function() {
+ it('should call the track changes api', function () {
return this.request
.calledWith({
url: `${this.settings.apis.trackchanges.url}${this.req.url}`,
@@ -167,13 +167,13 @@ describe('HistoryController', function() {
.should.equal(true)
})
- it('should pipe the response to the client', function() {
+ it('should pipe the response to the client', function () {
return this.proxy.pipe.calledWith(this.res).should.equal(true)
})
})
- describe('with an error', function() {
- beforeEach(function() {
+ describe('with an error', function () {
+ beforeEach(function () {
this.HistoryController.proxyToHistoryApi(this.req, this.res, this.next)
return this.proxy.events.error.call(
this.proxy,
@@ -181,14 +181,14 @@ describe('HistoryController', function() {
)
})
- it('should pass the error up the call chain', function() {
+ it('should pass the error up the call chain', function () {
return this.next.calledWith(this.error).should.equal(true)
})
})
})
- describe('proxyToHistoryApiAndInjectUserDetails', function() {
- beforeEach(function() {
+ describe('proxyToHistoryApiAndInjectUserDetails', function () {
+ beforeEach(function () {
this.req = { url: '/mock/url', method: 'POST' }
this.res = { json: sinon.stub() }
this.next = sinon.stub()
@@ -198,8 +198,8 @@ describe('HistoryController', function() {
.yields(null, (this.data_with_users = 'mock-injected-data')))
})
- describe('for a project with the project history flag', function() {
- beforeEach(function() {
+ describe('for a project with the project history flag', function () {
+ beforeEach(function () {
this.req.useProjectHistory = true
return this.HistoryController.proxyToHistoryApiAndInjectUserDetails(
this.req,
@@ -208,13 +208,13 @@ describe('HistoryController', function() {
)
})
- it('should get the user id', function() {
+ it('should get the user id', function () {
return this.AuthenticationController.getLoggedInUserId
.calledWith(this.req)
.should.equal(true)
})
- it('should call the project history api', function() {
+ it('should call the project history api', function () {
return this.request
.calledWith({
url: `${this.settings.apis.project_history.url}${this.req.url}`,
@@ -227,19 +227,19 @@ describe('HistoryController', function() {
.should.equal(true)
})
- it('should inject the user data', function() {
+ it('should inject the user data', function () {
return this.HistoryManager.injectUserDetails
.calledWith(this.data)
.should.equal(true)
})
- it('should return the data with users to the client', function() {
+ it('should return the data with users to the client', function () {
return this.res.json.calledWith(this.data_with_users).should.equal(true)
})
})
- describe('for a project without the project history flag', function() {
- beforeEach(function() {
+ describe('for a project without the project history flag', function () {
+ beforeEach(function () {
this.req.useProjectHistory = false
return this.HistoryController.proxyToHistoryApiAndInjectUserDetails(
this.req,
@@ -248,13 +248,13 @@ describe('HistoryController', function() {
)
})
- it('should get the user id', function() {
+ it('should get the user id', function () {
return this.AuthenticationController.getLoggedInUserId
.calledWith(this.req)
.should.equal(true)
})
- it('should call the track changes api', function() {
+ it('should call the track changes api', function () {
return this.request
.calledWith({
url: `${this.settings.apis.trackchanges.url}${this.req.url}`,
@@ -267,20 +267,20 @@ describe('HistoryController', function() {
.should.equal(true)
})
- it('should inject the user data', function() {
+ it('should inject the user data', function () {
return this.HistoryManager.injectUserDetails
.calledWith(this.data)
.should.equal(true)
})
- it('should return the data with users to the client', function() {
+ it('should return the data with users to the client', function () {
return this.res.json.calledWith(this.data_with_users).should.equal(true)
})
})
})
- describe('proxyToHistoryApiAndInjectUserDetails (with the history API failing)', function() {
- beforeEach(function() {
+ describe('proxyToHistoryApiAndInjectUserDetails (with the history API failing)', function () {
+ beforeEach(function () {
this.req = { url: '/mock/url', method: 'POST', useProjectHistory: true }
this.res = { json: sinon.stub() }
this.next = sinon.stub()
@@ -295,20 +295,20 @@ describe('HistoryController', function() {
)
})
- it('should not inject the user data', function() {
+ it('should not inject the user data', function () {
return this.HistoryManager.injectUserDetails
.calledWith(this.data)
.should.equal(false)
})
- it('should not return the data with users to the client', function() {
+ it('should not return the data with users to the client', function () {
return this.res.json.calledWith(this.data_with_users).should.equal(false)
})
})
- describe('resyncProjectHistory', function() {
- describe('for a project without project-history enabled', function() {
- beforeEach(function() {
+ describe('resyncProjectHistory', function () {
+ describe('for a project without project-history enabled', function () {
+ beforeEach(function () {
this.project_id = 'mock-project-id'
this.req = { params: { Project_id: this.project_id } }
this.res = { sendStatus: sinon.stub() }
@@ -326,13 +326,13 @@ describe('HistoryController', function() {
)
})
- it('response with a 404', function() {
+ it('response with a 404', function () {
return this.res.sendStatus.calledWith(404).should.equal(true)
})
})
- describe('for a project with project-history enabled', function() {
- beforeEach(function() {
+ describe('for a project with project-history enabled', function () {
+ beforeEach(function () {
this.project_id = 'mock-project-id'
this.req = { params: { Project_id: this.project_id } }
this.res = { sendStatus: sinon.stub() }
@@ -349,13 +349,13 @@ describe('HistoryController', function() {
)
})
- it('resyncs the project', function() {
+ it('resyncs the project', function () {
return this.ProjectEntityUpdateHandler.resyncProjectHistory
.calledWith(this.project_id)
.should.equal(true)
})
- it('responds with a 204', function() {
+ it('responds with a 204', function () {
return this.res.sendStatus.calledWith(204).should.equal(true)
})
})
diff --git a/services/web/test/unit/src/History/HistoryManagerTests.js b/services/web/test/unit/src/History/HistoryManagerTests.js
index 5b88738133..b9f8d1fca6 100644
--- a/services/web/test/unit/src/History/HistoryManagerTests.js
+++ b/services/web/test/unit/src/History/HistoryManagerTests.js
@@ -5,8 +5,8 @@ const { ObjectId } = require('mongodb')
const MODULE_PATH = '../../../../app/src/Features/History/HistoryManager'
-describe('HistoryManager', function() {
- beforeEach(function() {
+describe('HistoryManager', function () {
+ beforeEach(function () {
this.user_id = 'user-id-123'
this.AuthenticationController = {
getLoggedInUserId: sinon.stub().returns(this.user_id)
@@ -52,14 +52,14 @@ describe('HistoryManager', function() {
})
})
- describe('initializeProject', function() {
- describe('with project history enabled', function() {
- beforeEach(function() {
+ describe('initializeProject', function () {
+ describe('with project history enabled', function () {
+ beforeEach(function () {
this.settings.apis.project_history.initializeHistoryForNewProjects = true
})
- describe('project history returns a successful response', function() {
- beforeEach(async function() {
+ describe('project history returns a successful response', function () {
+ beforeEach(async function () {
this.overleaf_id = 1234
this.request.post.resolves(
JSON.stringify({ project: { id: this.overleaf_id } })
@@ -67,7 +67,7 @@ describe('HistoryManager', function() {
this.result = await this.HistoryManager.promises.initializeProject()
})
- it('should call the project history api', function() {
+ it('should call the project history api', function () {
this.request.post
.calledWith({
url: `${this.settings.apis.project_history.url}/project`
@@ -75,21 +75,21 @@ describe('HistoryManager', function() {
.should.equal(true)
})
- it('should return the overleaf id', function() {
+ it('should return the overleaf id', function () {
expect(this.result).to.deep.equal({ overleaf_id: this.overleaf_id })
})
})
- describe('project history returns a response without the project id', function() {
- it('should throw an error', async function() {
+ describe('project history returns a response without the project id', function () {
+ it('should throw an error', async function () {
this.request.post.resolves(JSON.stringify({ project: {} }))
await expect(this.HistoryManager.promises.initializeProject()).to.be
.rejected
})
})
- describe('project history errors', function() {
- it('should propagate the error', async function() {
+ describe('project history errors', function () {
+ it('should propagate the error', async function () {
this.request.post.rejects(new Error('problem connecting'))
await expect(this.HistoryManager.promises.initializeProject()).to.be
.rejected
@@ -97,8 +97,8 @@ describe('HistoryManager', function() {
})
})
- describe('with project history disabled', function() {
- it('should return without errors', async function() {
+ describe('with project history disabled', function () {
+ it('should return without errors', async function () {
this.settings.apis.project_history.initializeHistoryForNewProjects = false
await expect(this.HistoryManager.promises.initializeProject()).to.be
.fulfilled
@@ -106,8 +106,8 @@ describe('HistoryManager', function() {
})
})
- describe('injectUserDetails', function() {
- beforeEach(function() {
+ describe('injectUserDetails', function () {
+ beforeEach(function () {
this.user1 = {
_id: (this.user_id1 = '123456'),
first_name: 'Jane',
@@ -137,8 +137,8 @@ describe('HistoryManager', function() {
this.UserGetter.promises.getUsers.resolves([this.user1, this.user2])
})
- describe('with a diff', function() {
- it('should turn user_ids into user objects', async function() {
+ describe('with a diff', function () {
+ it('should turn user_ids into user objects', async function () {
const diff = await this.HistoryManager.promises.injectUserDetails({
diff: [
{
@@ -159,7 +159,7 @@ describe('HistoryManager', function() {
expect(diff.diff[1].meta.users).to.deep.equal([this.user2_view])
})
- it('should handle v1 user ids', async function() {
+ it('should handle v1 user ids', async function () {
const diff = await this.HistoryManager.promises.injectUserDetails({
diff: [
{
@@ -180,7 +180,7 @@ describe('HistoryManager', function() {
expect(diff.diff[1].meta.users).to.deep.equal([this.user2_view])
})
- it('should leave user objects', async function() {
+ it('should leave user objects', async function () {
const diff = await this.HistoryManager.promises.injectUserDetails({
diff: [
{
@@ -201,7 +201,7 @@ describe('HistoryManager', function() {
expect(diff.diff[1].meta.users).to.deep.equal([this.user2_view])
})
- it('should handle a binary diff marker', async function() {
+ it('should handle a binary diff marker', async function () {
const diff = await this.HistoryManager.promises.injectUserDetails({
diff: { binary: true }
})
@@ -209,8 +209,8 @@ describe('HistoryManager', function() {
})
})
- describe('with a list of updates', function() {
- it('should turn user_ids into user objects', async function() {
+ describe('with a list of updates', function () {
+ it('should turn user_ids into user objects', async function () {
const updates = await this.HistoryManager.promises.injectUserDetails({
updates: [
{
@@ -233,7 +233,7 @@ describe('HistoryManager', function() {
expect(updates.updates[1].meta.users).to.deep.equal([this.user2_view])
})
- it('should leave user objects', async function() {
+ it('should leave user objects', async function () {
const updates = await this.HistoryManager.promises.injectUserDetails({
updates: [
{
@@ -258,21 +258,21 @@ describe('HistoryManager', function() {
})
})
- describe('deleteProject', function() {
+ describe('deleteProject', function () {
const projectId = new ObjectId()
const historyId = new ObjectId()
- beforeEach(async function() {
+ beforeEach(async function () {
await this.HistoryManager.promises.deleteProject(projectId, historyId)
})
- it('should call the project-history service', async function() {
+ it('should call the project-history service', async function () {
expect(this.request.delete).to.have.been.calledWith(
`${this.projectHistoryUrl}/project/${projectId}`
)
})
- it('should call the v1-history service', async function() {
+ it('should call the v1-history service', async function () {
expect(this.request.delete).to.have.been.calledWith({
url: `${this.v1HistoryUrl}/projects/${historyId}`,
auth: {
diff --git a/services/web/test/unit/src/History/RestoreManagerTests.js b/services/web/test/unit/src/History/RestoreManagerTests.js
index e6037f2f3c..a8d5dfcfd9 100644
--- a/services/web/test/unit/src/History/RestoreManagerTests.js
+++ b/services/web/test/unit/src/History/RestoreManagerTests.js
@@ -22,8 +22,8 @@ const Errors = require('../../../../app/src/Features/Errors/Errors')
const tk = require('timekeeper')
const moment = require('moment')
-describe('RestoreManager', function() {
- beforeEach(function() {
+describe('RestoreManager', function () {
+ beforeEach(function () {
tk.freeze(Date.now()) // freeze the time for these tests
this.RestoreManager = SandboxedModule.require(modulePath, {
requires: {
@@ -40,12 +40,12 @@ describe('RestoreManager', function() {
return (this.callback = sinon.stub())
})
- afterEach(function() {
+ afterEach(function () {
return tk.reset()
})
- describe('restoreFileFromV2', function() {
- beforeEach(function() {
+ describe('restoreFileFromV2', function () {
+ beforeEach(function () {
this.RestoreManager._writeFileVersionToDisk = sinon
.stub()
.yields(null, (this.fsPath = '/tmp/path/on/disk'))
@@ -57,8 +57,8 @@ describe('RestoreManager', function() {
.yields(null, (this.entity = 'mock-entity')))
})
- describe('with a file not in a folder', function() {
- beforeEach(function() {
+ describe('with a file not in a folder', function () {
+ beforeEach(function () {
this.pathname = 'foo.tex'
return this.RestoreManager.restoreFileFromV2(
this.user_id,
@@ -69,19 +69,19 @@ describe('RestoreManager', function() {
)
})
- it('should write the file version to disk', function() {
+ it('should write the file version to disk', function () {
return this.RestoreManager._writeFileVersionToDisk
.calledWith(this.project_id, this.version, this.pathname)
.should.equal(true)
})
- it('should find the root folder', function() {
+ it('should find the root folder', function () {
return this.RestoreManager._findOrCreateFolder
.calledWith(this.project_id, '')
.should.equal(true)
})
- it('should add the entity', function() {
+ it('should add the entity', function () {
return this.FileSystemImportManager.addEntity
.calledWith(
this.user_id,
@@ -94,13 +94,13 @@ describe('RestoreManager', function() {
.should.equal(true)
})
- it('should call the callback with the entity', function() {
+ it('should call the callback with the entity', function () {
return this.callback.calledWith(null, this.entity).should.equal(true)
})
})
- describe('with a file in a folder', function() {
- beforeEach(function() {
+ describe('with a file in a folder', function () {
+ beforeEach(function () {
this.pathname = 'foo/bar.tex'
return this.RestoreManager.restoreFileFromV2(
this.user_id,
@@ -111,13 +111,13 @@ describe('RestoreManager', function() {
)
})
- it('should find the folder', function() {
+ it('should find the folder', function () {
return this.RestoreManager._findOrCreateFolder
.calledWith(this.project_id, 'foo')
.should.equal(true)
})
- it('should add the entity by its basename', function() {
+ it('should add the entity by its basename', function () {
return this.FileSystemImportManager.addEntity
.calledWith(
this.user_id,
@@ -132,8 +132,8 @@ describe('RestoreManager', function() {
})
})
- describe('_findOrCreateFolder', function() {
- beforeEach(function() {
+ describe('_findOrCreateFolder', function () {
+ beforeEach(function () {
this.EditorController.mkdirp = sinon
.stub()
.yields(null, [], { _id: (this.folder_id = 'mock-folder-id') })
@@ -144,25 +144,25 @@ describe('RestoreManager', function() {
)
})
- it('should look up or create the folder', function() {
+ it('should look up or create the folder', function () {
return this.EditorController.mkdirp
.calledWith(this.project_id, 'folder/name')
.should.equal(true)
})
- it('should return the folder_id', function() {
+ it('should return the folder_id', function () {
return this.callback.calledWith(null, this.folder_id).should.equal(true)
})
})
- describe('_addEntityWithUniqueName', function() {
- beforeEach(function() {
+ describe('_addEntityWithUniqueName', function () {
+ beforeEach(function () {
this.addEntityWithName = sinon.stub()
return (this.name = 'foo.tex')
})
- describe('with a valid name', function() {
- beforeEach(function() {
+ describe('with a valid name', function () {
+ beforeEach(function () {
this.addEntityWithName.yields(null, (this.entity = 'mock-entity'))
return this.RestoreManager._addEntityWithUniqueName(
this.addEntityWithName,
@@ -171,17 +171,17 @@ describe('RestoreManager', function() {
)
})
- it('should add the entity', function() {
+ it('should add the entity', function () {
return this.addEntityWithName.calledWith(this.name).should.equal(true)
})
- it('should return the entity', function() {
+ it('should return the entity', function () {
return this.callback.calledWith(null, this.entity).should.equal(true)
})
})
- describe('with an invalid name', function() {
- beforeEach(function() {
+ describe('with an invalid name', function () {
+ beforeEach(function () {
this.addEntityWithName
.onFirstCall()
.yields(new Errors.InvalidNameError())
@@ -195,18 +195,18 @@ describe('RestoreManager', function() {
)
})
- it('should try to add the entity with its original name', function() {
+ it('should try to add the entity with its original name', function () {
return this.addEntityWithName.calledWith('foo.tex').should.equal(true)
})
- it('should try to add the entity with a unique name', function() {
+ it('should try to add the entity with a unique name', function () {
const date = moment(new Date()).format('Do MMM YY H:mm:ss')
return this.addEntityWithName
.calledWith(`foo (Restored on ${date}).tex`)
.should.equal(true)
})
- it('should return the entity', function() {
+ it('should return the entity', function () {
return this.callback.calledWith(null, this.entity).should.equal(true)
})
})
diff --git a/services/web/test/unit/src/InactiveData/InactiveProjectManagerTests.js b/services/web/test/unit/src/InactiveData/InactiveProjectManagerTests.js
index 30d89a49db..0a8b589fb4 100644
--- a/services/web/test/unit/src/InactiveData/InactiveProjectManagerTests.js
+++ b/services/web/test/unit/src/InactiveData/InactiveProjectManagerTests.js
@@ -22,8 +22,8 @@ const modulePath = path.join(
const { expect } = require('chai')
const { ObjectId } = require('mongodb')
-describe('InactiveProjectManager', function() {
- beforeEach(function() {
+describe('InactiveProjectManager', function () {
+ beforeEach(function () {
this.settings = {}
this.DocstoreManager = {
unarchiveProject: sinon.stub(),
@@ -47,14 +47,14 @@ describe('InactiveProjectManager', function() {
return (this.project_id = '1234')
})
- describe('reactivateProjectIfRequired', function() {
- beforeEach(function() {
+ describe('reactivateProjectIfRequired', function () {
+ beforeEach(function () {
this.project = { active: false }
this.ProjectGetter.getProject.callsArgWith(2, null, this.project)
return this.ProjectUpdateHandler.markAsActive.callsArgWith(1)
})
- it('should call unarchiveProject', function(done) {
+ it('should call unarchiveProject', function (done) {
this.DocstoreManager.unarchiveProject.callsArgWith(1)
return this.InactiveProjectManager.reactivateProjectIfRequired(
this.project_id,
@@ -70,7 +70,7 @@ describe('InactiveProjectManager', function() {
)
})
- it('should not mark project as active if error with unarchiving', function(done) {
+ it('should not mark project as active if error with unarchiving', function (done) {
const error = new Error('error')
this.DocstoreManager.unarchiveProject.callsArgWith(1, error)
return this.InactiveProjectManager.reactivateProjectIfRequired(
@@ -88,7 +88,7 @@ describe('InactiveProjectManager', function() {
)
})
- it('should not call unarchiveProject if it is active', function(done) {
+ it('should not call unarchiveProject if it is active', function (done) {
this.project.active = true
this.DocstoreManager.unarchiveProject.callsArgWith(1)
return this.InactiveProjectManager.reactivateProjectIfRequired(
@@ -106,8 +106,8 @@ describe('InactiveProjectManager', function() {
})
})
- describe('deactivateProject', function() {
- it('should call unarchiveProject and markAsInactive', function(done) {
+ describe('deactivateProject', function () {
+ it('should call unarchiveProject and markAsInactive', function (done) {
this.DocstoreManager.archiveProject.callsArgWith(1)
this.ProjectUpdateHandler.markAsInactive.callsArgWith(1)
@@ -126,7 +126,7 @@ describe('InactiveProjectManager', function() {
)
})
- it('should not call markAsInactive if there was a problem archiving in docstore', function(done) {
+ it('should not call markAsInactive if there was a problem archiving in docstore', function (done) {
this.DocstoreManager.archiveProject.callsArgWith(1, 'errorrr')
this.ProjectUpdateHandler.markAsInactive.callsArgWith(1)
diff --git a/services/web/test/unit/src/Institutions/InstitutionHelperTests.js b/services/web/test/unit/src/Institutions/InstitutionHelperTests.js
index dacec20d84..d29b6a5c74 100644
--- a/services/web/test/unit/src/Institutions/InstitutionHelperTests.js
+++ b/services/web/test/unit/src/Institutions/InstitutionHelperTests.js
@@ -5,9 +5,9 @@ const InstitutionsHelper = require(path.join(
'/../../../../app/src/Features/Institutions/InstitutionsHelper'
))
-describe('InstitutionsHelper', function() {
- describe('emailHasLicence', function() {
- it('returns licence', function() {
+describe('InstitutionsHelper', function () {
+ describe('emailHasLicence', function () {
+ it('returns licence', function () {
const emailHasLicence = InstitutionsHelper.emailHasLicence({
confirmedAt: new Date(),
affiliation: {
@@ -18,7 +18,7 @@ describe('InstitutionsHelper', function() {
expect(emailHasLicence).to.be.true
})
- it('returns false if licence is free', function() {
+ it('returns false if licence is free', function () {
const emailHasLicence = InstitutionsHelper.emailHasLicence({
confirmedAt: new Date(),
affiliation: {
@@ -29,7 +29,7 @@ describe('InstitutionsHelper', function() {
expect(emailHasLicence).to.be.false
})
- it('returns false if licence is null', function() {
+ it('returns false if licence is null', function () {
const emailHasLicence = InstitutionsHelper.emailHasLicence({
confirmedAt: new Date(),
affiliation: {
@@ -40,7 +40,7 @@ describe('InstitutionsHelper', function() {
expect(emailHasLicence).to.be.false
})
- it('returns false if institution is not confirmed', function() {
+ it('returns false if institution is not confirmed', function () {
const emailHasLicence = InstitutionsHelper.emailHasLicence({
confirmedAt: new Date(),
affiliation: {
@@ -51,7 +51,7 @@ describe('InstitutionsHelper', function() {
expect(emailHasLicence).to.be.false
})
- it('returns false if email is not confirmed', function() {
+ it('returns false if email is not confirmed', function () {
const emailHasLicence = InstitutionsHelper.emailHasLicence({
confirmedAt: null,
affiliation: {
diff --git a/services/web/test/unit/src/Institutions/InstitutionsAPITests.js b/services/web/test/unit/src/Institutions/InstitutionsAPITests.js
index bf6a2501c9..a28deb78dd 100644
--- a/services/web/test/unit/src/Institutions/InstitutionsAPITests.js
+++ b/services/web/test/unit/src/Institutions/InstitutionsAPITests.js
@@ -8,8 +8,8 @@ const modulePath = path.join(
)
const Errors = require('../../../../app/src/Features/Errors/Errors')
-describe('InstitutionsAPI', function() {
- beforeEach(function() {
+describe('InstitutionsAPI', function () {
+ beforeEach(function () {
this.settings = { apis: { v1: { url: 'v1.url', user: '', pass: '' } } }
this.request = sinon.stub()
this.ipMatcherNotification = {
@@ -36,8 +36,8 @@ describe('InstitutionsAPI', function() {
this.newEmail = 'bob@bob.com'
})
- describe('getInstitutionAffiliations', function() {
- it('get affiliations', function(done) {
+ describe('getInstitutionAffiliations', function () {
+ it('get affiliations', function (done) {
this.institutionId = 123
const responseBody = ['123abc', '456def']
this.request.yields(null, { statusCode: 200 }, responseBody)
@@ -57,7 +57,7 @@ describe('InstitutionsAPI', function() {
)
})
- it('handle empty response', function(done) {
+ it('handle empty response', function (done) {
this.settings.apis.v1.url = ''
this.InstitutionsAPI.getInstitutionAffiliations(
@@ -72,8 +72,8 @@ describe('InstitutionsAPI', function() {
})
})
- describe('getInstitutionLicences', function() {
- it('get licences', function(done) {
+ describe('getInstitutionLicences', function () {
+ it('get licences', function (done) {
this.institutionId = 123
const responseBody = {
lag: 'monthly',
@@ -104,10 +104,10 @@ describe('InstitutionsAPI', function() {
})
})
- describe('getLicencesForAnalytics', function() {
+ describe('getLicencesForAnalytics', function () {
const lag = 'daily'
const queryDate = '2017-01-07:00:00.000Z'
- it('should send the request to v1', function(done) {
+ it('should send the request to v1', function (done) {
const v1Result = {
lag: 'daily',
date: queryDate,
@@ -130,7 +130,7 @@ describe('InstitutionsAPI', function() {
}
)
})
- it('should handle errors', function(done) {
+ it('should handle errors', function (done) {
this.request.callsArgWith(1, null, { statusCode: 500 })
this.InstitutionsAPI.getLicencesForAnalytics(
lag,
@@ -143,8 +143,8 @@ describe('InstitutionsAPI', function() {
})
})
- describe('getUserAffiliations', function() {
- it('get affiliations', function(done) {
+ describe('getUserAffiliations', function () {
+ it('get affiliations', function (done) {
const responseBody = [{ foo: 'bar' }]
this.request.callsArgWith(1, null, { statusCode: 201 }, responseBody)
this.InstitutionsAPI.getUserAffiliations(
@@ -163,7 +163,7 @@ describe('InstitutionsAPI', function() {
)
})
- it('handle error', function(done) {
+ it('handle error', function (done) {
const body = { errors: 'affiliation error message' }
this.request.callsArgWith(1, null, { statusCode: 503 }, body)
this.InstitutionsAPI.getUserAffiliations(this.stubbedUser._id, err => {
@@ -172,7 +172,7 @@ describe('InstitutionsAPI', function() {
})
})
- it('handle empty response', function(done) {
+ it('handle empty response', function (done) {
this.settings.apis.v1.url = ''
this.InstitutionsAPI.getUserAffiliations(
this.stubbedUser._id,
@@ -186,12 +186,12 @@ describe('InstitutionsAPI', function() {
})
})
- describe('addAffiliation', function() {
- beforeEach(function() {
+ describe('addAffiliation', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 201 })
})
- it('add affiliation', function(done) {
+ it('add affiliation', function (done) {
const affiliationOptions = {
university: { id: 1 },
role: 'Prof',
@@ -225,7 +225,7 @@ describe('InstitutionsAPI', function() {
)
})
- it('handle error', function(done) {
+ it('handle error', function (done) {
const body = { errors: 'affiliation error message' }
this.request.callsArgWith(1, null, { statusCode: 422 }, body)
this.InstitutionsAPI.addAffiliation(
@@ -242,12 +242,12 @@ describe('InstitutionsAPI', function() {
})
})
- describe('removeAffiliation', function() {
- beforeEach(function() {
+ describe('removeAffiliation', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 404 })
})
- it('remove affiliation', function(done) {
+ it('remove affiliation', function (done) {
this.InstitutionsAPI.removeAffiliation(
this.stubbedUser._id,
this.newEmail,
@@ -264,7 +264,7 @@ describe('InstitutionsAPI', function() {
)
})
- it('handle error', function(done) {
+ it('handle error', function (done) {
this.request.callsArgWith(1, null, { statusCode: 500 })
this.InstitutionsAPI.removeAffiliation(
this.stubbedUser._id,
@@ -278,8 +278,8 @@ describe('InstitutionsAPI', function() {
})
})
- describe('deleteAffiliations', function() {
- it('delete affiliations', function(done) {
+ describe('deleteAffiliations', function () {
+ it('delete affiliations', function (done) {
this.request.callsArgWith(1, null, { statusCode: 200 })
this.InstitutionsAPI.deleteAffiliations(this.stubbedUser._id, err => {
expect(err).not.to.exist
@@ -292,7 +292,7 @@ describe('InstitutionsAPI', function() {
})
})
- it('handle error', function(done) {
+ it('handle error', function (done) {
const body = { errors: 'affiliation error message' }
this.request.callsArgWith(1, null, { statusCode: 518 }, body)
this.InstitutionsAPI.deleteAffiliations(this.stubbedUser._id, err => {
@@ -302,12 +302,12 @@ describe('InstitutionsAPI', function() {
})
})
- describe('endorseAffiliation', function() {
- beforeEach(function() {
+ describe('endorseAffiliation', function () {
+ beforeEach(function () {
this.request.callsArgWith(1, null, { statusCode: 204 })
})
- it('endorse affiliation', function(done) {
+ it('endorse affiliation', function (done) {
this.InstitutionsAPI.endorseAffiliation(
this.stubbedUser._id,
this.newEmail,
diff --git a/services/web/test/unit/src/Institutions/InstitutionsControllerTests.js b/services/web/test/unit/src/Institutions/InstitutionsControllerTests.js
index 65dada5e7c..d4701536de 100644
--- a/services/web/test/unit/src/Institutions/InstitutionsControllerTests.js
+++ b/services/web/test/unit/src/Institutions/InstitutionsControllerTests.js
@@ -20,12 +20,9 @@ const modulePath = path.join(
'../../../../app/src/Features/Institutions/InstitutionsController'
)
-describe('InstitutionsController', function() {
- beforeEach(function() {
- this.host = 'mit.edu'
- .split('')
- .reverse()
- .join('')
+describe('InstitutionsController', function () {
+ beforeEach(function () {
+ this.host = 'mit.edu'.split('').reverse().join('')
this.stubbedUser1 = {
_id: '3131231',
name: 'bob',
@@ -102,8 +99,8 @@ describe('InstitutionsController', function() {
return (this.next = sinon.stub())
})
- describe('affiliateUsers', function() {
- it('should add affiliations for matching users', function(done) {
+ describe('affiliateUsers', function () {
+ it('should add affiliations for matching users', function (done) {
this.res.sendStatus = code => {
code.should.equal(200)
this.getUsersByHostname.calledOnce.should.equal(true)
@@ -145,7 +142,7 @@ describe('InstitutionsController', function() {
)
})
- it('should return errors if last affiliation cannot be added', function(done) {
+ it('should return errors if last affiliation cannot be added', function (done) {
this.addAffiliation.onCall(2).callsArgWith(3, new Error('error'))
this.next = error => {
expect(error).to.exist
diff --git a/services/web/test/unit/src/Institutions/InstitutionsFeaturesTests.js b/services/web/test/unit/src/Institutions/InstitutionsFeaturesTests.js
index e264f7ad6c..c5b0683c11 100644
--- a/services/web/test/unit/src/Institutions/InstitutionsFeaturesTests.js
+++ b/services/web/test/unit/src/Institutions/InstitutionsFeaturesTests.js
@@ -19,8 +19,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Institutions/InstitutionsFeatures.js'
)
-describe('InstitutionsFeatures', function() {
- beforeEach(function() {
+describe('InstitutionsFeatures', function () {
+ beforeEach(function () {
this.UserGetter = { getUserFullEmails: sinon.stub() }
this.PlansLocator = { findLocalPlanInSettings: sinon.stub() }
this.institutionPlanCode = 'institution_plan_code'
@@ -37,8 +37,8 @@ describe('InstitutionsFeatures', function() {
return (this.userId = '12345abcde')
})
- describe('hasLicence', function() {
- it('should handle error', function(done) {
+ describe('hasLicence', function () {
+ it('should handle error', function (done) {
this.UserGetter.getUserFullEmails.yields(new Error('Nope'))
return this.InstitutionsFeatures.hasLicence(
this.userId,
@@ -49,7 +49,7 @@ describe('InstitutionsFeatures', function() {
)
})
- it('should return false if user has no paid affiliations', function(done) {
+ it('should return false if user has no paid affiliations', function (done) {
const emailData = [{ emailHasInstitutionLicence: false }]
this.UserGetter.getUserFullEmails.yields(null, emailData)
return this.InstitutionsFeatures.hasLicence(
@@ -62,7 +62,7 @@ describe('InstitutionsFeatures', function() {
)
})
- it('should return true if user has confirmed paid affiliation', function(done) {
+ it('should return true if user has confirmed paid affiliation', function (done) {
const emailData = [
{ emailHasInstitutionLicence: true },
{ emailHasInstitutionLicence: false }
@@ -79,8 +79,8 @@ describe('InstitutionsFeatures', function() {
})
})
- describe('getInstitutionsFeatures', function() {
- beforeEach(function() {
+ describe('getInstitutionsFeatures', function () {
+ beforeEach(function () {
this.InstitutionsFeatures.getInstitutionsPlan = sinon.stub()
this.testFeatures = { features: { institution: 'all' } }
return this.PlansLocator.findLocalPlanInSettings
@@ -88,7 +88,7 @@ describe('InstitutionsFeatures', function() {
.returns(this.testFeatures)
})
- it('should handle error', function(done) {
+ it('should handle error', function (done) {
this.InstitutionsFeatures.getInstitutionsPlan.yields(new Error('Nope'))
return this.InstitutionsFeatures.getInstitutionsFeatures(
this.userId,
@@ -99,7 +99,7 @@ describe('InstitutionsFeatures', function() {
)
})
- it('should return no feaures if user has no plan code', function(done) {
+ it('should return no feaures if user has no plan code', function (done) {
this.InstitutionsFeatures.getInstitutionsPlan.yields(null, null)
return this.InstitutionsFeatures.getInstitutionsFeatures(
this.userId,
@@ -111,7 +111,7 @@ describe('InstitutionsFeatures', function() {
)
})
- it('should return feaures if user has affiliations plan code', function(done) {
+ it('should return feaures if user has affiliations plan code', function (done) {
this.InstitutionsFeatures.getInstitutionsPlan.yields(
null,
this.institutionPlanCode
@@ -127,12 +127,12 @@ describe('InstitutionsFeatures', function() {
})
})
- describe('getInstitutionsPlan', function() {
- beforeEach(function() {
+ describe('getInstitutionsPlan', function () {
+ beforeEach(function () {
return (this.InstitutionsFeatures.hasLicence = sinon.stub())
})
- it('should handle error', function(done) {
+ it('should handle error', function (done) {
this.InstitutionsFeatures.hasLicence.yields(new Error('Nope'))
return this.InstitutionsFeatures.getInstitutionsPlan(
this.userId,
@@ -143,7 +143,7 @@ describe('InstitutionsFeatures', function() {
)
})
- it('should return no plan if user has no licence', function(done) {
+ it('should return no plan if user has no licence', function (done) {
this.InstitutionsFeatures.hasLicence.yields(null, false)
return this.InstitutionsFeatures.getInstitutionsPlan(
this.userId,
@@ -155,7 +155,7 @@ describe('InstitutionsFeatures', function() {
)
})
- it('should return plan if user has licence', function(done) {
+ it('should return plan if user has licence', function (done) {
this.InstitutionsFeatures.hasLicence.yields(null, true)
return this.InstitutionsFeatures.getInstitutionsPlan(
this.userId,
diff --git a/services/web/test/unit/src/Institutions/InstitutionsGetterTests.js b/services/web/test/unit/src/Institutions/InstitutionsGetterTests.js
index 4299ab74ca..29a5f61ef0 100644
--- a/services/web/test/unit/src/Institutions/InstitutionsGetterTests.js
+++ b/services/web/test/unit/src/Institutions/InstitutionsGetterTests.js
@@ -17,8 +17,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Institutions/InstitutionsGetter.js'
)
-describe('InstitutionsGetter', function() {
- beforeEach(function() {
+describe('InstitutionsGetter', function () {
+ beforeEach(function () {
this.UserGetter = { getUserFullEmails: sinon.stub() }
this.InstitutionsGetter = SandboxedModule.require(modulePath, {
requires: {
@@ -31,8 +31,8 @@ describe('InstitutionsGetter', function() {
return (this.userId = '12345abcde')
})
- describe('getConfirmedInstitutions', function() {
- it('filters unconfirmed affiliations', function(done) {
+ describe('getConfirmedInstitutions', function () {
+ it('filters unconfirmed affiliations', function (done) {
this.userEmails = [
{
confirmedAt: null,
@@ -61,7 +61,7 @@ describe('InstitutionsGetter', function() {
)
})
- it('should handle empty response', function(done) {
+ it('should handle empty response', function (done) {
this.UserGetter.getUserFullEmails.yields(null, [])
return this.InstitutionsGetter.getConfirmedInstitutions(
this.userId,
@@ -73,7 +73,7 @@ describe('InstitutionsGetter', function() {
)
})
- it('should handle error', function(done) {
+ it('should handle error', function (done) {
this.UserGetter.getUserFullEmails.yields(new Error('Nope'))
return this.InstitutionsGetter.getConfirmedInstitutions(
this.userId,
diff --git a/services/web/test/unit/src/Institutions/InstitutionsManagerTests.js b/services/web/test/unit/src/Institutions/InstitutionsManagerTests.js
index cdb7995bfc..cc763cb3b7 100644
--- a/services/web/test/unit/src/Institutions/InstitutionsManagerTests.js
+++ b/services/web/test/unit/src/Institutions/InstitutionsManagerTests.js
@@ -7,8 +7,8 @@ const modulePath = path.join(
'../../../../app/src/Features/Institutions/InstitutionsManager'
)
-describe('InstitutionsManager', function() {
- beforeEach(function() {
+describe('InstitutionsManager', function () {
+ beforeEach(function () {
this.institutionId = 123
this.user = {}
this.getInstitutionAffiliations = sinon.stub()
@@ -70,8 +70,8 @@ describe('InstitutionsManager', function() {
})
})
- describe('refreshInstitutionUsers', function() {
- beforeEach(function() {
+ describe('refreshInstitutionUsers', function () {
+ beforeEach(function () {
this.user1Id = '123abc123abc123abc123abc'
this.user2Id = '456def456def456def456def'
this.affiliations = [{ user_id: this.user1Id }, { user_id: this.user2Id }]
@@ -94,7 +94,7 @@ describe('InstitutionsManager', function() {
this.getInstitutionAffiliations.yields(null, this.affiliations)
})
- it('refresh all users Features', function(done) {
+ it('refresh all users Features', function (done) {
this.InstitutionsManager.refreshInstitutionUsers(
this.institutionId,
false,
@@ -114,7 +114,7 @@ describe('InstitutionsManager', function() {
)
})
- it('notifies users if their features have been upgraded', function(done) {
+ it('notifies users if their features have been upgraded', function (done) {
this.InstitutionsManager.refreshInstitutionUsers(
this.institutionId,
true,
@@ -133,7 +133,7 @@ describe('InstitutionsManager', function() {
)
})
- it('notifies users if they have a subscription that should be cancelled', function(done) {
+ it('notifies users if they have a subscription that should be cancelled', function (done) {
this.InstitutionsManager.refreshInstitutionUsers(
this.institutionId,
true,
@@ -153,8 +153,8 @@ describe('InstitutionsManager', function() {
})
})
- describe('checkInstitutionUsers', function() {
- it('check all users Features', function(done) {
+ describe('checkInstitutionUsers', function () {
+ it('check all users Features', function (done) {
const affiliations = [{ email: 'foo@bar.com' }, { email: 'baz@boo.edu' }]
const stubbedUsers = [
{
@@ -200,8 +200,8 @@ describe('InstitutionsManager', function() {
})
})
- describe('getInstitutionUsersSubscriptions', function() {
- it('returns all institution users subscriptions', function(done) {
+ describe('getInstitutionUsersSubscriptions', function () {
+ it('returns all institution users subscriptions', function (done) {
const stubbedUsers = [
{ user_id: '123abc123abc123abc123abc' },
{ user_id: '456def456def456def456def' },
diff --git a/services/web/test/unit/src/Metadata/MetaControllerTests.js b/services/web/test/unit/src/Metadata/MetaControllerTests.js
index b9792670c3..a41419d674 100644
--- a/services/web/test/unit/src/Metadata/MetaControllerTests.js
+++ b/services/web/test/unit/src/Metadata/MetaControllerTests.js
@@ -14,8 +14,8 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/Metadata/MetaController'
const SandboxedModule = require('sandboxed-module')
-describe('MetaController', function() {
- beforeEach(function() {
+describe('MetaController', function () {
+ beforeEach(function () {
this.projectId = 'somekindofid'
this.EditorRealTimeController = {
emitToRoom: sinon.stub()
@@ -32,8 +32,8 @@ describe('MetaController', function() {
}))
})
- describe('getMetadata', function() {
- beforeEach(function() {
+ describe('getMetadata', function () {
+ beforeEach(function () {
this.fakeLabels = { somedoc: ['a_label'] }
this.MetaHandler.getAllMetaForProject = sinon
.stub()
@@ -43,7 +43,7 @@ describe('MetaController', function() {
return (this.next = sinon.stub())
})
- it('should call MetaHandler.getAllMetaForProject', function() {
+ it('should call MetaHandler.getAllMetaForProject', function () {
this.MetadataController.getMetadata(this.req, this.res, this.next)
this.MetaHandler.getAllMetaForProject.callCount.should.equal(1)
return this.MetaHandler.getAllMetaForProject
@@ -51,12 +51,12 @@ describe('MetaController', function() {
.should.equal(true)
})
- it('should call not call next with an error', function() {
+ it('should call not call next with an error', function () {
this.MetadataController.getMetadata(this.req, this.res, this.next)
return this.next.callCount.should.equal(0)
})
- it('should send a json response', function() {
+ it('should send a json response', function () {
this.MetadataController.getMetadata(this.req, this.res, this.next)
this.res.json.callCount.should.equal(1)
return expect(this.res.json.lastCall.args[0]).to.have.all.keys([
@@ -65,8 +65,8 @@ describe('MetaController', function() {
])
})
- describe('when MetaHandler.getAllMetaForProject produces an error', function() {
- beforeEach(function() {
+ describe('when MetaHandler.getAllMetaForProject produces an error', function () {
+ beforeEach(function () {
this.MetaHandler.getAllMetaForProject = sinon
.stub()
.callsArgWith(1, new Error('woops'))
@@ -75,7 +75,7 @@ describe('MetaController', function() {
return (this.next = sinon.stub())
})
- it('should call MetaHandler.getAllMetaForProject', function() {
+ it('should call MetaHandler.getAllMetaForProject', function () {
this.MetadataController.getMetadata(this.req, this.res, this.next)
this.MetaHandler.getAllMetaForProject.callCount.should.equal(1)
return this.MetaHandler.getAllMetaForProject
@@ -83,21 +83,21 @@ describe('MetaController', function() {
.should.equal(true)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.MetadataController.getMetadata(this.req, this.res, this.next)
this.next.callCount.should.equal(1)
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
- it('should not send a json response', function() {
+ it('should not send a json response', function () {
this.MetadataController.getMetadata(this.req, this.res, this.next)
return this.res.json.callCount.should.equal(0)
})
})
})
- describe('broadcastMetadataForDoc', function() {
- beforeEach(function() {
+ describe('broadcastMetadataForDoc', function () {
+ beforeEach(function () {
this.MetaHandler.getMetaForDoc = sinon
.stub()
.callsArgWith(2, null, this.fakeLabels)
@@ -107,15 +107,15 @@ describe('MetaController', function() {
return (this.next = sinon.stub())
})
- describe('with broadcast:true', function() {
- beforeEach(function() {
+ describe('with broadcast:true', function () {
+ beforeEach(function () {
this.req = {
params: { project_id: this.projectId, doc_id: this.docId },
body: { broadcast: true }
}
})
- it('should call MetaHandler.getMetaForDoc', function() {
+ it('should call MetaHandler.getMetaForDoc', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
@@ -127,7 +127,7 @@ describe('MetaController', function() {
.should.equal(true)
})
- it('should call not call next with an error', function() {
+ it('should call not call next with an error', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
@@ -136,7 +136,7 @@ describe('MetaController', function() {
return this.next.callCount.should.equal(0)
})
- it('should send a success response', function() {
+ it('should send a success response', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
@@ -146,7 +146,7 @@ describe('MetaController', function() {
return this.res.sendStatus.calledWith(200).should.equal(true)
})
- it('should emit a message to room', function() {
+ it('should emit a message to room', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
@@ -160,15 +160,15 @@ describe('MetaController', function() {
})
})
- describe('with broadcast:false', function() {
- beforeEach(function() {
+ describe('with broadcast:false', function () {
+ beforeEach(function () {
this.req = {
params: { project_id: this.projectId, doc_id: this.docId },
body: { broadcast: false }
}
})
- it('should call MetaHandler.getMetaForDoc', function() {
+ it('should call MetaHandler.getMetaForDoc', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
@@ -180,7 +180,7 @@ describe('MetaController', function() {
.should.equal(true)
})
- it('should call not call next with an error', function() {
+ it('should call not call next with an error', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
@@ -189,7 +189,7 @@ describe('MetaController', function() {
return this.next.callCount.should.equal(0)
})
- it('should send the metadata in the response', function() {
+ it('should send the metadata in the response', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
@@ -201,7 +201,7 @@ describe('MetaController', function() {
.should.equal(true)
})
- it('should not emit a message to room', function() {
+ it('should not emit a message to room', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
@@ -213,8 +213,8 @@ describe('MetaController', function() {
})
})
- describe('when MetaHandler.getMetaForDoc produces an error', function() {
- beforeEach(function() {
+ describe('when MetaHandler.getMetaForDoc produces an error', function () {
+ beforeEach(function () {
this.MetaHandler.getMetaForDoc = sinon
.stub()
.callsArgWith(2, new Error('woops'))
@@ -228,7 +228,7 @@ describe('MetaController', function() {
return (this.next = sinon.stub())
})
- it('should call MetaHandler.getMetaForDoc', function() {
+ it('should call MetaHandler.getMetaForDoc', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
@@ -240,7 +240,7 @@ describe('MetaController', function() {
.should.equal(true)
})
- it('should call next with an error', function() {
+ it('should call next with an error', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
@@ -250,7 +250,7 @@ describe('MetaController', function() {
return expect(this.next.lastCall.args[0]).to.be.instanceof(Error)
})
- it('should not send a json response', function() {
+ it('should not send a json response', function () {
this.MetadataController.broadcastMetadataForDoc(
this.req,
this.res,
diff --git a/services/web/test/unit/src/Metadata/MetaHandlerTests.js b/services/web/test/unit/src/Metadata/MetaHandlerTests.js
index 1b4025cf4d..688f1817c4 100644
--- a/services/web/test/unit/src/Metadata/MetaHandlerTests.js
+++ b/services/web/test/unit/src/Metadata/MetaHandlerTests.js
@@ -15,8 +15,8 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/Metadata/MetaHandler'
const SandboxedModule = require('sandboxed-module')
-describe('MetaHandler', function() {
- beforeEach(function() {
+describe('MetaHandler', function () {
+ beforeEach(function () {
this.projectId = 'someprojectid'
this.docId = 'somedocid'
this.ProjectEntityHandler = {
@@ -61,8 +61,8 @@ describe('MetaHandler', function() {
}))
})
- describe('extractMetaFromDoc', function() {
- beforeEach(function() {
+ describe('extractMetaFromDoc', function () {
+ beforeEach(function () {
return (this.lines = [
'\\usepackage{foo}',
'\\usepackage{amsmath, booktabs}',
@@ -75,7 +75,7 @@ describe('MetaHandler', function() {
])
})
- it('should extract all the labels and packages', function() {
+ it('should extract all the labels and packages', function () {
const docMeta = this.MetaHandler.extractMetaFromDoc(this.lines)
return expect(docMeta).to.deep.equal({
labels: ['aaa', 'bbb'],
@@ -99,8 +99,8 @@ describe('MetaHandler', function() {
})
})
- describe('extractMetaFromProjectDocs', function() {
- beforeEach(function() {
+ describe('extractMetaFromProjectDocs', function () {
+ beforeEach(function () {
return (this.docs = {
doc_one: {
_id: 'id_one',
@@ -135,7 +135,7 @@ describe('MetaHandler', function() {
})
})
- it('should extract all metadata', function() {
+ it('should extract all metadata', function () {
const projectMeta = this.MetaHandler.extractMetaFromProjectDocs(this.docs)
return expect(projectMeta).to.deep.equal({
id_one: { labels: ['aaa'], packages: {} },
@@ -185,8 +185,8 @@ describe('MetaHandler', function() {
})
})
- describe('getMetaForDoc', function() {
- beforeEach(function() {
+ describe('getMetaForDoc', function () {
+ beforeEach(function () {
this.fakeLines = ['\\usepackage{abc}', 'one', '\\label{aaa}', 'two']
this.fakeMeta = { labels: ['aaa'], packages: ['abc'] }
this.DocumentUpdaterHandler.flushDocToMongo = sinon
@@ -205,21 +205,21 @@ describe('MetaHandler', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, docMeta) => {
expect(err).to.equal(null)
return done()
})
})
- it('should produce docMeta', function(done) {
+ it('should produce docMeta', function (done) {
return this.call((err, docMeta) => {
expect(docMeta).to.equal(this.fakeMeta)
return done()
})
})
- it('should call flushDocToMongo', function(done) {
+ it('should call flushDocToMongo', function (done) {
return this.call((err, docMeta) => {
this.DocumentUpdaterHandler.flushDocToMongo.callCount.should.equal(1)
this.DocumentUpdaterHandler.flushDocToMongo
@@ -229,7 +229,7 @@ describe('MetaHandler', function() {
})
})
- it('should call getDoc', function(done) {
+ it('should call getDoc', function (done) {
return this.call((err, docMeta) => {
this.ProjectEntityHandler.getDoc.callCount.should.equal(1)
this.ProjectEntityHandler.getDoc
@@ -239,7 +239,7 @@ describe('MetaHandler', function() {
})
})
- it('should call extractMetaFromDoc', function(done) {
+ it('should call extractMetaFromDoc', function (done) {
return this.call((err, docMeta) => {
this.MetaHandler.extractMetaFromDoc.callCount.should.equal(1)
this.MetaHandler.extractMetaFromDoc
@@ -250,8 +250,8 @@ describe('MetaHandler', function() {
})
})
- describe('getAllMetaForProject', function() {
- beforeEach(function() {
+ describe('getAllMetaForProject', function () {
+ beforeEach(function () {
this.fakeDocs = {
doc_one: {
lines: ['\\usepackage[some-options,more=foo]{foo}', '\\label{aaa}']
@@ -291,21 +291,21 @@ describe('MetaHandler', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, projectMeta) => {
expect(err).to.equal(null)
return done()
})
})
- it('should produce projectMeta', function(done) {
+ it('should produce projectMeta', function (done) {
return this.call((err, projectMeta) => {
expect(projectMeta).to.equal(this.fakeMeta)
return done()
})
})
- it('should call getAllDocs', function(done) {
+ it('should call getAllDocs', function (done) {
return this.call((err, projectMeta) => {
this.ProjectEntityHandler.getAllDocs.callCount.should.equal(1)
this.ProjectEntityHandler.getAllDocs
@@ -315,7 +315,7 @@ describe('MetaHandler', function() {
})
})
- it('should call extractMetaFromDoc', function(done) {
+ it('should call extractMetaFromDoc', function (done) {
return this.call((err, docMeta) => {
this.MetaHandler.extractMetaFromProjectDocs.callCount.should.equal(1)
this.MetaHandler.extractMetaFromProjectDocs
diff --git a/services/web/test/unit/src/Newsletter/NewsletterManagerTests.js b/services/web/test/unit/src/Newsletter/NewsletterManagerTests.js
index d8d9ae7d4c..29972668d0 100644
--- a/services/web/test/unit/src/Newsletter/NewsletterManagerTests.js
+++ b/services/web/test/unit/src/Newsletter/NewsletterManagerTests.js
@@ -4,8 +4,8 @@ const SandboxedModule = require('sandboxed-module')
const MODULE_PATH = '../../../../app/src/Features/Newsletter/NewsletterManager'
-describe('NewsletterManager', function() {
- beforeEach('setup mocks', function() {
+describe('NewsletterManager', function () {
+ beforeEach('setup mocks', function () {
this.Settings = {
mailchimp: {
api_key: 'api_key',
@@ -42,8 +42,8 @@ describe('NewsletterManager', function() {
this.emailHash = 'c02f60ed0ef51818186274e406c9a48f'
})
- describe('subscribe', function() {
- it('calls Mailchimp to subscribe the user', async function() {
+ describe('subscribe', function () {
+ it('calls Mailchimp to subscribe the user', async function () {
await this.NewsletterManager.subscribe(this.user)
expect(this.mailchimp.put).to.have.been.calledWith(
`/lists/list_id/members/${this.emailHash}`,
@@ -57,9 +57,9 @@ describe('NewsletterManager', function() {
})
})
- describe('unsubscribe', function() {
- describe('when unsubscribing normally', function() {
- it('calls Mailchimp to unsubscribe the user', async function() {
+ describe('unsubscribe', function () {
+ describe('when unsubscribing normally', function () {
+ it('calls Mailchimp to unsubscribe the user', async function () {
await this.NewsletterManager.unsubscribe(this.user)
expect(this.mailchimp.patch).to.have.been.calledWith(
`/lists/list_id/members/${this.emailHash}`,
@@ -70,7 +70,7 @@ describe('NewsletterManager', function() {
)
})
- it('ignores a Mailchimp error about fake emails', async function() {
+ it('ignores a Mailchimp error about fake emails', async function () {
this.mailchimp.patch.rejects(
new Error(
'overleaf.duck@example.com looks fake or invalid, please enter a real email address'
@@ -80,7 +80,7 @@ describe('NewsletterManager', function() {
.fulfilled
})
- it('rejects on other errors', async function() {
+ it('rejects on other errors', async function () {
this.mailchimp.patch.rejects(
new Error('something really wrong is happening')
)
@@ -89,15 +89,15 @@ describe('NewsletterManager', function() {
})
})
- describe('when deleting', function() {
- it('calls Mailchimp to delete the user', async function() {
+ describe('when deleting', function () {
+ it('calls Mailchimp to delete the user', async function () {
await this.NewsletterManager.unsubscribe(this.user, { delete: true })
expect(this.mailchimp.delete).to.have.been.calledWith(
`/lists/list_id/members/${this.emailHash}`
)
})
- it('ignores a Mailchimp error about fake emails', async function() {
+ it('ignores a Mailchimp error about fake emails', async function () {
this.mailchimp.delete.rejects(
new Error(
'overleaf.duck@example.com looks fake or invalid, please enter a real email address'
@@ -108,7 +108,7 @@ describe('NewsletterManager', function() {
).to.be.fulfilled
})
- it('rejects on other errors', async function() {
+ it('rejects on other errors', async function () {
this.mailchimp.delete.rejects(
new Error('something really wrong is happening')
)
@@ -119,8 +119,8 @@ describe('NewsletterManager', function() {
})
})
- describe('changeEmail', function() {
- it('calls Mailchimp to change the subscriber email', async function() {
+ describe('changeEmail', function () {
+ it('calls Mailchimp to change the subscriber email', async function () {
await this.NewsletterManager.changeEmail(
this.user,
'overleaf.squirrel@example.com'
@@ -134,7 +134,7 @@ describe('NewsletterManager', function() {
)
})
- it('deletes the old email if changing the address fails', async function() {
+ it('deletes the old email if changing the address fails', async function () {
this.mailchimp.patch
.withArgs(`/lists/list_id/members/${this.emailHash}`, {
email_address: 'overleaf.squirrel@example.com',
@@ -154,7 +154,7 @@ describe('NewsletterManager', function() {
)
})
- it('does not reject on non-fatal error ', async function() {
+ it('does not reject on non-fatal error ', async function () {
const nonFatalError = new Error('merge fields were invalid')
this.mailchimp.patch.rejects(nonFatalError)
await expect(
@@ -165,7 +165,7 @@ describe('NewsletterManager', function() {
).to.be.fulfilled
})
- it('rejects on any other error', async function() {
+ it('rejects on any other error', async function () {
const fatalError = new Error('fatal error')
this.mailchimp.patch.rejects(fatalError)
await expect(
diff --git a/services/web/test/unit/src/Notifications/NotificationsBuilderTests.js b/services/web/test/unit/src/Notifications/NotificationsBuilderTests.js
index 9c21f7f7a0..a373446c1c 100644
--- a/services/web/test/unit/src/Notifications/NotificationsBuilderTests.js
+++ b/services/web/test/unit/src/Notifications/NotificationsBuilderTests.js
@@ -5,11 +5,11 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Notifications/NotificationsBuilder.js'
)
-describe('NotificationsBuilder', function() {
+describe('NotificationsBuilder', function () {
const userId = '123nd3ijdks'
- describe('ipMatcherAffiliation', function() {
- beforeEach(function() {
+ describe('ipMatcherAffiliation', function () {
+ beforeEach(function () {
this.handler = { createNotification: sinon.stub().callsArgWith(6) }
this.settings = { apis: { v1: { url: 'v1.url', user: '', pass: '' } } }
this.request = sinon.stub()
@@ -22,8 +22,8 @@ describe('NotificationsBuilder', function() {
})
})
- describe('with portal and with SSO', function() {
- beforeEach(function() {
+ describe('with portal and with SSO', function () {
+ beforeEach(function () {
this.body = {
id: 1,
name: 'stanford',
@@ -35,7 +35,7 @@ describe('NotificationsBuilder', function() {
this.request.callsArgWith(1, null, { statusCode: 200 }, this.body)
})
- it('should call v1 and create affiliation notifications', function(done) {
+ it('should call v1 and create affiliation notifications', function (done) {
const ip = '192.168.0.1'
this.controller.ipMatcherAffiliation(userId).create(ip, callback => {
this.request.calledOnce.should.equal(true)
@@ -58,8 +58,8 @@ describe('NotificationsBuilder', function() {
})
})
})
- describe('without portal and without SSO', function() {
- beforeEach(function() {
+ describe('without portal and without SSO', function () {
+ beforeEach(function () {
this.body = {
id: 1,
name: 'stanford',
@@ -71,7 +71,7 @@ describe('NotificationsBuilder', function() {
this.request.callsArgWith(1, null, { statusCode: 200 }, this.body)
})
- it('should call v1 and create affiliation notifications', function(done) {
+ it('should call v1 and create affiliation notifications', function (done) {
const ip = '192.168.0.1'
this.controller.ipMatcherAffiliation(userId).create(ip, callback => {
this.request.calledOnce.should.equal(true)
diff --git a/services/web/test/unit/src/Notifications/NotificationsControllerTests.js b/services/web/test/unit/src/Notifications/NotificationsControllerTests.js
index faaa023fac..2c18a6407e 100644
--- a/services/web/test/unit/src/Notifications/NotificationsControllerTests.js
+++ b/services/web/test/unit/src/Notifications/NotificationsControllerTests.js
@@ -19,11 +19,11 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Notifications/NotificationsController.js'
)
-describe('NotificationsController', function() {
+describe('NotificationsController', function () {
const user_id = '123nd3ijdks'
const notification_id = '123njdskj9jlk'
- beforeEach(function() {
+ beforeEach(function () {
this.handler = {
getUserNotifications: sinon.stub().callsArgWith(1),
markAsRead: sinon.stub().callsArgWith(2)
@@ -53,7 +53,7 @@ describe('NotificationsController', function() {
}))
})
- it('should ask the handler for all unread notifications', function(done) {
+ it('should ask the handler for all unread notifications', function (done) {
const allNotifications = [{ _id: notification_id, user_id }]
this.handler.getUserNotifications = sinon
.stub()
@@ -67,7 +67,7 @@ describe('NotificationsController', function() {
})
})
- it('should send a delete request when a delete has been received to mark a notification', function(done) {
+ it('should send a delete request when a delete has been received to mark a notification', function (done) {
return this.controller.markNotificationAsRead(this.req, {
sendStatus: () => {
this.handler.markAsRead
diff --git a/services/web/test/unit/src/Notifications/NotificationsHandlerTests.js b/services/web/test/unit/src/Notifications/NotificationsHandlerTests.js
index 62e99b65bc..ebbaf681b6 100644
--- a/services/web/test/unit/src/Notifications/NotificationsHandlerTests.js
+++ b/services/web/test/unit/src/Notifications/NotificationsHandlerTests.js
@@ -21,12 +21,12 @@ const modulePath = require('path').join(
)
const _ = require('underscore')
-describe('NotificationsHandler', function() {
+describe('NotificationsHandler', function () {
const user_id = '123nd3ijdks'
const notification_id = '123njdskj9jlk'
const notificationUrl = 'notification.sharelatex.testing'
- beforeEach(function() {
+ beforeEach(function () {
this.request = sinon.stub().callsArgWith(1)
return (this.handler = SandboxedModule.require(modulePath, {
requires: {
@@ -38,8 +38,8 @@ describe('NotificationsHandler', function() {
}))
})
- describe('getUserNotifications', function() {
- it('should get unread notifications', function(done) {
+ describe('getUserNotifications', function () {
+ it('should get unread notifications', function (done) {
const stubbedNotifications = [{ _id: notification_id, user_id }]
this.request.callsArgWith(
1,
@@ -63,7 +63,7 @@ describe('NotificationsHandler', function() {
)
})
- it('should return empty arrays if there are no notifications', function() {
+ it('should return empty arrays if there are no notifications', function () {
this.request.callsArgWith(1, null, { statusCode: 200 }, null)
return this.handler.getUserNotifications(
user_id,
@@ -74,12 +74,12 @@ describe('NotificationsHandler', function() {
})
})
- describe('markAsRead', function() {
- beforeEach(function() {
+ describe('markAsRead', function () {
+ beforeEach(function () {
return (this.key = 'some key here')
})
- it('should send a delete request when a delete has been received to mark a notification', function(done) {
+ it('should send a delete request when a delete has been received to mark a notification', function (done) {
return this.handler.markAsReadWithKey(user_id, this.key, () => {
const opts = {
uri: `${notificationUrl}/user/${user_id}`,
@@ -95,15 +95,15 @@ describe('NotificationsHandler', function() {
})
})
- describe('createNotification', function() {
- beforeEach(function() {
+ describe('createNotification', function () {
+ beforeEach(function () {
this.key = 'some key here'
this.messageOpts = { value: 12344 }
this.templateKey = 'renderThisHtml'
return (this.expiry = null)
})
- it('should post the message over', function(done) {
+ it('should post the message over', function (done) {
return this.handler.createNotification(
user_id,
this.key,
@@ -126,15 +126,15 @@ describe('NotificationsHandler', function() {
)
})
- describe('when expiry date is supplied', function() {
- beforeEach(function() {
+ describe('when expiry date is supplied', function () {
+ beforeEach(function () {
this.key = 'some key here'
this.messageOpts = { value: 12344 }
this.templateKey = 'renderThisHtml'
return (this.expiry = new Date())
})
- it('should post the message over with expiry field', function(done) {
+ it('should post the message over with expiry field', function (done) {
return this.handler.createNotification(
user_id,
this.key,
@@ -160,12 +160,12 @@ describe('NotificationsHandler', function() {
})
})
- describe('markAsReadByKeyOnly', function() {
- beforeEach(function() {
+ describe('markAsReadByKeyOnly', function () {
+ beforeEach(function () {
return (this.key = 'some key here')
})
- it('should send a delete request when a delete has been received to mark a notification', function(done) {
+ it('should send a delete request when a delete has been received to mark a notification', function (done) {
return this.handler.markAsReadByKeyOnly(this.key, () => {
const opts = {
uri: `${notificationUrl}/key/${this.key}`,
diff --git a/services/web/test/unit/src/PasswordReset/PasswordResetControllerTests.js b/services/web/test/unit/src/PasswordReset/PasswordResetControllerTests.js
index 62d2ef786d..e8bd654cb0 100644
--- a/services/web/test/unit/src/PasswordReset/PasswordResetControllerTests.js
+++ b/services/web/test/unit/src/PasswordReset/PasswordResetControllerTests.js
@@ -9,8 +9,8 @@ const MODULE_PATH = path.join(
'../../../../app/src/Features/PasswordReset/PasswordResetController'
)
-describe('PasswordResetController', function() {
- beforeEach(function() {
+describe('PasswordResetController', function () {
+ beforeEach(function () {
this.email = 'bob@bob.com'
this.user_id = 'mock-user-id'
this.token = 'my security token that was emailed to me'
@@ -69,8 +69,8 @@ describe('PasswordResetController', function() {
})
})
- describe('requestReset', function() {
- it('should error if the rate limit is hit', function(done) {
+ describe('requestReset', function () {
+ it('should error if the rate limit is hit', function (done) {
this.PasswordResetHandler.generateAndEmailResetToken.callsArgWith(
1,
null,
@@ -85,7 +85,7 @@ describe('PasswordResetController', function() {
done()
})
- it('should tell the handler to process that email', function(done) {
+ it('should tell the handler to process that email', function (done) {
this.RateLimiter.addCount.callsArgWith(1, null, true)
this.PasswordResetHandler.generateAndEmailResetToken.callsArgWith(
1,
@@ -100,7 +100,7 @@ describe('PasswordResetController', function() {
done()
})
- it('should send a 500 if there is an error', function(done) {
+ it('should send a 500 if there is an error', function (done) {
this.RateLimiter.addCount.callsArgWith(1, null, true)
this.PasswordResetHandler.generateAndEmailResetToken.callsArgWith(
1,
@@ -112,7 +112,7 @@ describe('PasswordResetController', function() {
})
})
- it("should send a 404 if the email doesn't exist", function(done) {
+ it("should send a 404 if the email doesn't exist", function (done) {
this.RateLimiter.addCount.callsArgWith(1, null, true)
this.PasswordResetHandler.generateAndEmailResetToken.callsArgWith(
1,
@@ -124,7 +124,7 @@ describe('PasswordResetController', function() {
done()
})
- it('should send a 404 if the email is registered as a secondard email', function(done) {
+ it('should send a 404 if the email is registered as a secondard email', function (done) {
this.RateLimiter.addCount.callsArgWith(1, null, true)
this.PasswordResetHandler.generateAndEmailResetToken.callsArgWith(
1,
@@ -136,7 +136,7 @@ describe('PasswordResetController', function() {
done()
})
- it('should normalize the email address', function(done) {
+ it('should normalize the email address', function (done) {
this.email = ' UPperCaseEMAILWithSpacesAround@example.Com '
this.req.body.email = this.email
this.RateLimiter.addCount.callsArgWith(1, null, true)
@@ -154,12 +154,12 @@ describe('PasswordResetController', function() {
})
})
- describe('setNewUserPassword', function() {
- beforeEach(function() {
+ describe('setNewUserPassword', function () {
+ beforeEach(function () {
this.req.session.resetToken = this.token
})
- it('should tell the user handler to reset the password', function(done) {
+ it('should tell the user handler to reset the password', function (done) {
this.res.sendStatus = code => {
code.should.equal(200)
this.PasswordResetHandler.promises.setNewUserPassword
@@ -170,7 +170,7 @@ describe('PasswordResetController', function() {
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should preserve spaces in the password', function(done) {
+ it('should preserve spaces in the password', function (done) {
this.password = this.req.body.password = ' oh! clever! spaces around! '
this.res.sendStatus = code => {
code.should.equal(200)
@@ -183,7 +183,7 @@ describe('PasswordResetController', function() {
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should send 404 if the token was not found', function(done) {
+ it('should send 404 if the token was not found', function (done) {
this.PasswordResetHandler.promises.setNewUserPassword.resolves({
found: false,
reset: false,
@@ -196,7 +196,7 @@ describe('PasswordResetController', function() {
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should return 500 if not reset', function(done) {
+ it('should return 500 if not reset', function (done) {
this.PasswordResetHandler.promises.setNewUserPassword.resolves({
found: true,
reset: false,
@@ -209,7 +209,7 @@ describe('PasswordResetController', function() {
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should return 400 (Bad Request) if there is no password', function(done) {
+ it('should return 400 (Bad Request) if there is no password', function (done) {
this.req.body.password = ''
this.res.sendStatus = code => {
code.should.equal(400)
@@ -221,7 +221,7 @@ describe('PasswordResetController', function() {
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should return 400 (Bad Request) if there is no passwordResetToken', function(done) {
+ it('should return 400 (Bad Request) if there is no passwordResetToken', function (done) {
this.req.body.passwordResetToken = ''
this.res.sendStatus = code => {
code.should.equal(400)
@@ -233,7 +233,7 @@ describe('PasswordResetController', function() {
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should return 400 (Bad Request) if the password is invalid', function(done) {
+ it('should return 400 (Bad Request) if the password is invalid', function (done) {
this.req.body.password = 'correct horse battery staple'
const err = new Error('bad')
err.name = 'InvalidPasswordError'
@@ -248,7 +248,7 @@ describe('PasswordResetController', function() {
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should clear the session.resetToken', function(done) {
+ it('should clear the session.resetToken', function (done) {
this.res.sendStatus = code => {
code.should.equal(200)
this.req.session.should.not.have.property('resetToken')
@@ -257,7 +257,7 @@ describe('PasswordResetController', function() {
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should clear sessions', function(done) {
+ it('should clear sessions', function (done) {
this.res.sendStatus = code => {
this.UserSessionsManager.promises.revokeAllUserSessions.callCount.should.equal(
1
@@ -267,7 +267,7 @@ describe('PasswordResetController', function() {
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should call removeReconfirmFlag', function(done) {
+ it('should call removeReconfirmFlag', function (done) {
this.res.sendStatus = code => {
this.UserUpdater.promises.removeReconfirmFlag.callCount.should.equal(1)
done()
@@ -275,8 +275,8 @@ describe('PasswordResetController', function() {
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- describe('catch errors', function() {
- it('should return 404 for NotFoundError', function(done) {
+ describe('catch errors', function () {
+ it('should return 404 for NotFoundError', function (done) {
const anError = new Error('oops')
anError.name = 'NotFoundError'
this.PasswordResetHandler.promises.setNewUserPassword.rejects(anError)
@@ -286,7 +286,7 @@ describe('PasswordResetController', function() {
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should return 400 for InvalidPasswordError', function(done) {
+ it('should return 400 for InvalidPasswordError', function (done) {
const anError = new Error('oops')
anError.name = 'InvalidPasswordError'
this.PasswordResetHandler.promises.setNewUserPassword.rejects(anError)
@@ -296,7 +296,7 @@ describe('PasswordResetController', function() {
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
- it('should return 500 for other errors', function(done) {
+ it('should return 500 for other errors', function (done) {
const anError = new Error('oops')
this.PasswordResetHandler.promises.setNewUserPassword.rejects(anError)
this.res.sendStatus = code => {
@@ -307,8 +307,8 @@ describe('PasswordResetController', function() {
})
})
- describe('when doLoginAfterPasswordReset is set', function() {
- beforeEach(function() {
+ describe('when doLoginAfterPasswordReset is set', function () {
+ beforeEach(function () {
this.user = {
_id: this.userId,
email: 'joe@example.com'
@@ -317,7 +317,7 @@ describe('PasswordResetController', function() {
this.req.session.doLoginAfterPasswordReset = 'true'
})
- it('should login user', function(done) {
+ it('should login user', function (done) {
this.AuthenticationController.finishLogin.callsFake((...args) => {
expect(args[0]).to.equal(this.user)
done()
@@ -327,13 +327,13 @@ describe('PasswordResetController', function() {
})
})
- describe('renderSetPasswordForm', function() {
- describe('with token in query-string', function() {
- beforeEach(function() {
+ describe('renderSetPasswordForm', function () {
+ describe('with token in query-string', function () {
+ beforeEach(function () {
this.req.query.passwordResetToken = this.token
})
- it('should set session.resetToken and redirect', function(done) {
+ it('should set session.resetToken and redirect', function (done) {
this.req.session.should.not.have.property('resetToken')
this.res.redirect = path => {
path.should.equal('/user/password/set')
@@ -344,13 +344,13 @@ describe('PasswordResetController', function() {
})
})
- describe('with token and email in query-string', function() {
- beforeEach(function() {
+ describe('with token and email in query-string', function () {
+ beforeEach(function () {
this.req.query.passwordResetToken = this.token
this.req.query.email = 'foo@bar.com'
})
- it('should set session.resetToken and redirect with email', function(done) {
+ it('should set session.resetToken and redirect with email', function (done) {
this.req.session.should.not.have.property('resetToken')
this.res.redirect = path => {
path.should.equal('/user/password/set?email=foo%40bar.com')
@@ -361,13 +361,13 @@ describe('PasswordResetController', function() {
})
})
- describe('with token and invalid email in query-string', function() {
- beforeEach(function() {
+ describe('with token and invalid email in query-string', function () {
+ beforeEach(function () {
this.req.query.passwordResetToken = this.token
this.req.query.email = 'not-an-email'
})
- it('should set session.resetToken and redirect without email', function(done) {
+ it('should set session.resetToken and redirect without email', function (done) {
this.req.session.should.not.have.property('resetToken')
this.res.redirect = path => {
path.should.equal('/user/password/set')
@@ -378,13 +378,13 @@ describe('PasswordResetController', function() {
})
})
- describe('with token and non-string email in query-string', function() {
- beforeEach(function() {
+ describe('with token and non-string email in query-string', function () {
+ beforeEach(function () {
this.req.query.passwordResetToken = this.token
this.req.query.email = { foo: 'bar' }
})
- it('should set session.resetToken and redirect without email', function(done) {
+ it('should set session.resetToken and redirect without email', function (done) {
this.req.session.should.not.have.property('resetToken')
this.res.redirect = path => {
path.should.equal('/user/password/set')
@@ -395,13 +395,13 @@ describe('PasswordResetController', function() {
})
})
- describe('without a token in query-string', function() {
- describe('with token in session', function() {
- beforeEach(function() {
+ describe('without a token in query-string', function () {
+ describe('with token in session', function () {
+ beforeEach(function () {
this.req.session.resetToken = this.token
})
- it('should render the page, passing the reset token', function(done) {
+ it('should render the page, passing the reset token', function (done) {
this.res.render = (templatePath, options) => {
options.passwordResetToken.should.equal(this.req.session.resetToken)
done()
@@ -410,8 +410,8 @@ describe('PasswordResetController', function() {
})
})
- describe('without a token in session', function() {
- it('should redirect to the reset request page', function(done) {
+ describe('without a token in session', function () {
+ it('should redirect to the reset request page', function (done) {
this.res.redirect = path => {
path.should.equal('/user/password/reset')
this.req.session.should.not.have.property('resetToken')
diff --git a/services/web/test/unit/src/PasswordReset/PasswordResetHandlerTests.js b/services/web/test/unit/src/PasswordReset/PasswordResetHandlerTests.js
index 3c4331977e..90ccc5d49f 100644
--- a/services/web/test/unit/src/PasswordReset/PasswordResetHandlerTests.js
+++ b/services/web/test/unit/src/PasswordReset/PasswordResetHandlerTests.js
@@ -21,8 +21,8 @@ const modulePath = path.join(
'../../../../app/src/Features/PasswordReset/PasswordResetHandler'
)
-describe('PasswordResetHandler', function() {
- beforeEach(function() {
+describe('PasswordResetHandler', function () {
+ beforeEach(function () {
this.settings = { siteUrl: 'www.sharelatex.com' }
this.OneTimeTokenHandler = {
getNewToken: sinon.stub(),
@@ -63,12 +63,12 @@ describe('PasswordResetHandler', function() {
this.settings.overleaf = true
})
- afterEach(function() {
+ afterEach(function () {
this.settings.overleaf = false
})
- describe('generateAndEmailResetToken', function() {
- it('should check the user exists', function() {
+ describe('generateAndEmailResetToken', function () {
+ it('should check the user exists', function () {
this.UserGetter.getUserByAnyEmail.yields()
this.PasswordResetHandler.generateAndEmailResetToken(
this.user.email,
@@ -79,7 +79,7 @@ describe('PasswordResetHandler', function() {
)
})
- it('should send the email with the token', function(done) {
+ it('should send the email with the token', function (done) {
this.UserGetter.getUserByAnyEmail.yields(null, this.user)
this.OneTimeTokenHandler.getNewToken.yields(null, this.token)
this.EmailHandler.sendEmail.yields()
@@ -100,8 +100,8 @@ describe('PasswordResetHandler', function() {
)
})
- describe('when the email exists', function() {
- beforeEach(function() {
+ describe('when the email exists', function () {
+ beforeEach(function () {
this.UserGetter.getUserByAnyEmail.yields(null, this.user)
this.OneTimeTokenHandler.getNewToken.yields(null, this.token)
this.EmailHandler.sendEmail.yields()
@@ -111,7 +111,7 @@ describe('PasswordResetHandler', function() {
)
})
- it('should set the password token data to the user id and email', function() {
+ it('should set the password token data to the user id and email', function () {
this.OneTimeTokenHandler.getNewToken.should.have.been.calledWith(
'password',
{
@@ -121,7 +121,7 @@ describe('PasswordResetHandler', function() {
)
})
- it('should send an email with the token', function() {
+ it('should send an email with the token', function () {
this.EmailHandler.sendEmail.called.should.equal(true)
const args = this.EmailHandler.sendEmail.args[0]
args[0].should.equal('passwordResetRequested')
@@ -132,13 +132,13 @@ describe('PasswordResetHandler', function() {
)
})
- it('should return status == true', function() {
+ it('should return status == true', function () {
this.callback.calledWith(null, 'primary').should.equal(true)
})
})
- describe("when the email doesn't exist", function() {
- beforeEach(function() {
+ describe("when the email doesn't exist", function () {
+ beforeEach(function () {
this.UserGetter.getUserByAnyEmail.yields(null, null)
this.PasswordResetHandler.generateAndEmailResetToken(
this.email,
@@ -146,21 +146,21 @@ describe('PasswordResetHandler', function() {
)
})
- it('should not set the password token data', function() {
+ it('should not set the password token data', function () {
this.OneTimeTokenHandler.getNewToken.called.should.equal(false)
})
- it('should send an email with the token', function() {
+ it('should send an email with the token', function () {
this.EmailHandler.sendEmail.called.should.equal(false)
})
- it('should return status == null', function() {
+ it('should return status == null', function () {
this.callback.calledWith(null, null).should.equal(true)
})
})
- describe('when the email is a secondary email', function() {
- beforeEach(function() {
+ describe('when the email is a secondary email', function () {
+ beforeEach(function () {
this.UserGetter.getUserByAnyEmail.callsArgWith(1, null, this.user)
this.PasswordResetHandler.generateAndEmailResetToken(
'secondary@email.com',
@@ -168,30 +168,30 @@ describe('PasswordResetHandler', function() {
)
})
- it('should not set the password token data', function() {
+ it('should not set the password token data', function () {
this.OneTimeTokenHandler.getNewToken.called.should.equal(false)
})
- it('should not send an email with the token', function() {
+ it('should not send an email with the token', function () {
this.EmailHandler.sendEmail.called.should.equal(false)
})
- it('should return status == secondary', function() {
+ it('should return status == secondary', function () {
this.callback.calledWith(null, 'secondary').should.equal(true)
})
})
})
- describe('setNewUserPassword', function() {
- beforeEach(function() {
+ describe('setNewUserPassword', function () {
+ beforeEach(function () {
this.auditLog = { ip: '0:0:0:0' }
})
- describe('when no data is found', function() {
- beforeEach(function() {
+ describe('when no data is found', function () {
+ beforeEach(function () {
this.OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, null)
})
- it('should return found == false and reset == false', function() {
+ it('should return found == false and reset == false', function () {
this.PasswordResetHandler.setNewUserPassword(
this.token,
this.password,
@@ -208,8 +208,8 @@ describe('PasswordResetHandler', function() {
})
})
- describe('when the token has a user_id and email', function() {
- beforeEach(function() {
+ describe('when the token has a user_id and email', function () {
+ beforeEach(function () {
this.OneTimeTokenHandler.getValueFromTokenAndExpire
.withArgs('password', this.token)
.yields(null, {
@@ -221,14 +221,14 @@ describe('PasswordResetHandler', function() {
.resolves(true)
})
- describe('when no user is found with this email', function() {
- beforeEach(function() {
+ describe('when no user is found with this email', function () {
+ beforeEach(function () {
this.UserGetter.getUserByMainEmail
.withArgs(this.email)
.yields(null, null)
})
- it('should return found == false and reset == false', function(done) {
+ it('should return found == false and reset == false', function (done) {
this.PasswordResetHandler.setNewUserPassword(
this.token,
this.password,
@@ -244,14 +244,14 @@ describe('PasswordResetHandler', function() {
})
})
- describe("when the email and user don't match", function() {
- beforeEach(function() {
+ describe("when the email and user don't match", function () {
+ beforeEach(function () {
this.UserGetter.getUserByMainEmail
.withArgs(this.email)
.yields(null, { _id: 'not-the-same', email: this.email })
})
- it('should return found == false and reset == false', function(done) {
+ it('should return found == false and reset == false', function (done) {
this.PasswordResetHandler.setNewUserPassword(
this.token,
this.password,
@@ -267,13 +267,13 @@ describe('PasswordResetHandler', function() {
})
})
- describe('when the email and user match', function() {
- describe('success', function() {
- beforeEach(function() {
+ describe('when the email and user match', function () {
+ describe('success', function () {
+ beforeEach(function () {
this.UserGetter.getUserByMainEmail.yields(null, this.user)
})
- it('should update the user audit log', function(done) {
+ it('should update the user audit log', function (done) {
this.PasswordResetHandler.setNewUserPassword(
this.token,
this.password,
@@ -293,7 +293,7 @@ describe('PasswordResetHandler', function() {
)
})
- it('should return reset == true and the user id', function(done) {
+ it('should return reset == true and the user id', function (done) {
this.PasswordResetHandler.setNewUserPassword(
this.token,
this.password,
@@ -308,11 +308,11 @@ describe('PasswordResetHandler', function() {
)
})
- describe('when logged in', function() {
- beforeEach(function() {
+ describe('when logged in', function () {
+ beforeEach(function () {
this.auditLog.initiatorId = this.user_id
})
- it('should update the user audit log with initiatorId', function(done) {
+ it('should update the user audit log with initiatorId', function (done) {
this.PasswordResetHandler.setNewUserPassword(
this.token,
this.password,
@@ -334,9 +334,9 @@ describe('PasswordResetHandler', function() {
})
})
- describe('errors', function() {
- describe('via UserAuditLogHandler', function() {
- beforeEach(function() {
+ describe('errors', function () {
+ describe('via UserAuditLogHandler', function () {
+ beforeEach(function () {
this.PasswordResetHandler.promises.getUserForPasswordResetToken = sinon
.stub()
.withArgs(this.token)
@@ -345,7 +345,7 @@ describe('PasswordResetHandler', function() {
new Error('oops')
)
})
- it('should return the error', function(done) {
+ it('should return the error', function (done) {
this.PasswordResetHandler.setNewUserPassword(
this.token,
this.password,
@@ -366,8 +366,8 @@ describe('PasswordResetHandler', function() {
})
})
- describe('when the token has a v1_user_id and email', function() {
- beforeEach(function() {
+ describe('when the token has a v1_user_id and email', function () {
+ beforeEach(function () {
this.user.overleaf = { id: 184 }
this.OneTimeTokenHandler.getValueFromTokenAndExpire
.withArgs('password', this.token)
@@ -380,14 +380,14 @@ describe('PasswordResetHandler', function() {
.resolves(true)
})
- describe('when no user is reset with this email', function() {
- beforeEach(function() {
+ describe('when no user is reset with this email', function () {
+ beforeEach(function () {
this.UserGetter.getUserByMainEmail
.withArgs(this.email)
.yields(null, null)
})
- it('should return reset == false', function(done) {
+ it('should return reset == false', function (done) {
this.PasswordResetHandler.setNewUserPassword(
this.token,
this.password,
@@ -402,8 +402,8 @@ describe('PasswordResetHandler', function() {
})
})
- describe("when the email and user don't match", function() {
- beforeEach(function() {
+ describe("when the email and user don't match", function () {
+ beforeEach(function () {
this.UserGetter.getUserByMainEmail.withArgs(this.email).yields(null, {
_id: this.user._id,
email: this.email,
@@ -411,7 +411,7 @@ describe('PasswordResetHandler', function() {
})
})
- it('should return reset == false', function(done) {
+ it('should return reset == false', function (done) {
this.PasswordResetHandler.setNewUserPassword(
this.token,
this.password,
@@ -426,14 +426,14 @@ describe('PasswordResetHandler', function() {
})
})
- describe('when the email and user match', function() {
- beforeEach(function() {
+ describe('when the email and user match', function () {
+ beforeEach(function () {
this.UserGetter.getUserByMainEmail
.withArgs(this.email)
.yields(null, this.user)
})
- it('should return reset == true and the user id', function(done) {
+ it('should return reset == true and the user id', function (done) {
this.PasswordResetHandler.setNewUserPassword(
this.token,
this.password,
diff --git a/services/web/test/unit/src/Project/DocLinesComparitorTests.js b/services/web/test/unit/src/Project/DocLinesComparitorTests.js
index dc93291007..0dc9be41b7 100644
--- a/services/web/test/unit/src/Project/DocLinesComparitorTests.js
+++ b/services/web/test/unit/src/Project/DocLinesComparitorTests.js
@@ -15,75 +15,75 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/Project/DocLinesComparitor.js'
const SandboxedModule = require('sandboxed-module')
-describe('doc lines comparitor', function() {
- beforeEach(function() {
+describe('doc lines comparitor', function () {
+ beforeEach(function () {
return (this.comparitor = SandboxedModule.require(modulePath, {}))
})
- it('should return true when the lines are the same', function() {
+ it('should return true when the lines are the same', function () {
const lines1 = ['hello', 'world']
const lines2 = ['hello', 'world']
const result = this.comparitor.areSame(lines1, lines2)
return result.should.equal(true)
})
- it('should return false when the lines are different', function() {
+ it('should return false when the lines are different', function () {
const lines1 = ['hello', 'world']
const lines2 = ['diff', 'world']
const result = this.comparitor.areSame(lines1, lines2)
return result.should.equal(false)
})
- it('should return false when the lines are different', function() {
+ it('should return false when the lines are different', function () {
const lines1 = ['hello', 'world']
const lines2 = ['hello', 'wrld']
const result = this.comparitor.areSame(lines1, lines2)
return result.should.equal(false)
})
- it('should return true when the lines are same', function() {
+ it('should return true when the lines are same', function () {
const lines1 = ['hello', 'world']
const lines2 = ['hello', 'world']
const result = this.comparitor.areSame(lines1, lines2)
return result.should.equal(true)
})
- it('should return false if the doc lines are different in length', function() {
+ it('should return false if the doc lines are different in length', function () {
const lines1 = ['hello', 'world']
const lines2 = ['hello', 'world', 'please']
const result = this.comparitor.areSame(lines1, lines2)
return result.should.equal(false)
})
- it('should return false if the first array is undefined', function() {
+ it('should return false if the first array is undefined', function () {
const lines1 = undefined
const lines2 = ['hello', 'world']
const result = this.comparitor.areSame(lines1, lines2)
return result.should.equal(false)
})
- it('should return false if the second array is undefined', function() {
+ it('should return false if the second array is undefined', function () {
const lines1 = ['hello']
const lines2 = undefined
const result = this.comparitor.areSame(lines1, lines2)
return result.should.equal(false)
})
- it('should return false if the second array is not an array', function() {
+ it('should return false if the second array is not an array', function () {
const lines1 = ['hello']
const lines2 = ''
const result = this.comparitor.areSame(lines1, lines2)
return result.should.equal(false)
})
- it('should return true when comparing equal orchard docs', function() {
+ it('should return true when comparing equal orchard docs', function () {
const lines1 = [{ text: 'hello world' }]
const lines2 = [{ text: 'hello world' }]
const result = this.comparitor.areSame(lines1, lines2)
return result.should.equal(true)
})
- it('should return false when comparing different orchard docs', function() {
+ it('should return false when comparing different orchard docs', function () {
const lines1 = [{ text: 'goodbye world' }]
const lines2 = [{ text: 'hello world' }]
const result = this.comparitor.areSame(lines1, lines2)
diff --git a/services/web/test/unit/src/Project/FolderStructureBuilderTests.js b/services/web/test/unit/src/Project/FolderStructureBuilderTests.js
index d44aa4525d..73414af725 100644
--- a/services/web/test/unit/src/Project/FolderStructureBuilderTests.js
+++ b/services/web/test/unit/src/Project/FolderStructureBuilderTests.js
@@ -6,8 +6,8 @@ const MODULE_PATH =
'../../../../app/src/Features/Project/FolderStructureBuilder'
const MOCK_OBJECT_ID = 'MOCK_OBJECT_ID'
-describe('FolderStructureBuilder', function() {
- beforeEach(function() {
+describe('FolderStructureBuilder', function () {
+ beforeEach(function () {
this.ObjectId = sinon.stub().returns(MOCK_OBJECT_ID)
this.FolderStructureBuilder = SandboxedModule.require(MODULE_PATH, {
requires: {
@@ -16,13 +16,13 @@ describe('FolderStructureBuilder', function() {
})
})
- describe('buildFolderStructure', function() {
- describe('when given no documents at all', function() {
- beforeEach(function() {
+ describe('buildFolderStructure', function () {
+ describe('when given no documents at all', function () {
+ beforeEach(function () {
this.result = this.FolderStructureBuilder.buildFolderStructure([], [])
})
- it('returns an empty root folder', function() {
+ it('returns an empty root folder', function () {
expect(this.result).to.deep.equal({
_id: MOCK_OBJECT_ID,
name: 'rootFolder',
@@ -33,8 +33,8 @@ describe('FolderStructureBuilder', function() {
})
})
- describe('when given documents and files', function() {
- beforeEach(function() {
+ describe('when given documents and files', function () {
+ beforeEach(function () {
const docUploads = [
{ path: '/main.tex', doc: { _id: 'doc-1', name: 'main.tex' } },
{ path: '/foo/other.tex', doc: { _id: 'doc-2', name: 'other.tex' } },
@@ -55,7 +55,7 @@ describe('FolderStructureBuilder', function() {
)
})
- it('returns a full folder structure', function() {
+ it('returns a full folder structure', function () {
expect(this.result).to.deep.equal({
_id: MOCK_OBJECT_ID,
name: 'rootFolder',
@@ -100,8 +100,8 @@ describe('FolderStructureBuilder', function() {
})
})
- describe('when given duplicate files', function() {
- it('throws an error', function() {
+ describe('when given duplicate files', function () {
+ it('throws an error', function () {
const docUploads = [
{ path: '/foo/doc.tex', doc: { _id: 'doc-1', name: 'doc.tex' } },
{ path: '/foo/doc.tex', doc: { _id: 'doc-2', name: 'doc.tex' } }
diff --git a/services/web/test/unit/src/Project/ProjectApiControllerTests.js b/services/web/test/unit/src/Project/ProjectApiControllerTests.js
index 073fd6be70..7985ec1b98 100644
--- a/services/web/test/unit/src/Project/ProjectApiControllerTests.js
+++ b/services/web/test/unit/src/Project/ProjectApiControllerTests.js
@@ -14,8 +14,8 @@ const modulePath = '../../../../app/src/Features/Project/ProjectApiController'
const SandboxedModule = require('sandboxed-module')
const sinon = require('sinon')
-describe('Project api controller', function() {
- beforeEach(function() {
+describe('Project api controller', function () {
+ beforeEach(function () {
this.ProjectDetailsHandler = { getDetails: sinon.stub() }
this.controller = SandboxedModule.require(modulePath, {
requires: {
@@ -36,8 +36,8 @@ describe('Project api controller', function() {
return (this.projDetails = { name: 'something' })
})
- describe('getProjectDetails', function() {
- it('should ask the project details handler for proj details', function(done) {
+ describe('getProjectDetails', function () {
+ it('should ask the project details handler for proj details', function (done) {
this.ProjectDetailsHandler.getDetails.callsArgWith(
1,
null,
@@ -53,7 +53,7 @@ describe('Project api controller', function() {
return this.controller.getProjectDetails(this.req, this.res)
})
- it('should send a 500 if there is an error', function() {
+ it('should send a 500 if there is an error', function () {
this.ProjectDetailsHandler.getDetails.callsArgWith(1, 'error')
this.controller.getProjectDetails(this.req, this.res, this.next)
return this.next.calledWith('error').should.equal(true)
diff --git a/services/web/test/unit/src/Project/ProjectAuditLogHandlerTests.js b/services/web/test/unit/src/Project/ProjectAuditLogHandlerTests.js
index 19061c0434..4943f6cec2 100644
--- a/services/web/test/unit/src/Project/ProjectAuditLogHandlerTests.js
+++ b/services/web/test/unit/src/Project/ProjectAuditLogHandlerTests.js
@@ -7,8 +7,8 @@ const { Project } = require('../helpers/models/Project')
const MODULE_PATH =
'../../../../app/src/Features/Project/ProjectAuditLogHandler'
-describe('ProjectAuditLogHandler', function() {
- beforeEach(function() {
+describe('ProjectAuditLogHandler', function () {
+ beforeEach(function () {
this.projectId = ObjectId()
this.userId = ObjectId()
this.ProjectMock = sinon.mock(Project)
@@ -19,13 +19,13 @@ describe('ProjectAuditLogHandler', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
this.ProjectMock.restore()
})
- describe('addEntry', function() {
- describe('success', function() {
- beforeEach(async function() {
+ describe('addEntry', function () {
+ describe('success', function () {
+ beforeEach(async function () {
this.dbUpdate = this.ProjectMock.expects('updateOne').withArgs(
{ _id: this.projectId },
{
@@ -53,19 +53,19 @@ describe('ProjectAuditLogHandler', function() {
)
})
- it('writes a log', async function() {
+ it('writes a log', async function () {
this.ProjectMock.verify()
})
})
- describe('when the project does not exist', function() {
- beforeEach(function() {
+ describe('when the project does not exist', function () {
+ beforeEach(function () {
this.ProjectMock.expects('updateOne')
.chain('exec')
.resolves({ nModified: 0 })
})
- it('throws an error', async function() {
+ it('throws an error', async function () {
await expect(
this.ProjectAuditLogHandler.promises.addEntry(
this.projectId,
diff --git a/services/web/test/unit/src/Project/ProjectCollabratecDetailsTest.js b/services/web/test/unit/src/Project/ProjectCollabratecDetailsTest.js
index bfac5b5c5d..2f59eb90d2 100644
--- a/services/web/test/unit/src/Project/ProjectCollabratecDetailsTest.js
+++ b/services/web/test/unit/src/Project/ProjectCollabratecDetailsTest.js
@@ -23,8 +23,8 @@ const modulePath = Path.join(
'../../../../app/src/Features/Project/ProjectCollabratecDetailsHandler'
)
-describe('ProjectCollabratecDetailsHandler', function() {
- beforeEach(function() {
+describe('ProjectCollabratecDetailsHandler', function () {
+ beforeEach(function () {
this.projectId = ObjectId('5bea8747c7bba6012fcaceb3')
this.userId = ObjectId('5be316a9c7f6aa03802ea8fb')
this.userId2 = ObjectId('5c1794b3f0e89b1d1c577eca')
@@ -41,9 +41,9 @@ describe('ProjectCollabratecDetailsHandler', function() {
return (this.callback = sinon.stub())
})
- describe('initializeCollabratecProject', function() {
- describe('when update succeeds', function() {
- beforeEach(function() {
+ describe('initializeCollabratecProject', function () {
+ describe('when update succeeds', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub().yields()
return this.ProjectCollabratecDetailsHandler.initializeCollabratecProject(
this.projectId,
@@ -54,7 +54,7 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should update project model', function() {
+ it('should update project model', function () {
const update = {
$set: {
collabratecUsers: [
@@ -74,8 +74,8 @@ describe('ProjectCollabratecDetailsHandler', function() {
})
})
- describe('when update has error', function() {
- beforeEach(function() {
+ describe('when update has error', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub().yields('error')
return this.ProjectCollabratecDetailsHandler.initializeCollabratecProject(
this.projectId,
@@ -86,13 +86,13 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback).to.have.been.calledWith('error')
})
})
- describe('with invalid args', function() {
- beforeEach(function() {
+ describe('with invalid args', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub()
return this.ProjectCollabratecDetailsHandler.initializeCollabratecProject(
'bad-project-id',
@@ -103,24 +103,24 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should not update', function() {
+ it('should not update', function () {
return expect(this.ProjectModel.updateOne).not.to.have.been.called
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.firstCall.args[0]).to.be.instanceOf(Error)
})
})
})
- describe('isLinkedCollabratecUserProject', function() {
- beforeEach(function() {
+ describe('isLinkedCollabratecUserProject', function () {
+ beforeEach(function () {
return (this.ProjectModel.findOne = sinon.stub().yields())
})
- describe('when find succeeds', function() {
- describe('when user project found', function() {
- beforeEach(function() {
+ describe('when find succeeds', function () {
+ describe('when user project found', function () {
+ beforeEach(function () {
this.ProjectModel.findOne = sinon.stub().yields(null, 'project')
return this.ProjectCollabratecDetailsHandler.isLinkedCollabratecUserProject(
this.projectId,
@@ -129,7 +129,7 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should call find with project and user id', function() {
+ it('should call find with project and user id', function () {
return expect(this.ProjectModel.findOne).to.have.been.calledWithMatch(
{
_id: ObjectId(this.projectId),
@@ -142,13 +142,13 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should callback with true', function() {
+ it('should callback with true', function () {
return expect(this.callback).to.have.been.calledWith(null, true)
})
})
- describe('when user project found', function() {
- beforeEach(function() {
+ describe('when user project found', function () {
+ beforeEach(function () {
this.ProjectModel.findOne = sinon.stub().yields(null, null)
return this.ProjectCollabratecDetailsHandler.isLinkedCollabratecUserProject(
this.projectId,
@@ -157,14 +157,14 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should callback with false', function() {
+ it('should callback with false', function () {
return expect(this.callback).to.have.been.calledWith(null, false)
})
})
})
- describe('when find has error', function() {
- beforeEach(function() {
+ describe('when find has error', function () {
+ beforeEach(function () {
this.ProjectModel.findOne = sinon.stub().yields('error')
return this.ProjectCollabratecDetailsHandler.isLinkedCollabratecUserProject(
this.projectId,
@@ -173,13 +173,13 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback).to.have.been.calledWith('error')
})
})
- describe('with invalid args', function() {
- beforeEach(function() {
+ describe('with invalid args', function () {
+ beforeEach(function () {
this.ProjectModel.findOne = sinon.stub()
return this.ProjectCollabratecDetailsHandler.isLinkedCollabratecUserProject(
'bad-project-id',
@@ -188,19 +188,19 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should not update', function() {
+ it('should not update', function () {
return expect(this.ProjectModel.findOne).not.to.have.been.called
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.firstCall.args[0]).to.be.instanceOf(Error)
})
})
})
- describe('linkCollabratecUserProject', function() {
- describe('when update succeeds', function() {
- beforeEach(function() {
+ describe('linkCollabratecUserProject', function () {
+ describe('when update succeeds', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub().yields()
return this.ProjectCollabratecDetailsHandler.linkCollabratecUserProject(
this.projectId,
@@ -210,7 +210,7 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should update project model', function() {
+ it('should update project model', function () {
const query = {
_id: this.projectId,
collabratecUsers: {
@@ -238,8 +238,8 @@ describe('ProjectCollabratecDetailsHandler', function() {
})
})
- describe('when update has error', function() {
- beforeEach(function() {
+ describe('when update has error', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub().yields('error')
return this.ProjectCollabratecDetailsHandler.linkCollabratecUserProject(
this.projectId,
@@ -249,13 +249,13 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback).to.have.been.calledWith('error')
})
})
- describe('with invalid args', function() {
- beforeEach(function() {
+ describe('with invalid args', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub()
return this.ProjectCollabratecDetailsHandler.linkCollabratecUserProject(
'bad-project-id',
@@ -265,18 +265,18 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should not update', function() {
+ it('should not update', function () {
return expect(this.ProjectModel.updateOne).not.to.have.been.called
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.firstCall.args[0]).to.be.instanceOf(Error)
})
})
})
- describe('setCollabratecUsers', function() {
- beforeEach(function() {
+ describe('setCollabratecUsers', function () {
+ beforeEach(function () {
return (this.collabratecUsers = [
{
user_id: this.userId,
@@ -291,8 +291,8 @@ describe('ProjectCollabratecDetailsHandler', function() {
])
})
- describe('when update succeeds', function() {
- beforeEach(function() {
+ describe('when update succeeds', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub().yields()
return this.ProjectCollabratecDetailsHandler.setCollabratecUsers(
this.projectId,
@@ -301,7 +301,7 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should update project model', function() {
+ it('should update project model', function () {
const update = {
$set: {
collabratecUsers: this.collabratecUsers
@@ -315,8 +315,8 @@ describe('ProjectCollabratecDetailsHandler', function() {
})
})
- describe('when update has error', function() {
- beforeEach(function() {
+ describe('when update has error', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub().yields('error')
return this.ProjectCollabratecDetailsHandler.setCollabratecUsers(
this.projectId,
@@ -325,13 +325,13 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback).to.have.been.calledWith('error')
})
})
- describe('with invalid project_id', function() {
- beforeEach(function() {
+ describe('with invalid project_id', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub()
return this.ProjectCollabratecDetailsHandler.setCollabratecUsers(
'bad-project-id',
@@ -340,17 +340,17 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should not update', function() {
+ it('should not update', function () {
return expect(this.ProjectModel.updateOne).not.to.have.been.called
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.firstCall.args[0]).to.be.instanceOf(Error)
})
})
- describe('with invalid user_id', function() {
- beforeEach(function() {
+ describe('with invalid user_id', function () {
+ beforeEach(function () {
this.collabratecUsers[1].user_id = 'bad-user-id'
this.ProjectModel.updateOne = sinon.stub()
return this.ProjectCollabratecDetailsHandler.setCollabratecUsers(
@@ -360,19 +360,19 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should not update', function() {
+ it('should not update', function () {
return expect(this.ProjectModel.updateOne).not.to.have.been.called
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.firstCall.args[0]).to.be.instanceOf(Error)
})
})
})
- describe('unlinkCollabratecUserProject', function() {
- describe('when update succeeds', function() {
- beforeEach(function() {
+ describe('unlinkCollabratecUserProject', function () {
+ describe('when update succeeds', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub().yields()
return this.ProjectCollabratecDetailsHandler.unlinkCollabratecUserProject(
this.projectId,
@@ -381,7 +381,7 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should update project model', function() {
+ it('should update project model', function () {
const query = { _id: this.projectId }
const update = {
$pull: {
@@ -398,8 +398,8 @@ describe('ProjectCollabratecDetailsHandler', function() {
})
})
- describe('when update has error', function() {
- beforeEach(function() {
+ describe('when update has error', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub().yields('error')
return this.ProjectCollabratecDetailsHandler.unlinkCollabratecUserProject(
this.projectId,
@@ -408,13 +408,13 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback).to.have.been.calledWith('error')
})
})
- describe('with invalid args', function() {
- beforeEach(function() {
+ describe('with invalid args', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub()
return this.ProjectCollabratecDetailsHandler.unlinkCollabratecUserProject(
'bad-project-id',
@@ -423,19 +423,19 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should not update', function() {
+ it('should not update', function () {
return expect(this.ProjectModel.updateOne).not.to.have.been.called
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.firstCall.args[0]).to.be.instanceOf(Error)
})
})
})
- describe('updateCollabratecUserIds', function() {
- describe('when update succeeds', function() {
- beforeEach(function() {
+ describe('updateCollabratecUserIds', function () {
+ describe('when update succeeds', function () {
+ beforeEach(function () {
this.ProjectModel.updateMany = sinon.stub().yields()
return this.ProjectCollabratecDetailsHandler.updateCollabratecUserIds(
this.userId,
@@ -444,7 +444,7 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should update project model', function() {
+ it('should update project model', function () {
return expect(this.ProjectModel.updateMany).to.have.been.calledWith(
{ 'collabratecUsers.user_id': this.userId },
{ $set: { 'collabratecUsers.$.user_id': this.userId2 } },
@@ -453,8 +453,8 @@ describe('ProjectCollabratecDetailsHandler', function() {
})
})
- describe('when update has error', function() {
- beforeEach(function() {
+ describe('when update has error', function () {
+ beforeEach(function () {
this.ProjectModel.updateMany = sinon.stub().yields('error')
return this.ProjectCollabratecDetailsHandler.updateCollabratecUserIds(
this.userId,
@@ -463,13 +463,13 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback).to.have.been.calledWith('error')
})
})
- describe('with invalid old_user_id', function() {
- beforeEach(function() {
+ describe('with invalid old_user_id', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub()
return this.ProjectCollabratecDetailsHandler.updateCollabratecUserIds(
'bad-user-id',
@@ -478,17 +478,17 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should not update', function() {
+ it('should not update', function () {
return expect(this.ProjectModel.updateOne).not.to.have.been.called
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.firstCall.args[0]).to.be.instanceOf(Error)
})
})
- describe('with invalid new_user_id', function() {
- beforeEach(function() {
+ describe('with invalid new_user_id', function () {
+ beforeEach(function () {
this.ProjectModel.updateOne = sinon.stub()
return this.ProjectCollabratecDetailsHandler.updateCollabratecUserIds(
this.userId,
@@ -497,11 +497,11 @@ describe('ProjectCollabratecDetailsHandler', function() {
)
})
- it('should not update', function() {
+ it('should not update', function () {
return expect(this.ProjectModel.updateOne).not.to.have.been.called
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.firstCall.args[0]).to.be.instanceOf(Error)
})
})
diff --git a/services/web/test/unit/src/Project/ProjectControllerTests.js b/services/web/test/unit/src/Project/ProjectControllerTests.js
index 22cc4cf83b..180bc4bfa5 100644
--- a/services/web/test/unit/src/Project/ProjectControllerTests.js
+++ b/services/web/test/unit/src/Project/ProjectControllerTests.js
@@ -10,8 +10,8 @@ const MODULE_PATH = path.join(
'../../../../app/src/Features/Project/ProjectController'
)
-describe('ProjectController', function() {
- beforeEach(function() {
+describe('ProjectController', function () {
+ beforeEach(function () {
this.project_id = ObjectId('abcdefabcdefabcdefabcdef')
this.user = {
@@ -194,8 +194,8 @@ describe('ProjectController', function() {
}
})
- describe('updateProjectSettings', function() {
- it('should update the name', function(done) {
+ describe('updateProjectSettings', function () {
+ it('should update the name', function (done) {
this.EditorController.renameProject = sinon.stub().callsArg(2)
this.req.body = { name: (this.name = 'New name') }
this.res.sendStatus = code => {
@@ -208,7 +208,7 @@ describe('ProjectController', function() {
this.ProjectController.updateProjectSettings(this.req, this.res)
})
- it('should update the compiler', function(done) {
+ it('should update the compiler', function (done) {
this.EditorController.setCompiler = sinon.stub().callsArg(2)
this.req.body = { compiler: (this.compiler = 'pdflatex') }
this.res.sendStatus = code => {
@@ -221,7 +221,7 @@ describe('ProjectController', function() {
this.ProjectController.updateProjectSettings(this.req, this.res)
})
- it('should update the imageName', function(done) {
+ it('should update the imageName', function (done) {
this.EditorController.setImageName = sinon.stub().callsArg(2)
this.req.body = { imageName: (this.imageName = 'texlive-1234.5') }
this.res.sendStatus = code => {
@@ -234,7 +234,7 @@ describe('ProjectController', function() {
this.ProjectController.updateProjectSettings(this.req, this.res)
})
- it('should update the spell check language', function(done) {
+ it('should update the spell check language', function (done) {
this.EditorController.setSpellCheckLanguage = sinon.stub().callsArg(2)
this.req.body = { spellCheckLanguage: (this.languageCode = 'fr') }
this.res.sendStatus = code => {
@@ -247,7 +247,7 @@ describe('ProjectController', function() {
this.ProjectController.updateProjectSettings(this.req, this.res)
})
- it('should update the root doc', function(done) {
+ it('should update the root doc', function (done) {
this.EditorController.setRootDoc = sinon.stub().callsArg(2)
this.req.body = { rootDocId: (this.rootDocId = 'root-doc-id') }
this.res.sendStatus = code => {
@@ -261,8 +261,8 @@ describe('ProjectController', function() {
})
})
- describe('updateProjectAdminSettings', function() {
- it('should update the public access level', function(done) {
+ describe('updateProjectAdminSettings', function () {
+ it('should update the public access level', function (done) {
this.EditorController.setPublicAccessLevel = sinon.stub().callsArg(2)
this.req.body = {
publicAccessLevel: (this.publicAccessLevel = 'readonly')
@@ -278,8 +278,8 @@ describe('ProjectController', function() {
})
})
- describe('deleteProject', function() {
- it('should call the project deleter', function(done) {
+ describe('deleteProject', function () {
+ it('should call the project deleter', function (done) {
this.res.sendStatus = code => {
this.ProjectDeleter.deleteProject
.calledWith(this.project_id, {
@@ -294,8 +294,8 @@ describe('ProjectController', function() {
})
})
- describe('restoreProject', function() {
- it('should tell the project deleter', function(done) {
+ describe('restoreProject', function () {
+ it('should tell the project deleter', function (done) {
this.res.sendStatus = code => {
this.ProjectDeleter.restoreProject
.calledWith(this.project_id)
@@ -307,8 +307,8 @@ describe('ProjectController', function() {
})
})
- describe('cloneProject', function() {
- it('should call the project duplicator', function(done) {
+ describe('cloneProject', function () {
+ it('should call the project duplicator', function (done) {
this.res.send = json => {
this.ProjectDuplicator.duplicate
.calledWith(this.user, this.project_id, this.projectName)
@@ -320,8 +320,8 @@ describe('ProjectController', function() {
})
})
- describe('newProject', function() {
- it('should call the projectCreationHandler with createExampleProject', function(done) {
+ describe('newProject', function () {
+ it('should call the projectCreationHandler with createExampleProject', function (done) {
this.req.body.template = 'example'
this.res.send = json => {
this.ProjectCreationHandler.createExampleProject
@@ -335,7 +335,7 @@ describe('ProjectController', function() {
this.ProjectController.newProject(this.req, this.res)
})
- it('should call the projectCreationHandler with createBasicProject', function(done) {
+ it('should call the projectCreationHandler with createBasicProject', function (done) {
this.req.body.template = 'basic'
this.res.send = json => {
this.ProjectCreationHandler.createExampleProject.called.should.equal(
@@ -350,8 +350,8 @@ describe('ProjectController', function() {
})
})
- describe('projectListPage', function() {
- beforeEach(function() {
+ describe('projectListPage', function () {
+ beforeEach(function () {
this.tags = [
{ name: 1, project_ids: ['1', '2', '3'] },
{ name: 2, project_ids: ['a', '1'] },
@@ -404,7 +404,7 @@ describe('ProjectController', function() {
)
})
- it('should render the project/list page', function(done) {
+ it('should render the project/list page', function (done) {
this.res.render = (pageName, opts) => {
pageName.should.equal('project/list')
done()
@@ -412,7 +412,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should send the tags', function(done) {
+ it('should send the tags', function (done) {
this.res.render = (pageName, opts) => {
opts.tags.length.should.equal(this.tags.length)
done()
@@ -420,7 +420,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should create trigger ip matcher notifications', function(done) {
+ it('should create trigger ip matcher notifications', function (done) {
this.settings.overleaf = true
this.res.render = (pageName, opts) => {
this.NotificationBuilder.ipMatcherAffiliation.called.should.equal(true)
@@ -429,7 +429,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should send the projects', function(done) {
+ it('should send the projects', function (done) {
this.res.render = (pageName, opts) => {
opts.projects.length.should.equal(
this.projects.length +
@@ -443,7 +443,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should send the user', function(done) {
+ it('should send the user', function (done) {
this.res.render = (pageName, opts) => {
opts.user.should.deep.equal(this.user)
done()
@@ -451,7 +451,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should inject the users', function(done) {
+ it('should inject the users', function (done) {
this.res.render = (pageName, opts) => {
opts.projects[0].owner.should.equal(
this.users[this.projects[0].owner_ref]
@@ -467,7 +467,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should send hasSubscription == false when no subscription', function(done) {
+ it('should send hasSubscription == false when no subscription', function (done) {
this.res.render = (pageName, opts) => {
opts.hasSubscription.should.equal(false)
done()
@@ -475,7 +475,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should send hasSubscription == true when there is a subscription', function(done) {
+ it('should send hasSubscription == true when there is a subscription', function (done) {
this.LimitationsManager.hasPaidSubscription = sinon
.stub()
.callsArgWith(1, null, true)
@@ -486,14 +486,14 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- describe('front widget', function(done) {
- beforeEach(function() {
+ describe('front widget', function (done) {
+ beforeEach(function () {
this.settings.overleaf = {
front_chat_widget_room_id: 'chat-room-id'
}
})
- it('should show for paid users', function(done) {
+ it('should show for paid users', function (done) {
this.user.features.github = true
this.user.features.dropbox = true
this.res.render = (pageName, opts) => {
@@ -505,7 +505,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should show for sample users', function(done) {
+ it('should show for sample users', function (done) {
this.user._id = ObjectId('588f3ddae8ebc1bac07c9f00') // last two digits
this.res.render = (pageName, opts) => {
opts.frontChatWidgetRoomId.should.equal(
@@ -516,7 +516,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should not show for non sample users', function(done) {
+ it('should not show for non sample users', function (done) {
this.user._id = ObjectId('588f3ddae8ebc1bac07c9fff') // last two digits
this.res.render = (pageName, opts) => {
expect(opts.frontChatWidgetRoomId).to.equal(undefined)
@@ -526,8 +526,8 @@ describe('ProjectController', function() {
})
})
- describe('With Institution SSO feature', function() {
- beforeEach(function(done) {
+ describe('With Institution SSO feature', function () {
+ beforeEach(function (done) {
this.institutionEmail = 'test@overleaf.com'
this.institutionName = 'Overleaf'
this.Features.hasFeature.withArgs('saml').returns(true)
@@ -535,7 +535,7 @@ describe('ProjectController', function() {
this.Features.hasFeature.withArgs('overleaf-integration').returns(true)
done()
})
- it('should show institution SSO available notification for confirmed domains', function() {
+ it('should show institution SSO available notification for confirmed domains', function () {
this.UserGetter.getUserFullEmails.yields(null, [
{
email: 'test@overleaf.com',
@@ -560,7 +560,7 @@ describe('ProjectController', function() {
}
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should show a linked notification', function() {
+ it('should show a linked notification', function () {
this.req.session.saml = {
institutionEmail: this.institutionEmail,
linked: {
@@ -577,7 +577,7 @@ describe('ProjectController', function() {
}
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should show a linked another email notification', function() {
+ it('should show a linked another email notification', function () {
// when they request to link an email but the institution returns
// a different email
this.res.render = (pageName, opts) => {
@@ -599,7 +599,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should show a notification when intent was to register via SSO but account existed', function() {
+ it('should show a notification when intent was to register via SSO but account existed', function () {
this.res.render = (pageName, opts) => {
expect(opts.notificationsInstitution).to.deep.include({
email: this.institutionEmail,
@@ -620,7 +620,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should not show a register notification if the flow was abandoned', function() {
+ it('should not show a register notification if the flow was abandoned', function () {
// could initially start to register with an SSO email and then
// abandon flow and login with an existing non-institution SSO email
this.res.render = (pageName, opts) => {
@@ -638,7 +638,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should show error notification', function() {
+ it('should show error notification', function () {
this.res.render = (pageName, opts) => {
expect(opts.notificationsInstitution.length).to.equal(1)
expect(opts.notificationsInstitution[0].templateKey).to.equal(
@@ -655,8 +655,8 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- describe('for an unconfirmed domain for an SSO institution', function() {
- beforeEach(function(done) {
+ describe('for an unconfirmed domain for an SSO institution', function () {
+ beforeEach(function (done) {
this.UserGetter.getUserFullEmails.yields(null, [
{
email: 'test@overleaf-uncofirmed.com',
@@ -673,15 +673,15 @@ describe('ProjectController', function() {
])
done()
})
- it('should not show institution SSO available notification', function() {
+ it('should not show institution SSO available notification', function () {
this.res.render = (pageName, opts) => {
expect(opts.notificationsInstitution.length).to.equal(0)
}
this.ProjectController.projectListPage(this.req, this.res)
})
})
- describe('when linking/logging in initiated on institution side', function() {
- it('should not show a linked another email notification', function() {
+ describe('when linking/logging in initiated on institution side', function () {
+ it('should not show a linked another email notification', function () {
// this is only used when initated on Overleaf,
// because we keep track of the requested email they tried to link
this.res.render = (pageName, opts) => {
@@ -702,8 +702,8 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
})
- describe('Institution with SSO beta testable', function() {
- beforeEach(function(done) {
+ describe('Institution with SSO beta testable', function () {
+ beforeEach(function (done) {
this.UserGetter.getUserFullEmails.yields(null, [
{
email: 'beta@beta.com',
@@ -720,7 +720,7 @@ describe('ProjectController', function() {
])
done()
})
- it('should show institution SSO available notification when on a beta testing session', function() {
+ it('should show institution SSO available notification when on a beta testing session', function () {
this.req.session.samlBeta = true
this.res.render = (pageName, opts) => {
expect(opts.notificationsInstitution).to.deep.include({
@@ -732,7 +732,7 @@ describe('ProjectController', function() {
}
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should not show institution SSO available notification when not on a beta testing session', function() {
+ it('should not show institution SSO available notification when not on a beta testing session', function () {
this.req.session.samlBeta = false
this.res.render = (pageName, opts) => {
expect(opts.notificationsInstitution).to.deep.not.include({
@@ -747,12 +747,12 @@ describe('ProjectController', function() {
})
})
- describe('Without Institution SSO feature', function() {
- beforeEach(function(done) {
+ describe('Without Institution SSO feature', function () {
+ beforeEach(function (done) {
this.Features.hasFeature.withArgs('saml').returns(false)
done()
})
- it('should not show institution sso available notification', function() {
+ it('should not show institution sso available notification', function () {
this.res.render = (pageName, opts) => {
expect(opts.notificationsInstitution).to.deep.not.include({
email: 'test@overleaf.com',
@@ -766,8 +766,8 @@ describe('ProjectController', function() {
})
})
- describe('projectListPage with duplicate projects', function() {
- beforeEach(function() {
+ describe('projectListPage with duplicate projects', function () {
+ beforeEach(function () {
this.tags = [
{ name: 1, project_ids: ['1', '2', '3'] },
{ name: 2, project_ids: ['a', '1'] },
@@ -820,7 +820,7 @@ describe('ProjectController', function() {
)
})
- it('should render the project/list page', function(done) {
+ it('should render the project/list page', function (done) {
this.res.render = (pageName, opts) => {
pageName.should.equal('project/list')
done()
@@ -828,7 +828,7 @@ describe('ProjectController', function() {
this.ProjectController.projectListPage(this.req, this.res)
})
- it('should omit one of the projects', function(done) {
+ it('should omit one of the projects', function (done) {
this.res.render = (pageName, opts) => {
opts.projects.length.should.equal(
this.projects.length +
@@ -844,13 +844,13 @@ describe('ProjectController', function() {
})
})
- describe('renameProject', function() {
- beforeEach(function() {
+ describe('renameProject', function () {
+ beforeEach(function () {
this.newProjectName = 'my supper great new project'
this.req.body.newProjectName = this.newProjectName
})
- it('should call the editor controller', function(done) {
+ it('should call the editor controller', function (done) {
this.EditorController.renameProject.callsArgWith(2)
this.res.sendStatus = code => {
code.should.equal(200)
@@ -862,7 +862,7 @@ describe('ProjectController', function() {
this.ProjectController.renameProject(this.req, this.res)
})
- it('should send an error to next() if there is a problem', function(done) {
+ it('should send an error to next() if there is a problem', function (done) {
let error
this.EditorController.renameProject.callsArgWith(
2,
@@ -876,8 +876,8 @@ describe('ProjectController', function() {
})
})
- describe('loadEditor', function() {
- beforeEach(function() {
+ describe('loadEditor', function () {
+ beforeEach(function () {
this.settings.editorIsOpen = true
this.project = {
name: 'my proj',
@@ -911,7 +911,7 @@ describe('ProjectController', function() {
this.ProjectUpdateHandler.markAsOpened.callsArgWith(1)
})
- it('should render the project/editor page', function(done) {
+ it('should render the project/editor page', function (done) {
this.res.render = (pageName, opts) => {
pageName.should.equal('project/editor')
done()
@@ -919,7 +919,7 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- it('should add user', function(done) {
+ it('should add user', function (done) {
this.res.render = (pageName, opts) => {
opts.user.email.should.equal(this.user.email)
done()
@@ -927,7 +927,7 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- it('should add on userSettings', function(done) {
+ it('should add on userSettings', function (done) {
this.res.render = (pageName, opts) => {
opts.userSettings.fontSize.should.equal(this.user.ace.fontSize)
opts.userSettings.editorTheme.should.equal(this.user.ace.theme)
@@ -936,7 +936,7 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- it('should add isRestrictedTokenMember', function(done) {
+ it('should add isRestrictedTokenMember', function (done) {
this.res.render = (pageName, opts) => {
opts.isRestrictedTokenMember.should.exist
opts.isRestrictedTokenMember.should.equal(false)
@@ -945,7 +945,7 @@ describe('ProjectController', function() {
return this.ProjectController.loadEditor(this.req, this.res)
})
- it('should set isRestrictedTokenMember when appropriate', function(done) {
+ it('should set isRestrictedTokenMember when appropriate', function (done) {
this.AuthorizationManager.isRestrictedUser.returns(true)
this.res.render = (pageName, opts) => {
opts.isRestrictedTokenMember.should.exist
@@ -955,7 +955,7 @@ describe('ProjectController', function() {
return this.ProjectController.loadEditor(this.req, this.res)
})
- it('should render the closed page if the editor is closed', function(done) {
+ it('should render the closed page if the editor is closed', function (done) {
this.settings.editorIsOpen = false
this.res.render = (pageName, opts) => {
pageName.should.equal('general/closed')
@@ -964,7 +964,7 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- it('should not render the page if the project can not be accessed', function(done) {
+ it('should not render the page if the project can not be accessed', function (done) {
this.AuthorizationManager.getPrivilegeLevelForProject = sinon
.stub()
.callsArgWith(3, null, null)
@@ -975,7 +975,7 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- it('should reactivateProjectIfRequired', function(done) {
+ it('should reactivateProjectIfRequired', function (done) {
this.res.render = (pageName, opts) => {
this.InactiveProjectManager.reactivateProjectIfRequired
.calledWith(this.project_id)
@@ -985,7 +985,7 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- it('should mark project as opened', function(done) {
+ it('should mark project as opened', function (done) {
this.res.render = (pageName, opts) => {
this.ProjectUpdateHandler.markAsOpened
.calledWith(this.project_id)
@@ -995,7 +995,7 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- it('should call the brand variations handler for branded projects', function(done) {
+ it('should call the brand variations handler for branded projects', function (done) {
this.ProjectGetter.getProject.callsArgWith(2, null, this.brandedProject)
this.res.render = (pageName, opts) => {
this.BrandVariationsHandler.getBrandVariationById
@@ -1006,7 +1006,7 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- it('should not call the brand variations handler for unbranded projects', function(done) {
+ it('should not call the brand variations handler for unbranded projects', function (done) {
this.res.render = (pageName, opts) => {
this.BrandVariationsHandler.getBrandVariationById.called.should.equal(
false
@@ -1016,7 +1016,7 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- it('should expose the brand variation details as locals for branded projects', function(done) {
+ it('should expose the brand variation details as locals for branded projects', function (done) {
this.ProjectGetter.getProject.callsArgWith(2, null, this.brandedProject)
this.res.render = (pageName, opts) => {
opts.brandVariation.should.deep.equal(this.brandVariationDetails)
@@ -1025,7 +1025,7 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- it('flushes the project to TPDS if a flush is pending', function(done) {
+ it('flushes the project to TPDS if a flush is pending', function (done) {
this.res.render = () => {
this.TpdsProjectFlusher.flushProjectToTpdsIfNeeded.should.have.been.calledWith(
this.project_id
@@ -1035,9 +1035,9 @@ describe('ProjectController', function() {
this.ProjectController.loadEditor(this.req, this.res)
})
- describe('wsUrl', function() {
+ describe('wsUrl', function () {
function checkLoadEditorWsMetric(metric) {
- it(`should inc metric ${metric}`, function(done) {
+ it(`should inc metric ${metric}`, function (done) {
this.res.render = () => {
this.Metrics.inc.calledWith(metric).should.equal(true)
done()
@@ -1046,12 +1046,12 @@ describe('ProjectController', function() {
})
}
function checkWsFallback(isBeta, isV2) {
- describe('with ws=fallback', function() {
- beforeEach(function() {
+ describe('with ws=fallback', function () {
+ beforeEach(function () {
this.req.query = {}
this.req.query.ws = 'fallback'
})
- it('should unset the wsUrl', function(done) {
+ it('should unset the wsUrl', function (done) {
this.res.render = (pageName, opts) => {
;(opts.wsUrl || '/socket.io').should.equal('/socket.io')
done()
@@ -1066,10 +1066,10 @@ describe('ProjectController', function() {
})
}
- beforeEach(function() {
+ beforeEach(function () {
this.settings.wsUrl = '/other.socket.io'
})
- it('should set the custom wsUrl', function(done) {
+ it('should set the custom wsUrl', function (done) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/other.socket.io')
done()
@@ -1079,12 +1079,12 @@ describe('ProjectController', function() {
checkLoadEditorWsMetric('load-editor-ws')
checkWsFallback(false)
- describe('beta program', function() {
- beforeEach(function() {
+ describe('beta program', function () {
+ beforeEach(function () {
this.settings.wsUrlBeta = '/beta.socket.io'
})
- describe('for a normal user', function() {
- it('should set the normal custom wsUrl', function(done) {
+ describe('for a normal user', function () {
+ it('should set the normal custom wsUrl', function (done) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/other.socket.io')
done()
@@ -1095,11 +1095,11 @@ describe('ProjectController', function() {
checkWsFallback(false)
})
- describe('for a beta user', function() {
- beforeEach(function() {
+ describe('for a beta user', function () {
+ beforeEach(function () {
this.user.betaProgram = true
})
- it('should set the beta wsUrl', function(done) {
+ it('should set the beta wsUrl', function (done) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/beta.socket.io')
done()
@@ -1111,14 +1111,14 @@ describe('ProjectController', function() {
})
})
- describe('v2-rollout', function() {
- beforeEach(function() {
+ describe('v2-rollout', function () {
+ beforeEach(function () {
this.settings.wsUrlBeta = '/beta.socket.io'
this.settings.wsUrlV2 = '/socket.io.v2'
})
function checkNonMatch() {
- it('should set the normal custom wsUrl', function(done) {
+ it('should set the normal custom wsUrl', function (done) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/other.socket.io')
done()
@@ -1129,7 +1129,7 @@ describe('ProjectController', function() {
checkWsFallback(false)
}
function checkMatch() {
- it('should set the v2 wsUrl', function(done) {
+ it('should set the v2 wsUrl', function (done) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/socket.io.v2')
done()
@@ -1140,11 +1140,11 @@ describe('ProjectController', function() {
checkWsFallback(false, true)
}
function checkForBetaUser() {
- describe('for a beta user', function() {
- beforeEach(function() {
+ describe('for a beta user', function () {
+ beforeEach(function () {
this.user.betaProgram = true
})
- it('should set the beta wsUrl', function(done) {
+ it('should set the beta wsUrl', function (done) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/beta.socket.io')
done()
@@ -1156,105 +1156,105 @@ describe('ProjectController', function() {
})
}
- describe('when the roll out percentage is 0', function() {
- beforeEach(function() {
+ describe('when the roll out percentage is 0', function () {
+ beforeEach(function () {
this.settings.wsUrlV2Percentage = 0
})
- describe('when the projectId does not match (0)', function() {
- beforeEach(function() {
+ describe('when the projectId does not match (0)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(0)
})
checkNonMatch()
})
- describe('when the projectId does not match (42)', function() {
- beforeEach(function() {
+ describe('when the projectId does not match (42)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(42)
})
checkNonMatch()
})
checkForBetaUser()
})
- describe('when the roll out percentage is 1', function() {
- beforeEach(function() {
+ describe('when the roll out percentage is 1', function () {
+ beforeEach(function () {
this.settings.wsUrlV2Percentage = 1
})
- describe('when the projectId matches (0)', function() {
- beforeEach(function() {
+ describe('when the projectId matches (0)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(0)
})
checkMatch()
checkForBetaUser()
})
- describe('when the projectId does not match (1)', function() {
- beforeEach(function() {
+ describe('when the projectId does not match (1)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(1)
})
checkNonMatch()
checkForBetaUser()
})
- describe('when the projectId does not match (42)', function() {
- beforeEach(function() {
+ describe('when the projectId does not match (42)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(42)
})
checkNonMatch()
})
})
- describe('when the roll out percentage is 10', function() {
- beforeEach(function() {
+ describe('when the roll out percentage is 10', function () {
+ beforeEach(function () {
this.settings.wsUrlV2Percentage = 10
})
- describe('when the projectId matches (0)', function() {
- beforeEach(function() {
+ describe('when the projectId matches (0)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(0)
})
checkMatch()
})
- describe('when the projectId matches (9)', function() {
- beforeEach(function() {
+ describe('when the projectId matches (9)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(9)
})
checkMatch()
checkForBetaUser()
})
- describe('when the projectId does not match (10)', function() {
- beforeEach(function() {
+ describe('when the projectId does not match (10)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(10)
})
checkNonMatch()
})
- describe('when the projectId does not match (42)', function() {
- beforeEach(function() {
+ describe('when the projectId does not match (42)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(42)
})
checkNonMatch()
checkForBetaUser()
})
})
- describe('when the roll out percentage is 100', function() {
- beforeEach(function() {
+ describe('when the roll out percentage is 100', function () {
+ beforeEach(function () {
this.settings.wsUrlV2Percentage = 100
})
- describe('when the projectId matches (0)', function() {
- beforeEach(function() {
+ describe('when the projectId matches (0)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(0)
})
checkMatch()
checkForBetaUser()
})
- describe('when the projectId matches (10)', function() {
- beforeEach(function() {
+ describe('when the projectId matches (10)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(10)
})
checkMatch()
})
- describe('when the projectId matches (42)', function() {
- beforeEach(function() {
+ describe('when the projectId matches (42)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(42)
})
checkMatch()
})
- describe('when the projectId matches (99)', function() {
- beforeEach(function() {
+ describe('when the projectId matches (99)', function () {
+ beforeEach(function () {
this.req.params.Project_id = ObjectId.createFromTime(99)
})
checkMatch()
@@ -1264,8 +1264,8 @@ describe('ProjectController', function() {
})
})
- describe('userProjectsJson', function() {
- beforeEach(function(done) {
+ describe('userProjectsJson', function () {
+ beforeEach(function (done) {
const projects = [
{
archived: true,
@@ -1323,7 +1323,7 @@ describe('ProjectController', function() {
done()
})
- it('should produce a list of projects', function(done) {
+ it('should produce a list of projects', function (done) {
this.res.json = data => {
expect(data).to.deep.equal({
projects: [
@@ -1337,8 +1337,8 @@ describe('ProjectController', function() {
})
})
- describe('projectEntitiesJson', function() {
- beforeEach(function() {
+ describe('projectEntitiesJson', function () {
+ beforeEach(function () {
this.AuthenticationController.getLoggedInUserId = sinon
.stub()
.returns('abc')
@@ -1357,7 +1357,7 @@ describe('ProjectController', function() {
.callsArgWith(1, null, this.docs, this.files)
})
- it('should produce a list of entities', function(done) {
+ it('should produce a list of entities', function (done) {
this.res.json = data => {
expect(data).to.deep.equal({
project_id: 'abcd',
@@ -1377,8 +1377,8 @@ describe('ProjectController', function() {
})
})
- describe('_buildProjectViewModel', function() {
- beforeEach(function() {
+ describe('_buildProjectViewModel', function () {
+ beforeEach(function () {
this.ProjectHelper.isArchived.returns(false)
this.ProjectHelper.isTrashed.returns(false)
@@ -1398,8 +1398,8 @@ describe('ProjectController', function() {
}
})
- describe('project not being archived or trashed', function() {
- it('should produce a model of the project', function() {
+ describe('project not being archived or trashed', function () {
+ it('should produce a model of the project', function () {
const result = this.ProjectController._buildProjectViewModel(
this.project,
'readAndWrite',
@@ -1424,13 +1424,13 @@ describe('ProjectController', function() {
})
})
- describe('project being simultaneously archived and trashed', function() {
- beforeEach(function() {
+ describe('project being simultaneously archived and trashed', function () {
+ beforeEach(function () {
this.ProjectHelper.isArchived.returns(true)
this.ProjectHelper.isTrashed.returns(true)
})
- it('should produce a model of the project', function() {
+ it('should produce a model of the project', function () {
const result = this.ProjectController._buildProjectViewModel(
this.project,
'readAndWrite',
@@ -1455,8 +1455,8 @@ describe('ProjectController', function() {
})
})
- describe('when token-read-only access', function() {
- it('should redact the owner and last-updated data', function() {
+ describe('when token-read-only access', function () {
+ it('should redact the owner and last-updated data', function () {
const result = this.ProjectController._buildProjectViewModel(
this.project,
'readOnly',
@@ -1481,8 +1481,8 @@ describe('ProjectController', function() {
})
})
})
- describe('_isInPercentageRollout', function() {
- before(function() {
+ describe('_isInPercentageRollout', function () {
+ before(function () {
this.ids = [
'5a05cd7621f9fe22be131740',
'5a05cd7821f9fe22be131741',
@@ -1507,7 +1507,7 @@ describe('ProjectController', function() {
]
})
- it('should produce the expected results', function() {
+ it('should produce the expected results', function () {
expect(
this.ids.map(i =>
this.ProjectController._isInPercentageRollout('abcd', i, 50)
diff --git a/services/web/test/unit/src/Project/ProjectCreationHandlerTests.js b/services/web/test/unit/src/Project/ProjectCreationHandlerTests.js
index 8f3f1658e0..e4da7c1a07 100644
--- a/services/web/test/unit/src/Project/ProjectCreationHandlerTests.js
+++ b/services/web/test/unit/src/Project/ProjectCreationHandlerTests.js
@@ -6,14 +6,14 @@ const SandboxedModule = require('sandboxed-module')
const Path = require('path')
const { ObjectId } = require('mongodb')
-describe('ProjectCreationHandler', function() {
+describe('ProjectCreationHandler', function () {
const ownerId = '4eecb1c1bffa66588e0000a1'
const projectName = 'project name goes here'
const projectId = '4eecaffcbffa66588e000008'
const docId = '4eecb17ebffa66588e00003f'
const rootFolderId = '234adfa3r2afe'
- beforeEach(function() {
+ beforeEach(function () {
this.ProjectModel = class Project {
constructor(options) {
if (options == null) {
@@ -81,8 +81,8 @@ describe('ProjectCreationHandler', function() {
})
})
- describe('Creating a Blank project', function() {
- beforeEach(function() {
+ describe('Creating a Blank project', function () {
+ beforeEach(function () {
this.overleafId = 1234
this.HistoryManager.initializeProject = sinon
.stub()
@@ -90,15 +90,15 @@ describe('ProjectCreationHandler', function() {
this.ProjectModel.prototype.save = sinon.stub().callsArg(0)
})
- describe('successfully', function() {
- it('should save the project', function(done) {
+ describe('successfully', function () {
+ it('should save the project', function (done) {
this.handler.createBlankProject(ownerId, projectName, () => {
this.ProjectModel.prototype.save.called.should.equal(true)
done()
})
})
- it('should return the project in the callback', function(done) {
+ it('should return the project in the callback', function (done) {
this.handler.createBlankProject(
ownerId,
projectName,
@@ -114,12 +114,12 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should initialize the project overleaf if history id not provided', function(done) {
+ it('should initialize the project overleaf if history id not provided', function (done) {
this.handler.createBlankProject(ownerId, projectName, done)
this.HistoryManager.initializeProject.calledWith().should.equal(true)
})
- it('should set the overleaf id if overleaf id not provided', function(done) {
+ it('should set the overleaf id if overleaf id not provided', function (done) {
this.handler.createBlankProject(
ownerId,
projectName,
@@ -133,7 +133,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should set the overleaf id if overleaf id provided', function(done) {
+ it('should set the overleaf id if overleaf id provided', function (done) {
const overleafId = 2345
const attributes = {
overleaf: {
@@ -156,7 +156,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should set the language from the user', function(done) {
+ it('should set the language from the user', function (done) {
this.handler.createBlankProject(
ownerId,
projectName,
@@ -170,7 +170,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should set the imageName to currentImageName if set and no imageName attribute', function(done) {
+ it('should set the imageName to currentImageName if set and no imageName attribute', function (done) {
this.Settings.currentImageName = 'mock-image-name'
this.handler.createBlankProject(
ownerId,
@@ -185,7 +185,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should not set the imageName if no currentImageName', function(done) {
+ it('should not set the imageName if no currentImageName', function (done) {
this.Settings.currentImageName = null
this.handler.createBlankProject(
ownerId,
@@ -200,7 +200,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should set the imageName to the attribute value if set and not overwrite it with the currentImageName', function(done) {
+ it('should set the imageName to the attribute value if set and not overwrite it with the currentImageName', function (done) {
this.Settings.currentImageName = 'mock-image-name'
const attributes = { imageName: 'attribute-image-name' }
this.handler.createBlankProject(
@@ -217,7 +217,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should not set the overleaf.history.display if not configured in settings', function(done) {
+ it('should not set the overleaf.history.display if not configured in settings', function (done) {
this.Settings.apis.project_history.displayHistoryForNewProjects = false
this.handler.createBlankProject(
ownerId,
@@ -232,7 +232,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should set the overleaf.history.display if configured in settings', function(done) {
+ it('should set the overleaf.history.display if configured in settings', function (done) {
this.Settings.apis.project_history.displayHistoryForNewProjects = true
this.handler.createBlankProject(
ownerId,
@@ -247,7 +247,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should send a project-created event to analytics', function(done) {
+ it('should send a project-created event to analytics', function (done) {
this.handler.createBlankProject(
ownerId,
projectName,
@@ -267,7 +267,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should send a project-created event with template information if provided', function(done) {
+ it('should send a project-created event with template information if provided', function (done) {
const attributes = {
fromV1TemplateId: 100
}
@@ -292,7 +292,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should send a project-imported event when importing a project', function(done) {
+ it('should send a project-imported event when importing a project', function (done) {
const attributes = {
overleaf: {
history: {
@@ -321,41 +321,41 @@ describe('ProjectCreationHandler', function() {
})
})
- describe('with an error', function() {
- beforeEach(function() {
+ describe('with an error', function () {
+ beforeEach(function () {
this.ProjectModel.prototype.save = sinon
.stub()
.callsArgWith(0, new Error('something went wrong'))
this.handler.createBlankProject(ownerId, projectName, this.callback)
})
- it('should return the error to the callback', function() {
+ it('should return the error to the callback', function () {
expect(this.callback.args[0][0]).to.exist
})
})
- describe('with an invalid name', function() {
- beforeEach(function() {
+ describe('with an invalid name', function () {
+ beforeEach(function () {
this.ProjectDetailsHandler.validateProjectName = sinon
.stub()
.yields(new Error('bad name'))
this.handler.createBlankProject(ownerId, projectName, this.callback)
})
- it('should return the error to the callback', function() {
+ it('should return the error to the callback', function () {
expect(this.callback.args[0][0]).to.exist
})
- it('should not try to create the project', function() {
+ it('should not try to create the project', function () {
this.ProjectModel.prototype.save.called.should.equal(false)
})
})
})
- describe('Creating a basic project', function() {
- beforeEach(function() {
+ describe('Creating a basic project', function () {
+ beforeEach(function () {
this.project = new this.ProjectModel()
- this.handler._buildTemplate = function(
+ this.handler._buildTemplate = function (
templateName,
user,
projectName,
@@ -376,27 +376,27 @@ describe('ProjectCreationHandler', function() {
this.handler.createBasicProject(ownerId, projectName, this.callback)
})
- it('should create a blank project first', function() {
+ it('should create a blank project first', function () {
this.handler.createBlankProject
.calledWith(ownerId, projectName)
.should.equal(true)
})
- it('should create the root document', function() {
+ it('should create the root document', function () {
this.handler._createRootDoc
.calledWith(this.project, ownerId, ['mainbasic.tex', 'lines'])
.should.equal(true)
})
- it('should build the mainbasic.tex template', function() {
+ it('should build the mainbasic.tex template', function () {
this.handler._buildTemplate
.calledWith('mainbasic.tex', ownerId, projectName)
.should.equal(true)
})
})
- describe('Creating a project from a snippet', function() {
- beforeEach(function() {
+ describe('Creating a project from a snippet', function () {
+ beforeEach(function () {
this.project = new this.ProjectModel()
this.handler.createBlankProject = sinon
.stub()
@@ -412,23 +412,23 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should create a blank project first', function() {
+ it('should create a blank project first', function () {
this.handler.createBlankProject
.calledWith(ownerId, projectName)
.should.equal(true)
})
- it('should create the root document', function() {
+ it('should create the root document', function () {
this.handler._createRootDoc
.calledWith(this.project, ownerId, ['snippet line 1', 'snippet line 2'])
.should.equal(true)
})
})
- describe('Creating an example project', function() {
- beforeEach(function() {
+ describe('Creating an example project', function () {
+ beforeEach(function () {
this.project = new this.ProjectModel()
- this.handler._buildTemplate = function(
+ this.handler._buildTemplate = function (
templateName,
user,
projectName,
@@ -452,19 +452,19 @@ describe('ProjectCreationHandler', function() {
this.handler.createExampleProject(ownerId, projectName, this.callback)
})
- it('should create a blank project first', function() {
+ it('should create a blank project first', function () {
this.handler.createBlankProject
.calledWith(ownerId, projectName)
.should.equal(true)
})
- it('should create the root document', function() {
+ it('should create the root document', function () {
this.handler._createRootDoc
.calledWith(this.project, ownerId, ['main.tex', 'lines'])
.should.equal(true)
})
- it('should insert references.bib', function() {
+ it('should insert references.bib', function () {
this.ProjectEntityUpdateHandler.addDoc
.calledWith(
projectId,
@@ -476,7 +476,7 @@ describe('ProjectCreationHandler', function() {
.should.equal(true)
})
- it('should insert universe.jpg', function() {
+ it('should insert universe.jpg', function () {
this.ProjectEntityUpdateHandler.addFile
.calledWith(
projectId,
@@ -494,21 +494,21 @@ describe('ProjectCreationHandler', function() {
.should.equal(true)
})
- it('should build the main.tex template', function() {
+ it('should build the main.tex template', function () {
this.handler._buildTemplate
.calledWith('main.tex', ownerId, projectName)
.should.equal(true)
})
- it('should build the references.bib template', function() {
+ it('should build the references.bib template', function () {
this.handler._buildTemplate
.calledWith('references.bib', ownerId, projectName)
.should.equal(true)
})
})
- describe('_buildTemplate', function() {
- beforeEach(function(done) {
+ describe('_buildTemplate', function () {
+ beforeEach(function (done) {
this.handler._buildTemplate(
'main.tex',
this.user_id,
@@ -525,36 +525,36 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should insert the project name into the template', function(done) {
+ it('should insert the project name into the template', function (done) {
this.template.indexOf(projectName).should.not.equal(-1)
done()
})
- it('should insert the users name into the template', function(done) {
+ it('should insert the users name into the template', function (done) {
this.template.indexOf(this.user.first_name).should.not.equal(-1)
this.template.indexOf(this.user.last_name).should.not.equal(-1)
done()
})
- it('should not have undefined in the template', function(done) {
+ it('should not have undefined in the template', function (done) {
this.template.indexOf('undefined').should.equal(-1)
done()
})
- it('should not have any underscore brackets in the output', function(done) {
+ it('should not have any underscore brackets in the output', function (done) {
this.template.indexOf('{{').should.equal(-1)
this.template.indexOf('<%=').should.equal(-1)
done()
})
- it('should put the year in', function(done) {
+ it('should put the year in', function (done) {
this.template.indexOf(new Date().getUTCFullYear()).should.not.equal(-1)
done()
})
})
- describe('_createRootDoc', function() {
- beforeEach(function(done) {
+ describe('_createRootDoc', function () {
+ beforeEach(function (done) {
this.project = new this.ProjectModel()
this.handler._createRootDoc(
@@ -565,7 +565,7 @@ describe('ProjectCreationHandler', function() {
)
})
- it('should insert main.tex', function() {
+ it('should insert main.tex', function () {
this.ProjectEntityUpdateHandler.addDoc
.calledWith(
projectId,
@@ -577,7 +577,7 @@ describe('ProjectCreationHandler', function() {
.should.equal(true)
})
- it('should set the main doc id', function() {
+ it('should set the main doc id', function () {
this.ProjectEntityUpdateHandler.setRootDoc
.calledWith(projectId, docId)
.should.equal(true)
diff --git a/services/web/test/unit/src/Project/ProjectDeleterTests.js b/services/web/test/unit/src/Project/ProjectDeleterTests.js
index d8185552ca..bb69c5e0b3 100644
--- a/services/web/test/unit/src/Project/ProjectDeleterTests.js
+++ b/services/web/test/unit/src/Project/ProjectDeleterTests.js
@@ -9,8 +9,8 @@ const { DeletedProject } = require('../helpers/models/DeletedProject')
const { ObjectId } = require('mongodb')
const Errors = require('../../../../app/src/Features/Errors/Errors')
-describe('ProjectDeleter', function() {
- beforeEach(function() {
+describe('ProjectDeleter', function () {
+ beforeEach(function () {
tk.freeze(Date.now())
this.ip = '192.170.18.1'
this.project = dummyProject()
@@ -32,9 +32,7 @@ describe('ProjectDeleter', function() {
_id: '5cf7f145c1401f0ca0eb1aaa',
deleterData: {
_id: '5cf7f145c1401f0ca0eb1aac',
- deletedAt: moment()
- .subtract(95, 'days')
- .toDate(),
+ deletedAt: moment().subtract(95, 'days').toDate(),
deleterId: '588f3ddae8ebc1bac07c9fa4',
deleterIpAddress: '172.19.0.1',
deletedProjectId: '5cf9270b4eff6e186cf8b05e'
@@ -52,9 +50,7 @@ describe('ProjectDeleter', function() {
_id: '5cf8eb11c1401f0ca0eb1ad7',
deleterData: {
_id: '5b74360c0fbe57011ae9938f',
- deletedAt: moment()
- .subtract(95, 'days')
- .toDate(),
+ deletedAt: moment().subtract(95, 'days').toDate(),
deleterId: '588f3ddae8ebc1bac07c9fa4',
deleterIpAddress: '172.20.0.1',
deletedProjectId: '5cf8f95a0c87371362c23919'
@@ -152,14 +148,14 @@ describe('ProjectDeleter', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
tk.reset()
this.DeletedProjectMock.restore()
this.ProjectMock.restore()
})
- describe('mark as deleted by external source', function() {
- beforeEach(function() {
+ describe('mark as deleted by external source', function () {
+ beforeEach(function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{ _id: this.project._id },
@@ -169,14 +165,14 @@ describe('ProjectDeleter', function() {
.resolves()
})
- it('should update the project with the flag set to true', async function() {
+ it('should update the project with the flag set to true', async function () {
await this.ProjectDeleter.promises.markAsDeletedByExternalSource(
this.project._id
)
this.ProjectMock.verify()
})
- it('should tell the editor controler so users are notified', async function() {
+ it('should tell the editor controler so users are notified', async function () {
await this.ProjectDeleter.promises.markAsDeletedByExternalSource(
this.project._id
)
@@ -187,8 +183,8 @@ describe('ProjectDeleter', function() {
})
})
- describe('unmarkAsDeletedByExternalSource', function() {
- beforeEach(async function() {
+ describe('unmarkAsDeletedByExternalSource', function () {
+ beforeEach(async function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{ _id: this.project._id },
@@ -201,13 +197,13 @@ describe('ProjectDeleter', function() {
)
})
- it('should remove the flag from the project', function() {
+ it('should remove the flag from the project', function () {
this.ProjectMock.verify()
})
})
- describe('deleteUsersProjects', function() {
- beforeEach(function() {
+ describe('deleteUsersProjects', function () {
+ beforeEach(function () {
this.projects = [dummyProject(), dummyProject()]
this.ProjectMock.expects('find')
.withArgs({ owner_ref: this.user._id })
@@ -235,13 +231,13 @@ describe('ProjectDeleter', function() {
}
})
- it('should delete all projects owned by the user', async function() {
+ it('should delete all projects owned by the user', async function () {
await this.ProjectDeleter.promises.deleteUsersProjects(this.user._id)
this.ProjectMock.verify()
this.DeletedProjectMock.verify()
})
- it('should remove any collaboration from this user', async function() {
+ it('should remove any collaboration from this user', async function () {
await this.ProjectDeleter.promises.deleteUsersProjects(this.user._id)
sinon.assert.calledWith(
this.CollaboratorsHandler.promises.removeUserFromAllProjects,
@@ -253,8 +249,8 @@ describe('ProjectDeleter', function() {
})
})
- describe('deleteProject', function() {
- beforeEach(function() {
+ describe('deleteProject', function () {
+ beforeEach(function () {
this.deleterData = {
deletedAt: new Date(),
deletedProjectId: this.project._id,
@@ -278,13 +274,11 @@ describe('ProjectDeleter', function() {
.resolves(this.project)
})
- it('should save a DeletedProject with additional deleterData', async function() {
+ it('should save a DeletedProject with additional deleterData', async function () {
this.deleterData.deleterIpAddress = this.ip
this.deleterData.deleterId = this.user._id
- this.ProjectMock.expects('deleteOne')
- .chain('exec')
- .resolves()
+ this.ProjectMock.expects('deleteOne').chain('exec').resolves()
this.DeletedProjectMock.expects('updateOne')
.withArgs(
{ 'deleterData.deletedProjectId': this.project._id },
@@ -303,10 +297,8 @@ describe('ProjectDeleter', function() {
this.DeletedProjectMock.verify()
})
- it('should flushProjectToMongoAndDelete in doc updater', async function() {
- this.ProjectMock.expects('deleteOne')
- .chain('exec')
- .resolves()
+ it('should flushProjectToMongoAndDelete in doc updater', async function () {
+ this.ProjectMock.expects('deleteOne').chain('exec').resolves()
this.DeletedProjectMock.expects('updateOne').resolves()
await this.ProjectDeleter.promises.deleteProject(this.project._id, {
@@ -318,10 +310,8 @@ describe('ProjectDeleter', function() {
.should.equal(true)
})
- it('should flush docs out of mongo', async function() {
- this.ProjectMock.expects('deleteOne')
- .chain('exec')
- .resolves()
+ it('should flush docs out of mongo', async function () {
+ this.ProjectMock.expects('deleteOne').chain('exec').resolves()
this.DeletedProjectMock.expects('updateOne').resolves()
await this.ProjectDeleter.promises.deleteProject(this.project._id, {
deleterUser: this.user,
@@ -332,10 +322,8 @@ describe('ProjectDeleter', function() {
).to.have.been.calledWith(this.project._id)
})
- it('should flush docs out of mongo and ignore errors', async function() {
- this.ProjectMock.expects('deleteOne')
- .chain('exec')
- .resolves()
+ it('should flush docs out of mongo and ignore errors', async function () {
+ this.ProjectMock.expects('deleteOne').chain('exec').resolves()
this.DeletedProjectMock.expects('updateOne').resolves()
this.DocstoreManager.promises.archiveProject.rejects(new Error('foo'))
await this.ProjectDeleter.promises.deleteProject(this.project._id, {
@@ -344,10 +332,8 @@ describe('ProjectDeleter', function() {
})
})
- it('should removeProjectFromAllTags', async function() {
- this.ProjectMock.expects('deleteOne')
- .chain('exec')
- .resolves()
+ it('should removeProjectFromAllTags', async function () {
+ this.ProjectMock.expects('deleteOne').chain('exec').resolves()
this.DeletedProjectMock.expects('updateOne').resolves()
await this.ProjectDeleter.promises.deleteProject(this.project._id)
@@ -363,7 +349,7 @@ describe('ProjectDeleter', function() {
)
})
- it('should remove the project from Mongo', async function() {
+ it('should remove the project from Mongo', async function () {
this.ProjectMock.expects('deleteOne')
.withArgs({ _id: this.project._id })
.chain('exec')
@@ -375,8 +361,8 @@ describe('ProjectDeleter', function() {
})
})
- describe('expireDeletedProjectsAfterDuration', function() {
- beforeEach(async function() {
+ describe('expireDeletedProjectsAfterDuration', function () {
+ beforeEach(async function () {
this.DeletedProjectMock.expects('find')
.withArgs({
'deleterData.deletedAt': {
@@ -415,13 +401,13 @@ describe('ProjectDeleter', function() {
await this.ProjectDeleter.promises.expireDeletedProjectsAfterDuration()
})
- it('should expire projects older than 90 days', function() {
+ it('should expire projects older than 90 days', function () {
this.DeletedProjectMock.verify()
})
})
- describe('expireDeletedProject', function() {
- beforeEach(async function() {
+ describe('expireDeletedProject', function () {
+ beforeEach(async function () {
this.DeletedProjectMock.expects('updateOne')
.withArgs(
{
@@ -449,17 +435,17 @@ describe('ProjectDeleter', function() {
)
})
- it('should find the specified deletedProject and remove its project and ip address', function() {
+ it('should find the specified deletedProject and remove its project and ip address', function () {
this.DeletedProjectMock.verify()
})
- it('should destroy the docs in docstore', function() {
+ it('should destroy the docs in docstore', function () {
expect(
this.DocstoreManager.promises.destroyProject
).to.have.been.calledWith(this.deletedProjects[0].project._id)
})
- it('should delete the project in history', function() {
+ it('should delete the project in history', function () {
expect(
this.HistoryManager.promises.deleteProject
).to.have.been.calledWith(
@@ -468,15 +454,15 @@ describe('ProjectDeleter', function() {
)
})
- it('should destroy the files in filestore', function() {
+ it('should destroy the files in filestore', function () {
expect(
this.FileStoreHandler.promises.deleteProject
).to.have.been.calledWith(this.deletedProjects[0].project._id)
})
})
- describe('archiveProject', function() {
- beforeEach(function() {
+ describe('archiveProject', function () {
+ beforeEach(function () {
let archived = [ObjectId(this.user._id)]
this.ProjectHelper.calculateArchivedArray.returns(archived)
@@ -496,7 +482,7 @@ describe('ProjectDeleter', function() {
.resolves()
})
- it('should update the project', async function() {
+ it('should update the project', async function () {
await this.ProjectDeleter.promises.archiveProject(
this.project._id,
this.user._id
@@ -504,7 +490,7 @@ describe('ProjectDeleter', function() {
this.ProjectMock.verify()
})
- it('calculates the archived array', async function() {
+ it('calculates the archived array', async function () {
await this.ProjectDeleter.promises.archiveProject(
this.project._id,
this.user._id
@@ -517,8 +503,8 @@ describe('ProjectDeleter', function() {
})
})
- describe('unarchiveProject', function() {
- beforeEach(function() {
+ describe('unarchiveProject', function () {
+ beforeEach(function () {
let archived = [ObjectId(this.user._id)]
this.ProjectHelper.calculateArchivedArray.returns(archived)
@@ -532,7 +518,7 @@ describe('ProjectDeleter', function() {
.resolves()
})
- it('should update the project', async function() {
+ it('should update the project', async function () {
await this.ProjectDeleter.promises.unarchiveProject(
this.project._id,
this.user._id
@@ -540,7 +526,7 @@ describe('ProjectDeleter', function() {
this.ProjectMock.verify()
})
- it('calculates the archived array', async function() {
+ it('calculates the archived array', async function () {
await this.ProjectDeleter.promises.unarchiveProject(
this.project._id,
this.user._id
@@ -553,8 +539,8 @@ describe('ProjectDeleter', function() {
})
})
- describe('trashProject', function() {
- beforeEach(function() {
+ describe('trashProject', function () {
+ beforeEach(function () {
let archived = [ObjectId(this.user._id)]
this.ProjectHelper.calculateArchivedArray.returns(archived)
@@ -574,7 +560,7 @@ describe('ProjectDeleter', function() {
.resolves()
})
- it('should update the project', async function() {
+ it('should update the project', async function () {
await this.ProjectDeleter.promises.trashProject(
this.project._id,
this.user._id
@@ -582,7 +568,7 @@ describe('ProjectDeleter', function() {
this.ProjectMock.verify()
})
- it('unarchives the project', async function() {
+ it('unarchives the project', async function () {
await this.ProjectDeleter.promises.trashProject(
this.project._id,
this.user._id
@@ -595,8 +581,8 @@ describe('ProjectDeleter', function() {
})
})
- describe('untrashProject', function() {
- beforeEach(function() {
+ describe('untrashProject', function () {
+ beforeEach(function () {
this.ProjectMock.expects('findOne')
.withArgs({ _id: this.project._id })
.chain('exec')
@@ -610,7 +596,7 @@ describe('ProjectDeleter', function() {
.resolves()
})
- it('should update the project', async function() {
+ it('should update the project', async function () {
await this.ProjectDeleter.promises.untrashProject(
this.project._id,
this.user._id
@@ -619,8 +605,8 @@ describe('ProjectDeleter', function() {
})
})
- describe('restoreProject', function() {
- beforeEach(function() {
+ describe('restoreProject', function () {
+ beforeEach(function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{
@@ -634,13 +620,13 @@ describe('ProjectDeleter', function() {
.resolves()
})
- it('should unset the archive attribute', async function() {
+ it('should unset the archive attribute', async function () {
await this.ProjectDeleter.promises.restoreProject(this.project._id)
})
})
- describe('undeleteProject', function() {
- beforeEach(function() {
+ describe('undeleteProject', function () {
+ beforeEach(function () {
this.deletedProject = {
_id: 'deleted',
project: this.project,
@@ -669,24 +655,22 @@ describe('ProjectDeleter', function() {
.withArgs({ 'deleterData.deletedProjectId': 'wombat' })
.chain('exec')
.resolves(null)
- this.DeletedProjectMock.expects('deleteOne')
- .chain('exec')
- .resolves()
+ this.DeletedProjectMock.expects('deleteOne').chain('exec').resolves()
})
- it('should return not found if the project does not exist', async function() {
+ it('should return not found if the project does not exist', async function () {
await expect(
this.ProjectDeleter.promises.undeleteProject('wombat')
).to.be.rejectedWith(Errors.NotFoundError, 'project_not_found')
})
- it('should return not found if the project has been expired', async function() {
+ it('should return not found if the project has been expired', async function () {
await expect(
this.ProjectDeleter.promises.undeleteProject('purgedProject')
).to.be.rejectedWith(Errors.NotFoundError, 'project_too_old_to_restore')
})
- it('should insert the project into the collection', async function() {
+ it('should insert the project into the collection', async function () {
await this.ProjectDeleter.promises.undeleteProject(this.project._id)
sinon.assert.calledWith(
this.db.projects.insertOne,
@@ -697,7 +681,7 @@ describe('ProjectDeleter', function() {
)
})
- it('should clear the archive bit', async function() {
+ it('should clear the archive bit', async function () {
this.project.archived = true
await this.ProjectDeleter.promises.undeleteProject(this.project._id)
sinon.assert.calledWith(
@@ -706,7 +690,7 @@ describe('ProjectDeleter', function() {
)
})
- it('should generate a unique name for the project', async function() {
+ it('should generate a unique name for the project', async function () {
await this.ProjectDeleter.promises.undeleteProject(this.project._id)
sinon.assert.calledWith(
this.ProjectDetailsHandler.promises.generateUniqueName,
@@ -714,7 +698,7 @@ describe('ProjectDeleter', function() {
)
})
- it('should add a suffix to the project name', async function() {
+ it('should add a suffix to the project name', async function () {
await this.ProjectDeleter.promises.undeleteProject(this.project._id)
sinon.assert.calledWith(
this.ProjectDetailsHandler.promises.generateUniqueName,
@@ -723,7 +707,7 @@ describe('ProjectDeleter', function() {
)
})
- it('should remove the DeletedProject', async function() {
+ it('should remove the DeletedProject', async function () {
// need to change the mock just to include the methods we want
this.DeletedProjectMock.restore()
this.DeletedProjectMock = sinon.mock(DeletedProject)
diff --git a/services/web/test/unit/src/Project/ProjectDetailsHandlerTests.js b/services/web/test/unit/src/Project/ProjectDetailsHandlerTests.js
index fc4eac0b50..48d6bde698 100644
--- a/services/web/test/unit/src/Project/ProjectDetailsHandlerTests.js
+++ b/services/web/test/unit/src/Project/ProjectDetailsHandlerTests.js
@@ -7,8 +7,8 @@ const ProjectHelper = require('../../../../app/src/Features/Project/ProjectHelpe
const MODULE_PATH = '../../../../app/src/Features/Project/ProjectDetailsHandler'
-describe('ProjectDetailsHandler', function() {
- beforeEach(function() {
+describe('ProjectDetailsHandler', function () {
+ beforeEach(function () {
this.user = {
_id: ObjectId(),
email: 'user@example.com',
@@ -80,8 +80,8 @@ describe('ProjectDetailsHandler', function() {
})
})
- describe('getDetails', function() {
- it('should find the project and owner', async function() {
+ describe('getDetails', function () {
+ it('should find the project and owner', async function () {
const details = await this.handler.promises.getDetails(this.project._id)
details.name.should.equal(this.project.name)
details.description.should.equal(this.project.description)
@@ -90,35 +90,35 @@ describe('ProjectDetailsHandler', function() {
expect(details.something).to.be.undefined
})
- it('should find overleaf metadata if it exists', async function() {
+ it('should find overleaf metadata if it exists', async function () {
this.project.overleaf = { id: 'id' }
const details = await this.handler.promises.getDetails(this.project._id)
details.overleaf.should.equal(this.project.overleaf)
expect(details.something).to.be.undefined
})
- it('should return an error for a non-existent project', async function() {
+ it('should return an error for a non-existent project', async function () {
this.ProjectGetter.promises.getProject.resolves(null)
await expect(
this.handler.promises.getDetails('0123456789012345678901234')
).to.be.rejectedWith(Errors.NotFoundError)
})
- it('should return the default features if no owner found', async function() {
+ it('should return the default features if no owner found', async function () {
this.UserGetter.promises.getUser.resolves(null)
const details = await this.handler.promises.getDetails(this.project._id)
details.features.should.equal(this.settings.defaultFeatures)
})
- it('should rethrow any error', async function() {
+ it('should rethrow any error', async function () {
this.ProjectGetter.promises.getProject.rejects(new Error('boom'))
await expect(this.handler.promises.getDetails(this.project._id)).to.be
.rejected
})
})
- describe('getProjectDescription', function() {
- it('should make a call to mongo just for the description', async function() {
+ describe('getProjectDescription', function () {
+ it('should make a call to mongo just for the description', async function () {
this.ProjectGetter.promises.getProject.resolves()
await this.handler.promises.getProjectDescription(this.project._id)
expect(
@@ -126,7 +126,7 @@ describe('ProjectDetailsHandler', function() {
).to.have.been.calledWith(this.project._id, { description: true })
})
- it('should return what the mongo call returns', async function() {
+ it('should return what the mongo call returns', async function () {
const expectedDescription = 'cool project'
this.ProjectGetter.promises.getProject.resolves({
description: expectedDescription
@@ -138,12 +138,12 @@ describe('ProjectDetailsHandler', function() {
})
})
- describe('setProjectDescription', function() {
- beforeEach(function() {
+ describe('setProjectDescription', function () {
+ beforeEach(function () {
this.description = 'updated teh description'
})
- it('should update the project detials', async function() {
+ it('should update the project detials', async function () {
await this.handler.promises.setProjectDescription(
this.project._id,
this.description
@@ -155,12 +155,12 @@ describe('ProjectDetailsHandler', function() {
})
})
- describe('renameProject', function() {
- beforeEach(function() {
+ describe('renameProject', function () {
+ beforeEach(function () {
this.newName = 'new name here'
})
- it('should update the project with the new name', async function() {
+ it('should update the project with the new name', async function () {
await this.handler.promises.renameProject(this.project._id, this.newName)
expect(this.ProjectModel.updateOne).to.have.been.calledWith(
{ _id: this.project._id },
@@ -168,7 +168,7 @@ describe('ProjectDetailsHandler', function() {
)
})
- it('should tell the TpdsUpdateSender', async function() {
+ it('should tell the TpdsUpdateSender', async function () {
await this.handler.promises.renameProject(this.project._id, this.newName)
expect(this.TpdsUpdateSender.promises.moveEntity).to.have.been.calledWith(
{
@@ -179,7 +179,7 @@ describe('ProjectDetailsHandler', function() {
)
})
- it('should not do anything with an invalid name', async function() {
+ it('should not do anything with an invalid name', async function () {
await expect(this.handler.promises.renameProject(this.project._id)).to.be
.rejected
expect(this.TpdsUpdateSender.promises.moveEntity).not.to.have.been.called
@@ -187,40 +187,40 @@ describe('ProjectDetailsHandler', function() {
})
})
- describe('validateProjectName', function() {
- it('should reject undefined names', async function() {
+ describe('validateProjectName', function () {
+ it('should reject undefined names', async function () {
await expect(this.handler.promises.validateProjectName(undefined)).to.be
.rejected
})
- it('should reject empty names', async function() {
+ it('should reject empty names', async function () {
await expect(this.handler.promises.validateProjectName('')).to.be.rejected
})
- it('should reject names with /s', async function() {
+ it('should reject names with /s', async function () {
await expect(this.handler.promises.validateProjectName('foo/bar')).to.be
.rejected
})
- it('should reject names with \\s', async function() {
+ it('should reject names with \\s', async function () {
await expect(this.handler.promises.validateProjectName('foo\\bar')).to.be
.rejected
})
- it('should reject long names', async function() {
+ it('should reject long names', async function () {
await expect(this.handler.promises.validateProjectName('a'.repeat(1000)))
.to.be.rejected
})
- it('should accept normal names', async function() {
+ it('should accept normal names', async function () {
await expect(this.handler.promises.validateProjectName('foobar')).to.be
.fulfilled
})
})
- describe('generateUniqueName', function() {
+ describe('generateUniqueName', function () {
// actually testing `ProjectHelper.promises.ensureNameIsUnique()`
- beforeEach(function() {
+ beforeEach(function () {
this.longName = 'x'.repeat(this.handler.MAX_PROJECT_NAME_LENGTH - 5)
const usersProjects = {
owned: [
@@ -281,7 +281,7 @@ describe('ProjectDetailsHandler', function() {
this.ProjectGetter.promises.findAllUsersProjects.resolves(usersProjects)
})
- it('should leave a unique name unchanged', async function() {
+ it('should leave a unique name unchanged', async function () {
const name = await this.handler.promises.generateUniqueName(
this.user._id,
'unique-name',
@@ -290,7 +290,7 @@ describe('ProjectDetailsHandler', function() {
expect(name).to.equal('unique-name')
})
- it('should append a suffix to an existing name', async function() {
+ it('should append a suffix to an existing name', async function () {
const name = await this.handler.promises.generateUniqueName(
this.user._id,
'name1',
@@ -299,7 +299,7 @@ describe('ProjectDetailsHandler', function() {
expect(name).to.equal('name1-test-suffix')
})
- it('should fallback to a second suffix when needed', async function() {
+ it('should fallback to a second suffix when needed', async function () {
const name = await this.handler.promises.generateUniqueName(
this.user._id,
'name1',
@@ -308,7 +308,7 @@ describe('ProjectDetailsHandler', function() {
expect(name).to.equal('name1-test-suffix')
})
- it('should truncate the name when append a suffix if the result is too long', async function() {
+ it('should truncate the name when append a suffix if the result is too long', async function () {
const name = await this.handler.promises.generateUniqueName(
this.user._id,
this.longName,
@@ -320,7 +320,7 @@ describe('ProjectDetailsHandler', function() {
)
})
- it('should use a numeric index if no suffix is supplied', async function() {
+ it('should use a numeric index if no suffix is supplied', async function () {
const name = await this.handler.promises.generateUniqueName(
this.user._id,
'name1',
@@ -329,7 +329,7 @@ describe('ProjectDetailsHandler', function() {
expect(name).to.equal('name1 (1)')
})
- it('should use a numeric index if all suffixes are exhausted', async function() {
+ it('should use a numeric index if all suffixes are exhausted', async function () {
const name = await this.handler.promises.generateUniqueName(
this.user._id,
'name',
@@ -338,7 +338,7 @@ describe('ProjectDetailsHandler', function() {
expect(name).to.equal('name (1)')
})
- it('should find the next lowest available numeric index for the base name', async function() {
+ it('should find the next lowest available numeric index for the base name', async function () {
const name = await this.handler.promises.generateUniqueName(
this.user._id,
'numeric',
@@ -347,7 +347,7 @@ describe('ProjectDetailsHandler', function() {
expect(name).to.equal('numeric (21)')
})
- it('should find the next available numeric index when a numeric index is already present', async function() {
+ it('should find the next available numeric index when a numeric index is already present', async function () {
const name = await this.handler.promises.generateUniqueName(
this.user._id,
'numeric (5)',
@@ -356,7 +356,7 @@ describe('ProjectDetailsHandler', function() {
expect(name).to.equal('numeric (21)')
})
- it('should not find a numeric index lower than the one already present', async function() {
+ it('should not find a numeric index lower than the one already present', async function () {
const name = await this.handler.promises.generateUniqueName(
this.user._id,
'numeric (31)',
@@ -366,36 +366,36 @@ describe('ProjectDetailsHandler', function() {
})
})
- describe('fixProjectName', function() {
- it('should change empty names to Untitled', function() {
+ describe('fixProjectName', function () {
+ it('should change empty names to Untitled', function () {
expect(this.handler.fixProjectName('')).to.equal('Untitled')
})
- it('should replace / with -', function() {
+ it('should replace / with -', function () {
expect(this.handler.fixProjectName('foo/bar')).to.equal('foo-bar')
})
- it("should replace \\ with ''", function() {
+ it("should replace \\ with ''", function () {
expect(this.handler.fixProjectName('foo \\ bar')).to.equal('foo bar')
})
- it('should truncate long names', function() {
+ it('should truncate long names', function () {
expect(this.handler.fixProjectName('a'.repeat(1000))).to.equal(
'a'.repeat(150)
)
})
- it('should accept normal names', function() {
+ it('should accept normal names', function () {
expect(this.handler.fixProjectName('foobar')).to.equal('foobar')
})
})
- describe('setPublicAccessLevel', function() {
- beforeEach(function() {
+ describe('setPublicAccessLevel', function () {
+ beforeEach(function () {
this.accessLevel = 'readOnly'
})
- it('should update the project with the new level', async function() {
+ it('should update the project with the new level', async function () {
await this.handler.promises.setPublicAccessLevel(
this.project._id,
this.accessLevel
@@ -406,7 +406,7 @@ describe('ProjectDetailsHandler', function() {
)
})
- it('should not produce an error', async function() {
+ it('should not produce an error', async function () {
await expect(
this.handler.promises.setPublicAccessLevel(
this.project._id,
@@ -415,12 +415,12 @@ describe('ProjectDetailsHandler', function() {
).to.be.fulfilled
})
- describe('when update produces an error', function() {
- beforeEach(function() {
+ describe('when update produces an error', function () {
+ beforeEach(function () {
this.ProjectModelUpdateQuery.exec.rejects(new Error('woops'))
})
- it('should produce an error', async function() {
+ it('should produce an error', async function () {
await expect(
this.handler.promises.setPublicAccessLevel(
this.project._id,
@@ -431,9 +431,9 @@ describe('ProjectDetailsHandler', function() {
})
})
- describe('ensureTokensArePresent', function() {
- describe('when the project has tokens', function() {
- beforeEach(function() {
+ describe('ensureTokensArePresent', function () {
+ describe('when the project has tokens', function () {
+ beforeEach(function () {
this.project = {
_id: this.project._id,
tokens: {
@@ -445,7 +445,7 @@ describe('ProjectDetailsHandler', function() {
this.ProjectGetter.promises.getProject.resolves(this.project)
})
- it('should get the project', async function() {
+ it('should get the project', async function () {
await this.handler.promises.ensureTokensArePresent(this.project._id)
expect(this.ProjectGetter.promises.getProject).to.have.been.calledOnce
expect(this.ProjectGetter.promises.getProject).to.have.been.calledWith(
@@ -456,12 +456,12 @@ describe('ProjectDetailsHandler', function() {
)
})
- it('should not update the project with new tokens', async function() {
+ it('should not update the project with new tokens', async function () {
await this.handler.promises.ensureTokensArePresent(this.project._id)
expect(this.ProjectModel.updateOne).not.to.have.been.called
})
- it('should produce the tokens without error', async function() {
+ it('should produce the tokens without error', async function () {
const tokens = await this.handler.promises.ensureTokensArePresent(
this.project._id
)
@@ -469,8 +469,8 @@ describe('ProjectDetailsHandler', function() {
})
})
- describe('when tokens are missing', function() {
- beforeEach(function() {
+ describe('when tokens are missing', function () {
+ beforeEach(function () {
this.project = { _id: this.project._id }
this.ProjectGetter.promises.getProject.resolves(this.project)
this.readOnlyToken = 'abc'
@@ -485,7 +485,7 @@ describe('ProjectDetailsHandler', function() {
})
})
- it('should get the project', async function() {
+ it('should get the project', async function () {
await this.handler.promises.ensureTokensArePresent(this.project._id)
expect(this.ProjectGetter.promises.getProject).to.have.been.calledOnce
expect(this.ProjectGetter.promises.getProject).to.have.been.calledWith(
@@ -496,7 +496,7 @@ describe('ProjectDetailsHandler', function() {
)
})
- it('should update the project with new tokens', async function() {
+ it('should update the project with new tokens', async function () {
await this.handler.promises.ensureTokensArePresent(this.project._id)
expect(this.TokenGenerator.promises.generateUniqueReadOnlyToken).to.have
.been.calledOnce
@@ -516,7 +516,7 @@ describe('ProjectDetailsHandler', function() {
)
})
- it('should produce the tokens without error', async function() {
+ it('should produce the tokens without error', async function () {
const tokens = await this.handler.promises.ensureTokensArePresent(
this.project._id
)
@@ -529,8 +529,8 @@ describe('ProjectDetailsHandler', function() {
})
})
- describe('clearTokens', function() {
- it('clears the tokens from the project', async function() {
+ describe('clearTokens', function () {
+ it('clears the tokens from the project', async function () {
await this.handler.promises.clearTokens(this.project._id)
expect(this.ProjectModel.updateOne).to.have.been.calledWith(
{ _id: this.project._id },
diff --git a/services/web/test/unit/src/Project/ProjectDuplicatorTests.js b/services/web/test/unit/src/Project/ProjectDuplicatorTests.js
index 7b6e33185b..37708e1e21 100644
--- a/services/web/test/unit/src/Project/ProjectDuplicatorTests.js
+++ b/services/web/test/unit/src/Project/ProjectDuplicatorTests.js
@@ -5,8 +5,8 @@ const { ObjectId } = require('mongodb')
const MODULE_PATH = '../../../../app/src/Features/Project/ProjectDuplicator.js'
-describe('ProjectDuplicator', function() {
- beforeEach(function() {
+describe('ProjectDuplicator', function () {
+ beforeEach(function () {
this.doc0 = { _id: 'doc0_id', name: 'rootDocHere' }
this.doc1 = { _id: 'doc1_id', name: 'level1folderDocName' }
this.doc2 = { _id: 'doc2_id', name: 'level2folderDocName' }
@@ -220,8 +220,8 @@ describe('ProjectDuplicator', function() {
})
})
- describe('when the copy succeeds', function() {
- beforeEach(async function() {
+ describe('when the copy succeeds', function () {
+ beforeEach(async function () {
this.newProjectName = 'New project name'
this.newProject = await this.ProjectDuplicator.promises.duplicate(
this.owner,
@@ -230,13 +230,13 @@ describe('ProjectDuplicator', function() {
)
})
- it('should flush the original project to mongo', function() {
+ it('should flush the original project to mongo', function () {
this.DocumentUpdaterHandler.promises.flushProjectToMongo.should.have.been.calledWith(
this.project._id
)
})
- it('should copy docs to docstore', function() {
+ it('should copy docs to docstore', function () {
for (const docLines of [this.doc0Lines, this.doc1Lines, this.doc2Lines]) {
this.DocstoreManager.promises.updateDoc.should.have.been.calledWith(
this.newProject._id.toString(),
@@ -248,7 +248,7 @@ describe('ProjectDuplicator', function() {
}
})
- it('should copy files to the filestore', function() {
+ it('should copy files to the filestore', function () {
for (const file of [this.file0, this.file1, this.file2]) {
this.FileStoreHandler.promises.copyFile.should.have.been.calledWith(
this.project._id,
@@ -259,7 +259,7 @@ describe('ProjectDuplicator', function() {
}
})
- it('should create a blank project', function() {
+ it('should create a blank project', function () {
this.ProjectCreationHandler.promises.createBlankProject.should.have.been.calledWith(
this.owner._id,
this.newProjectName
@@ -267,26 +267,26 @@ describe('ProjectDuplicator', function() {
this.newProject._id.should.equal(this.newBlankProject._id)
})
- it('should use the same compiler', function() {
+ it('should use the same compiler', function () {
this.ProjectOptionsHandler.promises.setCompiler.should.have.been.calledWith(
this.newProject._id,
this.project.compiler
)
})
- it('should use the same root doc', function() {
+ it('should use the same root doc', function () {
this.ProjectEntityUpdateHandler.promises.setRootDoc.should.have.been.calledWith(
this.newProject._id,
this.rootFolder.docs[0]._id
)
})
- it('should not copy the collaborators or read only refs', function() {
+ it('should not copy the collaborators or read only refs', function () {
this.newProject.collaberator_refs.length.should.equal(0)
this.newProject.readOnly_refs.length.should.equal(0)
})
- it('should copy all documents and files', function() {
+ it('should copy all documents and files', function () {
this.ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure.should.have.been.calledWith(
this.newProject._id,
this.docEntries,
@@ -294,7 +294,7 @@ describe('ProjectDuplicator', function() {
)
})
- it('should notify document updater of changes', function() {
+ it('should notify document updater of changes', function () {
this.DocumentUpdaterHandler.promises.updateProjectStructure.should.have.been.calledWith(
this.newProject._id,
this.newProject.overleaf.history.id,
@@ -307,15 +307,15 @@ describe('ProjectDuplicator', function() {
)
})
- it('should flush the project to TPDS', function() {
+ it('should flush the project to TPDS', function () {
this.TpdsProjectFlusher.promises.flushProjectToTpds.should.have.been.calledWith(
this.newProject._id
)
})
})
- describe('without a root doc', function() {
- beforeEach(async function() {
+ describe('without a root doc', function () {
+ beforeEach(async function () {
this.ProjectLocator.promises.findRootDoc.resolves({
element: null,
path: null
@@ -327,14 +327,14 @@ describe('ProjectDuplicator', function() {
)
})
- it('should not set the root doc on the copy', function() {
+ it('should not set the root doc on the copy', function () {
this.ProjectEntityUpdateHandler.promises.setRootDoc.should.not.have.been
.called
})
})
- describe('with an invalid root doc', function() {
- beforeEach(async function() {
+ describe('with an invalid root doc', function () {
+ beforeEach(async function () {
this.ProjectEntityUpdateHandler.isPathValidForRootDoc.returns(false)
this.newProject = await this.ProjectDuplicator.promises.duplicate(
this.owner,
@@ -343,14 +343,14 @@ describe('ProjectDuplicator', function() {
)
})
- it('should not set the root doc on the copy', function() {
+ it('should not set the root doc on the copy', function () {
this.ProjectEntityUpdateHandler.promises.setRootDoc.should.not.have.been
.called
})
})
- describe('when there is an error', function() {
- beforeEach(async function() {
+ describe('when there is an error', function () {
+ beforeEach(async function () {
this.ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure.rejects()
await expect(
this.ProjectDuplicator.promises.duplicate(
@@ -361,13 +361,13 @@ describe('ProjectDuplicator', function() {
).to.be.rejected
})
- it('should delete the broken cloned project', function() {
+ it('should delete the broken cloned project', function () {
this.ProjectDeleter.promises.deleteProject.should.have.been.calledWith(
this.newBlankProject._id
)
})
- it('should not delete the original project', function() {
+ it('should not delete the original project', function () {
this.ProjectDeleter.promises.deleteProject.should.not.have.been.calledWith(
this.project._id
)
diff --git a/services/web/test/unit/src/Project/ProjectEditorHandlerTests.js b/services/web/test/unit/src/Project/ProjectEditorHandlerTests.js
index 86024da621..3c5c77a854 100644
--- a/services/web/test/unit/src/Project/ProjectEditorHandlerTests.js
+++ b/services/web/test/unit/src/Project/ProjectEditorHandlerTests.js
@@ -15,8 +15,8 @@ const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/Project/ProjectEditorHandler'
const SandboxedModule = require('sandboxed-module')
-describe('ProjectEditorHandler', function() {
- beforeEach(function() {
+describe('ProjectEditorHandler', function () {
+ beforeEach(function () {
this.project = {
_id: 'project-id',
name: 'Project Name',
@@ -112,9 +112,9 @@ describe('ProjectEditorHandler', function() {
return (this.handler = SandboxedModule.require(modulePath))
})
- describe('buildProjectModelView', function() {
- describe('with owner, members and invites included', function() {
- beforeEach(function() {
+ describe('buildProjectModelView', function () {
+ describe('with owner, members and invites included', function () {
+ beforeEach(function () {
return (this.result = this.handler.buildProjectModelView(
this.project,
this.members,
@@ -123,27 +123,27 @@ describe('ProjectEditorHandler', function() {
))
})
- it('should include the id', function() {
+ it('should include the id', function () {
expect(this.result._id).to.exist
return this.result._id.should.equal('project-id')
})
- it('should include the name', function() {
+ it('should include the name', function () {
expect(this.result.name).to.exist
return this.result.name.should.equal('Project Name')
})
- it('should include the root doc id', function() {
+ it('should include the root doc id', function () {
expect(this.result.rootDoc_id).to.exist
return this.result.rootDoc_id.should.equal('file-id')
})
- it('should include the public access level', function() {
+ it('should include the public access level', function () {
expect(this.result.publicAccesLevel).to.exist
return this.result.publicAccesLevel.should.equal('private')
})
- it('should include the owner', function() {
+ it('should include the owner', function () {
expect(this.result.owner).to.exist
this.result.owner._id.should.equal('owner-id')
this.result.owner.email.should.equal('owner@sharelatex.com')
@@ -152,7 +152,7 @@ describe('ProjectEditorHandler', function() {
return this.result.owner.privileges.should.equal('owner')
})
- it('should include the deletedDocs', function() {
+ it('should include the deletedDocs', function () {
expect(this.result.deletedDocs).to.exist
this.result.deletedDocs.should.deep.equal([
{
@@ -164,12 +164,12 @@ describe('ProjectEditorHandler', function() {
])
})
- it('invites should not include the token', function() {
+ it('invites should not include the token', function () {
expect(this.result.invites[0].token).not.to.exist
expect(this.result.invites[1].token).not.to.exist
})
- it('should gather readOnly_refs and collaberators_refs into a list of members', function() {
+ it('should gather readOnly_refs and collaberators_refs into a list of members', function () {
const findMember = id => {
for (let member of Array.from(this.result.members)) {
if (member._id === id) {
@@ -198,7 +198,7 @@ describe('ProjectEditorHandler', function() {
)
})
- it('should include folders in the project', function() {
+ it('should include folders in the project', function () {
this.result.rootFolder[0]._id.should.equal('root-folder-id')
this.result.rootFolder[0].name.should.equal('')
@@ -206,12 +206,12 @@ describe('ProjectEditorHandler', function() {
return this.result.rootFolder[0].folders[0].name.should.equal('folder')
})
- it('should not duplicate folder contents', function() {
+ it('should not duplicate folder contents', function () {
this.result.rootFolder[0].docs.length.should.equal(0)
return this.result.rootFolder[0].fileRefs.length.should.equal(0)
})
- it('should include files in the project', function() {
+ it('should include files in the project', function () {
this.result.rootFolder[0].folders[0].fileRefs[0]._id.should.equal(
'file-id'
)
@@ -225,7 +225,7 @@ describe('ProjectEditorHandler', function() {
.to.exist
})
- it('should include docs in the project but not the lines', function() {
+ it('should include docs in the project but not the lines', function () {
this.result.rootFolder[0].folders[0].docs[0]._id.should.equal('doc-id')
this.result.rootFolder[0].folders[0].docs[0].name.should.equal(
'main.tex'
@@ -234,14 +234,14 @@ describe('ProjectEditorHandler', function() {
.exist
})
- it('should include invites', function() {
+ it('should include invites', function () {
expect(this.result.invites).to.exist
return this.result.invites.should.deep.equal(this.invites)
})
})
- describe('when docstore sends a deleted doc that is also present in the project', function() {
- beforeEach(function() {
+ describe('when docstore sends a deleted doc that is also present in the project', function () {
+ beforeEach(function () {
this.deletedDocsFromDocstore.push(this.project.deletedDocs[0])
this.result = this.handler.buildProjectModelView(
this.project,
@@ -251,7 +251,7 @@ describe('ProjectEditorHandler', function() {
)
})
- it('should not send any duplicate', function() {
+ it('should not send any duplicate', function () {
expect(this.result.deletedDocs).to.exist
this.result.deletedDocs.should.deep.equal([
this.project.deletedDocs[0],
@@ -260,8 +260,8 @@ describe('ProjectEditorHandler', function() {
})
})
- describe('deletedByExternalDataSource', function() {
- it('should set the deletedByExternalDataSource flag to false when it is not there', function() {
+ describe('deletedByExternalDataSource', function () {
+ it('should set the deletedByExternalDataSource flag to false when it is not there', function () {
delete this.project.deletedByExternalDataSource
const result = this.handler.buildProjectModelView(
this.project,
@@ -272,7 +272,7 @@ describe('ProjectEditorHandler', function() {
return result.deletedByExternalDataSource.should.equal(false)
})
- it('should set the deletedByExternalDataSource flag to false when it is false', function() {
+ it('should set the deletedByExternalDataSource flag to false when it is false', function () {
const result = this.handler.buildProjectModelView(
this.project,
this.members,
@@ -282,7 +282,7 @@ describe('ProjectEditorHandler', function() {
return result.deletedByExternalDataSource.should.equal(false)
})
- it('should set the deletedByExternalDataSource flag to true when it is true', function() {
+ it('should set the deletedByExternalDataSource flag to true when it is true', function () {
this.project.deletedByExternalDataSource = true
const result = this.handler.buildProjectModelView(
this.project,
@@ -294,8 +294,8 @@ describe('ProjectEditorHandler', function() {
})
})
- describe('features', function() {
- beforeEach(function() {
+ describe('features', function () {
+ beforeEach(function () {
this.owner.features = {
versioning: true,
collaborators: 3,
@@ -310,7 +310,7 @@ describe('ProjectEditorHandler', function() {
))
})
- it('should copy the owner features to the project', function() {
+ it('should copy the owner features to the project', function () {
this.result.features.versioning.should.equal(
this.owner.features.versioning
)
@@ -326,9 +326,9 @@ describe('ProjectEditorHandler', function() {
})
})
- describe('trackChangesState', function() {
- describe('when the owner does not have the trackChanges feature', function() {
- beforeEach(function() {
+ describe('trackChangesState', function () {
+ describe('when the owner does not have the trackChanges feature', function () {
+ beforeEach(function () {
this.owner.features = {
trackChanges: false
}
@@ -339,13 +339,13 @@ describe('ProjectEditorHandler', function() {
[]
)
})
- it('should not emit trackChangesState', function() {
+ it('should not emit trackChangesState', function () {
expect(this.result.trackChangesState).to.not.exist
})
})
- describe('when the owner has got the trackChanges feature', function() {
- beforeEach(function() {
+ describe('when the owner has got the trackChanges feature', function () {
+ beforeEach(function () {
this.owner.features = {
trackChanges: true
}
@@ -354,8 +354,8 @@ describe('ProjectEditorHandler', function() {
function genCase([dbEntry, expected]) {
describe(`when track_changes is ${JSON.stringify(
dbEntry
- )}`, function() {
- beforeEach(function() {
+ )}`, function () {
+ beforeEach(function () {
this.project.track_changes = dbEntry
this.result = this.handler.buildProjectModelView(
this.project,
@@ -364,7 +364,7 @@ describe('ProjectEditorHandler', function() {
[]
)
})
- it(`should set trackChangesState=${expected}`, function() {
+ it(`should set trackChangesState=${expected}`, function () {
expect(this.result.trackChangesState).to.deep.equal(expected)
})
})
@@ -381,8 +381,8 @@ describe('ProjectEditorHandler', function() {
})
})
- describe('buildOwnerAndMembersViews', function() {
- beforeEach(function() {
+ describe('buildOwnerAndMembersViews', function () {
+ beforeEach(function () {
this.owner.features = {
versioning: true,
collaborators: 3,
@@ -394,7 +394,7 @@ describe('ProjectEditorHandler', function() {
))
})
- it('should produce an object with the right keys', function() {
+ it('should produce an object with the right keys', function () {
return expect(this.result).to.have.all.keys([
'owner',
'ownerFeatures',
@@ -402,7 +402,7 @@ describe('ProjectEditorHandler', function() {
])
})
- it('should separate the owner from the members', function() {
+ it('should separate the owner from the members', function () {
this.result.members.length.should.equal(this.members.length - 1)
expect(this.result.owner._id).to.equal(this.owner._id)
expect(this.result.owner.email).to.equal(this.owner.email)
@@ -411,14 +411,14 @@ describe('ProjectEditorHandler', function() {
).to.equal(0)
})
- it('should extract the ownerFeatures from the owner object', function() {
+ it('should extract the ownerFeatures from the owner object', function () {
return expect(this.result.ownerFeatures).to.deep.equal(
this.owner.features
)
})
- describe('when there is no owner', function() {
- beforeEach(function() {
+ describe('when there is no owner', function () {
+ beforeEach(function () {
// remove the owner from members list
this.membersWithoutOwner = this.members.filter(
m => m.user._id !== this.owner._id
@@ -428,7 +428,7 @@ describe('ProjectEditorHandler', function() {
))
})
- it('should produce an object with the right keys', function() {
+ it('should produce an object with the right keys', function () {
return expect(this.result).to.have.all.keys([
'owner',
'ownerFeatures',
@@ -436,12 +436,12 @@ describe('ProjectEditorHandler', function() {
])
})
- it('should not separate out an owner', function() {
+ it('should not separate out an owner', function () {
this.result.members.length.should.equal(this.membersWithoutOwner.length)
return expect(this.result.owner).to.equal(null)
})
- it('should not extract the ownerFeatures from the owner object', function() {
+ it('should not extract the ownerFeatures from the owner object', function () {
return expect(this.result.ownerFeatures).to.equal(null)
})
})
diff --git a/services/web/test/unit/src/Project/ProjectEntityHandlerTests.js b/services/web/test/unit/src/Project/ProjectEntityHandlerTests.js
index d30a8fd0b1..6f8649989c 100644
--- a/services/web/test/unit/src/Project/ProjectEntityHandlerTests.js
+++ b/services/web/test/unit/src/Project/ProjectEntityHandlerTests.js
@@ -19,20 +19,20 @@ const modulePath = '../../../../app/src/Features/Project/ProjectEntityHandler'
const SandboxedModule = require('sandboxed-module')
const Errors = require('../../../../app/src/Features/Errors/Errors')
-describe('ProjectEntityHandler', function() {
+describe('ProjectEntityHandler', function () {
const project_id = '4eecb1c1bffa66588e0000a1'
const doc_id = '4eecb1c1bffa66588e0000a2'
const folder_id = '4eecaffcbffa66588e000008'
const rootFolderId = '4eecaffcbffa66588e000007'
const userId = 1234
- beforeEach(function() {
+ beforeEach(function () {
let Project
this.TpdsUpdateSender = {
addDoc: sinon.stub().callsArg(1),
addFile: sinon.stub().callsArg(1)
}
- this.ProjectModel = Project = (function() {
+ this.ProjectModel = Project = (function () {
Project = class Project {
static initClass() {
this.prototype.rootFolder = [this.rootFolder]
@@ -71,8 +71,8 @@ describe('ProjectEntityHandler', function() {
}))
})
- describe('getting folders, docs and files', function() {
- beforeEach(function() {
+ describe('getting folders, docs and files', function () {
+ beforeEach(function () {
this.project.rootFolder = [
{
docs: [
@@ -114,8 +114,8 @@ describe('ProjectEntityHandler', function() {
.yields(null, this.project)
})
- describe('getAllDocs', function() {
- beforeEach(function() {
+ describe('getAllDocs', function () {
+ beforeEach(function () {
this.docs = [
{
_id: this.doc1._id,
@@ -134,13 +134,13 @@ describe('ProjectEntityHandler', function() {
this.ProjectEntityHandler.getAllDocs(project_id, this.callback)
})
- it('should get the doc lines and rev from the docstore', function() {
+ it('should get the doc lines and rev from the docstore', function () {
this.DocstoreManager.getAllDocs
.calledWith(project_id)
.should.equal(true)
})
- it('should call the callback with the docs with the lines and rev included', function() {
+ it('should call the callback with the docs with the lines and rev included', function () {
this.callback
.calledWith(null, {
'/doc1': {
@@ -160,13 +160,13 @@ describe('ProjectEntityHandler', function() {
})
})
- describe('getAllFiles', function() {
- beforeEach(function() {
+ describe('getAllFiles', function () {
+ beforeEach(function () {
this.callback = sinon.stub()
this.ProjectEntityHandler.getAllFiles(project_id, this.callback)
})
- it('should call the callback with the files', function() {
+ it('should call the callback with the files', function () {
this.callback
.calledWith(null, {
'/file1': this.file1,
@@ -176,8 +176,8 @@ describe('ProjectEntityHandler', function() {
})
})
- describe('getAllDocPathsFromProject', function() {
- beforeEach(function() {
+ describe('getAllDocPathsFromProject', function () {
+ beforeEach(function () {
this.docs = [
{
_id: this.doc1._id,
@@ -197,7 +197,7 @@ describe('ProjectEntityHandler', function() {
)
})
- it('should call the callback with the path for each doc_id', function() {
+ it('should call the callback with the path for each doc_id', function () {
this.expected = {}
this.expected[this.doc1._id] = `/${this.doc1.name}`
this.expected[this.doc2._id] = `/folder1/${this.doc2.name}`
@@ -205,11 +205,11 @@ describe('ProjectEntityHandler', function() {
})
})
- describe('getDocPathByProjectIdAndDocId', function() {
- beforeEach(function() {
+ describe('getDocPathByProjectIdAndDocId', function () {
+ beforeEach(function () {
this.callback = sinon.stub()
})
- it('should call the callback with the path for an existing doc id at the root level', function() {
+ it('should call the callback with the path for an existing doc id at the root level', function () {
this.ProjectEntityHandler.getDocPathByProjectIdAndDocId(
project_id,
this.doc1._id,
@@ -218,7 +218,7 @@ describe('ProjectEntityHandler', function() {
this.callback.calledWith(null, `/${this.doc1.name}`).should.equal(true)
})
- it('should call the callback with the path for an existing doc id nested within a folder', function() {
+ it('should call the callback with the path for an existing doc id nested within a folder', function () {
this.ProjectEntityHandler.getDocPathByProjectIdAndDocId(
project_id,
this.doc2._id,
@@ -229,7 +229,7 @@ describe('ProjectEntityHandler', function() {
.should.equal(true)
})
- it('should call the callback with a NotFoundError for a non-existing doc', function() {
+ it('should call the callback with a NotFoundError for a non-existing doc', function () {
this.ProjectEntityHandler.getDocPathByProjectIdAndDocId(
project_id,
'non-existing-id',
@@ -240,7 +240,7 @@ describe('ProjectEntityHandler', function() {
)
})
- it('should call the callback with a NotFoundError for an existing file', function() {
+ it('should call the callback with a NotFoundError for an existing file', function () {
this.ProjectEntityHandler.getDocPathByProjectIdAndDocId(
project_id,
this.file1._id,
@@ -252,19 +252,19 @@ describe('ProjectEntityHandler', function() {
})
})
- describe('_getAllFolders', function() {
- beforeEach(function() {
+ describe('_getAllFolders', function () {
+ beforeEach(function () {
this.callback = sinon.stub()
this.ProjectEntityHandler._getAllFolders(project_id, this.callback)
})
- it('should get the project without the docs lines', function() {
+ it('should get the project without the docs lines', function () {
this.ProjectGetter.getProjectWithoutDocLines
.calledWith(project_id)
.should.equal(true)
})
- it('should call the callback with the folders', function() {
+ it('should call the callback with the folders', function () {
this.callback
.calledWith(null, {
'/': this.project.rootFolder[0],
@@ -274,8 +274,8 @@ describe('ProjectEntityHandler', function() {
})
})
- describe('_getAllFoldersFromProject', function() {
- beforeEach(function() {
+ describe('_getAllFoldersFromProject', function () {
+ beforeEach(function () {
this.callback = sinon.stub()
this.ProjectEntityHandler._getAllFoldersFromProject(
this.project,
@@ -283,7 +283,7 @@ describe('ProjectEntityHandler', function() {
)
})
- it('should call the callback with the folders', function() {
+ it('should call the callback with the folders', function () {
this.callback
.calledWith(null, {
'/': this.project.rootFolder[0],
@@ -294,8 +294,8 @@ describe('ProjectEntityHandler', function() {
})
})
- describe('getDoc', function() {
- beforeEach(function() {
+ describe('getDoc', function () {
+ beforeEach(function () {
this.lines = ['mock', 'doc', 'lines']
this.rev = 5
this.version = 42
@@ -307,23 +307,23 @@ describe('ProjectEntityHandler', function() {
this.ProjectEntityHandler.getDoc(project_id, doc_id, this.callback)
})
- it('should call the docstore', function() {
+ it('should call the docstore', function () {
this.DocstoreManager.getDoc
.calledWith(project_id, doc_id)
.should.equal(true)
})
- it('should call the callback with the lines, version and rev', function() {
+ it('should call the callback with the lines, version and rev', function () {
this.callback
.calledWith(null, this.lines, this.rev, this.version, this.ranges)
.should.equal(true)
})
})
- describe('promises.getDoc', function() {
+ describe('promises.getDoc', function () {
let result
- beforeEach(async function() {
+ beforeEach(async function () {
this.lines = ['mock', 'doc', 'lines']
this.rev = 5
this.version = 42
@@ -338,13 +338,13 @@ describe('ProjectEntityHandler', function() {
)
})
- it('should call the docstore', function() {
+ it('should call the docstore', function () {
this.DocstoreManager.getDoc
.calledWith(project_id, doc_id)
.should.equal(true)
})
- it('should return the lines, rev, version and ranges', function() {
+ it('should return the lines, rev, version and ranges', function () {
expect(result.lines).to.equal(this.lines)
expect(result.rev).to.equal(this.rev)
expect(result.version).to.equal(this.version)
diff --git a/services/web/test/unit/src/Project/ProjectEntityMongoUpdateHandlerTests.js b/services/web/test/unit/src/Project/ProjectEntityMongoUpdateHandlerTests.js
index 9caa039ce4..71ee778111 100644
--- a/services/web/test/unit/src/Project/ProjectEntityMongoUpdateHandlerTests.js
+++ b/services/web/test/unit/src/Project/ProjectEntityMongoUpdateHandlerTests.js
@@ -10,8 +10,8 @@ const { Project } = require('../helpers/models/Project')
const MODULE_PATH =
'../../../../app/src/Features/Project/ProjectEntityMongoUpdateHandler'
-describe('ProjectEntityMongoUpdateHandler', function() {
- beforeEach(function() {
+describe('ProjectEntityMongoUpdateHandler', function () {
+ beforeEach(function () {
this.doc = {
_id: ObjectId(),
name: 'test-doc.txt',
@@ -194,21 +194,21 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
this.DeletedFileMock.restore()
this.ProjectMock.restore()
})
- beforeEach(function() {
+ beforeEach(function () {
tk.freeze(Date.now())
})
- afterEach(function() {
+ afterEach(function () {
tk.reset()
})
- describe('addDoc', function() {
- beforeEach(async function() {
+ describe('addDoc', function () {
+ beforeEach(async function () {
const doc = { _id: ObjectId(), name: 'other.txt' }
this.ProjectMock.expects('findOneAndUpdate')
.withArgs(
@@ -227,11 +227,11 @@ describe('ProjectEntityMongoUpdateHandler', function() {
)
})
- it('adds the document in Mongo', function() {
+ it('adds the document in Mongo', function () {
this.ProjectMock.verify()
})
- it('returns path info and the project', function() {
+ it('returns path info and the project', function () {
expect(this.result).to.deep.equal({
result: {
path: {
@@ -244,8 +244,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('addFile', function() {
- beforeEach(function() {
+ describe('addFile', function () {
+ beforeEach(function () {
this.newFile = { _id: ObjectId(), name: 'picture.jpg' }
this.ProjectMock.expects('findOneAndUpdate')
.withArgs(
@@ -259,8 +259,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
.resolves(this.project)
})
- describe('happy path', function() {
- beforeEach(async function() {
+ describe('happy path', function () {
+ beforeEach(async function () {
this.result = await this.subject.promises.addFile(
this.project._id,
this.folder._id,
@@ -268,11 +268,11 @@ describe('ProjectEntityMongoUpdateHandler', function() {
)
})
- it('adds the file in Mongo', function() {
+ it('adds the file in Mongo', function () {
this.ProjectMock.verify()
})
- it('returns path info and the project', function() {
+ it('returns path info and the project', function () {
expect(this.result).to.deep.equal({
result: {
path: {
@@ -285,17 +285,17 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('when entity limit is reached', function() {
- beforeEach(function() {
+ describe('when entity limit is reached', function () {
+ beforeEach(function () {
this.savedMaxEntities = this.Settings.maxEntitiesPerProject
this.Settings.maxEntitiesPerProject = 3
})
- afterEach(function() {
+ afterEach(function () {
this.Settings.maxEntitiesPerProject = this.savedMaxEntities
})
- it('should throw an error', async function() {
+ it('should throw an error', async function () {
await expect(
this.subject.promises.addFile(
this.project._id,
@@ -307,8 +307,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('addFolder', function() {
- beforeEach(async function() {
+ describe('addFolder', function () {
+ beforeEach(async function () {
const folderName = 'New folder'
this.FolderModel.withArgs({ name: folderName }).returns({
_id: ObjectId(),
@@ -335,13 +335,13 @@ describe('ProjectEntityMongoUpdateHandler', function() {
)
})
- it('adds the folder in Mongo', function() {
+ it('adds the folder in Mongo', function () {
this.ProjectMock.verify()
})
})
- describe('replaceFileWithNew', function() {
- beforeEach(async function() {
+ describe('replaceFileWithNew', function () {
+ beforeEach(async function () {
const newFile = {
_id: ObjectId(),
name: 'some-other-file.png',
@@ -385,56 +385,56 @@ describe('ProjectEntityMongoUpdateHandler', function() {
)
})
- it('updates the database', function() {
+ it('updates the database', function () {
this.DeletedFileMock.verify()
this.ProjectMock.verify()
})
})
- describe('mkdirp', function() {
- describe('when the path is just a slash', function() {
- beforeEach(async function() {
+ describe('mkdirp', function () {
+ describe('when the path is just a slash', function () {
+ beforeEach(async function () {
this.result = await this.subject.promises.mkdirp(this.project._id, '/')
})
- it('should return the root folder', function() {
+ it('should return the root folder', function () {
expect(this.result.folder).to.deep.equal(this.rootFolder)
})
- it('should not report a parent folder', function() {
+ it('should not report a parent folder', function () {
expect(this.result.folder.parentFolder_id).not.to.exist
})
- it('should not return new folders', function() {
+ it('should not return new folders', function () {
expect(this.result.newFolders).to.have.length(0)
})
})
- describe('when the folder already exists', function() {
- beforeEach(async function() {
+ describe('when the folder already exists', function () {
+ beforeEach(async function () {
this.result = await this.subject.promises.mkdirp(
this.project._id,
'/test-folder'
)
})
- it('should return the existing folder', function() {
+ it('should return the existing folder', function () {
expect(this.result.folder).to.deep.equal(this.folder)
})
- it('should report the parent folder', function() {
+ it('should report the parent folder', function () {
expect(this.result.folder.parentFolder_id).not.equal(
this.rootFolder._id
)
})
- it('should not return new folders', function() {
+ it('should not return new folders', function () {
expect(this.result.newFolders).to.have.length(0)
})
})
- describe('when the path is a new folder at the top level', function() {
- beforeEach(async function() {
+ describe('when the path is a new folder at the top level', function () {
+ beforeEach(async function () {
this.newFolder = { _id: ObjectId(), name: 'new-folder' }
this.FolderModel.returns(this.newFolder)
this.exactCaseMatch = false
@@ -454,31 +454,31 @@ describe('ProjectEntityMongoUpdateHandler', function() {
{ exactCaseMatch: this.exactCaseMatch }
)
})
- it('should update the database', function() {
+ it('should update the database', function () {
this.ProjectMock.verify()
})
- it('should make just one folder', function() {
+ it('should make just one folder', function () {
expect(this.result.newFolders).to.have.length(1)
})
- it('should return the new folder', function() {
+ it('should return the new folder', function () {
expect(this.result.folder.name).to.equal('new-folder')
})
- it('should return the parent folder', function() {
+ it('should return the parent folder', function () {
expect(this.result.folder.parentFolder_id).to.equal(this.rootFolder._id)
})
- it('should pass the exactCaseMatch option to ProjectLocator', function() {
+ it('should pass the exactCaseMatch option to ProjectLocator', function () {
expect(
this.ProjectLocator.promises.findElementByPath
).to.have.been.calledWithMatch({ exactCaseMatch: this.exactCaseMatch })
})
})
- describe('adding a subfolder', function() {
- beforeEach(async function() {
+ describe('adding a subfolder', function () {
+ beforeEach(async function () {
this.newFolder = { _id: ObjectId(), name: 'new-folder' }
this.FolderModel.returns(this.newFolder)
this.ProjectMock.expects('findOneAndUpdate')
@@ -501,25 +501,25 @@ describe('ProjectEntityMongoUpdateHandler', function() {
)
})
- it('should update the database', function() {
+ it('should update the database', function () {
this.ProjectMock.verify()
})
- it('should create one folder', function() {
+ it('should create one folder', function () {
expect(this.result.newFolders).to.have.length(1)
})
- it('should return the new folder', function() {
+ it('should return the new folder', function () {
expect(this.result.folder.name).to.equal('new-folder')
})
- it('should return the parent folder', function() {
+ it('should return the parent folder', function () {
expect(this.result.folder.parentFolder_id).to.equal(this.folder._id)
})
})
- describe('when mutliple folders are missing', async function() {
- beforeEach(function() {
+ describe('when mutliple folders are missing', async function () {
+ beforeEach(function () {
this.folder1 = { _id: ObjectId(), name: 'folder1' }
this.folder1Path = {
fileSystem: '/test-folder/folder1',
@@ -591,30 +591,30 @@ describe('ProjectEntityMongoUpdateHandler', function() {
path: '/test-folder/folder1/folder2/'
}
].forEach(({ description, path }) => {
- describe(description, function() {
- beforeEach(async function() {
+ describe(description, function () {
+ beforeEach(async function () {
this.result = await this.subject.promises.mkdirp(
this.project._id,
path
)
})
- it('should update the database', function() {
+ it('should update the database', function () {
this.ProjectMock.verify()
})
- it('should add multiple folders', function() {
+ it('should add multiple folders', function () {
const newFolders = this.result.newFolders
expect(newFolders).to.have.length(2)
expect(newFolders[0].name).to.equal('folder1')
expect(newFolders[1].name).to.equal('folder2')
})
- it('should return the last folder', function() {
+ it('should return the last folder', function () {
expect(this.result.folder.name).to.equal('folder2')
})
- it('should return the parent folder', function() {
+ it('should return the parent folder', function () {
expect(this.result.folder.parentFolder_id).to.equal(
this.folder1._id
)
@@ -624,9 +624,9 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('moveEntity', function() {
- describe('moving a doc into a different folder', function() {
- beforeEach(async function() {
+ describe('moveEntity', function () {
+ describe('moving a doc into a different folder', function () {
+ beforeEach(async function () {
this.pathAfterMove = {
fileSystem: '/somewhere/else.txt'
}
@@ -670,11 +670,11 @@ describe('ProjectEntityMongoUpdateHandler', function() {
)
})
- it('should update the database', function() {
+ it('should update the database', function () {
this.ProjectMock.verify()
})
- it('should report what changed', function() {
+ it('should report what changed', function () {
expect(this.result).to.deep.equal({
project: this.project,
startPath: '/test-doc.txt',
@@ -691,8 +691,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('when moving a folder inside itself', function() {
- it('throws an error', async function() {
+ describe('when moving a folder inside itself', function () {
+ it('throws an error', async function () {
await expect(
this.subject.promises.moveEntity(
this.project._id,
@@ -704,8 +704,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('when moving a folder to a subfolder of itself', function() {
- it('throws an error', async function() {
+ describe('when moving a folder to a subfolder of itself', function () {
+ it('throws an error', async function () {
await expect(
this.subject.promises.moveEntity(
this.project._id,
@@ -718,8 +718,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('deleteEntity', function() {
- beforeEach(async function() {
+ describe('deleteEntity', function () {
+ beforeEach(async function () {
this.ProjectMock.expects('findOneAndUpdate')
.withArgs(
{ _id: this.project._id },
@@ -737,14 +737,14 @@ describe('ProjectEntityMongoUpdateHandler', function() {
)
})
- it('should update the database', function() {
+ it('should update the database', function () {
this.ProjectMock.verify()
})
})
- describe('renameEntity', function() {
- describe('happy path', function() {
- beforeEach(async function() {
+ describe('renameEntity', function () {
+ describe('happy path', function () {
+ beforeEach(async function () {
this.newName = 'new.tex'
this.oldDocs = ['old-doc']
this.oldFiles = ['old-file']
@@ -776,11 +776,11 @@ describe('ProjectEntityMongoUpdateHandler', function() {
)
})
- it('should update the database', function() {
+ it('should update the database', function () {
this.ProjectMock.verify()
})
- it('returns info', function() {
+ it('returns info', function () {
expect(this.result).to.deep.equal({
project: this.project,
startPath: '/test-doc.txt',
@@ -797,8 +797,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('name already exists', function() {
- it('should throw an error', async function() {
+ describe('name already exists', function () {
+ it('should throw an error', async function () {
await expect(
this.subject.promises.renameEntity(
this.project._id,
@@ -811,10 +811,10 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('_putElement', function() {
- describe('updating the project', function() {
- describe('when the parent folder is given', function() {
- beforeEach(function() {
+ describe('_putElement', function () {
+ describe('updating the project', function () {
+ describe('when the parent folder is given', function () {
+ beforeEach(function () {
this.newFile = { _id: ObjectId(), name: 'new file.png' }
this.ProjectMock.expects('findOneAndUpdate')
.withArgs(
@@ -828,7 +828,7 @@ describe('ProjectEntityMongoUpdateHandler', function() {
.resolves(this.project)
})
- it('should update the database', async function() {
+ it('should update the database', async function () {
await this.subject.promises._putElement(
this.project,
this.folder._id,
@@ -838,7 +838,7 @@ describe('ProjectEntityMongoUpdateHandler', function() {
this.ProjectMock.verify()
})
- it('should add an s onto the type if not included', async function() {
+ it('should add an s onto the type if not included', async function () {
await this.subject.promises._putElement(
this.project,
this.folder._id,
@@ -849,8 +849,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('error cases', function() {
- it('should throw an error if element is null', async function() {
+ describe('error cases', function () {
+ it('should throw an error if element is null', async function () {
await expect(
this.subject.promises._putElement(
this.project,
@@ -861,7 +861,7 @@ describe('ProjectEntityMongoUpdateHandler', function() {
).to.be.rejected
})
- it('should error if the element has no _id', async function() {
+ it('should error if the element has no _id', async function () {
const file = { name: 'something' }
await expect(
this.subject.promises._putElement(
@@ -873,7 +873,7 @@ describe('ProjectEntityMongoUpdateHandler', function() {
).to.be.rejected
})
- it('should error if element name contains invalid characters', async function() {
+ it('should error if element name contains invalid characters', async function () {
const file = { _id: ObjectId(), name: 'something*bad' }
await expect(
this.subject.promises._putElement(
@@ -885,7 +885,7 @@ describe('ProjectEntityMongoUpdateHandler', function() {
).to.be.rejected
})
- it('should error if element name is too long', async function() {
+ it('should error if element name is too long', async function () {
const file = {
_id: ObjectId(),
name: 'long-'.repeat(1000) + 'something'
@@ -900,7 +900,7 @@ describe('ProjectEntityMongoUpdateHandler', function() {
).to.be.rejectedWith(Errors.InvalidNameError)
})
- it('should error if the folder name is too long', async function() {
+ it('should error if the folder name is too long', async function () {
const file = {
_id: ObjectId(),
name: 'something'
@@ -925,7 +925,7 @@ describe('ProjectEntityMongoUpdateHandler', function() {
).to.be.rejectedWith(Errors.InvalidNameError)
})
;['file', 'doc', 'folder'].forEach(entityType => {
- it(`should error if a ${entityType} already exists with the same name`, async function() {
+ it(`should error if a ${entityType} already exists with the same name`, async function () {
const file = {
_id: ObjectId(),
name: this[entityType].name
@@ -943,8 +943,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('when the parent folder is not given', function() {
- it('should default to root folder insert', async function() {
+ describe('when the parent folder is not given', function () {
+ it('should default to root folder insert', async function () {
this.newFile = { _id: ObjectId(), name: 'new file.png' }
this.ProjectMock.expects('findOneAndUpdate')
.withArgs(
@@ -966,8 +966,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('_insertDeletedFileReference', function() {
- beforeEach(async function() {
+ describe('_insertDeletedFileReference', function () {
+ beforeEach(async function () {
this.DeletedFileMock.expects('create')
.withArgs({
projectId: this.project._id,
@@ -984,13 +984,13 @@ describe('ProjectEntityMongoUpdateHandler', function() {
)
})
- it('should update the database', function() {
+ it('should update the database', function () {
this.DeletedFileMock.verify()
})
})
- describe('createNewFolderStructure', function() {
- beforeEach(function() {
+ describe('createNewFolderStructure', function () {
+ beforeEach(function () {
this.mockRootFolder = 'MOCK_ROOT_FOLDER'
this.docUploads = ['MOCK_DOC_UPLOAD']
this.fileUploads = ['MOCK_FILE_UPLOAD']
@@ -1011,8 +1011,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
.chain('exec')
})
- describe('happy path', function() {
- beforeEach(async function() {
+ describe('happy path', function () {
+ beforeEach(async function () {
this.updateExpectation.resolves({ version: 1 })
await this.subject.promises.createNewFolderStructure(
this.project._id,
@@ -1021,17 +1021,17 @@ describe('ProjectEntityMongoUpdateHandler', function() {
)
})
- it('updates the database', function() {
+ it('updates the database', function () {
this.ProjectMock.verify()
})
})
- describe("when the update doesn't find a matching document", function() {
- beforeEach(async function() {
+ describe("when the update doesn't find a matching document", function () {
+ beforeEach(async function () {
this.updateExpectation.resolves(null)
})
- it('throws an error', async function() {
+ it('throws an error', async function () {
await expect(
this.subject.promises.createNewFolderStructure(
this.project._id,
@@ -1043,8 +1043,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('replaceDocWithFile', function() {
- it('should simultaneously remove the doc and add the file', async function() {
+ describe('replaceDocWithFile', function () {
+ it('should simultaneously remove the doc and add the file', async function () {
this.ProjectMock.expects('findOneAndUpdate')
.withArgs(
{ _id: this.project._id },
@@ -1066,8 +1066,8 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})
})
- describe('replaceFileWithDoc', function() {
- it('should simultaneously remove the file and add the doc', async function() {
+ describe('replaceFileWithDoc', function () {
+ it('should simultaneously remove the file and add the doc', async function () {
this.ProjectMock.expects('findOneAndUpdate')
.withArgs(
{ _id: this.project._id },
diff --git a/services/web/test/unit/src/Project/ProjectEntityUpdateHandlerTests.js b/services/web/test/unit/src/Project/ProjectEntityUpdateHandlerTests.js
index e7e5f9ab58..a3ed392bb9 100644
--- a/services/web/test/unit/src/Project/ProjectEntityUpdateHandlerTests.js
+++ b/services/web/test/unit/src/Project/ProjectEntityUpdateHandlerTests.js
@@ -7,7 +7,7 @@ const { ObjectId } = require('mongodb')
const MODULE_PATH =
'../../../../app/src/Features/Project/ProjectEntityUpdateHandler'
-describe('ProjectEntityUpdateHandler', function() {
+describe('ProjectEntityUpdateHandler', function () {
const projectId = '4eecb1c1bffa66588e0000a1'
const projectHistoryId = '123456'
const docId = '4eecb1c1bffa66588e0000a2'
@@ -16,7 +16,7 @@ describe('ProjectEntityUpdateHandler', function() {
const newFileId = '4eecaffcbffa66588e000099'
const userId = 1234
- beforeEach(function() {
+ beforeEach(function () {
this.project = {
_id: projectId,
name: 'project name',
@@ -167,8 +167,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('updateDocLines', function() {
- beforeEach(function() {
+ describe('updateDocLines', function () {
+ beforeEach(function () {
this.path = '/somewhere/something.tex'
this.doc = {
_id: docId
@@ -185,8 +185,8 @@ describe('ProjectEntityUpdateHandler', function() {
this.TpdsUpdateSender.addDoc.yields()
})
- describe('when the doc has been modified', function() {
- beforeEach(function() {
+ describe('when the doc has been modified', function () {
+ beforeEach(function () {
this.DocstoreManager.updateDoc.yields(null, true, (this.rev = 5))
this.ProjectEntityUpdateHandler.updateDocLines(
projectId,
@@ -200,7 +200,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should get the project with very few fields', function() {
+ it('should get the project with very few fields', function () {
this.ProjectGetter.getProject
.calledWith(projectId, {
name: true,
@@ -209,7 +209,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('should find the doc', function() {
+ it('should find the doc', function () {
this.ProjectLocator.findElement
.calledWith({
project: this.project,
@@ -219,7 +219,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('should update the doc in the docstore', function() {
+ it('should update the doc in the docstore', function () {
this.DocstoreManager.updateDoc
.calledWith(
projectId,
@@ -231,7 +231,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('should mark the project as updated', function() {
+ it('should mark the project as updated', function () {
sinon.assert.calledWith(
this.ProjectUpdater.markAsUpdated,
projectId,
@@ -240,7 +240,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should send the doc the to the TPDS', function() {
+ it('should send the doc the to the TPDS', function () {
this.TpdsUpdateSender.addDoc
.calledWith({
project_id: projectId,
@@ -252,13 +252,13 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('when the doc has not been modified', function() {
- beforeEach(function() {
+ describe('when the doc has not been modified', function () {
+ beforeEach(function () {
this.DocstoreManager.updateDoc.yields(null, false, (this.rev = 5))
this.ProjectEntityUpdateHandler.updateDocLines(
projectId,
@@ -272,21 +272,21 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should not mark the project as updated', function() {
+ it('should not mark the project as updated', function () {
this.ProjectUpdater.markAsUpdated.called.should.equal(false)
})
- it('should not send the doc the to the TPDS', function() {
+ it('should not send the doc the to the TPDS', function () {
this.TpdsUpdateSender.addDoc.called.should.equal(false)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('when the doc has been deleted', function() {
- beforeEach(function() {
+ describe('when the doc has been deleted', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.yields(null, this.project)
this.ProjectLocator.findElement.yields(new Errors.NotFoundError())
this.DocstoreManager.isDocDeleted.yields(null, true)
@@ -303,7 +303,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should update the doc in the docstore', function() {
+ it('should update the doc in the docstore', function () {
this.DocstoreManager.updateDoc
.calledWith(
projectId,
@@ -315,21 +315,21 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('should not mark the project as updated', function() {
+ it('should not mark the project as updated', function () {
this.ProjectUpdater.markAsUpdated.called.should.equal(false)
})
- it('should not send the doc the to the TPDS', function() {
+ it('should not send the doc the to the TPDS', function () {
this.TpdsUpdateSender.addDoc.called.should.equal(false)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('when projects and docs collection are de-synced', function() {
- beforeEach(function() {
+ describe('when projects and docs collection are de-synced', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.yields(null, this.project)
// The doc is not in the file-tree, but also not marked as deleted.
@@ -350,7 +350,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should update the doc in the docstore', function() {
+ it('should update the doc in the docstore', function () {
this.DocstoreManager.updateDoc
.calledWith(
projectId,
@@ -362,21 +362,21 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('should not mark the project as updated', function() {
+ it('should not mark the project as updated', function () {
this.ProjectUpdater.markAsUpdated.called.should.equal(false)
})
- it('should not send the doc the to the TPDS', function() {
+ it('should not send the doc the to the TPDS', function () {
this.TpdsUpdateSender.addDoc.called.should.equal(false)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('when the doc is not related to the project', function() {
- beforeEach(function() {
+ describe('when the doc is not related to the project', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.yields(null, this.project)
this.ProjectLocator.findElement.yields(new Errors.NotFoundError())
this.DocstoreManager.isDocDeleted.yields(new Errors.NotFoundError())
@@ -392,23 +392,23 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should return a not found error', function() {
+ it('should return a not found error', function () {
this.callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
})
- it('should not update the doc', function() {
+ it('should not update the doc', function () {
this.DocstoreManager.updateDoc.called.should.equal(false)
})
- it('should not send the doc the to the TPDS', function() {
+ it('should not send the doc the to the TPDS', function () {
this.TpdsUpdateSender.addDoc.called.should.equal(false)
})
})
- describe('when the project is not found', function() {
- beforeEach(function() {
+ describe('when the project is not found', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.yields(new Errors.NotFoundError())
this.ProjectEntityUpdateHandler.updateDocLines(
projectId,
@@ -422,28 +422,28 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should return a not found error', function() {
+ it('should return a not found error', function () {
this.callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
})
- it('should not update the doc', function() {
+ it('should not update the doc', function () {
this.DocstoreManager.updateDoc.called.should.equal(false)
})
- it('should not send the doc the to the TPDS', function() {
+ it('should not send the doc the to the TPDS', function () {
this.TpdsUpdateSender.addDoc.called.should.equal(false)
})
})
})
- describe('setRootDoc', function() {
- beforeEach(function() {
+ describe('setRootDoc', function () {
+ beforeEach(function () {
this.rootDocId = 'root-doc-id-123123'
})
- it('should call Project.updateOne when the doc exists and has a valid extension', function() {
+ it('should call Project.updateOne when the doc exists and has a valid extension', function () {
this.ProjectEntityHandler.getDocPathByProjectIdAndDocId.yields(
null,
`/main.tex`
@@ -459,7 +459,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it("should not call Project.updateOne when the doc doesn't exist", function() {
+ it("should not call Project.updateOne when the doc doesn't exist", function () {
this.ProjectEntityHandler.getDocPathByProjectIdAndDocId.yields(
Errors.NotFoundError
)
@@ -474,7 +474,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(false)
})
- it('should call the callback with an UnsupportedFileTypeError when the doc has an unaccepted file extension', function() {
+ it('should call the callback with an UnsupportedFileTypeError when the doc has an unaccepted file extension', function () {
this.ProjectEntityHandler.getDocPathByProjectIdAndDocId.yields(
null,
`/foo/bar.baz`
@@ -491,8 +491,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('unsetRootDoc', function() {
- it('should call Project.updateOne', function() {
+ describe('unsetRootDoc', function () {
+ it('should call Project.updateOne', function () {
this.ProjectEntityUpdateHandler.unsetRootDoc(projectId)
this.ProjectModel.updateOne
.calledWith({ _id: projectId }, { $unset: { rootDoc_id: true } })
@@ -500,9 +500,9 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('addDoc', function() {
- describe('adding a doc', function() {
- beforeEach(function() {
+ describe('addDoc', function () {
+ describe('adding a doc', function () {
+ beforeEach(function () {
this.path = '/path/to/doc'
this.newDoc = new this.DocModel({
@@ -528,13 +528,13 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('creates the doc without history', function() {
+ it('creates the doc without history', function () {
this.DocstoreManager.updateDoc
.calledWith(projectId, docId, this.docLines, 0, {})
.should.equal(true)
})
- it('sends the change in project structure to the doc updater', function() {
+ it('sends the change in project structure to the doc updater', function () {
const newDocs = [
{
doc: this.newDoc,
@@ -551,8 +551,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('adding a doc with an invalid name', function() {
- beforeEach(function() {
+ describe('adding a doc with an invalid name', function () {
+ beforeEach(function () {
this.path = '/path/to/doc'
this.newDoc = { _id: docId }
@@ -566,16 +566,16 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
})
- describe('addFile', function() {
- describe('adding a file', function() {
- beforeEach(function() {
+ describe('addFile', function () {
+ describe('adding a file', function () {
+ beforeEach(function () {
this.path = '/path/to/file'
this.newFile = {
@@ -606,7 +606,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('updates the file in the filestore', function() {
+ it('updates the file in the filestore', function () {
this.FileStoreHandler.uploadFileFromDisk
.calledWith(
projectId,
@@ -616,7 +616,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('updates the file in mongo', function() {
+ it('updates the file in mongo', function () {
const fileMatcher = sinon.match(file => {
return file.name === this.fileName
})
@@ -626,7 +626,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('notifies the tpds', function() {
+ it('notifies the tpds', function () {
this.TpdsUpdateSender.addFile
.calledWith({
project_id: projectId,
@@ -638,14 +638,14 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('should mark the project as updated', function() {
+ it('should mark the project as updated', function () {
const args = this.ProjectUpdater.markAsUpdated.args[0]
args[0].should.equal(projectId)
args[1].should.exist
args[2].should.equal(userId)
})
- it('sends the change in project structure to the doc updater', function() {
+ it('sends the change in project structure to the doc updater', function () {
const newFiles = [
{
file: this.newFile,
@@ -662,8 +662,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('adding a file with an invalid name', function() {
- beforeEach(function() {
+ describe('adding a file with an invalid name', function () {
+ beforeEach(function () {
this.path = '/path/to/file'
this.newFile = {
@@ -689,15 +689,15 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
})
- describe('replaceFile', function() {
- beforeEach(function() {
+ describe('replaceFile', function () {
+ beforeEach(function () {
// replacement file now creates a new file object
this.newFileUrl = 'new-file-url'
this.newFile = {
@@ -732,7 +732,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('uploads a new version of the file', function() {
+ it('uploads a new version of the file', function () {
this.FileStoreHandler.uploadFileFromDisk
.calledWith(
projectId,
@@ -745,13 +745,13 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('replaces the file in mongo', function() {
+ it('replaces the file in mongo', function () {
this.ProjectEntityMongoUpdateHandler.replaceFileWithNew
.calledWith(projectId, fileId, this.newFile)
.should.equal(true)
})
- it('notifies the tpds', function() {
+ it('notifies the tpds', function () {
this.TpdsUpdateSender.addFile
.calledWith({
project_id: projectId,
@@ -763,14 +763,14 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('should mark the project as updated', function() {
+ it('should mark the project as updated', function () {
const args = this.ProjectUpdater.markAsUpdated.args[0]
args[0].should.equal(projectId)
args[1].should.exist
args[2].should.equal(userId)
})
- it('updates the project structure in the doc updater', function() {
+ it('updates the project structure in the doc updater', function () {
const oldFiles = [
{
file: this.oldFile,
@@ -794,9 +794,9 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('upsertDoc', function() {
- describe('upserting into an invalid folder', function() {
- beforeEach(function() {
+ describe('upsertDoc', function () {
+ describe('upserting into an invalid folder', function () {
+ beforeEach(function () {
this.ProjectLocator.findElement.yields()
this.ProjectEntityUpdateHandler.upsertDoc(
projectId,
@@ -809,14 +809,14 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Error)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
- describe('updating an existing doc', function() {
- beforeEach(function() {
+ describe('updating an existing doc', function () {
+ beforeEach(function () {
this.existingDoc = { _id: docId, name: this.docName }
this.existingFile = { _id: fileId, name: this.fileName }
this.folder = {
@@ -838,7 +838,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('tries to find the folder', function() {
+ it('tries to find the folder', function () {
this.ProjectLocator.findElement
.calledWith({
project_id: projectId,
@@ -848,7 +848,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('updates the doc contents', function() {
+ it('updates the doc contents', function () {
this.DocumentUpdaterHandler.setDocument
.calledWith(
projectId,
@@ -860,19 +860,19 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('flushes the doc contents', function() {
+ it('flushes the doc contents', function () {
this.DocumentUpdaterHandler.flushDocToMongo
.calledWith(projectId, this.existingDoc._id)
.should.equal(true)
})
- it('returns the doc', function() {
+ it('returns the doc', function () {
this.callback.calledWith(null, this.existingDoc, false)
})
})
- describe('creating a new doc', function() {
- beforeEach(function() {
+ describe('creating a new doc', function () {
+ beforeEach(function () {
this.folder = { _id: folderId, docs: [], fileRefs: [] }
this.newDoc = { _id: docId }
this.ProjectLocator.findElement.yields(null, this.folder)
@@ -891,7 +891,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('tries to find the folder', function() {
+ it('tries to find the folder', function () {
this.ProjectLocator.findElement
.calledWith({
project_id: projectId,
@@ -901,7 +901,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('adds the doc', function() {
+ it('adds the doc', function () {
this.ProjectEntityUpdateHandler.addDocWithRanges.withoutLock
.calledWith(
projectId,
@@ -914,13 +914,13 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('returns the doc', function() {
+ it('returns the doc', function () {
this.callback.calledWith(null, this.newDoc, true)
})
})
- describe('upserting a new doc with an invalid name', function() {
- beforeEach(function() {
+ describe('upserting a new doc with an invalid name', function () {
+ beforeEach(function () {
this.folder = { _id: folderId, docs: [], fileRefs: [] }
this.newDoc = { _id: docId }
this.ProjectLocator.findElement.yields(null, this.folder)
@@ -939,14 +939,14 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
- describe('upserting a doc on top of a file', function() {
- beforeEach(function() {
+ describe('upserting a doc on top of a file', function () {
+ beforeEach(function () {
this.newProject = {
name: 'new project',
overleaf: { history: { id: projectHistoryId } }
@@ -984,7 +984,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('notifies docstore of the new doc', function() {
+ it('notifies docstore of the new doc', function () {
expect(this.DocstoreManager.updateDoc).to.have.been.calledWith(
projectId,
this.newDoc._id,
@@ -992,7 +992,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('adds the new doc and removes the file in one go', function() {
+ it('adds the new doc and removes the file in one go', function () {
expect(
this.ProjectEntityMongoUpdateHandler.replaceFileWithDoc
).to.have.been.calledWithMatch(
@@ -1002,7 +1002,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('sends the doc to TPDS', function() {
+ it('sends the doc to TPDS', function () {
expect(this.TpdsUpdateSender.addDoc).to.have.been.calledWith({
project_id: projectId,
doc_id: this.newDoc._id,
@@ -1012,7 +1012,7 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- it('sends the updates to the doc updater', function() {
+ it('sends the updates to the doc updater', function () {
const oldFiles = [
{
file: this.existingFile,
@@ -1035,7 +1035,7 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- it('should notify everyone of the file deletion', function() {
+ it('should notify everyone of the file deletion', function () {
expect(
this.EditorRealTimeController.emitToRoom
).to.have.been.calledWith(
@@ -1048,8 +1048,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('upsertFile', function() {
- beforeEach(function() {
+ describe('upsertFile', function () {
+ beforeEach(function () {
this.FileStoreHandler.uploadFileFromDisk.yields(
null,
this.fileUrl,
@@ -1057,8 +1057,8 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- describe('upserting into an invalid folder', function() {
- beforeEach(function() {
+ describe('upserting into an invalid folder', function () {
+ beforeEach(function () {
this.ProjectLocator.findElement.yields()
this.ProjectEntityUpdateHandler.upsertFile(
projectId,
@@ -1071,14 +1071,14 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Error)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
- describe('updating an existing file', function() {
- beforeEach(function() {
+ describe('updating an existing file', function () {
+ beforeEach(function () {
this.existingFile = { _id: fileId, name: this.fileName }
this.folder = { _id: folderId, fileRefs: [this.existingFile], docs: [] }
this.ProjectLocator.findElement.yields(null, this.folder)
@@ -1097,7 +1097,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('replaces the file', function() {
+ it('replaces the file', function () {
expect(
this.ProjectEntityUpdateHandler.replaceFile.mainTask
).to.be.calledWith(
@@ -1109,13 +1109,13 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns the file', function() {
+ it('returns the file', function () {
this.callback.calledWith(null, this.existingFile, false)
})
})
- describe('creating a new file', function() {
- beforeEach(function() {
+ describe('creating a new file', function () {
+ beforeEach(function () {
this.folder = { _id: folderId, fileRefs: [], docs: [] }
this.newFile = { _id: fileId }
this.ProjectLocator.findElement.yields(null, this.folder)
@@ -1134,7 +1134,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('tries to find the folder', function() {
+ it('tries to find the folder', function () {
this.ProjectLocator.findElement
.calledWith({
project_id: projectId,
@@ -1144,7 +1144,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('adds the file', function() {
+ it('adds the file', function () {
this.ProjectEntityUpdateHandler.addFile.mainTask
.calledWith(
projectId,
@@ -1157,13 +1157,13 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('returns the file', function() {
+ it('returns the file', function () {
this.callback.calledWith(null, this.newFile, true)
})
})
- describe('upserting a new file with an invalid name', function() {
- beforeEach(function() {
+ describe('upserting a new file with an invalid name', function () {
+ beforeEach(function () {
this.folder = { _id: folderId, fileRefs: [] }
this.newFile = { _id: fileId }
this.ProjectLocator.findElement.yields(null, this.folder)
@@ -1182,14 +1182,14 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
- describe('upserting file on top of a doc', function() {
- beforeEach(function(done) {
+ describe('upserting file on top of a doc', function () {
+ beforeEach(function (done) {
this.path = '/path/to/doc'
this.existingDoc = { _id: new ObjectId(), name: this.fileName }
this.folder = {
@@ -1244,13 +1244,13 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('replaces the existing doc with a file', function() {
+ it('replaces the existing doc with a file', function () {
expect(
this.ProjectEntityMongoUpdateHandler.replaceDocWithFile
).to.have.been.calledWith(projectId, this.existingDoc._id, this.newFile)
})
- it('updates the doc structure', function() {
+ it('updates the doc structure', function () {
const oldDocs = [
{
doc: this.existingDoc,
@@ -1274,7 +1274,7 @@ describe('ProjectEntityUpdateHandler', function() {
).to.have.been.calledWith(projectId, projectHistoryId, userId, updates)
})
- it('tells everyone in the room the doc is removed', function() {
+ it('tells everyone in the room the doc is removed', function () {
expect(
this.EditorRealTimeController.emitToRoom
).to.have.been.calledWith(
@@ -1287,9 +1287,9 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('upsertDocWithPath', function() {
- describe('upserting a doc', function() {
- beforeEach(function() {
+ describe('upsertDocWithPath', function () {
+ describe('upserting a doc', function () {
+ beforeEach(function () {
this.path = '/folder/doc.tex'
this.newFolders = ['mock-a', 'mock-b']
this.folder = { _id: folderId }
@@ -1312,13 +1312,13 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('creates any necessary folders', function() {
+ it('creates any necessary folders', function () {
this.ProjectEntityUpdateHandler.mkdirp.withoutLock
.calledWith(projectId, '/folder')
.should.equal(true)
})
- it('upserts the doc', function() {
+ it('upserts the doc', function () {
this.ProjectEntityUpdateHandler.upsertDoc.withoutLock
.calledWith(
projectId,
@@ -1331,7 +1331,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('calls the callback', function() {
+ it('calls the callback', function () {
this.callback
.calledWith(
null,
@@ -1344,8 +1344,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('upserting a doc with an invalid path', function() {
- beforeEach(function() {
+ describe('upserting a doc with an invalid path', function () {
+ beforeEach(function () {
this.path = '/*folder/doc.tex'
this.newFolders = ['mock-a', 'mock-b']
this.folder = { _id: folderId }
@@ -1368,14 +1368,14 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
- describe('upserting a doc with an invalid name', function() {
- beforeEach(function() {
+ describe('upserting a doc with an invalid name', function () {
+ beforeEach(function () {
this.path = '/folder/*doc.tex'
this.newFolders = ['mock-a', 'mock-b']
this.folder = { _id: folderId }
@@ -1398,16 +1398,16 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
})
- describe('upsertFileWithPath', function() {
- describe('upserting a file', function() {
- beforeEach(function() {
+ describe('upsertFileWithPath', function () {
+ describe('upserting a file', function () {
+ beforeEach(function () {
this.path = '/folder/file.png'
this.newFolders = ['mock-a', 'mock-b']
this.folder = { _id: folderId }
@@ -1435,13 +1435,13 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('creates any necessary folders', function() {
+ it('creates any necessary folders', function () {
this.ProjectEntityUpdateHandler.mkdirp.withoutLock
.calledWith(projectId, '/folder')
.should.equal(true)
})
- it('upserts the file', function() {
+ it('upserts the file', function () {
this.ProjectEntityUpdateHandler.upsertFile.mainTask
.calledWith(
projectId,
@@ -1454,7 +1454,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('calls the callback', function() {
+ it('calls the callback', function () {
this.callback
.calledWith(
null,
@@ -1468,8 +1468,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('upserting a file with an invalid path', function() {
- beforeEach(function() {
+ describe('upserting a file with an invalid path', function () {
+ beforeEach(function () {
this.path = '/*folder/file.png'
this.newFolders = ['mock-a', 'mock-b']
this.folder = { _id: folderId }
@@ -1492,14 +1492,14 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
- describe('upserting a file with an invalid name', function() {
- beforeEach(function() {
+ describe('upserting a file with an invalid name', function () {
+ beforeEach(function () {
this.path = '/folder/*file.png'
this.newFolders = ['mock-a', 'mock-b']
this.folder = { _id: folderId }
@@ -1522,15 +1522,15 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
})
- describe('deleteEntity', function() {
- beforeEach(function() {
+ describe('deleteEntity', function () {
+ beforeEach(function () {
this.path = '/path/to/doc.tex'
this.doc = { _id: docId }
this.projectBeforeDeletion = { _id: projectId, name: 'project' }
@@ -1553,13 +1553,13 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('deletes the entity in mongo', function() {
+ it('deletes the entity in mongo', function () {
this.ProjectEntityMongoUpdateHandler.deleteEntity
.calledWith(projectId, docId, 'doc')
.should.equal(true)
})
- it('cleans up the doc in the docstore', function() {
+ it('cleans up the doc in the docstore', function () {
this.ProjectEntityUpdateHandler._cleanUpEntity
.calledWith(
this.projectBeforeDeletion,
@@ -1572,7 +1572,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('it notifies the tpds', function() {
+ it('it notifies the tpds', function () {
this.TpdsUpdateSender.deleteEntity
.calledWith({
project_id: projectId,
@@ -1582,14 +1582,14 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('retuns the entity_id', function() {
+ it('retuns the entity_id', function () {
this.callback.calledWith(null, docId).should.equal(true)
})
})
- describe('deleteEntityWithPath', function() {
- describe('when the entity exists', function() {
- beforeEach(function() {
+ describe('deleteEntityWithPath', function () {
+ describe('when the entity exists', function () {
+ beforeEach(function () {
this.doc = { _id: docId }
this.ProjectLocator.findElementByPath.yields(null, this.doc, 'doc')
this.ProjectEntityUpdateHandler.deleteEntity = {
@@ -1604,21 +1604,21 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('finds the entity', function() {
+ it('finds the entity', function () {
this.ProjectLocator.findElementByPath
.calledWith({ project_id: projectId, path: this.path })
.should.equal(true)
})
- it('deletes the entity', function() {
+ it('deletes the entity', function () {
this.ProjectEntityUpdateHandler.deleteEntity.withoutLock
.calledWith(projectId, this.doc._id, 'doc', userId, this.callback)
.should.equal(true)
})
})
- describe('when the entity does not exist', function() {
- beforeEach(function() {
+ describe('when the entity does not exist', function () {
+ beforeEach(function () {
this.ProjectLocator.findElementByPath.yields()
this.path = '/doc.tex'
this.ProjectEntityUpdateHandler.deleteEntityWithPath(
@@ -1629,7 +1629,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
this.callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
@@ -1637,8 +1637,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('mkdirp', function() {
- beforeEach(function() {
+ describe('mkdirp', function () {
+ beforeEach(function () {
this.docPath = '/folder/doc.tex'
this.ProjectEntityMongoUpdateHandler.mkdirp.yields()
this.ProjectEntityUpdateHandler.mkdirp(
@@ -1648,15 +1648,15 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('calls ProjectEntityMongoUpdateHandler', function() {
+ it('calls ProjectEntityMongoUpdateHandler', function () {
this.ProjectEntityMongoUpdateHandler.mkdirp
.calledWith(projectId, this.docPath)
.should.equal(true)
})
})
- describe('mkdirpWithExactCase', function() {
- beforeEach(function() {
+ describe('mkdirpWithExactCase', function () {
+ beforeEach(function () {
this.docPath = '/folder/doc.tex'
this.ProjectEntityMongoUpdateHandler.mkdirp.yields()
this.ProjectEntityUpdateHandler.mkdirpWithExactCase(
@@ -1666,16 +1666,16 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('calls ProjectEntityMongoUpdateHandler', function() {
+ it('calls ProjectEntityMongoUpdateHandler', function () {
this.ProjectEntityMongoUpdateHandler.mkdirp
.calledWith(projectId, this.docPath, { exactCaseMatch: true })
.should.equal(true)
})
})
- describe('addFolder', function() {
- describe('adding a folder', function() {
- beforeEach(function() {
+ describe('addFolder', function () {
+ describe('adding a folder', function () {
+ beforeEach(function () {
this.parentFolderId = '123asdf'
this.folderName = 'new-folder'
this.ProjectEntityMongoUpdateHandler.addFolder.yields()
@@ -1687,15 +1687,15 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('calls ProjectEntityMongoUpdateHandler', function() {
+ it('calls ProjectEntityMongoUpdateHandler', function () {
this.ProjectEntityMongoUpdateHandler.addFolder
.calledWith(projectId, this.parentFolderId, this.folderName)
.should.equal(true)
})
})
- describe('adding a folder with an invalid name', function() {
- beforeEach(function() {
+ describe('adding a folder with an invalid name', function () {
+ beforeEach(function () {
this.parentFolderId = '123asdf'
this.folderName = '*new-folder'
this.ProjectEntityMongoUpdateHandler.addFolder.yields()
@@ -1707,15 +1707,15 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
})
- describe('moveEntity', function() {
- beforeEach(function() {
+ describe('moveEntity', function () {
+ beforeEach(function () {
this.project_name = 'project name'
this.startPath = '/a.tex'
this.endPath = '/folder/b.tex'
@@ -1740,13 +1740,13 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('moves the entity in mongo', function() {
+ it('moves the entity in mongo', function () {
this.ProjectEntityMongoUpdateHandler.moveEntity
.calledWith(projectId, docId, folderId, 'doc')
.should.equal(true)
})
- it('notifies tpds', function() {
+ it('notifies tpds', function () {
this.TpdsUpdateSender.promises.moveEntity
.calledWith({
project_id: projectId,
@@ -1758,7 +1758,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('sends the changes in project structure to the doc updater', function() {
+ it('sends the changes in project structure to the doc updater', function () {
this.DocumentUpdaterHandler.updateProjectStructure
.calledWith(
projectId,
@@ -1771,9 +1771,9 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('renameEntity', function() {
- describe('renaming an entity', function() {
- beforeEach(function() {
+ describe('renameEntity', function () {
+ describe('renaming an entity', function () {
+ beforeEach(function () {
this.project_name = 'project name'
this.startPath = '/folder/a.tex'
this.endPath = '/folder/b.tex'
@@ -1799,13 +1799,13 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('moves the entity in mongo', function() {
+ it('moves the entity in mongo', function () {
this.ProjectEntityMongoUpdateHandler.renameEntity
.calledWith(projectId, docId, 'doc', this.newDocName)
.should.equal(true)
})
- it('notifies tpds', function() {
+ it('notifies tpds', function () {
this.TpdsUpdateSender.promises.moveEntity
.calledWith({
project_id: projectId,
@@ -1817,7 +1817,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('sends the changes in project structure to the doc updater', function() {
+ it('sends the changes in project structure to the doc updater', function () {
this.DocumentUpdaterHandler.updateProjectStructure
.calledWith(
projectId,
@@ -1830,8 +1830,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('renaming an entity to an invalid name', function() {
- beforeEach(function() {
+ describe('renaming an entity to an invalid name', function () {
+ beforeEach(function () {
this.project_name = 'project name'
this.startPath = '/folder/a.tex'
this.endPath = '/folder/b.tex'
@@ -1857,16 +1857,16 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('returns an error', function() {
+ it('returns an error', function () {
const errorMatcher = sinon.match.instanceOf(Errors.InvalidNameError)
this.callback.calledWithMatch(errorMatcher).should.equal(true)
})
})
})
- describe('resyncProjectHistory', function() {
- describe('a deleted project', function() {
- beforeEach(function() {
+ describe('resyncProjectHistory', function () {
+ describe('a deleted project', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.yields()
this.ProjectEntityUpdateHandler.resyncProjectHistory(
@@ -1875,7 +1875,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
expect(this.callback).to.have.been.calledWith(
sinon.match
.instanceOf(Errors.ProjectHistoryDisabledError)
@@ -1889,8 +1889,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('a project without project-history enabled', function() {
- beforeEach(function() {
+ describe('a project without project-history enabled', function () {
+ beforeEach(function () {
this.project.overleaf = {}
this.ProjectGetter.getProject.yields(null, this.project)
@@ -1900,7 +1900,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
expect(this.callback).to.have.been.calledWith(
sinon.match
.instanceOf(Errors.ProjectHistoryDisabledError)
@@ -1914,8 +1914,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('a project with project-history enabled', function() {
- beforeEach(function() {
+ describe('a project with project-history enabled', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.yields(null, this.project)
const docs = [
{
@@ -1948,17 +1948,17 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('gets the project', function() {
+ it('gets the project', function () {
this.ProjectGetter.getProject.calledWith(projectId).should.equal(true)
})
- it('gets the entities for the project', function() {
+ it('gets the entities for the project', function () {
this.ProjectEntityHandler.getAllEntitiesFromProject
.calledWith(this.project)
.should.equal(true)
})
- it('tells the doc updater to sync the project', function() {
+ it('tells the doc updater to sync the project', function () {
const docs = [
{
doc: docId,
@@ -1977,22 +1977,22 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('calls the callback', function() {
+ it('calls the callback', function () {
this.callback.called.should.equal(true)
})
})
})
- describe('_cleanUpEntity', function() {
- beforeEach(function() {
+ describe('_cleanUpEntity', function () {
+ beforeEach(function () {
this.entityId = '4eecaffcbffa66588e000009'
this.FileStoreHandler.deleteFile.yields()
this.ProjectEntityUpdateHandler.unsetRootDoc = sinon.stub().yields()
this.ProjectEntityMongoUpdateHandler._insertDeletedFileReference.yields()
})
- describe('a file', function() {
- beforeEach(function(done) {
+ describe('a file', function () {
+ beforeEach(function (done) {
this.path = '/file/system/path.png'
this.entity = { _id: this.entityId }
this.newProject = 'new-project'
@@ -2007,23 +2007,23 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should insert the file into the deletedFiles collection', function() {
+ it('should insert the file into the deletedFiles collection', function () {
this.ProjectEntityMongoUpdateHandler._insertDeletedFileReference
.calledWith(this.project._id, this.entity)
.should.equal(true)
})
- it('should not delete the file from FileStoreHandler', function() {
+ it('should not delete the file from FileStoreHandler', function () {
this.FileStoreHandler.deleteFile
.calledWith(projectId, this.entityId)
.should.equal(false)
})
- it('should not attempt to delete from the document updater', function() {
+ it('should not attempt to delete from the document updater', function () {
this.DocumentUpdaterHandler.deleteDoc.called.should.equal(false)
})
- it('should should send the update to the doc updater', function() {
+ it('should should send the update to the doc updater', function () {
const oldFiles = [{ file: this.entity, path: this.path }]
this.DocumentUpdaterHandler.updateProjectStructure
.calledWith(projectId, projectHistoryId, userId, {
@@ -2034,8 +2034,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('a doc', function() {
- beforeEach(function(done) {
+ describe('a doc', function () {
+ beforeEach(function (done) {
this.path = '/file/system/path.tex'
this.ProjectEntityUpdateHandler._cleanUpDoc = sinon.stub().yields()
this.entity = { _id: this.entityId }
@@ -2051,13 +2051,13 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should clean up the doc', function() {
+ it('should clean up the doc', function () {
this.ProjectEntityUpdateHandler._cleanUpDoc
.calledWith(this.project, this.entity, this.path, userId)
.should.equal(true)
})
- it('should should send the update to the doc updater', function() {
+ it('should should send the update to the doc updater', function () {
const oldDocs = [{ doc: this.entity, path: this.path }]
this.DocumentUpdaterHandler.updateProjectStructure
.calledWith(projectId, projectHistoryId, userId, {
@@ -2068,8 +2068,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('a folder', function() {
- beforeEach(function(done) {
+ describe('a folder', function () {
+ beforeEach(function (done) {
this.folder = {
folders: [
{
@@ -2100,7 +2100,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should clean up all sub files', function() {
+ it('should clean up all sub files', function () {
this.ProjectEntityUpdateHandler._cleanUpFile
.calledWith(
this.project,
@@ -2114,7 +2114,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('should clean up all sub docs', function() {
+ it('should clean up all sub docs', function () {
this.ProjectEntityUpdateHandler._cleanUpDoc
.calledWith(
this.project,
@@ -2128,7 +2128,7 @@ describe('ProjectEntityUpdateHandler', function() {
.should.equal(true)
})
- it('should should send one update to the doc updater for all docs and files', function() {
+ it('should should send one update to the doc updater for all docs and files', function () {
const oldFiles = [
{ file: this.file2, path: '/folder/file-name-2' },
{ file: this.file1, path: '/folder/subfolder/file-name-1' }
@@ -2148,8 +2148,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('_cleanUpDoc', function() {
- beforeEach(function() {
+ describe('_cleanUpDoc', function () {
+ beforeEach(function () {
this.doc = {
_id: ObjectId(),
name: 'test.tex'
@@ -2159,8 +2159,8 @@ describe('ProjectEntityUpdateHandler', function() {
this.DocstoreManager.deleteDoc.yields()
})
- describe('when the doc is the root doc', function() {
- beforeEach(function() {
+ describe('when the doc is the root doc', function () {
+ beforeEach(function () {
this.project.rootDoc_id = this.doc._id
this.ProjectEntityUpdateHandler._cleanUpDoc(
this.project,
@@ -2171,31 +2171,31 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should unset the root doc', function() {
+ it('should unset the root doc', function () {
this.ProjectEntityUpdateHandler.unsetRootDoc
.calledWith(projectId)
.should.equal(true)
})
- it('should delete the doc in the doc updater', function() {
+ it('should delete the doc in the doc updater', function () {
this.DocumentUpdaterHandler.deleteDoc
.calledWith(projectId, this.doc._id.toString())
.should.equal(true)
})
- it('should delete the doc in the doc store', function() {
+ it('should delete the doc in the doc store', function () {
this.DocstoreManager.deleteDoc
.calledWith(projectId, this.doc._id.toString(), 'test.tex')
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('when the doc is not the root doc', function() {
- beforeEach(function() {
+ describe('when the doc is not the root doc', function () {
+ beforeEach(function () {
this.project.rootDoc_id = ObjectId()
this.ProjectEntityUpdateHandler._cleanUpDoc(
this.project,
@@ -2206,18 +2206,18 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should not unset the root doc', function() {
+ it('should not unset the root doc', function () {
this.ProjectEntityUpdateHandler.unsetRootDoc.called.should.equal(false)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
})
- describe('convertDocToFile', function() {
- beforeEach(function() {
+ describe('convertDocToFile', function () {
+ beforeEach(function () {
this.docPath = '/folder/doc.tex'
this.docLines = ['line one', 'line two']
this.tmpFilePath = '/tmp/file'
@@ -2253,8 +2253,8 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- describe('successfully', function() {
- beforeEach(function(done) {
+ describe('successfully', function () {
+ beforeEach(function (done) {
this.ProjectEntityUpdateHandler.convertDocToFile(
this.project._id,
this.doc._id,
@@ -2263,14 +2263,14 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('deletes the document in doc updater', function() {
+ it('deletes the document in doc updater', function () {
expect(this.DocumentUpdaterHandler.deleteDoc).to.have.been.calledWith(
this.project._id,
this.doc._id
)
})
- it('uploads the file to filestore', function() {
+ it('uploads the file to filestore', function () {
expect(
this.FileStoreHandler.uploadFileFromDisk
).to.have.been.calledWith(
@@ -2280,17 +2280,17 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('cleans up the temporary file', function() {
+ it('cleans up the temporary file', function () {
expect(this.fs.unlink).to.have.been.calledWith(this.tmpFilePath)
})
- it('replaces the doc with the file', function() {
+ it('replaces the doc with the file', function () {
expect(
this.ProjectEntityMongoUpdateHandler.replaceDocWithFile
).to.have.been.calledWith(this.project._id, this.doc._id, this.file)
})
- it('notifies document updater of changes', function() {
+ it('notifies document updater of changes', function () {
expect(
this.DocumentUpdaterHandler.updateProjectStructure
).to.have.been.calledWith(
@@ -2307,7 +2307,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should notify real-time of the doc deletion', function() {
+ it('should notify real-time of the doc deletion', function () {
expect(
this.EditorRealTimeController.emitToRoom
).to.have.been.calledWith(
@@ -2318,7 +2318,7 @@ describe('ProjectEntityUpdateHandler', function() {
)
})
- it('should notify real-time of the file creation', function() {
+ it('should notify real-time of the file creation', function () {
expect(
this.EditorRealTimeController.emitToRoom
).to.have.been.calledWith(
@@ -2332,8 +2332,8 @@ describe('ProjectEntityUpdateHandler', function() {
})
})
- describe('when the doc has ranges', function() {
- it('should throw a DocHasRangesError', function(done) {
+ describe('when the doc has ranges', function () {
+ it('should throw a DocHasRangesError', function (done) {
this.ranges = { comments: [{ id: 123 }] }
this.DocstoreManager.getDoc
.withArgs(this.project._id, this.doc._id)
diff --git a/services/web/test/unit/src/Project/ProjectGetterTests.js b/services/web/test/unit/src/Project/ProjectGetterTests.js
index d667b33905..c4695c5b49 100644
--- a/services/web/test/unit/src/Project/ProjectGetterTests.js
+++ b/services/web/test/unit/src/Project/ProjectGetterTests.js
@@ -4,8 +4,8 @@ const modulePath = '../../../../app/src/Features/Project/ProjectGetter.js'
const SandboxedModule = require('sandboxed-module')
const { ObjectId } = require('mongodb')
-describe('ProjectGetter', function() {
- beforeEach(function() {
+describe('ProjectGetter', function () {
+ beforeEach(function () {
this.callback = sinon.stub()
this.project = { _id: new ObjectId() }
this.projectIdStr = this.project._id.toString()
@@ -61,26 +61,26 @@ describe('ProjectGetter', function() {
})
})
- describe('getProjectWithoutDocLines', function() {
- beforeEach(function() {
+ describe('getProjectWithoutDocLines', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject = sinon.stub().yields()
})
- describe('passing an id', function() {
- beforeEach(function() {
+ describe('passing an id', function () {
+ beforeEach(function () {
this.ProjectGetter.getProjectWithoutDocLines(
this.project._id,
this.callback
)
})
- it('should call find with the project id', function() {
+ it('should call find with the project id', function () {
this.ProjectGetter.getProject
.calledWith(this.project._id)
.should.equal(true)
})
- it('should exclude the doc lines', function() {
+ it('should exclude the doc lines', function () {
const excludes = {
'rootFolder.docs.lines': 0,
'rootFolder.folders.docs.lines': 0,
@@ -97,32 +97,32 @@ describe('ProjectGetter', function() {
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
})
- describe('getProjectWithOnlyFolders', function() {
- beforeEach(function() {
+ describe('getProjectWithOnlyFolders', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject = sinon.stub().yields()
})
- describe('passing an id', function() {
- beforeEach(function() {
+ describe('passing an id', function () {
+ beforeEach(function () {
this.ProjectGetter.getProjectWithOnlyFolders(
this.project._id,
this.callback
)
})
- it('should call find with the project id', function() {
+ it('should call find with the project id', function () {
this.ProjectGetter.getProject
.calledWith(this.project._id)
.should.equal(true)
})
- it('should exclude the docs and files linesaaaa', function() {
+ it('should exclude the docs and files linesaaaa', function () {
const excludes = {
'rootFolder.docs': 0,
'rootFolder.fileRefs': 0,
@@ -146,20 +146,20 @@ describe('ProjectGetter', function() {
.should.equal(true)
})
- it('should call the callback with the project', function() {
+ it('should call the callback with the project', function () {
this.callback.called.should.equal(true)
})
})
})
- describe('getProject', function() {
- describe('without projection', function() {
- describe('with project id', function() {
- beforeEach(function() {
+ describe('getProject', function () {
+ describe('without projection', function () {
+ describe('with project id', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject(this.projectIdStr, this.callback)
})
- it('should call findOne with the project id', function() {
+ it('should call findOne with the project id', function () {
expect(this.db.projects.findOne.callCount).to.equal(1)
expect(
this.db.projects.findOne.lastCall.args[0]._id.toString()
@@ -167,25 +167,25 @@ describe('ProjectGetter', function() {
})
})
- describe('without project id', function() {
- beforeEach(function() {
+ describe('without project id', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject(null, this.callback)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
expect(this.db.projects.findOne.callCount).to.equal(0)
expect(this.callback.lastCall.args[0]).to.be.instanceOf(Error)
})
})
})
- describe('with projection', function() {
- beforeEach(function() {
+ describe('with projection', function () {
+ beforeEach(function () {
this.projection = { _id: 1 }
})
- describe('with project id', function() {
- beforeEach(function() {
+ describe('with project id', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject(
this.projectIdStr,
this.projection,
@@ -193,7 +193,7 @@ describe('ProjectGetter', function() {
)
})
- it('should call findOne with the project id', function() {
+ it('should call findOne with the project id', function () {
expect(this.db.projects.findOne.callCount).to.equal(1)
expect(
this.db.projects.findOne.lastCall.args[0]._id.toString()
@@ -204,12 +204,12 @@ describe('ProjectGetter', function() {
})
})
- describe('without project id', function() {
- beforeEach(function() {
+ describe('without project id', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject(null, this.callback)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
expect(this.db.projects.findOne.callCount).to.equal(0)
expect(this.callback.lastCall.args[0]).to.be.instanceOf(Error)
})
@@ -217,17 +217,17 @@ describe('ProjectGetter', function() {
})
})
- describe('getProjectWithoutLock', function() {
- describe('without projection', function() {
- describe('with project id', function() {
- beforeEach(function() {
+ describe('getProjectWithoutLock', function () {
+ describe('without projection', function () {
+ describe('with project id', function () {
+ beforeEach(function () {
this.ProjectGetter.getProjectWithoutLock(
this.projectIdStr,
this.callback
)
})
- it('should call findOne with the project id', function() {
+ it('should call findOne with the project id', function () {
expect(this.db.projects.findOne.callCount).to.equal(1)
expect(
this.db.projects.findOne.lastCall.args[0]._id.toString()
@@ -235,25 +235,25 @@ describe('ProjectGetter', function() {
})
})
- describe('without project id', function() {
- beforeEach(function() {
+ describe('without project id', function () {
+ beforeEach(function () {
this.ProjectGetter.getProjectWithoutLock(null, this.callback)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
expect(this.db.projects.findOne.callCount).to.equal(0)
expect(this.callback.lastCall.args[0]).to.be.instanceOf(Error)
})
})
})
- describe('with projection', function() {
- beforeEach(function() {
+ describe('with projection', function () {
+ beforeEach(function () {
this.projection = { _id: 1 }
})
- describe('with project id', function() {
- beforeEach(function() {
+ describe('with project id', function () {
+ beforeEach(function () {
this.ProjectGetter.getProjectWithoutLock(
this.project._id,
this.projection,
@@ -261,7 +261,7 @@ describe('ProjectGetter', function() {
)
})
- it('should call findOne with the project id', function() {
+ it('should call findOne with the project id', function () {
expect(this.db.projects.findOne.callCount).to.equal(1)
expect(
this.db.projects.findOne.lastCall.args[0]._id.toString()
@@ -272,12 +272,12 @@ describe('ProjectGetter', function() {
})
})
- describe('without project id', function() {
- beforeEach(function() {
+ describe('without project id', function () {
+ beforeEach(function () {
this.ProjectGetter.getProjectWithoutLock(null, this.callback)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
expect(this.db.projects.findOne.callCount).to.equal(0)
expect(this.callback.lastCall.args[0]).to.be.instanceOf(Error)
})
@@ -285,8 +285,8 @@ describe('ProjectGetter', function() {
})
})
- describe('findAllUsersProjects', function() {
- beforeEach(function() {
+ describe('findAllUsersProjects', function () {
+ beforeEach(function () {
this.fields = { mock: 'fields' }
this.Project.find
.withArgs({ owner_ref: this.userId }, this.fields)
@@ -304,7 +304,7 @@ describe('ProjectGetter', function() {
)
})
- it('should call the callback with all the projects', function() {
+ it('should call the callback with all the projects', function () {
this.callback
.calledWith(null, {
owned: ['mock-owned-projects'],
@@ -317,28 +317,28 @@ describe('ProjectGetter', function() {
})
})
- describe('getProjectIdByReadAndWriteToken', function() {
- describe('when project find returns project', function() {
- this.beforeEach(function() {
+ describe('getProjectIdByReadAndWriteToken', function () {
+ describe('when project find returns project', function () {
+ this.beforeEach(function () {
this.ProjectGetter.getProjectIdByReadAndWriteToken(
'token',
this.callback
)
})
- it('should find project with token', function() {
+ it('should find project with token', function () {
this.Project.findOne
.calledWithMatch({ 'tokens.readAndWrite': 'token' })
.should.equal(true)
})
- it('should callback with project id', function() {
+ it('should callback with project id', function () {
this.callback.calledWith(null, this.project._id).should.equal(true)
})
})
- describe('when project not found', function() {
- this.beforeEach(function() {
+ describe('when project not found', function () {
+ this.beforeEach(function () {
this.Project.findOne.yields(null, null)
this.ProjectGetter.getProjectIdByReadAndWriteToken(
'token',
@@ -346,13 +346,13 @@ describe('ProjectGetter', function() {
)
})
- it('should callback empty', function() {
+ it('should callback empty', function () {
expect(this.callback.firstCall.args.length).to.equal(0)
})
})
- describe('when project find returns error', function() {
- this.beforeEach(function() {
+ describe('when project find returns error', function () {
+ this.beforeEach(function () {
this.Project.findOne.yields('error')
this.ProjectGetter.getProjectIdByReadAndWriteToken(
'token',
@@ -360,14 +360,14 @@ describe('ProjectGetter', function() {
)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
this.callback.calledWith('error').should.equal(true)
})
})
})
- describe('findUsersProjectsByName', function() {
- it('should perform a case-insensitive search', function(done) {
+ describe('findUsersProjectsByName', function () {
+ it('should perform a case-insensitive search', function (done) {
this.Project.find
.withArgs({ owner_ref: this.userId })
.yields(null, [
@@ -391,7 +391,7 @@ describe('ProjectGetter', function() {
)
})
- it('should search collaborations as well', function(done) {
+ it('should search collaborations as well', function (done) {
this.Project.find
.withArgs({ owner_ref: this.userId })
.yields(null, [{ name: 'find me!' }])
@@ -418,8 +418,8 @@ describe('ProjectGetter', function() {
})
})
- describe('getUsersDeletedProjects', function() {
- it('should look up the deleted projects by deletedProjectOwnerId', function(done) {
+ describe('getUsersDeletedProjects', function () {
+ it('should look up the deleted projects by deletedProjectOwnerId', function (done) {
this.ProjectGetter.getUsersDeletedProjects('giraffe', err => {
if (err) {
return done(err)
@@ -431,7 +431,7 @@ describe('ProjectGetter', function() {
})
})
- it('should pass the found projects to the callback', function(done) {
+ it('should pass the found projects to the callback', function (done) {
this.ProjectGetter.getUsersDeletedProjects('giraffe', (err, docs) => {
if (err) {
return done(err)
diff --git a/services/web/test/unit/src/Project/ProjectHelperTests.js b/services/web/test/unit/src/Project/ProjectHelperTests.js
index f2bb644ec5..40b2492bae 100644
--- a/services/web/test/unit/src/Project/ProjectHelperTests.js
+++ b/services/web/test/unit/src/Project/ProjectHelperTests.js
@@ -4,8 +4,8 @@ const { ObjectId } = require('mongodb')
const MODULE_PATH = '../../../../app/src/Features/Project/ProjectHelper.js'
-describe('ProjectHelper', function() {
- beforeEach(function() {
+describe('ProjectHelper', function () {
+ beforeEach(function () {
this.project = {
_id: '123213jlkj9kdlsaj'
}
@@ -41,9 +41,9 @@ describe('ProjectHelper', function() {
})
})
- describe('isArchived', function() {
- describe('project.archived being an array', function() {
- it('returns true if user id is found', function() {
+ describe('isArchived', function () {
+ describe('project.archived being an array', function () {
+ it('returns true if user id is found', function () {
this.project.archived = [
ObjectId('588f3ddae8ebc1bac07c9fa4'),
ObjectId('5c41deb2b4ca500153340809')
@@ -53,7 +53,7 @@ describe('ProjectHelper', function() {
).to.equal(true)
})
- it('returns false if user id is not found', function() {
+ it('returns false if user id is not found', function () {
this.project.archived = []
expect(
this.ProjectHelper.isArchived(this.project, this.user._id)
@@ -61,15 +61,15 @@ describe('ProjectHelper', function() {
})
})
- describe('project.archived being a boolean', function() {
- it('returns true if archived is true', function() {
+ describe('project.archived being a boolean', function () {
+ it('returns true if archived is true', function () {
this.project.archived = true
expect(
this.ProjectHelper.isArchived(this.project, this.user._id)
).to.equal(true)
})
- it('returns false if archived is false', function() {
+ it('returns false if archived is false', function () {
this.project.archived = false
expect(
this.ProjectHelper.isArchived(this.project, this.user._id)
@@ -77,8 +77,8 @@ describe('ProjectHelper', function() {
})
})
- describe('project.archived being undefined', function() {
- it('returns false if archived is undefined', function() {
+ describe('project.archived being undefined', function () {
+ it('returns false if archived is undefined', function () {
this.project.archived = undefined
expect(
this.ProjectHelper.isArchived(this.project, this.user._id)
@@ -87,8 +87,8 @@ describe('ProjectHelper', function() {
})
})
- describe('isTrashed', function() {
- it('returns true if user id is found', function() {
+ describe('isTrashed', function () {
+ it('returns true if user id is found', function () {
this.project.trashed = [
ObjectId('588f3ddae8ebc1bac07c9fa4'),
ObjectId('5c41deb2b4ca500153340809')
@@ -98,15 +98,15 @@ describe('ProjectHelper', function() {
).to.equal(true)
})
- it('returns false if user id is not found', function() {
+ it('returns false if user id is not found', function () {
this.project.trashed = []
expect(
this.ProjectHelper.isTrashed(this.project, this.user._id)
).to.equal(false)
})
- describe('project.trashed being undefined', function() {
- it('returns false if trashed is undefined', function() {
+ describe('project.trashed being undefined', function () {
+ it('returns false if trashed is undefined', function () {
this.project.trashed = undefined
expect(
this.ProjectHelper.isTrashed(this.project, this.user._id)
@@ -115,9 +115,9 @@ describe('ProjectHelper', function() {
})
})
- describe('calculateArchivedArray', function() {
- describe('project.archived being an array', function() {
- it('returns an array adding the current user id when archiving', function() {
+ describe('calculateArchivedArray', function () {
+ describe('project.archived being an array', function () {
+ it('returns an array adding the current user id when archiving', function () {
const project = { archived: [] }
const result = this.ProjectHelper.calculateArchivedArray(
project,
@@ -127,7 +127,7 @@ describe('ProjectHelper', function() {
expect(result).to.deep.equal([ObjectId('5c922599cdb09e014aa7d499')])
})
- it('returns an array without the current user id when unarchiving', function() {
+ it('returns an array without the current user id when unarchiving', function () {
const project = { archived: [ObjectId('5c922599cdb09e014aa7d499')] }
const result = this.ProjectHelper.calculateArchivedArray(
project,
@@ -138,8 +138,8 @@ describe('ProjectHelper', function() {
})
})
- describe('project.archived being a boolean and being true', function() {
- it('returns an array of all associated user ids when archiving', function() {
+ describe('project.archived being a boolean and being true', function () {
+ it('returns an array of all associated user ids when archiving', function () {
const project = {
archived: true,
owner_ref: this.user._id,
@@ -166,7 +166,7 @@ describe('ProjectHelper', function() {
])
})
- it('returns an array of all associated users without the current user id when unarchived', function() {
+ it('returns an array of all associated users without the current user id when unarchived', function () {
const project = {
archived: true,
owner_ref: this.user._id,
@@ -194,8 +194,8 @@ describe('ProjectHelper', function() {
})
})
- describe('project.archived being a boolean and being false', function() {
- it('returns an array adding the current user id when archiving', function() {
+ describe('project.archived being a boolean and being false', function () {
+ it('returns an array adding the current user id when archiving', function () {
const project = { archived: false }
const result = this.ProjectHelper.calculateArchivedArray(
project,
@@ -205,7 +205,7 @@ describe('ProjectHelper', function() {
expect(result).to.deep.equal([ObjectId('5c922599cdb09e014aa7d499')])
})
- it('returns an empty array when unarchiving', function() {
+ it('returns an empty array when unarchiving', function () {
const project = { archived: false }
const result = this.ProjectHelper.calculateArchivedArray(
project,
@@ -216,8 +216,8 @@ describe('ProjectHelper', function() {
})
})
- describe('project.archived not being set', function() {
- it('returns an array adding the current user id when archiving', function() {
+ describe('project.archived not being set', function () {
+ it('returns an array adding the current user id when archiving', function () {
const project = { archived: undefined }
const result = this.ProjectHelper.calculateArchivedArray(
project,
@@ -227,7 +227,7 @@ describe('ProjectHelper', function() {
expect(result).to.deep.equal([ObjectId('5c922599cdb09e014aa7d499')])
})
- it('returns an empty array when unarchiving', function() {
+ it('returns an empty array when unarchiving', function () {
const project = { archived: undefined }
const result = this.ProjectHelper.calculateArchivedArray(
project,
@@ -239,34 +239,34 @@ describe('ProjectHelper', function() {
})
})
- describe('compilerFromV1Engine', function() {
- it('returns the correct engine for latex_dvipdf', function() {
+ describe('compilerFromV1Engine', function () {
+ it('returns the correct engine for latex_dvipdf', function () {
expect(this.ProjectHelper.compilerFromV1Engine('latex_dvipdf')).to.equal(
'latex'
)
})
- it('returns the correct engine for pdflatex', function() {
+ it('returns the correct engine for pdflatex', function () {
expect(this.ProjectHelper.compilerFromV1Engine('pdflatex')).to.equal(
'pdflatex'
)
})
- it('returns the correct engine for xelatex', function() {
+ it('returns the correct engine for xelatex', function () {
expect(this.ProjectHelper.compilerFromV1Engine('xelatex')).to.equal(
'xelatex'
)
})
- it('returns the correct engine for lualatex', function() {
+ it('returns the correct engine for lualatex', function () {
expect(this.ProjectHelper.compilerFromV1Engine('lualatex')).to.equal(
'lualatex'
)
})
})
- describe('getAllowedImagesForUser', function() {
- it('filters out admin-only images when the user is anonymous', function() {
+ describe('getAllowedImagesForUser', function () {
+ it('filters out admin-only images when the user is anonymous', function () {
const images = this.ProjectHelper.getAllowedImagesForUser(null)
const imageNames = images.map(image => image.imageName)
expect(imageNames).to.deep.equal([
@@ -275,7 +275,7 @@ describe('ProjectHelper', function() {
])
})
- it('filters out admin-only images when the user is not admin', function() {
+ it('filters out admin-only images when the user is not admin', function () {
const images = this.ProjectHelper.getAllowedImagesForUser(this.user)
const imageNames = images.map(image => image.imageName)
expect(imageNames).to.deep.equal([
@@ -284,7 +284,7 @@ describe('ProjectHelper', function() {
])
})
- it('returns all images when the user is admin', function() {
+ it('returns all images when the user is admin', function () {
const images = this.ProjectHelper.getAllowedImagesForUser(this.adminUser)
const imageNames = images.map(image => image.imageName)
expect(imageNames).to.deep.equal([
diff --git a/services/web/test/unit/src/Project/ProjectHistoryHandlerTests.js b/services/web/test/unit/src/Project/ProjectHistoryHandlerTests.js
index f02ccf3c1b..f8c3f6a96c 100644
--- a/services/web/test/unit/src/Project/ProjectHistoryHandlerTests.js
+++ b/services/web/test/unit/src/Project/ProjectHistoryHandlerTests.js
@@ -17,13 +17,13 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/Project/ProjectHistoryHandler'
const SandboxedModule = require('sandboxed-module')
-describe('ProjectHistoryHandler', function() {
+describe('ProjectHistoryHandler', function () {
const project_id = '4eecb1c1bffa66588e0000a1'
const userId = 1234
- beforeEach(function() {
+ beforeEach(function () {
let Project
- this.ProjectModel = Project = (function() {
+ this.ProjectModel = Project = (function () {
Project = class Project {
static initClass() {
this.prototype.rootFolder = [this.rootFolder]
@@ -55,8 +55,8 @@ describe('ProjectHistoryHandler', function() {
}))
})
- describe('starting history for an existing project', function() {
- beforeEach(function() {
+ describe('starting history for an existing project', function () {
+ beforeEach(function () {
this.newHistoryId = 123456789
this.HistoryManager.initializeProject = sinon
.stub()
@@ -67,8 +67,8 @@ describe('ProjectHistoryHandler', function() {
.callsArg(1))
})
- describe('when the history does not already exist', function() {
- beforeEach(function() {
+ describe('when the history does not already exist', function () {
+ beforeEach(function () {
this.ProjectDetailsHandler.getDetails = sinon
.stub()
.withArgs(project_id)
@@ -82,17 +82,17 @@ describe('ProjectHistoryHandler', function() {
)
})
- it('should get any existing history id for the project', function() {
+ it('should get any existing history id for the project', function () {
return this.ProjectDetailsHandler.getDetails
.calledWith(project_id)
.should.equal(true)
})
- it('should initialize a new history in the v1 history service', function() {
+ it('should initialize a new history in the v1 history service', function () {
return this.HistoryManager.initializeProject.called.should.equal(true)
})
- it('should set the new history id on the project', function() {
+ it('should set the new history id on the project', function () {
return this.ProjectModel.updateOne
.calledWith(
{ _id: project_id, 'overleaf.history.id': { $exists: false } },
@@ -101,25 +101,25 @@ describe('ProjectHistoryHandler', function() {
.should.equal(true)
})
- it('should resync the project history', function() {
+ it('should resync the project history', function () {
return this.ProjectEntityUpdateHandler.resyncProjectHistory
.calledWith(project_id)
.should.equal(true)
})
- it('should flush the project history', function() {
+ it('should flush the project history', function () {
return this.HistoryManager.flushProject
.calledWith(project_id)
.should.equal(true)
})
- it('should call the callback without an error', function() {
+ it('should call the callback without an error', function () {
return this.callback.called.should.equal(true)
})
})
- describe('when the history already exists', function() {
- beforeEach(function() {
+ describe('when the history already exists', function () {
+ beforeEach(function () {
this.project.overleaf = { history: { id: 1234 } }
this.ProjectDetailsHandler.getDetails = sinon
.stub()
@@ -132,31 +132,31 @@ describe('ProjectHistoryHandler', function() {
)
})
- it('should get any existing history id for the project', function() {
+ it('should get any existing history id for the project', function () {
return this.ProjectDetailsHandler.getDetails
.calledWith(project_id)
.should.equal(true)
})
- it('should not initialize a new history in the v1 history service', function() {
+ it('should not initialize a new history in the v1 history service', function () {
return this.HistoryManager.initializeProject.called.should.equal(false)
})
- it('should not set the new history id on the project', function() {
+ it('should not set the new history id on the project', function () {
return this.ProjectModel.updateOne.called.should.equal(false)
})
- it('should not resync the project history', function() {
+ it('should not resync the project history', function () {
return this.ProjectEntityUpdateHandler.resyncProjectHistory.called.should.equal(
false
)
})
- it('should not flush the project history', function() {
+ it('should not flush the project history', function () {
return this.HistoryManager.flushProject.called.should.equal(false)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.calledWith().should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Project/ProjectLocatorTests.js b/services/web/test/unit/src/Project/ProjectLocatorTests.js
index e2695cbf9a..6681b2e916 100644
--- a/services/web/test/unit/src/Project/ProjectLocatorTests.js
+++ b/services/web/test/unit/src/Project/ProjectLocatorTests.js
@@ -38,8 +38,8 @@ const rootFolder = {
project.rootFolder[0] = rootFolder
project.rootDoc_id = rootDoc._id
-describe('ProjectLocator', function() {
- beforeEach(function() {
+describe('ProjectLocator', function () {
+ beforeEach(function () {
Project.findById = (projectId, callback) => {
callback(null, project)
}
@@ -61,8 +61,8 @@ describe('ProjectLocator', function() {
})
})
- describe('finding a doc', function() {
- it('finds one at the root level', function(done) {
+ describe('finding a doc', function () {
+ it('finds one at the root level', function (done) {
this.locator.findElement(
{ project_id: project._id, element_id: doc2._id, type: 'docs' },
(err, foundElement, path, parentFolder) => {
@@ -78,7 +78,7 @@ describe('ProjectLocator', function() {
)
})
- it('when it is nested', function(done) {
+ it('when it is nested', function (done) {
this.locator.findElement(
{ project_id: project._id, element_id: subSubDoc._id, type: 'doc' },
(err, foundElement, path, parentFolder) => {
@@ -96,7 +96,7 @@ describe('ProjectLocator', function() {
)
})
- it('should give error if element could not be found', function(done) {
+ it('should give error if element could not be found', function (done) {
this.locator.findElement(
{ project_id: project._id, element_id: 'ddsd432nj42', type: 'docs' },
(err, foundElement, path, parentFolder) => {
@@ -108,8 +108,8 @@ describe('ProjectLocator', function() {
})
})
- describe('finding a folder', function() {
- it('should return root folder when looking for root folder', function(done) {
+ describe('finding a folder', function () {
+ it('should return root folder when looking for root folder', function (done) {
this.locator.findElement(
{ project_id: project._id, element_id: rootFolder._id, type: 'folder' },
(err, foundElement, path, parentFolder) => {
@@ -122,7 +122,7 @@ describe('ProjectLocator', function() {
)
})
- it('when at root', function(done) {
+ it('when at root', function (done) {
this.locator.findElement(
{ project_id: project._id, element_id: subFolder._id, type: 'folder' },
(err, foundElement, path, parentFolder) => {
@@ -138,7 +138,7 @@ describe('ProjectLocator', function() {
)
})
- it('when deeply nested', function(done) {
+ it('when deeply nested', function (done) {
this.locator.findElement(
{
project_id: project._id,
@@ -161,8 +161,8 @@ describe('ProjectLocator', function() {
})
})
- describe('finding a file', function() {
- it('when at root', function(done) {
+ describe('finding a file', function () {
+ it('when at root', function (done) {
this.locator.findElement(
{ project_id: project._id, element_id: file1._id, type: 'fileRefs' },
(err, foundElement, path, parentFolder) => {
@@ -178,7 +178,7 @@ describe('ProjectLocator', function() {
)
})
- it('when deeply nested', function(done) {
+ it('when deeply nested', function (done) {
this.locator.findElement(
{
project_id: project._id,
@@ -201,8 +201,8 @@ describe('ProjectLocator', function() {
})
})
- describe('finding an element with wrong element type', function() {
- it('should add an s onto the element type', function(done) {
+ describe('finding an element with wrong element type', function () {
+ it('should add an s onto the element type', function (done) {
this.locator.findElement(
{ project_id: project._id, element_id: subSubDoc._id, type: 'doc' },
(err, foundElement, path, parentFolder) => {
@@ -215,7 +215,7 @@ describe('ProjectLocator', function() {
)
})
- it('should convert file to fileRefs', function(done) {
+ it('should convert file to fileRefs', function (done) {
this.locator.findElement(
{ project_id: project._id, element_id: file1._id, type: 'fileRefs' },
(err, foundElement, path, parentFolder) => {
@@ -229,7 +229,7 @@ describe('ProjectLocator', function() {
})
})
- describe('should be able to take actual project as well as id', function() {
+ describe('should be able to take actual project as well as id', function () {
const doc3 = {
_id: '123dsdj3',
name: 'doc3'
@@ -242,7 +242,7 @@ describe('ProjectLocator', function() {
_id: '1234566',
rootFolder: [rootFolder2]
}
- it('should find doc in project', function(done) {
+ it('should find doc in project', function (done) {
this.locator.findElement(
{ project: project2, element_id: doc3._id, type: 'docs' },
(err, foundElement, path, parentFolder) => {
@@ -259,8 +259,8 @@ describe('ProjectLocator', function() {
})
})
- describe('finding root doc', function() {
- it('should return root doc when passed project', function(done) {
+ describe('finding root doc', function () {
+ it('should return root doc when passed project', function (done) {
this.locator.findRootDoc(project, (err, doc) => {
if (err != null) {
return done(err)
@@ -270,7 +270,7 @@ describe('ProjectLocator', function() {
})
})
- it('should return root doc when passed project_id', function(done) {
+ it('should return root doc when passed project_id', function (done) {
this.locator.findRootDoc(project._id, (err, doc) => {
if (err != null) {
return done(err)
@@ -280,7 +280,7 @@ describe('ProjectLocator', function() {
})
})
- it('should return null when the project has no rootDoc', function(done) {
+ it('should return null when the project has no rootDoc', function (done) {
project.rootDoc_id = null
this.locator.findRootDoc(project, (err, doc) => {
if (err != null) {
@@ -291,7 +291,7 @@ describe('ProjectLocator', function() {
})
})
- it('should return null when the rootDoc_id no longer exists', function(done) {
+ it('should return null when the rootDoc_id no longer exists', function (done) {
project.rootDoc_id = 'doesntexist'
this.locator.findRootDoc(project, (err, doc) => {
if (err != null) {
@@ -303,8 +303,8 @@ describe('ProjectLocator', function() {
})
})
- describe('findElementByPath', function() {
- it('should take a doc path and return the element for a root level document', function(done) {
+ describe('findElementByPath', function () {
+ it('should take a doc path and return the element for a root level document', function (done) {
const path = `${doc1.name}`
this.locator.findElementByPath(
{ project, path },
@@ -319,7 +319,7 @@ describe('ProjectLocator', function() {
)
})
- it('should take a doc path and return the element for a root level document with a starting slash', function(done) {
+ it('should take a doc path and return the element for a root level document with a starting slash', function (done) {
const path = `/${doc1.name}`
this.locator.findElementByPath(
{ project, path },
@@ -334,7 +334,7 @@ describe('ProjectLocator', function() {
)
})
- it('should take a doc path and return the element for a nested document', function(done) {
+ it('should take a doc path and return the element for a nested document', function (done) {
const path = `${subFolder.name}/${secondSubFolder.name}/${subSubDoc.name}`
this.locator.findElementByPath(
{ project, path },
@@ -349,7 +349,7 @@ describe('ProjectLocator', function() {
)
})
- it('should take a file path and return the element for a root level document', function(done) {
+ it('should take a file path and return the element for a root level document', function (done) {
const path = `${file1.name}`
this.locator.findElementByPath(
{ project, path },
@@ -364,7 +364,7 @@ describe('ProjectLocator', function() {
)
})
- it('should take a file path and return the element for a nested document', function(done) {
+ it('should take a file path and return the element for a nested document', function (done) {
const path = `${subFolder.name}/${secondSubFolder.name}/${subSubFile.name}`
this.locator.findElementByPath(
{ project, path },
@@ -379,7 +379,7 @@ describe('ProjectLocator', function() {
)
})
- it('should take a file path and return the element for a nested document case insenstive', function(done) {
+ it('should take a file path and return the element for a nested document case insenstive', function (done) {
const path = `${subFolder.name.toUpperCase()}/${secondSubFolder.name.toUpperCase()}/${subSubFile.name.toUpperCase()}`
this.locator.findElementByPath(
{ project, path },
@@ -394,7 +394,7 @@ describe('ProjectLocator', function() {
)
})
- it('should take a file path and return the element for a nested folder', function(done) {
+ it('should take a file path and return the element for a nested folder', function (done) {
const path = `${subFolder.name}/${secondSubFolder.name}`
this.locator.findElementByPath(
{ project, path },
@@ -409,7 +409,7 @@ describe('ProjectLocator', function() {
)
})
- it('should take a file path and return the root folder', function(done) {
+ it('should take a file path and return the root folder', function (done) {
const path = '/'
this.locator.findElementByPath(
{ project, path },
@@ -424,7 +424,7 @@ describe('ProjectLocator', function() {
)
})
- it('should return an error if the file can not be found inside know folder', function(done) {
+ it('should return an error if the file can not be found inside know folder', function (done) {
const path = `${subFolder.name}/${secondSubFolder.name}/exist.txt`
this.locator.findElementByPath(
{ project, path },
@@ -437,7 +437,7 @@ describe('ProjectLocator', function() {
)
})
- it('should return an error if the file can not be found inside unknown folder', function(done) {
+ it('should return an error if the file can not be found inside unknown folder', function (done) {
const path = 'this/does/not/exist.txt'
this.locator.findElementByPath(
{ project, path },
@@ -450,8 +450,8 @@ describe('ProjectLocator', function() {
)
})
- describe('where duplicate folder exists', function() {
- beforeEach(function() {
+ describe('where duplicate folder exists', function () {
+ beforeEach(function () {
this.duplicateFolder = {
name: 'duplicate1',
_id: '1234',
@@ -477,14 +477,14 @@ describe('ProjectLocator', function() {
}
})
- it('should not call the callback more than once', function(done) {
+ it('should not call the callback more than once', function (done) {
const path = `${this.duplicateFolder.name}/${this.doc.name}`
this.locator.findElementByPath({ project: this.project, path }, () =>
done()
)
}) // mocha will throw exception if done called multiple times
- it('should not call the callback more than once when the path is longer than 1 level below the duplicate level', function(done) {
+ it('should not call the callback more than once when the path is longer than 1 level below the duplicate level', function (done) {
const path = `${this.duplicateFolder.name}/1/main.tex`
this.locator.findElementByPath({ project: this.project, path }, () =>
done()
@@ -492,8 +492,8 @@ describe('ProjectLocator', function() {
})
}) // mocha will throw exception if done called multiple times
- describe('with a null doc', function() {
- beforeEach(function() {
+ describe('with a null doc', function () {
+ beforeEach(function () {
this.project = {
rootFolder: [
{
@@ -505,7 +505,7 @@ describe('ProjectLocator', function() {
}
})
- it('should not crash with a null', function(done) {
+ it('should not crash with a null', function (done) {
const path = '/other.tex'
this.locator.findElementByPath(
{ project: this.project, path },
@@ -520,12 +520,12 @@ describe('ProjectLocator', function() {
})
})
- describe('with a null project', function() {
- beforeEach(function() {
+ describe('with a null project', function () {
+ beforeEach(function () {
this.ProjectGetter = { getProject: sinon.stub().callsArg(2) }
})
- it('should not crash with a null', function(done) {
+ it('should not crash with a null', function (done) {
const path = '/other.tex'
this.locator.findElementByPath(
{ project_id: project._id, path },
@@ -537,8 +537,8 @@ describe('ProjectLocator', function() {
})
})
- describe('with a project_id', function() {
- it('should take a doc path and return the element for a root level document', function(done) {
+ describe('with a project_id', function () {
+ it('should take a doc path and return the element for a root level document', function (done) {
const path = `${doc1.name}`
this.locator.findElementByPath(
{ project_id: project._id, path },
diff --git a/services/web/test/unit/src/Project/ProjectOptionsHandlerTests.js b/services/web/test/unit/src/Project/ProjectOptionsHandlerTests.js
index 91d0100d69..f6b898bd1f 100644
--- a/services/web/test/unit/src/Project/ProjectOptionsHandlerTests.js
+++ b/services/web/test/unit/src/Project/ProjectOptionsHandlerTests.js
@@ -19,10 +19,10 @@ const modulePath =
'../../../../app/src/Features/Project/ProjectOptionsHandler.js'
const SandboxedModule = require('sandboxed-module')
-describe('ProjectOptionsHandler', function() {
+describe('ProjectOptionsHandler', function () {
const project_id = '4eecaffcbffa66588e000008'
- beforeEach(function() {
+ beforeEach(function () {
let Project
this.projectModel = Project = class Project {
constructor(options) {}
@@ -47,8 +47,8 @@ describe('ProjectOptionsHandler', function() {
})
})
- describe('Setting the compiler', function() {
- it('should perform and update on mongo', function(done) {
+ describe('Setting the compiler', function () {
+ it('should perform and update on mongo', function (done) {
this.handler.setCompiler(project_id, 'xeLaTeX', err => {
const args = this.projectModel.updateOne.args[0]
args[0]._id.should.equal(project_id)
@@ -57,15 +57,15 @@ describe('ProjectOptionsHandler', function() {
})
})
- it('should not perform and update on mongo if it is not a recognised compiler', function(done) {
+ it('should not perform and update on mongo if it is not a recognised compiler', function (done) {
this.handler.setCompiler(project_id, 'something', err => {
this.projectModel.updateOne.called.should.equal(false)
done()
})
})
- describe('when called without arg', function() {
- it('should callback with null', function(done) {
+ describe('when called without arg', function () {
+ it('should callback with null', function (done) {
this.handler.setCompiler(project_id, null, err => {
expect(err).to.be.undefined
this.projectModel.updateOne.callCount.should.equal(0)
@@ -74,12 +74,12 @@ describe('ProjectOptionsHandler', function() {
})
})
- describe('when mongo update error occurs', function() {
- beforeEach(function() {
+ describe('when mongo update error occurs', function () {
+ beforeEach(function () {
this.projectModel.updateOne = sinon.stub().yields('error')
})
- it('should callback with error', function(done) {
+ it('should callback with error', function (done) {
this.handler.setCompiler(project_id, 'xeLaTeX', err => {
err.should.equal('error')
done()
@@ -88,8 +88,8 @@ describe('ProjectOptionsHandler', function() {
})
})
- describe('Setting the imageName', function() {
- it('should perform and update on mongo', function(done) {
+ describe('Setting the imageName', function () {
+ it('should perform and update on mongo', function (done) {
this.handler.setImageName(project_id, 'texlive-1234.5', err => {
const args = this.projectModel.updateOne.args[0]
args[0]._id.should.equal(project_id)
@@ -98,15 +98,15 @@ describe('ProjectOptionsHandler', function() {
})
})
- it('should not perform and update on mongo if it is not a reconised compiler', function(done) {
+ it('should not perform and update on mongo if it is not a reconised compiler', function (done) {
this.handler.setImageName(project_id, 'something', err => {
this.projectModel.updateOne.called.should.equal(false)
done()
})
})
- describe('when called without arg', function() {
- it('should callback with null', function(done) {
+ describe('when called without arg', function () {
+ it('should callback with null', function (done) {
this.handler.setImageName(project_id, null, err => {
expect(err).to.be.undefined
this.projectModel.updateOne.callCount.should.equal(0)
@@ -115,12 +115,12 @@ describe('ProjectOptionsHandler', function() {
})
})
- describe('when mongo update error occurs', function() {
- beforeEach(function() {
+ describe('when mongo update error occurs', function () {
+ beforeEach(function () {
this.projectModel.updateOne = sinon.stub().yields('error')
})
- it('should callback with error', function(done) {
+ it('should callback with error', function (done) {
this.handler.setImageName(project_id, 'texlive-1234.5', err => {
err.should.equal('error')
done()
@@ -129,8 +129,8 @@ describe('ProjectOptionsHandler', function() {
})
})
- describe('setting the spellCheckLanguage', function() {
- it('should perform and update on mongo', function(done) {
+ describe('setting the spellCheckLanguage', function () {
+ it('should perform and update on mongo', function (done) {
this.handler.setSpellCheckLanguage(project_id, 'fr', err => {
const args = this.projectModel.updateOne.args[0]
args[0]._id.should.equal(project_id)
@@ -139,26 +139,26 @@ describe('ProjectOptionsHandler', function() {
})
})
- it('should not perform and update on mongo if it is not a reconised compiler', function(done) {
+ it('should not perform and update on mongo if it is not a reconised compiler', function (done) {
this.handler.setSpellCheckLanguage(project_id, 'no a lang', err => {
this.projectModel.updateOne.called.should.equal(false)
done()
})
})
- it('should perform and update on mongo if the language is blank (means turn it off)', function(done) {
+ it('should perform and update on mongo if the language is blank (means turn it off)', function (done) {
this.handler.setSpellCheckLanguage(project_id, '', err => {
this.projectModel.updateOne.called.should.equal(true)
done()
})
})
- describe('when mongo update error occurs', function() {
- beforeEach(function() {
+ describe('when mongo update error occurs', function () {
+ beforeEach(function () {
this.projectModel.updateOne = sinon.stub().yields('error')
})
- it('should callback with error', function(done) {
+ it('should callback with error', function (done) {
this.handler.setSpellCheckLanguage(project_id, 'fr', err => {
err.should.equal('error')
done()
@@ -167,8 +167,8 @@ describe('ProjectOptionsHandler', function() {
})
})
- describe('setting the brandVariationId', function() {
- it('should perform and update on mongo', function(done) {
+ describe('setting the brandVariationId', function () {
+ it('should perform and update on mongo', function (done) {
this.handler.setBrandVariationId(project_id, '123', err => {
const args = this.projectModel.updateOne.args[0]
args[0]._id.should.equal(project_id)
@@ -177,26 +177,26 @@ describe('ProjectOptionsHandler', function() {
})
})
- it('should not perform and update on mongo if there is no brand variation', function(done) {
+ it('should not perform and update on mongo if there is no brand variation', function (done) {
this.handler.setBrandVariationId(project_id, null, err => {
this.projectModel.updateOne.called.should.equal(false)
done()
})
})
- it('should not perform and update on mongo if brand variation is an empty string', function(done) {
+ it('should not perform and update on mongo if brand variation is an empty string', function (done) {
this.handler.setBrandVariationId(project_id, '', err => {
this.projectModel.updateOne.called.should.equal(false)
done()
})
})
- describe('when mongo update error occurs', function() {
- beforeEach(function() {
+ describe('when mongo update error occurs', function () {
+ beforeEach(function () {
this.projectModel.updateOne = sinon.stub().yields('error')
})
- it('should callback with error', function(done) {
+ it('should callback with error', function (done) {
this.handler.setBrandVariationId(project_id, '123', err => {
err.should.equal('error')
done()
@@ -205,8 +205,8 @@ describe('ProjectOptionsHandler', function() {
})
})
- describe('unsetting the brandVariationId', function() {
- it('should perform and update on mongo', function(done) {
+ describe('unsetting the brandVariationId', function () {
+ it('should perform and update on mongo', function (done) {
this.handler.unsetBrandVariationId(project_id, err => {
const args = this.projectModel.updateOne.args[0]
args[0]._id.should.equal(project_id)
@@ -215,12 +215,12 @@ describe('ProjectOptionsHandler', function() {
})
})
- describe('when mongo update error occurs', function() {
- beforeEach(function() {
+ describe('when mongo update error occurs', function () {
+ beforeEach(function () {
this.projectModel.updateOne = sinon.stub().yields('error')
})
- it('should callback with error', function(done) {
+ it('should callback with error', function (done) {
this.handler.unsetBrandVariationId(project_id, err => {
err.should.equal('error')
done()
diff --git a/services/web/test/unit/src/Project/ProjectRootDocManagerTests.js b/services/web/test/unit/src/Project/ProjectRootDocManagerTests.js
index 9203768b85..28622bddad 100644
--- a/services/web/test/unit/src/Project/ProjectRootDocManagerTests.js
+++ b/services/web/test/unit/src/Project/ProjectRootDocManagerTests.js
@@ -17,8 +17,8 @@ const modulePath =
'../../../../app/src/Features/Project/ProjectRootDocManager.js'
const SandboxedModule = require('sandboxed-module')
-describe('ProjectRootDocManager', function() {
- beforeEach(function() {
+describe('ProjectRootDocManager', function () {
+ beforeEach(function () {
this.project_id = 'project-123'
this.docPaths = {
'doc-id-1': '/chapter1.tex',
@@ -49,15 +49,15 @@ describe('ProjectRootDocManager', function() {
}))
})
- describe('setRootDocAutomatically', function() {
- beforeEach(function() {
+ describe('setRootDocAutomatically', function () {
+ beforeEach(function () {
this.ProjectEntityUpdateHandler.setRootDoc = sinon.stub().callsArgWith(2)
this.ProjectEntityUpdateHandler.isPathValidForRootDoc = sinon
.stub()
.returns(true)
})
- describe('when there is a suitable root doc', function() {
- beforeEach(function(done) {
+ describe('when there is a suitable root doc', function () {
+ beforeEach(function (done) {
this.docs = {
'/chapter1.tex': {
_id: 'doc-id-1',
@@ -94,21 +94,21 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should check the docs of the project', function() {
+ it('should check the docs of the project', function () {
return this.ProjectEntityHandler.getAllDocs
.calledWith(this.project_id)
.should.equal(true)
})
- it('should set the root doc to the doc containing a documentclass', function() {
+ it('should set the root doc to the doc containing a documentclass', function () {
return this.ProjectEntityUpdateHandler.setRootDoc
.calledWith(this.project_id, 'doc-id-2')
.should.equal(true)
})
})
- describe('when the root doc is an Rtex file', function() {
- beforeEach(function(done) {
+ describe('when the root doc is an Rtex file', function () {
+ beforeEach(function (done) {
this.docs = {
'/chapter1.tex': {
_id: 'doc-id-1',
@@ -128,15 +128,15 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should set the root doc to the doc containing a documentclass', function() {
+ it('should set the root doc to the doc containing a documentclass', function () {
return this.ProjectEntityUpdateHandler.setRootDoc
.calledWith(this.project_id, 'doc-id-2')
.should.equal(true)
})
})
- describe('when there is no suitable root doc', function() {
- beforeEach(function(done) {
+ describe('when there is no suitable root doc', function () {
+ beforeEach(function (done) {
this.docs = {
'/chapter1.tex': {
_id: 'doc-id-1',
@@ -156,7 +156,7 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should not set the root doc to the doc containing a documentclass', function() {
+ it('should not set the root doc to the doc containing a documentclass', function () {
return this.ProjectEntityUpdateHandler.setRootDoc.called.should.equal(
false
)
@@ -164,8 +164,8 @@ describe('ProjectRootDocManager', function() {
})
})
- describe('findRootDocFileFromDirectory', function() {
- beforeEach(function() {
+ describe('findRootDocFileFromDirectory', function () {
+ beforeEach(function () {
this.fs.readFile
.withArgs('/foo/a.tex')
.callsArgWith(2, null, 'Hello World!')
@@ -184,8 +184,8 @@ describe('ProjectRootDocManager', function() {
return (this.documentclassContent = '% test\n\\documentclass\n% test')
})
- describe('when there is a file in a subfolder', function() {
- beforeEach(function() {
+ describe('when there is a file in a subfolder', function () {
+ beforeEach(function () {
// have to splice globbyFiles weirdly because of the way the stubbed globby method handles references
return this.globbyFiles.splice(
0,
@@ -197,7 +197,7 @@ describe('ProjectRootDocManager', function() {
)
})
- it('processes the root folder files first, and then the subfolder, in alphabetical order', function(done) {
+ it('processes the root folder files first, and then the subfolder, in alphabetical order', function (done) {
return this.ProjectRootDocManager.findRootDocFileFromDirectory(
'/foo',
(error, path) => {
@@ -214,7 +214,7 @@ describe('ProjectRootDocManager', function() {
)
})
- it('processes smaller files first', function(done) {
+ it('processes smaller files first', function (done) {
this.fs.stat.withArgs('/foo/c.tex').callsArgWith(1, null, { size: 1 })
return this.ProjectRootDocManager.findRootDocFileFromDirectory(
'/foo',
@@ -233,14 +233,14 @@ describe('ProjectRootDocManager', function() {
})
})
- describe('when main.tex contains a documentclass', function() {
- beforeEach(function() {
+ describe('when main.tex contains a documentclass', function () {
+ beforeEach(function () {
return this.fs.readFile
.withArgs('/foo/main.tex')
.callsArgWith(2, null, this.documentclassContent)
})
- it('returns main.tex', function(done) {
+ it('returns main.tex', function (done) {
return this.ProjectRootDocManager.findRootDocFileFromDirectory(
'/foo',
(error, path, content) => {
@@ -252,7 +252,7 @@ describe('ProjectRootDocManager', function() {
)
})
- it('processes main.text first and stops processing when it finds the content', function(done) {
+ it('processes main.text first and stops processing when it finds the content', function (done) {
return this.ProjectRootDocManager.findRootDocFileFromDirectory(
'/foo',
() => {
@@ -264,14 +264,14 @@ describe('ProjectRootDocManager', function() {
})
})
- describe('when a.tex contains a documentclass', function() {
- beforeEach(function() {
+ describe('when a.tex contains a documentclass', function () {
+ beforeEach(function () {
return this.fs.readFile
.withArgs('/foo/a.tex')
.callsArgWith(2, null, this.documentclassContent)
})
- it('returns a.tex', function(done) {
+ it('returns a.tex', function (done) {
return this.ProjectRootDocManager.findRootDocFileFromDirectory(
'/foo',
(error, path, content) => {
@@ -283,7 +283,7 @@ describe('ProjectRootDocManager', function() {
)
})
- it('processes main.text first and stops processing when it finds the content', function(done) {
+ it('processes main.text first and stops processing when it finds the content', function (done) {
return this.ProjectRootDocManager.findRootDocFileFromDirectory(
'/foo',
() => {
@@ -296,8 +296,8 @@ describe('ProjectRootDocManager', function() {
})
})
- describe('when there is no documentclass', function() {
- it('returns null with no error', function(done) {
+ describe('when there is no documentclass', function () {
+ it('returns null with no error', function (done) {
return this.ProjectRootDocManager.findRootDocFileFromDirectory(
'/foo',
(error, path, content) => {
@@ -309,7 +309,7 @@ describe('ProjectRootDocManager', function() {
)
})
- it('processes all the files', function(done) {
+ it('processes all the files', function (done) {
return this.ProjectRootDocManager.findRootDocFileFromDirectory(
'/foo',
() => {
@@ -322,14 +322,14 @@ describe('ProjectRootDocManager', function() {
})
})
- describe('when there is an error reading a file', function() {
- beforeEach(function() {
+ describe('when there is an error reading a file', function () {
+ beforeEach(function () {
return this.fs.readFile
.withArgs('/foo/a.tex')
.callsArgWith(2, new Error('something went wrong'))
})
- it('returns an error', function(done) {
+ it('returns an error', function (done) {
return this.ProjectRootDocManager.findRootDocFileFromDirectory(
'/foo',
(error, path, content) => {
@@ -343,9 +343,9 @@ describe('ProjectRootDocManager', function() {
})
})
- describe('setRootDocFromName', function() {
- describe('when there is a suitable root doc', function() {
- beforeEach(function(done) {
+ describe('setRootDocFromName', function () {
+ describe('when there is a suitable root doc', function () {
+ beforeEach(function (done) {
this.docPaths = {
'doc-id-1': '/chapter1.tex',
'doc-id-2': '/main.tex',
@@ -365,21 +365,21 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should check the docs of the project', function() {
+ it('should check the docs of the project', function () {
return this.ProjectEntityHandler.getAllDocPathsFromProjectById
.calledWith(this.project_id)
.should.equal(true)
})
- it('should set the root doc to main.tex', function() {
+ it('should set the root doc to main.tex', function () {
return this.ProjectEntityUpdateHandler.setRootDoc
.calledWith(this.project_id, 'doc-id-2')
.should.equal(true)
})
})
- describe('when there is a suitable root doc but the leading slash is missing', function() {
- beforeEach(function(done) {
+ describe('when there is a suitable root doc but the leading slash is missing', function () {
+ beforeEach(function (done) {
this.ProjectEntityHandler.getAllDocPathsFromProjectById = sinon
.stub()
.callsArgWith(1, null, this.docPaths)
@@ -393,21 +393,21 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should check the docs of the project', function() {
+ it('should check the docs of the project', function () {
return this.ProjectEntityHandler.getAllDocPathsFromProjectById
.calledWith(this.project_id)
.should.equal(true)
})
- it('should set the root doc to main.tex', function() {
+ it('should set the root doc to main.tex', function () {
return this.ProjectEntityUpdateHandler.setRootDoc
.calledWith(this.project_id, 'doc-id-2')
.should.equal(true)
})
})
- describe('when there is a suitable root doc with a basename match', function() {
- beforeEach(function(done) {
+ describe('when there is a suitable root doc with a basename match', function () {
+ beforeEach(function (done) {
this.ProjectEntityHandler.getAllDocPathsFromProjectById = sinon
.stub()
.callsArgWith(1, null, this.docPaths)
@@ -421,21 +421,21 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should check the docs of the project', function() {
+ it('should check the docs of the project', function () {
return this.ProjectEntityHandler.getAllDocPathsFromProjectById
.calledWith(this.project_id)
.should.equal(true)
})
- it('should set the root doc using the basename', function() {
+ it('should set the root doc using the basename', function () {
return this.ProjectEntityUpdateHandler.setRootDoc
.calledWith(this.project_id, 'doc-id-3')
.should.equal(true)
})
})
- describe('when there is a suitable root doc but the filename is in quotes', function() {
- beforeEach(function(done) {
+ describe('when there is a suitable root doc but the filename is in quotes', function () {
+ beforeEach(function (done) {
this.ProjectEntityHandler.getAllDocPathsFromProjectById = sinon
.stub()
.callsArgWith(1, null, this.docPaths)
@@ -449,21 +449,21 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should check the docs of the project', function() {
+ it('should check the docs of the project', function () {
return this.ProjectEntityHandler.getAllDocPathsFromProjectById
.calledWith(this.project_id)
.should.equal(true)
})
- it('should set the root doc to main.tex', function() {
+ it('should set the root doc to main.tex', function () {
return this.ProjectEntityUpdateHandler.setRootDoc
.calledWith(this.project_id, 'doc-id-2')
.should.equal(true)
})
})
- describe('when there is no suitable root doc', function() {
- beforeEach(function(done) {
+ describe('when there is no suitable root doc', function () {
+ beforeEach(function (done) {
this.ProjectEntityHandler.getAllDocPathsFromProjectById = sinon
.stub()
.callsArgWith(1, null, this.docPaths)
@@ -477,7 +477,7 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should not set the root doc', function() {
+ it('should not set the root doc', function () {
return this.ProjectEntityUpdateHandler.setRootDoc.called.should.equal(
false
)
@@ -485,8 +485,8 @@ describe('ProjectRootDocManager', function() {
})
})
- describe('ensureRootDocumentIsSet', function() {
- beforeEach(function() {
+ describe('ensureRootDocumentIsSet', function () {
+ beforeEach(function () {
this.project = {}
this.ProjectGetter.getProject = sinon
.stub()
@@ -496,8 +496,8 @@ describe('ProjectRootDocManager', function() {
.callsArgWith(1, null))
})
- describe('when the root doc is set', function() {
- beforeEach(function() {
+ describe('when the root doc is set', function () {
+ beforeEach(function () {
this.project.rootDoc_id = 'root-doc-id'
return this.ProjectRootDocManager.ensureRootDocumentIsSet(
this.project_id,
@@ -505,50 +505,50 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should find the project fetching only the rootDoc_id field', function() {
+ it('should find the project fetching only the rootDoc_id field', function () {
return this.ProjectGetter.getProject
.calledWith(this.project_id, { rootDoc_id: 1 })
.should.equal(true)
})
- it('should not try to update the project rootDoc_id', function() {
+ it('should not try to update the project rootDoc_id', function () {
return this.ProjectRootDocManager.setRootDocAutomatically.called.should.equal(
false
)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('when the root doc is not set', function() {
- beforeEach(function() {
+ describe('when the root doc is not set', function () {
+ beforeEach(function () {
return this.ProjectRootDocManager.ensureRootDocumentIsSet(
this.project_id,
this.callback
)
})
- it('should find the project with only the rootDoc_id field', function() {
+ it('should find the project with only the rootDoc_id field', function () {
return this.ProjectGetter.getProject
.calledWith(this.project_id, { rootDoc_id: 1 })
.should.equal(true)
})
- it('should update the project rootDoc_id', function() {
+ it('should update the project rootDoc_id', function () {
return this.ProjectRootDocManager.setRootDocAutomatically
.calledWith(this.project_id)
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('when the project does not exist', function() {
- beforeEach(function() {
+ describe('when the project does not exist', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, null)
return this.ProjectRootDocManager.ensureRootDocumentIsSet(
this.project_id,
@@ -556,7 +556,7 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
@@ -568,8 +568,8 @@ describe('ProjectRootDocManager', function() {
})
})
- describe('ensureRootDocumentIsValid', function() {
- beforeEach(function() {
+ describe('ensureRootDocumentIsValid', function () {
+ beforeEach(function () {
this.project = {}
this.ProjectGetter.getProject = sinon
.stub()
@@ -584,9 +584,9 @@ describe('ProjectRootDocManager', function() {
.callsArgWith(1, null))
})
- describe('when the root doc is set', function() {
- describe('when the root doc is valid', function() {
- beforeEach(function() {
+ describe('when the root doc is set', function () {
+ describe('when the root doc is valid', function () {
+ beforeEach(function () {
this.project.rootDoc_id = 'doc-id-2'
return this.ProjectRootDocManager.ensureRootDocumentIsValid(
this.project_id,
@@ -594,25 +594,25 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should find the project fetching only the rootDoc_id field', function() {
+ it('should find the project fetching only the rootDoc_id field', function () {
return this.ProjectGetter.getProject
.calledWith(this.project_id, { rootDoc_id: 1 })
.should.equal(true)
})
- it('should not try to update the project rootDoc_id', function() {
+ it('should not try to update the project rootDoc_id', function () {
return this.ProjectRootDocManager.setRootDocAutomatically.called.should.equal(
false
)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('when the root doc is not valid', function() {
- beforeEach(function() {
+ describe('when the root doc is not valid', function () {
+ beforeEach(function () {
this.project.rootDoc_id = 'bogus-doc-id'
return this.ProjectRootDocManager.ensureRootDocumentIsValid(
this.project_id,
@@ -620,57 +620,57 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should find the project fetching only the rootDoc_id field', function() {
+ it('should find the project fetching only the rootDoc_id field', function () {
return this.ProjectGetter.getProject
.calledWith(this.project_id, { rootDoc_id: 1 })
.should.equal(true)
})
- it('should unset the root doc', function() {
+ it('should unset the root doc', function () {
return this.ProjectEntityUpdateHandler.unsetRootDoc
.calledWith(this.project_id)
.should.equal(true)
})
- it('should try to find a new rootDoc', function() {
+ it('should try to find a new rootDoc', function () {
return this.ProjectRootDocManager.setRootDocAutomatically.called.should.equal(
true
)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
})
- describe('when the root doc is not set', function() {
- beforeEach(function() {
+ describe('when the root doc is not set', function () {
+ beforeEach(function () {
return this.ProjectRootDocManager.ensureRootDocumentIsSet(
this.project_id,
this.callback
)
})
- it('should find the project fetching only the rootDoc_id fiel', function() {
+ it('should find the project fetching only the rootDoc_id fiel', function () {
return this.ProjectGetter.getProject
.calledWith(this.project_id, { rootDoc_id: 1 })
.should.equal(true)
})
- it('should update the project rootDoc_id', function() {
+ it('should update the project rootDoc_id', function () {
return this.ProjectRootDocManager.setRootDocAutomatically
.calledWith(this.project_id)
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('when the project does not exist', function() {
- beforeEach(function() {
+ describe('when the project does not exist', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, null)
return this.ProjectRootDocManager.ensureRootDocumentIsSet(
this.project_id,
@@ -678,7 +678,7 @@ describe('ProjectRootDocManager', function() {
)
})
- it('should call the callback with an error', function() {
+ it('should call the callback with an error', function () {
return this.callback
.calledWith(
sinon.match
diff --git a/services/web/test/unit/src/Project/ProjectUpdateHandlerTests.js b/services/web/test/unit/src/Project/ProjectUpdateHandlerTests.js
index 1c5faca4a0..4a51220bf7 100644
--- a/services/web/test/unit/src/Project/ProjectUpdateHandlerTests.js
+++ b/services/web/test/unit/src/Project/ProjectUpdateHandlerTests.js
@@ -17,13 +17,13 @@ const modulePath =
'../../../../app/src/Features/Project/ProjectUpdateHandler.js'
const SandboxedModule = require('sandboxed-module')
-describe('ProjectUpdateHandler', function() {
- beforeEach(function() {
+describe('ProjectUpdateHandler', function () {
+ beforeEach(function () {
this.fakeTime = new Date()
this.clock = sinon.useFakeTimers(this.fakeTime.getTime())
})
- beforeEach(function() {
+ beforeEach(function () {
let Project
this.ProjectModel = Project = class Project {}
this.ProjectModel.updateOne = sinon.stub().callsArg(3)
@@ -34,14 +34,14 @@ describe('ProjectUpdateHandler', function() {
}))
})
- describe('marking a project as recently updated', function() {
- beforeEach(function() {
+ describe('marking a project as recently updated', function () {
+ beforeEach(function () {
this.project_id = 'project_id'
this.lastUpdatedAt = 987654321
return (this.lastUpdatedBy = 'fake-last-updater-id')
})
- it('should send an update to mongo', function(done) {
+ it('should send an update to mongo', function (done) {
return this.handler.markAsUpdated(
this.project_id,
this.lastUpdatedAt,
@@ -63,7 +63,7 @@ describe('ProjectUpdateHandler', function() {
)
})
- it('should set smart fallbacks', function(done) {
+ it('should set smart fallbacks', function (done) {
return this.handler.markAsUpdated(this.project_id, null, null, err => {
sinon.assert.calledWithMatch(
this.ProjectModel.updateOne,
@@ -81,8 +81,8 @@ describe('ProjectUpdateHandler', function() {
})
})
- describe('markAsOpened', function() {
- it('should send an update to mongo', function(done) {
+ describe('markAsOpened', function () {
+ it('should send an update to mongo', function (done) {
const project_id = 'project_id'
return this.handler.markAsOpened(project_id, err => {
const args = this.ProjectModel.updateOne.args[0]
@@ -95,8 +95,8 @@ describe('ProjectUpdateHandler', function() {
})
})
- describe('markAsInactive', function() {
- it('should send an update to mongo', function(done) {
+ describe('markAsInactive', function () {
+ it('should send an update to mongo', function (done) {
const project_id = 'project_id'
return this.handler.markAsInactive(project_id, err => {
const args = this.ProjectModel.updateOne.args[0]
@@ -107,8 +107,8 @@ describe('ProjectUpdateHandler', function() {
})
})
- describe('markAsActive', function() {
- it('should send an update to mongo', function(done) {
+ describe('markAsActive', function () {
+ it('should send an update to mongo', function (done) {
const project_id = 'project_id'
return this.handler.markAsActive(project_id, err => {
const args = this.ProjectModel.updateOne.args[0]
diff --git a/services/web/test/unit/src/Project/SafePathTests.js b/services/web/test/unit/src/Project/SafePathTests.js
index 93ca1806fe..0f6417bb74 100644
--- a/services/web/test/unit/src/Project/SafePathTests.js
+++ b/services/web/test/unit/src/Project/SafePathTests.js
@@ -15,83 +15,83 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/Project/SafePath'
const SandboxedModule = require('sandboxed-module')
-describe('SafePath', function() {
- beforeEach(function() {
+describe('SafePath', function () {
+ beforeEach(function () {
return (this.SafePath = SandboxedModule.require(modulePath))
})
- describe('isCleanFilename', function() {
- it('should accept a valid filename "main.tex"', function() {
+ describe('isCleanFilename', function () {
+ it('should accept a valid filename "main.tex"', function () {
const result = this.SafePath.isCleanFilename('main.tex')
return result.should.equal(true)
})
- it('should not accept an empty filename', function() {
+ it('should not accept an empty filename', function () {
const result = this.SafePath.isCleanFilename('')
return result.should.equal(false)
})
- it('should not accept / anywhere', function() {
+ it('should not accept / anywhere', function () {
const result = this.SafePath.isCleanFilename('foo/bar')
return result.should.equal(false)
})
- it('should not accept .', function() {
+ it('should not accept .', function () {
const result = this.SafePath.isCleanFilename('.')
return result.should.equal(false)
})
- it('should not accept ..', function() {
+ it('should not accept ..', function () {
const result = this.SafePath.isCleanFilename('..')
return result.should.equal(false)
})
- it('should not accept * anywhere', function() {
+ it('should not accept * anywhere', function () {
const result = this.SafePath.isCleanFilename('foo*bar')
return result.should.equal(false)
})
- it('should not accept leading whitespace', function() {
+ it('should not accept leading whitespace', function () {
const result = this.SafePath.isCleanFilename(' foobar.tex')
return result.should.equal(false)
})
- it('should not accept trailing whitespace', function() {
+ it('should not accept trailing whitespace', function () {
const result = this.SafePath.isCleanFilename('foobar.tex ')
return result.should.equal(false)
})
- it('should not accept leading and trailing whitespace', function() {
+ it('should not accept leading and trailing whitespace', function () {
const result = this.SafePath.isCleanFilename(' foobar.tex ')
return result.should.equal(false)
})
- it('should not accept control characters (0-31)', function() {
+ it('should not accept control characters (0-31)', function () {
const result = this.SafePath.isCleanFilename('foo\u0010bar')
return result.should.equal(false)
})
- it('should not accept control characters (127, delete)', function() {
+ it('should not accept control characters (127, delete)', function () {
const result = this.SafePath.isCleanFilename('foo\u007fbar')
return result.should.equal(false)
})
- it('should not accept control characters (128-159)', function() {
+ it('should not accept control characters (128-159)', function () {
const result = this.SafePath.isCleanFilename('foo\u0080\u0090bar')
return result.should.equal(false)
})
- it('should not accept surrogate characters (128-159)', function() {
+ it('should not accept surrogate characters (128-159)', function () {
const result = this.SafePath.isCleanFilename('foo\uD800\uDFFFbar')
return result.should.equal(false)
})
- it('should accept javascript property names', function() {
+ it('should accept javascript property names', function () {
const result = this.SafePath.isCleanFilename('prototype')
return result.should.equal(true)
})
- it('should accept javascript property names in the prototype', function() {
+ it('should accept javascript property names in the prototype', function () {
const result = this.SafePath.isCleanFilename('hasOwnProperty')
return result.should.equal(true)
})
@@ -105,171 +105,171 @@ describe('SafePath', function() {
// result = @SafePath.isCleanFilename 'hello.'
// result.should.equal false
- it('should not accept \\', function() {
+ it('should not accept \\', function () {
const result = this.SafePath.isCleanFilename('foo\\bar')
return result.should.equal(false)
})
- it('should reject filenames regardless of order (/g) for bad characters', function() {
+ it('should reject filenames regardless of order (/g) for bad characters', function () {
const result1 = this.SafePath.isCleanFilename('foo*bar.tex') // * is not allowed
const result2 = this.SafePath.isCleanFilename('*foobar.tex') // bad char location is before previous match
return result1.should.equal(false) && result2.should.equal(false)
})
- it('should reject filenames regardless of order (/g) for bad filenames', function() {
+ it('should reject filenames regardless of order (/g) for bad filenames', function () {
const result1 = this.SafePath.isCleanFilename('foo ') // trailing space
const result2 = this.SafePath.isCleanFilename(' foobar') // leading space, match location is before previous match
return result1.should.equal(false) && result2.should.equal(false)
})
})
- describe('isCleanPath', function() {
- it('should accept a valid filename "main.tex"', function() {
+ describe('isCleanPath', function () {
+ it('should accept a valid filename "main.tex"', function () {
const result = this.SafePath.isCleanPath('main.tex')
return result.should.equal(true)
})
- it('should accept a valid path "foo/main.tex"', function() {
+ it('should accept a valid path "foo/main.tex"', function () {
const result = this.SafePath.isCleanPath('foo/main.tex')
return result.should.equal(true)
})
- it('should accept empty path elements', function() {
+ it('should accept empty path elements', function () {
const result = this.SafePath.isCleanPath('foo//main.tex')
return result.should.equal(true)
})
- it('should not accept an empty filename', function() {
+ it('should not accept an empty filename', function () {
const result = this.SafePath.isCleanPath('foo/bar/')
return result.should.equal(false)
})
- it('should accept a path that starts with a slash', function() {
+ it('should accept a path that starts with a slash', function () {
const result = this.SafePath.isCleanPath('/etc/passwd')
return result.should.equal(true)
})
- it('should not accept a path that has an asterisk as the 0th element', function() {
+ it('should not accept a path that has an asterisk as the 0th element', function () {
const result = this.SafePath.isCleanPath('*/foo/bar')
return result.should.equal(false)
})
- it('should not accept a path that has an asterisk as a middle element', function() {
+ it('should not accept a path that has an asterisk as a middle element', function () {
const result = this.SafePath.isCleanPath('foo/*/bar')
return result.should.equal(false)
})
- it('should not accept a path that has an asterisk as the filename', function() {
+ it('should not accept a path that has an asterisk as the filename', function () {
const result = this.SafePath.isCleanPath('foo/bar/*')
return result.should.equal(false)
})
- it('should not accept a path that contains an asterisk in the 0th element', function() {
+ it('should not accept a path that contains an asterisk in the 0th element', function () {
const result = this.SafePath.isCleanPath('f*o/bar/baz')
return result.should.equal(false)
})
- it('should not accept a path that contains an asterisk in a middle element', function() {
+ it('should not accept a path that contains an asterisk in a middle element', function () {
const result = this.SafePath.isCleanPath('foo/b*r/baz')
return result.should.equal(false)
})
- it('should not accept a path that contains an asterisk in the filename', function() {
+ it('should not accept a path that contains an asterisk in the filename', function () {
const result = this.SafePath.isCleanPath('foo/bar/b*z')
return result.should.equal(false)
})
- it('should not accept multiple problematic elements', function() {
+ it('should not accept multiple problematic elements', function () {
const result = this.SafePath.isCleanPath('f*o/b*r/b*z')
return result.should.equal(false)
})
- it('should not accept a problematic path with an empty element', function() {
+ it('should not accept a problematic path with an empty element', function () {
const result = this.SafePath.isCleanPath('foo//*/bar')
return result.should.equal(false)
})
- it('should not accept javascript property names', function() {
+ it('should not accept javascript property names', function () {
const result = this.SafePath.isCleanPath('prototype')
return result.should.equal(false)
})
- it('should not accept javascript property names in the prototype', function() {
+ it('should not accept javascript property names in the prototype', function () {
const result = this.SafePath.isCleanPath('hasOwnProperty')
return result.should.equal(false)
})
- it('should not accept javascript property names resulting from substitutions', function() {
+ it('should not accept javascript property names resulting from substitutions', function () {
const result = this.SafePath.isCleanPath(' proto ')
return result.should.equal(false)
})
})
- describe('isAllowedLength', function() {
- it('should accept a valid path "main.tex"', function() {
+ describe('isAllowedLength', function () {
+ it('should accept a valid path "main.tex"', function () {
const result = this.SafePath.isAllowedLength('main.tex')
return result.should.equal(true)
})
- it('should not accept an extremely long path', function() {
+ it('should not accept an extremely long path', function () {
const longPath = new Array(1000).join('/subdir') + '/main.tex'
const result = this.SafePath.isAllowedLength(longPath)
return result.should.equal(false)
})
- it('should not accept an empty path', function() {
+ it('should not accept an empty path', function () {
const result = this.SafePath.isAllowedLength('')
return result.should.equal(false)
})
})
- describe('clean', function() {
- it('should not modify a valid filename', function() {
+ describe('clean', function () {
+ it('should not modify a valid filename', function () {
const result = this.SafePath.clean('main.tex')
return result.should.equal('main.tex')
})
- it('should replace invalid characters with _', function() {
+ it('should replace invalid characters with _', function () {
const result = this.SafePath.clean('foo/bar*/main.tex')
return result.should.equal('foo_bar__main.tex')
})
- it('should replace "." with "_"', function() {
+ it('should replace "." with "_"', function () {
const result = this.SafePath.clean('.')
return result.should.equal('_')
})
- it('should replace ".." with "__"', function() {
+ it('should replace ".." with "__"', function () {
const result = this.SafePath.clean('..')
return result.should.equal('__')
})
- it('should replace a single trailing space with _', function() {
+ it('should replace a single trailing space with _', function () {
const result = this.SafePath.clean('foo ')
return result.should.equal('foo_')
})
- it('should replace a multiple trailing spaces with ___', function() {
+ it('should replace a multiple trailing spaces with ___', function () {
const result = this.SafePath.clean('foo ')
return result.should.equal('foo__')
})
- it('should replace a single leading space with _', function() {
+ it('should replace a single leading space with _', function () {
const result = this.SafePath.clean(' foo')
return result.should.equal('_foo')
})
- it('should replace a multiple leading spaces with ___', function() {
+ it('should replace a multiple leading spaces with ___', function () {
const result = this.SafePath.clean(' foo')
return result.should.equal('__foo')
})
- it('should prefix javascript property names with @', function() {
+ it('should prefix javascript property names with @', function () {
const result = this.SafePath.clean('prototype')
return result.should.equal('@prototype')
})
- it('should prefix javascript property names in the prototype with @', function() {
+ it('should prefix javascript property names in the prototype with @', function () {
const result = this.SafePath.clean('hasOwnProperty')
return result.should.equal('@hasOwnProperty')
})
diff --git a/services/web/test/unit/src/Publishers/PublishersGetterTests.js b/services/web/test/unit/src/Publishers/PublishersGetterTests.js
index 7a769f35d3..7e64542f2b 100644
--- a/services/web/test/unit/src/Publishers/PublishersGetterTests.js
+++ b/services/web/test/unit/src/Publishers/PublishersGetterTests.js
@@ -19,8 +19,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Publishers/PublishersGetter.js'
)
-describe('PublishersGetter', function() {
- beforeEach(function() {
+describe('PublishersGetter', function () {
+ beforeEach(function () {
this.publisher = {
_id: 'mock-publsiher-id',
slug: 'ieee',
@@ -50,8 +50,8 @@ describe('PublishersGetter', function() {
return (this.userId = '12345abcde')
})
- describe('getManagedPublishers', function() {
- it('fetches v1 data before returning publisher list', function(done) {
+ describe('getManagedPublishers', function () {
+ it('fetches v1 data before returning publisher list', function (done) {
return this.PublishersGetter.getManagedPublishers(
this.userId,
(error, publishers) => {
diff --git a/services/web/test/unit/src/Referal/ReferalAllocatorTests.js b/services/web/test/unit/src/Referal/ReferalAllocatorTests.js
index a111d54782..4ac90abd48 100644
--- a/services/web/test/unit/src/Referal/ReferalAllocatorTests.js
+++ b/services/web/test/unit/src/Referal/ReferalAllocatorTests.js
@@ -5,8 +5,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Referal/ReferalAllocator.js'
)
-describe('ReferalAllocator', function() {
- beforeEach(function() {
+describe('ReferalAllocator', function () {
+ beforeEach(function () {
this.ReferalAllocator = SandboxedModule.require(modulePath, {
requires: {
'../../models/User': {
@@ -28,9 +28,9 @@ describe('ReferalAllocator', function() {
.callsArgWith(2, null, { _id: this.user_id })
})
- describe('allocate', function() {
- describe('when the referal was a bonus referal', function() {
- beforeEach(function() {
+ describe('allocate', function () {
+ describe('when the referal was a bonus referal', function () {
+ beforeEach(function () {
this.referal_source = 'bonus'
this.ReferalAllocator.allocate(
this.referal_id,
@@ -41,7 +41,7 @@ describe('ReferalAllocator', function() {
)
})
- it('should update the referring user with the refered users id', function() {
+ it('should update the referring user with the refered users id', function () {
this.User.updateOne
.calledWith(
{
@@ -59,25 +59,25 @@ describe('ReferalAllocator', function() {
.should.equal(true)
})
- it('find the referring users id', function() {
+ it('find the referring users id', function () {
this.User.findOne
.calledWith({ referal_id: this.referal_id })
.should.equal(true)
})
- it("should refresh the user's subscription", function() {
+ it("should refresh the user's subscription", function () {
this.FeaturesUpdater.refreshFeatures
.calledWith(this.user_id)
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('when there is no user for the referal id', function() {
- beforeEach(function() {
+ describe('when there is no user for the referal id', function () {
+ beforeEach(function () {
this.referal_source = 'bonus'
this.referal_id = 'wombat'
this.User.findOne = sinon.stub().callsArgWith(2, null, null)
@@ -90,27 +90,27 @@ describe('ReferalAllocator', function() {
)
})
- it('should find the referring users id', function() {
+ it('should find the referring users id', function () {
this.User.findOne
.calledWith({ referal_id: this.referal_id })
.should.equal(true)
})
- it('should not update the referring user with the refered users id', function() {
+ it('should not update the referring user with the refered users id', function () {
this.User.updateOne.called.should.equal(false)
})
- it('should not assign the user a bonus', function() {
+ it('should not assign the user a bonus', function () {
this.FeaturesUpdater.refreshFeatures.called.should.equal(false)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
- describe('when the referal is not a bonus referal', function() {
- beforeEach(function() {
+ describe('when the referal is not a bonus referal', function () {
+ beforeEach(function () {
this.referal_source = 'public_share'
this.ReferalAllocator.allocate(
this.referal_id,
@@ -121,21 +121,21 @@ describe('ReferalAllocator', function() {
)
})
- it('should not update the referring user with the refered users id', function() {
+ it('should not update the referring user with the refered users id', function () {
this.User.updateOne.called.should.equal(false)
})
- it('find the referring users id', function() {
+ it('find the referring users id', function () {
this.User.findOne
.calledWith({ referal_id: this.referal_id })
.should.equal(true)
})
- it('should not assign the user a bonus', function() {
+ it('should not assign the user a bonus', function () {
this.FeaturesUpdater.refreshFeatures.called.should.equal(false)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Referal/ReferalConnectTests.js b/services/web/test/unit/src/Referal/ReferalConnectTests.js
index 394534aeab..796fb60e00 100644
--- a/services/web/test/unit/src/Referal/ReferalConnectTests.js
+++ b/services/web/test/unit/src/Referal/ReferalConnectTests.js
@@ -4,12 +4,12 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Referal/ReferalConnect.js'
)
-describe('Referal connect middle wear', function() {
- beforeEach(function() {
+describe('Referal connect middle wear', function () {
+ beforeEach(function () {
this.connect = SandboxedModule.require(modulePath, {})
})
- it('should take a referal query string and put it on the session if it exists', function(done) {
+ it('should take a referal query string and put it on the session if it exists', function (done) {
const req = {
query: { referal: '12345' },
session: {}
@@ -20,7 +20,7 @@ describe('Referal connect middle wear', function() {
})
})
- it('should not change the referal_id on the session if not in query', function(done) {
+ it('should not change the referal_id on the session if not in query', function (done) {
const req = {
query: {},
session: { referal_id: 'same' }
@@ -31,7 +31,7 @@ describe('Referal connect middle wear', function() {
})
})
- it('should take a facebook referal query string and put it on the session if it exists', function(done) {
+ it('should take a facebook referal query string and put it on the session if it exists', function (done) {
const req = {
query: { fb_ref: '12345' },
session: {}
@@ -42,7 +42,7 @@ describe('Referal connect middle wear', function() {
})
})
- it('should map the facebook medium into the session', function(done) {
+ it('should map the facebook medium into the session', function (done) {
const req = {
query: { rm: 'fb' },
session: {}
@@ -53,7 +53,7 @@ describe('Referal connect middle wear', function() {
})
})
- it('should map the twitter medium into the session', function(done) {
+ it('should map the twitter medium into the session', function (done) {
const req = {
query: { rm: 't' },
session: {}
@@ -64,7 +64,7 @@ describe('Referal connect middle wear', function() {
})
})
- it('should map the google plus medium into the session', function(done) {
+ it('should map the google plus medium into the session', function (done) {
const req = {
query: { rm: 'gp' },
session: {}
@@ -75,7 +75,7 @@ describe('Referal connect middle wear', function() {
})
})
- it('should map the email medium into the session', function(done) {
+ it('should map the email medium into the session', function (done) {
const req = {
query: { rm: 'e' },
session: {}
@@ -86,7 +86,7 @@ describe('Referal connect middle wear', function() {
})
})
- it('should map the direct medium into the session', function(done) {
+ it('should map the direct medium into the session', function (done) {
const req = {
query: { rm: 'd' },
session: {}
@@ -97,7 +97,7 @@ describe('Referal connect middle wear', function() {
})
})
- it('should map the bonus source into the session', function(done) {
+ it('should map the bonus source into the session', function (done) {
const req = {
query: { rs: 'b' },
session: {}
@@ -108,7 +108,7 @@ describe('Referal connect middle wear', function() {
})
})
- it('should map the public share source into the session', function(done) {
+ it('should map the public share source into the session', function (done) {
const req = {
query: { rs: 'ps' },
session: {}
@@ -119,7 +119,7 @@ describe('Referal connect middle wear', function() {
})
})
- it('should map the collaborator invite into the session', function(done) {
+ it('should map the collaborator invite into the session', function (done) {
const req = {
query: { rs: 'ci' },
session: {}
diff --git a/services/web/test/unit/src/Referal/ReferalControllerTests.js b/services/web/test/unit/src/Referal/ReferalControllerTests.js
index d11c0e757a..bc5c20275c 100644
--- a/services/web/test/unit/src/Referal/ReferalControllerTests.js
+++ b/services/web/test/unit/src/Referal/ReferalControllerTests.js
@@ -4,8 +4,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Referal/ReferalController.js'
)
-describe('Referal controller', function() {
- beforeEach(function() {
+describe('Referal controller', function () {
+ beforeEach(function () {
this.controller = SandboxedModule.require(modulePath, {})
})
})
diff --git a/services/web/test/unit/src/Referal/ReferalFeaturesTests.js b/services/web/test/unit/src/Referal/ReferalFeaturesTests.js
index 7797730ddc..8d1debd016 100644
--- a/services/web/test/unit/src/Referal/ReferalFeaturesTests.js
+++ b/services/web/test/unit/src/Referal/ReferalFeaturesTests.js
@@ -5,8 +5,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Referal/ReferalFeatures.js'
)
-describe('ReferalFeatures', function() {
- beforeEach(function() {
+describe('ReferalFeatures', function () {
+ beforeEach(function () {
this.ReferalFeatures = SandboxedModule.require(modulePath, {
requires: {
'../../models/User': {
@@ -22,8 +22,8 @@ describe('ReferalFeatures', function() {
this.new_user_id = 'new-user-id-123'
})
- describe('getBonusFeatures', function() {
- beforeEach(function() {
+ describe('getBonusFeatures', function () {
+ beforeEach(function () {
this.refered_user_count = 3
this.Settings.bonus_features = {
3: {
@@ -41,19 +41,19 @@ describe('ReferalFeatures', function() {
this.ReferalFeatures.getBonusFeatures(this.user_id, this.callback)
})
- it('should get the users number of refered user', function() {
+ it('should get the users number of refered user', function () {
this.User.findOne.calledWith({ _id: this.user_id }).should.equal(true)
})
- it('should call the callback with the features', function() {
+ it('should call the callback with the features', function () {
this.callback
.calledWith(null, this.Settings.bonus_features[3])
.should.equal(true)
})
})
- describe('when the user is not at a bonus level', function() {
- beforeEach(function() {
+ describe('when the user is not at a bonus level', function () {
+ beforeEach(function () {
this.refered_user_count = 0
this.Settings.bonus_features = {
1: {
@@ -68,11 +68,11 @@ describe('ReferalFeatures', function() {
this.ReferalFeatures.getBonusFeatures(this.user_id, this.callback)
})
- it('should get the users number of refered user', function() {
+ it('should get the users number of refered user', function () {
this.User.findOne.calledWith({ _id: this.user_id }).should.equal(true)
})
- it('should call the callback with no features', function() {
+ it('should call the callback with no features', function () {
this.callback.calledWith(null, {}).should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Referal/ReferalHandlerTests.js b/services/web/test/unit/src/Referal/ReferalHandlerTests.js
index 1caa616ae6..c0d02b71d0 100644
--- a/services/web/test/unit/src/Referal/ReferalHandlerTests.js
+++ b/services/web/test/unit/src/Referal/ReferalHandlerTests.js
@@ -6,8 +6,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Referal/ReferalHandler.js'
)
-describe('Referal handler', function() {
- beforeEach(function() {
+describe('Referal handler', function () {
+ beforeEach(function () {
this.User = { findById: sinon.stub() }
this.handler = SandboxedModule.require(modulePath, {
requires: {
@@ -19,8 +19,8 @@ describe('Referal handler', function() {
this.user_id = '12313'
})
- describe('getting refered user_ids', function() {
- it('should get the user from mongo and return the refered users array', function(done) {
+ describe('getting refered user_ids', function () {
+ it('should get the user from mongo and return the refered users array', function (done) {
const user = {
refered_users: ['1234', '312312', '3213129'],
refered_user_count: 3
@@ -38,7 +38,7 @@ describe('Referal handler', function() {
)
})
- it('should return an empty array if it is not set', function(done) {
+ it('should return an empty array if it is not set', function (done) {
const user = {}
this.User.findById.callsArgWith(2, null, user)
@@ -52,7 +52,7 @@ describe('Referal handler', function() {
)
})
- it('should return a zero count if neither it or the array are set', function(done) {
+ it('should return a zero count if neither it or the array are set', function (done) {
const user = {}
this.User.findById.callsArgWith(2, null, user)
@@ -66,7 +66,7 @@ describe('Referal handler', function() {
)
})
- it('should return the array length if count is not set', function(done) {
+ it('should return the array length if count is not set', function (done) {
const user = { refered_users: ['1234', '312312', '3213129'] }
this.User.findById.callsArgWith(2, null, user)
@@ -80,7 +80,7 @@ describe('Referal handler', function() {
)
})
- it('should error if finding the user fails', function(done) {
+ it('should error if finding the user fails', function (done) {
this.User.findById.callsArgWith(2, new Error('user not found'))
this.handler.getReferedUsers(this.user_id, err => {
diff --git a/services/web/test/unit/src/References/ReferencesControllerTests.js b/services/web/test/unit/src/References/ReferencesControllerTests.js
index 1ba6a730eb..986289410e 100644
--- a/services/web/test/unit/src/References/ReferencesControllerTests.js
+++ b/services/web/test/unit/src/References/ReferencesControllerTests.js
@@ -18,8 +18,8 @@ const modulePath =
const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
-describe('ReferencesController', function() {
- beforeEach(function() {
+describe('ReferencesController', function () {
+ beforeEach(function () {
this.projectId = '2222'
this.controller = SandboxedModule.require(modulePath, {
requires: {
@@ -51,8 +51,8 @@ describe('ReferencesController', function() {
})
})
- describe('indexAll', function() {
- beforeEach(function() {
+ describe('indexAll', function () {
+ beforeEach(function () {
this.req.body = { shouldBroadcast: false }
this.ReferencesHandler.indexAll.callsArgWith(
1,
@@ -65,7 +65,7 @@ describe('ReferencesController', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(() => {
this.res.sendStatus.callCount.should.equal(0)
this.res.sendStatus.calledWith(500).should.equal(false)
@@ -74,7 +74,7 @@ describe('ReferencesController', function() {
})
})
- it('should return data', function(done) {
+ it('should return data', function (done) {
return this.call(() => {
this.res.json.callCount.should.equal(1)
this.res.json.calledWith(this.fakeResponseData).should.equal(true)
@@ -82,7 +82,7 @@ describe('ReferencesController', function() {
})
})
- it('should call ReferencesHandler.indexAll', function(done) {
+ it('should call ReferencesHandler.indexAll', function (done) {
return this.call(() => {
this.ReferencesHandler.indexAll.callCount.should.equal(1)
this.ReferencesHandler.indexAll
@@ -92,8 +92,8 @@ describe('ReferencesController', function() {
})
})
- describe('when shouldBroadcast is true', function() {
- beforeEach(function() {
+ describe('when shouldBroadcast is true', function () {
+ beforeEach(function () {
this.ReferencesHandler.index.callsArgWith(
2,
null,
@@ -102,14 +102,14 @@ describe('ReferencesController', function() {
return (this.req.body.shouldBroadcast = true)
})
- it('should call EditorRealTimeController.emitToRoom', function(done) {
+ it('should call EditorRealTimeController.emitToRoom', function (done) {
return this.call(() => {
this.EditorRealTimeController.emitToRoom.callCount.should.equal(1)
return done()
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(() => {
this.res.sendStatus.callCount.should.equal(0)
this.res.sendStatus.calledWith(500).should.equal(false)
@@ -118,7 +118,7 @@ describe('ReferencesController', function() {
})
})
- it('should still return data', function(done) {
+ it('should still return data', function (done) {
return this.call(() => {
this.res.json.callCount.should.equal(1)
this.res.json.calledWith(this.fakeResponseData).should.equal(true)
@@ -127,8 +127,8 @@ describe('ReferencesController', function() {
})
})
- describe('when shouldBroadcast is false', function() {
- beforeEach(function() {
+ describe('when shouldBroadcast is false', function () {
+ beforeEach(function () {
this.ReferencesHandler.index.callsArgWith(
2,
null,
@@ -137,14 +137,14 @@ describe('ReferencesController', function() {
return (this.req.body.shouldBroadcast = false)
})
- it('should not call EditorRealTimeController.emitToRoom', function(done) {
+ it('should not call EditorRealTimeController.emitToRoom', function (done) {
return this.call(() => {
this.EditorRealTimeController.emitToRoom.callCount.should.equal(0)
return done()
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(() => {
this.res.sendStatus.callCount.should.equal(0)
this.res.sendStatus.calledWith(500).should.equal(false)
@@ -153,7 +153,7 @@ describe('ReferencesController', function() {
})
})
- it('should still return data', function(done) {
+ it('should still return data', function (done) {
return this.call(() => {
this.res.json.callCount.should.equal(1)
this.res.json.calledWith(this.fakeResponseData).should.equal(true)
@@ -163,8 +163,8 @@ describe('ReferencesController', function() {
})
})
- describe('there is no data', function() {
- beforeEach(function() {
+ describe('there is no data', function () {
+ beforeEach(function () {
this.ReferencesHandler.indexAll.callsArgWith(1)
return (this.call = callback => {
this.controller.indexAll(this.req, this.res)
@@ -172,14 +172,14 @@ describe('ReferencesController', function() {
})
})
- it('should not call EditorRealTimeController.emitToRoom', function(done) {
+ it('should not call EditorRealTimeController.emitToRoom', function (done) {
return this.call(() => {
this.EditorRealTimeController.emitToRoom.callCount.should.equal(0)
return done()
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(() => {
this.res.sendStatus.callCount.should.equal(0)
this.res.sendStatus.calledWith(500).should.equal(false)
@@ -188,7 +188,7 @@ describe('ReferencesController', function() {
})
})
- it('should send a response with an empty keys list', function(done) {
+ it('should send a response with an empty keys list', function (done) {
return this.call(() => {
this.res.json.called.should.equal(true)
this.res.json
@@ -199,16 +199,16 @@ describe('ReferencesController', function() {
})
})
- describe('index', function() {
- beforeEach(function() {
+ describe('index', function () {
+ beforeEach(function () {
return (this.call = callback => {
this.controller.index(this.req, this.res)
return callback()
})
})
- describe('with docIds as an array and shouldBroadcast as false', function() {
- beforeEach(function() {
+ describe('with docIds as an array and shouldBroadcast as false', function () {
+ beforeEach(function () {
return this.ReferencesHandler.index.callsArgWith(
2,
null,
@@ -216,7 +216,7 @@ describe('ReferencesController', function() {
)
})
- it('should call ReferencesHandler.index', function(done) {
+ it('should call ReferencesHandler.index', function (done) {
return this.call(() => {
this.ReferencesHandler.index.callCount.should.equal(1)
this.ReferencesHandler.index
@@ -226,7 +226,7 @@ describe('ReferencesController', function() {
})
})
- it('should return data', function(done) {
+ it('should return data', function (done) {
return this.call(() => {
this.res.json.callCount.should.equal(1)
this.res.json.calledWith(this.fakeResponseData).should.equal(true)
@@ -234,7 +234,7 @@ describe('ReferencesController', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(() => {
this.res.sendStatus.callCount.should.equal(0)
this.res.sendStatus.calledWith(500).should.equal(false)
@@ -243,15 +243,15 @@ describe('ReferencesController', function() {
})
})
- it('should not call EditorRealTimController.emitToRoom', function(done) {
+ it('should not call EditorRealTimController.emitToRoom', function (done) {
return this.call(() => {
this.EditorRealTimeController.emitToRoom.callCount.should.equal(0)
return done()
})
})
- describe('when ReferencesHandler.index produces an error', function() {
- beforeEach(function() {
+ describe('when ReferencesHandler.index produces an error', function () {
+ beforeEach(function () {
return this.ReferencesHandler.index.callsArgWith(
2,
new Error('woops'),
@@ -259,7 +259,7 @@ describe('ReferencesController', function() {
)
})
- it('should produce an error response', function(done) {
+ it('should produce an error response', function (done) {
return this.call(() => {
this.res.sendStatus.callCount.should.equal(1)
this.res.sendStatus.calledWith(500).should.equal(true)
@@ -269,8 +269,8 @@ describe('ReferencesController', function() {
})
})
- describe('when shouldBroadcast is true', function() {
- beforeEach(function() {
+ describe('when shouldBroadcast is true', function () {
+ beforeEach(function () {
this.ReferencesHandler.index.callsArgWith(
2,
null,
@@ -279,14 +279,14 @@ describe('ReferencesController', function() {
return (this.req.body.shouldBroadcast = true)
})
- it('should call EditorRealTimeController.emitToRoom', function(done) {
+ it('should call EditorRealTimeController.emitToRoom', function (done) {
return this.call(() => {
this.EditorRealTimeController.emitToRoom.callCount.should.equal(1)
return done()
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(() => {
this.res.sendStatus.callCount.should.equal(0)
this.res.sendStatus.calledWith(500).should.equal(false)
@@ -295,7 +295,7 @@ describe('ReferencesController', function() {
})
})
- it('should still return data', function(done) {
+ it('should still return data', function (done) {
return this.call(() => {
this.res.json.callCount.should.equal(1)
this.res.json.calledWith(this.fakeResponseData).should.equal(true)
@@ -304,12 +304,12 @@ describe('ReferencesController', function() {
})
})
- describe('with missing docIds', function() {
- beforeEach(function() {
+ describe('with missing docIds', function () {
+ beforeEach(function () {
return delete this.req.body.docIds
})
- it('should produce an error response', function(done) {
+ it('should produce an error response', function (done) {
return this.call(() => {
this.res.sendStatus.callCount.should.equal(1)
this.res.sendStatus.calledWith(400).should.equal(true)
@@ -317,7 +317,7 @@ describe('ReferencesController', function() {
})
})
- it('should not call ReferencesHandler.index', function(done) {
+ it('should not call ReferencesHandler.index', function (done) {
return this.call(() => {
this.ReferencesHandler.index.callCount.should.equal(0)
return done()
@@ -325,12 +325,12 @@ describe('ReferencesController', function() {
})
})
- describe('with invalid docIds', function() {
- beforeEach(function() {
+ describe('with invalid docIds', function () {
+ beforeEach(function () {
return (this.req.body.docIds = 42)
})
- it('should produce an error response', function(done) {
+ it('should produce an error response', function (done) {
return this.call(() => {
this.res.sendStatus.callCount.should.equal(1)
this.res.sendStatus.calledWith(400).should.equal(true)
@@ -338,7 +338,7 @@ describe('ReferencesController', function() {
})
})
- it('should not call ReferencesHandler.index', function(done) {
+ it('should not call ReferencesHandler.index', function (done) {
return this.call(() => {
this.ReferencesHandler.index.callCount.should.equal(0)
return done()
diff --git a/services/web/test/unit/src/References/ReferencesHandlerTests.js b/services/web/test/unit/src/References/ReferencesHandlerTests.js
index 6a03977ca7..93d9c0a6e9 100644
--- a/services/web/test/unit/src/References/ReferencesHandlerTests.js
+++ b/services/web/test/unit/src/References/ReferencesHandlerTests.js
@@ -17,8 +17,8 @@ const { assert, expect } = require('chai')
const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/References/ReferencesHandler'
-describe('ReferencesHandler', function() {
- beforeEach(function() {
+describe('ReferencesHandler', function () {
+ beforeEach(function () {
this.projectId = '222'
this.fakeProject = {
_id: this.projectId,
@@ -78,8 +78,8 @@ describe('ReferencesHandler', function() {
})
})
- describe('index', function() {
- beforeEach(function() {
+ describe('index', function () {
+ beforeEach(function () {
sinon.stub(this.handler, '_findBibDocIds')
sinon.stub(this.handler, '_findBibFileIds')
sinon.stub(this.handler, '_isFullIndex').callsArgWith(1, null, true)
@@ -94,19 +94,19 @@ describe('ReferencesHandler', function() {
})
})
- describe('when references feature is disabled', function() {
- beforeEach(function() {
+ describe('when references feature is disabled', function () {
+ beforeEach(function () {
this.Features.hasFeature.withArgs('references').returns(false)
})
- it('should not try to retrieve any user information', function(done) {
+ it('should not try to retrieve any user information', function (done) {
this.call(() => {
this.UserGetter.getUser.callCount.should.equal(0)
done()
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.equal(undefined)
return done()
@@ -114,19 +114,19 @@ describe('ReferencesHandler', function() {
})
})
- describe('with docIds as an array', function() {
- beforeEach(function() {
+ describe('with docIds as an array', function () {
+ beforeEach(function () {
return (this.docIds = ['aaa', 'ccc'])
})
- it('should not call _findBibDocIds', function(done) {
+ it('should not call _findBibDocIds', function (done) {
return this.call((err, data) => {
this.handler._findBibDocIds.callCount.should.equal(0)
return done()
})
})
- it('should call ProjectGetter.getProject', function(done) {
+ it('should call ProjectGetter.getProject', function (done) {
return this.call((err, data) => {
this.ProjectGetter.getProject.callCount.should.equal(1)
this.ProjectGetter.getProject
@@ -136,14 +136,14 @@ describe('ReferencesHandler', function() {
})
})
- it('should not call _findBibDocIds', function(done) {
+ it('should not call _findBibDocIds', function (done) {
return this.call((err, data) => {
this.handler._findBibDocIds.callCount.should.equal(0)
return done()
})
})
- it('should call DocumentUpdaterHandler.flushDocToMongo', function(done) {
+ it('should call DocumentUpdaterHandler.flushDocToMongo', function (done) {
return this.call((err, data) => {
this.DocumentUpdaterHandler.flushDocToMongo.callCount.should.equal(2)
this.docIds.forEach(docId => {
@@ -155,7 +155,7 @@ describe('ReferencesHandler', function() {
})
})
- it('should make a request to references service', function(done) {
+ it('should make a request to references service', function (done) {
return this.call((err, data) => {
this.request.post.callCount.should.equal(1)
const arg = this.request.post.firstCall.args[0]
@@ -166,14 +166,14 @@ describe('ReferencesHandler', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, data) => {
expect(err).to.equal(null)
return done()
})
})
- it('should return data', function(done) {
+ it('should return data', function (done) {
return this.call((err, data) => {
expect(data).to.not.equal(null)
expect(data).to.not.equal(undefined)
@@ -183,12 +183,12 @@ describe('ReferencesHandler', function() {
})
})
- describe('when ProjectGetter.getProject produces an error', function() {
- beforeEach(function() {
+ describe('when ProjectGetter.getProject produces an error', function () {
+ beforeEach(function () {
return this.ProjectGetter.getProject.callsArgWith(2, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, data) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -197,7 +197,7 @@ describe('ReferencesHandler', function() {
})
})
- it('should not send request', function(done) {
+ it('should not send request', function (done) {
return this.call((err, data) => {
this.request.post.callCount.should.equal(0)
return done()
@@ -205,13 +205,13 @@ describe('ReferencesHandler', function() {
})
})
- describe('when _isFullIndex produces an error', function() {
- beforeEach(function() {
+ describe('when _isFullIndex produces an error', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject)
return this.handler._isFullIndex.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, data) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -220,7 +220,7 @@ describe('ReferencesHandler', function() {
})
})
- it('should not send request', function(done) {
+ it('should not send request', function (done) {
return this.call((err, data) => {
this.request.post.callCount.should.equal(0)
return done()
@@ -228,8 +228,8 @@ describe('ReferencesHandler', function() {
})
})
- describe('when flushDocToMongo produces an error', function() {
- beforeEach(function() {
+ describe('when flushDocToMongo produces an error', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject)
this.handler._isFullIndex.callsArgWith(1, false)
return this.DocumentUpdaterHandler.flushDocToMongo.callsArgWith(
@@ -238,7 +238,7 @@ describe('ReferencesHandler', function() {
)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, data) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -247,7 +247,7 @@ describe('ReferencesHandler', function() {
})
})
- it('should not send request', function(done) {
+ it('should not send request', function (done) {
return this.call((err, data) => {
this.request.post.callCount.should.equal(0)
return done()
@@ -255,15 +255,15 @@ describe('ReferencesHandler', function() {
})
})
- describe('when request produces an error', function() {
- beforeEach(function() {
+ describe('when request produces an error', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject)
this.handler._isFullIndex.callsArgWith(1, null, false)
this.DocumentUpdaterHandler.flushDocToMongo.callsArgWith(2, null)
return this.request.post.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, data) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -273,8 +273,8 @@ describe('ReferencesHandler', function() {
})
})
- describe('when request responds with error status', function() {
- beforeEach(function() {
+ describe('when request responds with error status', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject)
this.handler._isFullIndex.callsArgWith(1, null, false)
return this.request.post.callsArgWith(
@@ -285,7 +285,7 @@ describe('ReferencesHandler', function() {
)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, data) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -296,8 +296,8 @@ describe('ReferencesHandler', function() {
})
})
- describe('indexAll', function() {
- beforeEach(function() {
+ describe('indexAll', function () {
+ beforeEach(function () {
sinon.stub(this.handler, '_findBibDocIds').returns(['aaa', 'ccc'])
sinon.stub(this.handler, '_findBibFileIds').returns(['fff', 'ggg'])
sinon.stub(this.handler, '_isFullIndex').callsArgWith(1, null, true)
@@ -312,7 +312,7 @@ describe('ReferencesHandler', function() {
})
})
- it('should call _findBibDocIds', function(done) {
+ it('should call _findBibDocIds', function (done) {
return this.call((err, data) => {
this.handler._findBibDocIds.callCount.should.equal(1)
this.handler._findBibDocIds
@@ -322,7 +322,7 @@ describe('ReferencesHandler', function() {
})
})
- it('should call _findBibFileIds', function(done) {
+ it('should call _findBibFileIds', function (done) {
return this.call((err, data) => {
this.handler._findBibDocIds.callCount.should.equal(1)
this.handler._findBibDocIds
@@ -332,14 +332,14 @@ describe('ReferencesHandler', function() {
})
})
- it('should call DocumentUpdaterHandler.flushDocToMongo', function(done) {
+ it('should call DocumentUpdaterHandler.flushDocToMongo', function (done) {
return this.call((err, data) => {
this.DocumentUpdaterHandler.flushDocToMongo.callCount.should.equal(2)
return done()
})
})
- it('should make a request to references service', function(done) {
+ it('should make a request to references service', function (done) {
return this.call((err, data) => {
this.request.post.callCount.should.equal(1)
const arg = this.request.post.firstCall.args[0]
@@ -350,14 +350,14 @@ describe('ReferencesHandler', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, data) => {
expect(err).to.equal(null)
return done()
})
})
- it('should return data', function(done) {
+ it('should return data', function (done) {
return this.call((err, data) => {
expect(data).to.not.equal(null)
expect(data).to.not.equal(undefined)
@@ -366,12 +366,12 @@ describe('ReferencesHandler', function() {
})
})
- describe('when ProjectGetter.getProject produces an error', function() {
- beforeEach(function() {
+ describe('when ProjectGetter.getProject produces an error', function () {
+ beforeEach(function () {
return this.ProjectGetter.getProject.callsArgWith(2, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, data) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -380,7 +380,7 @@ describe('ReferencesHandler', function() {
})
})
- it('should not send request', function(done) {
+ it('should not send request', function (done) {
return this.call((err, data) => {
this.request.post.callCount.should.equal(0)
return done()
@@ -388,13 +388,13 @@ describe('ReferencesHandler', function() {
})
})
- describe('when _isFullIndex produces an error', function() {
- beforeEach(function() {
+ describe('when _isFullIndex produces an error', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject)
return this.handler._isFullIndex.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, data) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -403,7 +403,7 @@ describe('ReferencesHandler', function() {
})
})
- it('should not send request', function(done) {
+ it('should not send request', function (done) {
return this.call((err, data) => {
this.request.post.callCount.should.equal(0)
return done()
@@ -411,8 +411,8 @@ describe('ReferencesHandler', function() {
})
})
- describe('when flushDocToMongo produces an error', function() {
- beforeEach(function() {
+ describe('when flushDocToMongo produces an error', function () {
+ beforeEach(function () {
this.ProjectGetter.getProject.callsArgWith(2, null, this.fakeProject)
this.handler._isFullIndex.callsArgWith(1, false)
return this.DocumentUpdaterHandler.flushDocToMongo.callsArgWith(
@@ -421,7 +421,7 @@ describe('ReferencesHandler', function() {
)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, data) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -430,7 +430,7 @@ describe('ReferencesHandler', function() {
})
})
- it('should not send request', function(done) {
+ it('should not send request', function (done) {
return this.call((err, data) => {
this.request.post.callCount.should.equal(0)
return done()
@@ -439,8 +439,8 @@ describe('ReferencesHandler', function() {
})
})
- describe('_findBibDocIds', function() {
- beforeEach(function() {
+ describe('_findBibDocIds', function () {
+ beforeEach(function () {
this.fakeProject = {
rootFolder: [
{
@@ -457,20 +457,20 @@ describe('ReferencesHandler', function() {
return (this.expectedIds = ['aaa', 'ccc'])
})
- it('should select the correct docIds', function() {
+ it('should select the correct docIds', function () {
const result = this.handler._findBibDocIds(this.fakeProject)
return expect(result).to.deep.equal(this.expectedIds)
})
- it('should not error with a non array of folders from dirty data', function() {
+ it('should not error with a non array of folders from dirty data', function () {
this.fakeProject.rootFolder[0].folders[0].folders = {}
const result = this.handler._findBibDocIds(this.fakeProject)
return expect(result).to.deep.equal(this.expectedIds)
})
})
- describe('_findBibFileIds', function() {
- beforeEach(function() {
+ describe('_findBibFileIds', function () {
+ beforeEach(function () {
this.fakeProject = {
rootFolder: [
{
@@ -492,14 +492,14 @@ describe('ReferencesHandler', function() {
return (this.expectedIds = ['ddd', 'ghg'])
})
- it('should select the correct docIds', function() {
+ it('should select the correct docIds', function () {
const result = this.handler._findBibFileIds(this.fakeProject)
return expect(result).to.deep.equal(this.expectedIds)
})
})
- describe('_isFullIndex', function() {
- beforeEach(function() {
+ describe('_isFullIndex', function () {
+ beforeEach(function () {
this.fakeProject = { owner_ref: (this.owner_ref = 'owner-ref-123') }
this.owner = {
features: {
@@ -515,12 +515,12 @@ describe('ReferencesHandler', function() {
})
})
- describe('with references feature on', function() {
- beforeEach(function() {
+ describe('with references feature on', function () {
+ beforeEach(function () {
return (this.owner.features.references = true)
})
- it('should return true', function() {
+ it('should return true', function () {
return this.call((err, isFullIndex) => {
expect(err).to.equal(null)
return expect(isFullIndex).to.equal(true)
@@ -528,12 +528,12 @@ describe('ReferencesHandler', function() {
})
})
- describe('with references feature off', function() {
- beforeEach(function() {
+ describe('with references feature off', function () {
+ beforeEach(function () {
return (this.owner.features.references = false)
})
- it('should return false', function() {
+ it('should return false', function () {
return this.call((err, isFullIndex) => {
expect(err).to.equal(null)
return expect(isFullIndex).to.equal(false)
@@ -541,15 +541,15 @@ describe('ReferencesHandler', function() {
})
})
- describe('with referencesSearch', function() {
- beforeEach(function() {
+ describe('with referencesSearch', function () {
+ beforeEach(function () {
return (this.owner.features = {
referencesSearch: true,
references: false
})
})
- it('should return true', function() {
+ it('should return true', function () {
return this.call((err, isFullIndex) => {
expect(err).to.equal(null)
return expect(isFullIndex).to.equal(true)
diff --git a/services/web/test/unit/src/SamlLog/SamlLogHandlerTests.js b/services/web/test/unit/src/SamlLog/SamlLogHandlerTests.js
index 9e881a8389..8553405764 100644
--- a/services/web/test/unit/src/SamlLog/SamlLogHandlerTests.js
+++ b/services/web/test/unit/src/SamlLog/SamlLogHandlerTests.js
@@ -5,16 +5,16 @@ const { expect } = require('chai')
const modulePath = `${APP_ROOT}/Features/SamlLog/SamlLogHandler`
-describe('SamlLogHandler', function() {
+describe('SamlLogHandler', function () {
let SamlLog, SamlLogHandler, SamlLogModel
let data, providerId, samlLog, sessionId
- beforeEach(function() {
+ beforeEach(function () {
samlLog = {
save: sinon.stub()
}
- SamlLog = function() {
+ SamlLog = function () {
return samlLog
}
SamlLogModel = { SamlLog }
@@ -29,12 +29,12 @@ describe('SamlLogHandler', function() {
sessionId = 'session-id'
})
- describe('with valid data object', function() {
- beforeEach(function() {
+ describe('with valid data object', function () {
+ beforeEach(function () {
SamlLogHandler.log(providerId, sessionId, data)
})
- it('should log data', function() {
+ it('should log data', function () {
samlLog.providerId.should.equal(providerId)
samlLog.sessionId.should.equal(sessionId.substr(0, 8))
samlLog.jsonData.should.equal('{"foo":true}')
@@ -43,15 +43,15 @@ describe('SamlLogHandler', function() {
})
})
- describe('when a json stringify error occurs', function() {
- beforeEach(function() {
+ describe('when a json stringify error occurs', function () {
+ beforeEach(function () {
const circularRef = {}
circularRef.circularRef = circularRef
SamlLogHandler.log(providerId, sessionId, circularRef)
})
- it('should log without data and log error', function() {
+ it('should log without data and log error', function () {
samlLog.providerId.should.equal(providerId)
samlLog.sessionId.should.equal(sessionId.substr(0, 8))
expect(samlLog.data).to.be.undefined
@@ -64,14 +64,14 @@ describe('SamlLogHandler', function() {
})
})
- describe('when logging error occurs', function() {
- beforeEach(function() {
+ describe('when logging error occurs', function () {
+ beforeEach(function () {
samlLog.save = sinon.stub().yields('error')
SamlLogHandler.log(providerId, sessionId, data)
})
- it('should log error', function() {
+ it('should log error', function () {
this.logger.error.should.have.been.calledOnce.and.calledWithMatch(
{ err: 'error', providerId, sessionId: sessionId.substr(0, 8) },
'SamlLog Error'
diff --git a/services/web/test/unit/src/Security/LoginRateLimiterTests.js b/services/web/test/unit/src/Security/LoginRateLimiterTests.js
index b3580601d2..ee8a383d72 100644
--- a/services/web/test/unit/src/Security/LoginRateLimiterTests.js
+++ b/services/web/test/unit/src/Security/LoginRateLimiterTests.js
@@ -18,8 +18,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Security/LoginRateLimiter'
)
-describe('LoginRateLimiter', function() {
- beforeEach(function() {
+describe('LoginRateLimiter', function () {
+ beforeEach(function () {
this.email = 'bob@bob.com'
this.RateLimiter = {
clearRateLimit: sinon.stub(),
@@ -33,14 +33,14 @@ describe('LoginRateLimiter', function() {
}))
})
- describe('processLoginRequest', function() {
- beforeEach(function() {
+ describe('processLoginRequest', function () {
+ beforeEach(function () {
return (this.RateLimiter.addCount = sinon
.stub()
.callsArgWith(1, null, true))
})
- it('should call RateLimiter.addCount', function(done) {
+ it('should call RateLimiter.addCount', function (done) {
return this.LoginRateLimiter.processLoginRequest(
this.email,
(err, allow) => {
@@ -56,14 +56,14 @@ describe('LoginRateLimiter', function() {
)
})
- describe('when login is allowed', function() {
- beforeEach(function() {
+ describe('when login is allowed', function () {
+ beforeEach(function () {
return (this.RateLimiter.addCount = sinon
.stub()
.callsArgWith(1, null, true))
})
- it('should call pass allow=true', function(done) {
+ it('should call pass allow=true', function (done) {
return this.LoginRateLimiter.processLoginRequest(
this.email,
(err, allow) => {
@@ -75,14 +75,14 @@ describe('LoginRateLimiter', function() {
})
})
- describe('when login is blocked', function() {
- beforeEach(function() {
+ describe('when login is blocked', function () {
+ beforeEach(function () {
return (this.RateLimiter.addCount = sinon
.stub()
.callsArgWith(1, null, false))
})
- it('should call pass allow=false', function(done) {
+ it('should call pass allow=false', function (done) {
return this.LoginRateLimiter.processLoginRequest(
this.email,
(err, allow) => {
@@ -94,14 +94,14 @@ describe('LoginRateLimiter', function() {
})
})
- describe('when addCount produces an error', function() {
- beforeEach(function() {
+ describe('when addCount produces an error', function () {
+ beforeEach(function () {
return (this.RateLimiter.addCount = sinon
.stub()
.callsArgWith(1, new Error('woops')))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.LoginRateLimiter.processLoginRequest(
this.email,
(err, allow) => {
@@ -114,14 +114,14 @@ describe('LoginRateLimiter', function() {
})
})
- describe('recordSuccessfulLogin', function() {
- beforeEach(function() {
+ describe('recordSuccessfulLogin', function () {
+ beforeEach(function () {
return (this.RateLimiter.clearRateLimit = sinon
.stub()
.callsArgWith(2, null))
})
- it('should call clearRateLimit', function(done) {
+ it('should call clearRateLimit', function (done) {
return this.LoginRateLimiter.recordSuccessfulLogin(this.email, () => {
this.RateLimiter.clearRateLimit.callCount.should.equal(1)
this.RateLimiter.clearRateLimit
diff --git a/services/web/test/unit/src/Security/OneTimeTokenHandlerTests.js b/services/web/test/unit/src/Security/OneTimeTokenHandlerTests.js
index a055d2f370..553c8ee457 100644
--- a/services/web/test/unit/src/Security/OneTimeTokenHandlerTests.js
+++ b/services/web/test/unit/src/Security/OneTimeTokenHandlerTests.js
@@ -22,8 +22,8 @@ const { expect } = require('chai')
const Errors = require('../../../../app/src/Features/Errors/Errors')
const tk = require('timekeeper')
-describe('OneTimeTokenHandler', function() {
- beforeEach(function() {
+describe('OneTimeTokenHandler', function () {
+ beforeEach(function () {
tk.freeze(Date.now()) // freeze the time for these tests
this.stubbedToken = 'mock-token'
this.callback = sinon.stub()
@@ -40,17 +40,17 @@ describe('OneTimeTokenHandler', function() {
}))
})
- afterEach(function() {
+ afterEach(function () {
return tk.reset()
})
- describe('getNewToken', function() {
- beforeEach(function() {
+ describe('getNewToken', function () {
+ beforeEach(function () {
return (this.db.tokens.insertOne = sinon.stub().yields())
})
- describe('normally', function() {
- beforeEach(function() {
+ describe('normally', function () {
+ beforeEach(function () {
return this.OneTimeTokenHandler.getNewToken(
'password',
'mock-data-to-store',
@@ -58,7 +58,7 @@ describe('OneTimeTokenHandler', function() {
)
})
- it('should insert a generated token with a 1 hour expiry', function() {
+ it('should insert a generated token with a 1 hour expiry', function () {
return this.db.tokens.insertOne
.calledWith({
use: 'password',
@@ -70,15 +70,15 @@ describe('OneTimeTokenHandler', function() {
.should.equal(true)
})
- it('should call the callback with the token', function() {
+ it('should call the callback with the token', function () {
return this.callback
.calledWith(null, this.stubbedToken)
.should.equal(true)
})
})
- describe('with an optional expiresIn parameter', function() {
- beforeEach(function() {
+ describe('with an optional expiresIn parameter', function () {
+ beforeEach(function () {
return this.OneTimeTokenHandler.getNewToken(
'password',
'mock-data-to-store',
@@ -87,7 +87,7 @@ describe('OneTimeTokenHandler', function() {
)
})
- it('should insert a generated token with a custom expiry', function() {
+ it('should insert a generated token with a custom expiry', function () {
return this.db.tokens.insertOne
.calledWith({
use: 'password',
@@ -99,7 +99,7 @@ describe('OneTimeTokenHandler', function() {
.should.equal(true)
})
- it('should call the callback with the token', function() {
+ it('should call the callback with the token', function () {
return this.callback
.calledWith(null, this.stubbedToken)
.should.equal(true)
@@ -107,9 +107,9 @@ describe('OneTimeTokenHandler', function() {
})
})
- describe('getValueFromTokenAndExpire', function() {
- describe('successfully', function() {
- beforeEach(function() {
+ describe('getValueFromTokenAndExpire', function () {
+ describe('successfully', function () {
+ beforeEach(function () {
this.db.tokens.findOneAndUpdate = sinon
.stub()
.yields(null, { value: { data: 'mock-data' } })
@@ -120,7 +120,7 @@ describe('OneTimeTokenHandler', function() {
)
})
- it('should expire the token', function() {
+ it('should expire the token', function () {
return this.db.tokens.findOneAndUpdate
.calledWith(
{
@@ -136,13 +136,13 @@ describe('OneTimeTokenHandler', function() {
.should.equal(true)
})
- it('should return the data', function() {
+ it('should return the data', function () {
return this.callback.calledWith(null, 'mock-data').should.equal(true)
})
})
- describe('when a valid token is not found', function() {
- beforeEach(function() {
+ describe('when a valid token is not found', function () {
+ beforeEach(function () {
this.db.tokens.findOneAndUpdate = sinon
.stub()
.yields(null, { value: null })
@@ -153,7 +153,7 @@ describe('OneTimeTokenHandler', function() {
)
})
- it('should return a NotFoundError', function() {
+ it('should return a NotFoundError', function () {
return this.callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
diff --git a/services/web/test/unit/src/Security/RateLimiterMiddlewareTests.js b/services/web/test/unit/src/Security/RateLimiterMiddlewareTests.js
index 08a071964d..699f93ea16 100644
--- a/services/web/test/unit/src/Security/RateLimiterMiddlewareTests.js
+++ b/services/web/test/unit/src/Security/RateLimiterMiddlewareTests.js
@@ -18,8 +18,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Security/RateLimiterMiddleware'
)
-describe('RateLimiterMiddleware', function() {
- beforeEach(function() {
+describe('RateLimiterMiddleware', function () {
+ beforeEach(function () {
this.AuthenticationController = {
getLoggedInUserId: () => {
return __guard__(
@@ -49,8 +49,8 @@ describe('RateLimiterMiddleware', function() {
return (this.next = sinon.stub())
})
- describe('rateLimit', function() {
- beforeEach(function() {
+ describe('rateLimit', function () {
+ beforeEach(function () {
this.rateLimiter = this.RateLimiterMiddleware.rateLimit({
endpointName: 'test-endpoint',
params: ['project_id', 'doc_id'],
@@ -63,14 +63,14 @@ describe('RateLimiterMiddleware', function() {
})
})
- describe('when there is no session', function() {
- beforeEach(function() {
+ describe('when there is no session', function () {
+ beforeEach(function () {
this.RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true)
this.req.ip = this.ip = '1.2.3.4'
return this.rateLimiter(this.req, this.res, this.next)
})
- it('should call the rate limiter backend with the ip address', function() {
+ it('should call the rate limiter backend with the ip address', function () {
return this.RateLimiter.addCount
.calledWith({
endpointName: 'test-endpoint',
@@ -81,11 +81,11 @@ describe('RateLimiterMiddleware', function() {
.should.equal(true)
})
- it('should pass on to next()', function() {})
+ it('should pass on to next()', function () {})
})
- describe('when smoke test user', function() {
- beforeEach(function() {
+ describe('when smoke test user', function () {
+ beforeEach(function () {
this.req.session = {
user: {
_id: (this.user_id = 'smoke-test-user-id')
@@ -96,7 +96,7 @@ describe('RateLimiterMiddleware', function() {
return this.rateLimiter(this.req, this.res, this.next)
})
- it('should not call the rate limiter backend with the user_id', function() {
+ it('should not call the rate limiter backend with the user_id', function () {
this.RateLimiter.addCount
.calledWith({
endpointName: 'test-endpoint',
@@ -108,13 +108,13 @@ describe('RateLimiterMiddleware', function() {
this.RateLimiter.addCount.callCount.should.equal(0)
})
- it('should pass on to next()', function() {
+ it('should pass on to next()', function () {
return this.next.called.should.equal(true)
})
})
- describe('when under the rate limit with logged in user', function() {
- beforeEach(function() {
+ describe('when under the rate limit with logged in user', function () {
+ beforeEach(function () {
this.req.session = {
user: {
_id: (this.user_id = 'user-id')
@@ -124,7 +124,7 @@ describe('RateLimiterMiddleware', function() {
return this.rateLimiter(this.req, this.res, this.next)
})
- it('should call the rate limiter backend with the user_id', function() {
+ it('should call the rate limiter backend with the user_id', function () {
return this.RateLimiter.addCount
.calledWith({
endpointName: 'test-endpoint',
@@ -135,19 +135,19 @@ describe('RateLimiterMiddleware', function() {
.should.equal(true)
})
- it('should pass on to next()', function() {
+ it('should pass on to next()', function () {
return this.next.called.should.equal(true)
})
})
- describe('when under the rate limit with anonymous user', function() {
- beforeEach(function() {
+ describe('when under the rate limit with anonymous user', function () {
+ beforeEach(function () {
this.req.ip = this.ip = '1.2.3.4'
this.RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true)
return this.rateLimiter(this.req, this.res, this.next)
})
- it('should call the rate limiter backend with the ip address', function() {
+ it('should call the rate limiter backend with the ip address', function () {
return this.RateLimiter.addCount
.calledWith({
endpointName: 'test-endpoint',
@@ -158,13 +158,13 @@ describe('RateLimiterMiddleware', function() {
.should.equal(true)
})
- it('should pass on to next()', function() {
+ it('should pass on to next()', function () {
return this.next.called.should.equal(true)
})
})
- describe('when over the rate limit', function() {
- beforeEach(function() {
+ describe('when over the rate limit', function () {
+ beforeEach(function () {
this.req.session = {
user: {
_id: (this.user_id = 'user-id')
@@ -174,16 +174,16 @@ describe('RateLimiterMiddleware', function() {
return this.rateLimiter(this.req, this.res, this.next)
})
- it('should return a 429', function() {
+ it('should return a 429', function () {
this.res.status.calledWith(429).should.equal(true)
return this.res.end.called.should.equal(true)
})
- it('should not continue', function() {
+ it('should not continue', function () {
return this.next.called.should.equal(false)
})
- it('should log a warning', function() {
+ it('should log a warning', function () {
return this.logger.warn
.calledWith(
{
diff --git a/services/web/test/unit/src/Security/SessionAutostartMiddlewareTests.js b/services/web/test/unit/src/Security/SessionAutostartMiddlewareTests.js
index b48fd4d8f5..6ba74177d4 100644
--- a/services/web/test/unit/src/Security/SessionAutostartMiddlewareTests.js
+++ b/services/web/test/unit/src/Security/SessionAutostartMiddlewareTests.js
@@ -4,14 +4,14 @@ const modulePath =
'../../../../app/src/infrastructure/SessionAutostartMiddleware.js'
const SandboxedModule = require('sandboxed-module')
-describe('SessionAutostartMiddleware', function() {
+describe('SessionAutostartMiddleware', function () {
let SessionAutostartMiddleware, middleware, Settings
const cookieName = 'coookieee'
const excludedRoute = '/wombat/potato'
const excludedMethod = 'POST'
const excludedCallback = () => 'call me'
- beforeEach(function() {
+ beforeEach(function () {
Settings = {
cookieName: cookieName
}
@@ -30,10 +30,10 @@ describe('SessionAutostartMiddleware', function() {
)
})
- describe('middleware', function() {
+ describe('middleware', function () {
let req, next
- beforeEach(function() {
+ beforeEach(function () {
req = {
path: excludedRoute,
method: excludedMethod,
@@ -43,33 +43,33 @@ describe('SessionAutostartMiddleware', function() {
next = sinon.stub()
})
- it('executes the callback for the excluded route', function() {
+ it('executes the callback for the excluded route', function () {
middleware.middleware(req, {}, next)
expect(req.session.noSessionCallback).to.equal(excludedCallback)
})
- it('does not execute the callback if the method is not excluded', function() {
+ it('does not execute the callback if the method is not excluded', function () {
req.method = 'GET'
middleware.middleware(req, {}, next)
expect(req.session).not.to.exist
})
- it('does not execute the callback if the path is not excluded', function() {
+ it('does not execute the callback if the path is not excluded', function () {
req.path = '/giraffe'
middleware.middleware(req, {}, next)
expect(req.session).not.to.exist
})
- it('does not execute the callback if there is a cookie', function() {
+ it('does not execute the callback if there is a cookie', function () {
req.signedCookies[cookieName] = 'a very useful session cookie'
middleware.middleware(req, {}, next)
expect(req.session).not.to.exist
})
})
- describe('bot middlewear', function() {
+ describe('bot middlewear', function () {
let req, next
- beforeEach(function() {
+ beforeEach(function () {
req = {
signedCookies: {},
headers: {}
@@ -77,19 +77,19 @@ describe('SessionAutostartMiddleware', function() {
next = sinon.stub()
})
- it('GoogleHC user agent should have an empty session', function() {
+ it('GoogleHC user agent should have an empty session', function () {
req.headers['user-agent'] = 'GoogleHC'
middleware.middleware(req, {}, next)
expect(req.session.noSessionCallback).to.deep.exist
})
- it('should not add empty session with a firefox useragent', function() {
+ it('should not add empty session with a firefox useragent', function () {
req.headers['user-agent'] = 'firefox'
middleware.middleware(req, {}, next)
expect(req.session).not.to.exist
})
- it('should not add empty session with a empty useragent', function() {
+ it('should not add empty session with a empty useragent', function () {
middleware.middleware(req, {}, next)
expect(req.session).not.to.exist
})
diff --git a/services/web/test/unit/src/Security/SessionStoreManagerTests.js b/services/web/test/unit/src/Security/SessionStoreManagerTests.js
index d739a7eb66..c1ba51891c 100644
--- a/services/web/test/unit/src/Security/SessionStoreManagerTests.js
+++ b/services/web/test/unit/src/Security/SessionStoreManagerTests.js
@@ -3,8 +3,8 @@ const { expect } = require('chai')
const modulePath = '../../../../app/src/infrastructure/SessionStoreManager.js'
const SandboxedModule = require('sandboxed-module')
-describe('SessionStoreManager', function() {
- beforeEach(function() {
+describe('SessionStoreManager', function () {
+ beforeEach(function () {
this.SessionStoreManager = SandboxedModule.require(modulePath, {
requires: {
'@overleaf/metrics': (this.Metrics = { inc: sinon.stub() })
@@ -17,34 +17,34 @@ describe('SessionStoreManager', function() {
})
}
})
- describe('enableValidationToken', function() {
- beforeEach(function() {
+ describe('enableValidationToken', function () {
+ beforeEach(function () {
this.originalGenerate = this.sessionStore.generate
this.SessionStoreManager.enableValidationToken(this.sessionStore)
})
- it('should set up a wrapper around the generate function', function() {
+ it('should set up a wrapper around the generate function', function () {
expect(this.sessionStore.generate).to.not.equal(this.originalGenerate)
})
- it('should add a validationToken when the generate function is called', function() {
+ it('should add a validationToken when the generate function is called', function () {
this.req = { sessionID: '123456789' }
this.sessionStore.generate(this.req)
expect(this.req.session.validationToken).to.equal('v1:6789')
})
- it('should not allow the token to be overwritten', function() {
+ it('should not allow the token to be overwritten', function () {
this.req = { sessionID: '123456789' }
this.sessionStore.generate(this.req)
this.req.session.validationToken = 'try-to-overwrite-token'
expect(this.req.session.validationToken).to.equal('v1:6789')
})
})
- describe('validationMiddleware', function() {
- this.beforeEach(function() {
+ describe('validationMiddleware', function () {
+ this.beforeEach(function () {
this.SessionStoreManager.enableValidationToken(this.sessionStore)
this.req = { sessionID: '123456789' }
this.next = sinon.stub()
this.sessionStore.generate(this.req)
})
- it('should accept the request when the session id matches the validation token', function() {
+ it('should accept the request when the session id matches the validation token', function () {
this.SessionStoreManager.validationMiddleware(
this.req,
this.res,
@@ -52,7 +52,7 @@ describe('SessionStoreManager', function() {
)
expect(this.next).to.be.calledWithExactly()
})
- it('should destroy the session and return an error when the session id does not match the validation token', function() {
+ it('should destroy the session and return an error when the session id does not match the validation token', function () {
this.req.sessionID = 'abcdefghijklmnopqrstuvwxyz'
this.next = sinon.stub()
this.SessionStoreManager.validationMiddleware(
@@ -67,7 +67,7 @@ describe('SessionStoreManager', function() {
.and(sinon.match.has('message', 'invalid session'))
)
})
- it('should accept the request when the session does not have a validation token', function() {
+ it('should accept the request when the session does not have a validation token', function () {
this.req = { sessionID: '123456789', session: {} }
this.next = sinon.stub()
this.SessionStoreManager.validationMiddleware(
@@ -78,21 +78,21 @@ describe('SessionStoreManager', function() {
expect(this.next).to.be.calledWithExactly()
})
})
- describe('hasValidationToken', function() {
- this.beforeEach(function() {
+ describe('hasValidationToken', function () {
+ this.beforeEach(function () {
this.req = { sessionID: '123456789' }
})
- it('should return true when the session is valid', function() {
+ it('should return true when the session is valid', function () {
this.req.session = { validationToken: 'v1:6789' }
const result = this.SessionStoreManager.hasValidationToken(this.req)
expect(result).to.equal(true)
})
- it('should return false when the session is valid', function() {
+ it('should return false when the session is valid', function () {
this.req.session = { validationToken: 'v1:abcd' }
const result = this.SessionStoreManager.hasValidationToken(this.req)
expect(result).to.equal(true)
})
- it('should return false when the validation token is missing', function() {
+ it('should return false when the validation token is missing', function () {
this.req.session = {}
const result = this.SessionStoreManager.hasValidationToken(this.req)
expect(result).to.equal(false)
diff --git a/services/web/test/unit/src/Settings/SettingsTests.js b/services/web/test/unit/src/Settings/SettingsTests.js
index a995e6fa67..4e3d4645d7 100644
--- a/services/web/test/unit/src/Settings/SettingsTests.js
+++ b/services/web/test/unit/src/Settings/SettingsTests.js
@@ -11,8 +11,8 @@ function clearSettingsCache() {
settingsDeps.forEach(dep => delete require.cache[dep])
}
-describe('settings.defaults', function() {
- it('additional text extensions can be added via config', function() {
+describe('settings.defaults', function () {
+ it('additional text extensions can be added via config', function () {
clearSettingsCache()
process.env.ADDITIONAL_TEXT_EXTENSIONS = 'abc, xyz'
const settings = require('settings-sharelatex')
diff --git a/services/web/test/unit/src/Spelling/SpellingControllerTests.js b/services/web/test/unit/src/Spelling/SpellingControllerTests.js
index 2aab39be41..5f2cc33c67 100644
--- a/services/web/test/unit/src/Spelling/SpellingControllerTests.js
+++ b/services/web/test/unit/src/Spelling/SpellingControllerTests.js
@@ -10,10 +10,10 @@ const TEN_SECONDS = 1000 * 10
const SPELLING_HOST = 'http://spelling.service.test'
const SPELLING_URL = 'http://spelling.service.test'
-describe('SpellingController', function() {
+describe('SpellingController', function () {
const userId = '123nd3ijdks'
- beforeEach(function() {
+ beforeEach(function () {
this.requestStreamPipe = sinon.stub()
this.requestStreamOn = sinon
.stub()
@@ -58,15 +58,15 @@ describe('SpellingController', function() {
this.res.json = sinon.stub()
})
- describe('proxyRequestToSpellingApi', function() {
- describe('on successful call', function() {
- beforeEach(function() {
+ describe('proxyRequestToSpellingApi', function () {
+ describe('on successful call', function () {
+ beforeEach(function () {
this.req.session.user._id = this.userId = 'user-id-123'
this.req.body = { language: 'en', words: ['blab'] }
this.controller.proxyRequestToSpellingApi(this.req, this.res)
})
- it('should send a request to the spelling host', function() {
+ it('should send a request to the spelling host', function () {
this.request
.calledWith({
url: `${SPELLING_URL}/user/${this.userId}/check`,
@@ -78,86 +78,86 @@ describe('SpellingController', function() {
.should.equal(true)
})
- it('should stream the response to the request', function() {
+ it('should stream the response to the request', function () {
this.requestStreamPipe.calledWith(this.res).should.equal(true)
})
- it('should add an error callback to the request', function() {
+ it('should add an error callback to the request', function () {
this.requestStreamOn.calledWith('error').should.equal(true)
})
})
- describe('when the requested language is not supported', function() {
- beforeEach(function() {
+ describe('when the requested language is not supported', function () {
+ beforeEach(function () {
this.req.session.user._id = this.userId = 'user-id-123'
this.req.body = { language: 'fi', words: ['blab'] }
})
- describe('when the request is a check request', function() {
- beforeEach(function() {
+ describe('when the request is a check request', function () {
+ beforeEach(function () {
this.controller.proxyRequestToSpellingApi(this.req, this.res)
})
- it('should not send a request to the spelling host', function() {
+ it('should not send a request to the spelling host', function () {
this.request.called.should.equal(false)
})
- it('should return an empty misspellings array', function() {
+ it('should return an empty misspellings array', function () {
this.res.send
.calledWith(JSON.stringify({ misspellings: [] }))
.should.equal(true)
})
- it('should return a 422 status', function() {
+ it('should return a 422 status', function () {
this.res.status.calledWith(422).should.equal(true)
})
})
- describe('when the request is not a check request', function() {
- beforeEach(function() {
+ describe('when the request is not a check request', function () {
+ beforeEach(function () {
this.req.url = '/spelling/learn'
this.controller.proxyRequestToSpellingApi(this.req, this.res)
})
- it('should send a request to the spelling host', function() {
+ it('should send a request to the spelling host', function () {
this.request.called.should.equal(true)
})
})
})
- describe('when no language is indicated', function() {
- beforeEach(function() {
+ describe('when no language is indicated', function () {
+ beforeEach(function () {
this.req.session.user._id = this.userId = 'user-id-123'
this.req.body = { words: ['blab'] }
})
- describe('when the request is a check request', function() {
- beforeEach(function() {
+ describe('when the request is a check request', function () {
+ beforeEach(function () {
this.controller.proxyRequestToSpellingApi(this.req, this.res)
})
- it('should not send a request to the spelling host', function() {
+ it('should not send a request to the spelling host', function () {
this.request.called.should.equal(false)
})
- it('should return an empty misspellings array', function() {
+ it('should return an empty misspellings array', function () {
this.res.send
.calledWith(JSON.stringify({ misspellings: [] }))
.should.equal(true)
})
- it('should return a 422 status', function() {
+ it('should return a 422 status', function () {
this.res.status.calledWith(422).should.equal(true)
})
})
- describe('when the request is not a check request', function() {
- beforeEach(function() {
+ describe('when the request is not a check request', function () {
+ beforeEach(function () {
this.req.url = '/spelling/learn'
this.controller.proxyRequestToSpellingApi(this.req, this.res)
})
- it('should send a request to the spelling host', function() {
+ it('should send a request to the spelling host', function () {
this.request.called.should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Spelling/SpellingHandlerTests.js b/services/web/test/unit/src/Spelling/SpellingHandlerTests.js
index 89391b9dca..6f0a8ff534 100644
--- a/services/web/test/unit/src/Spelling/SpellingHandlerTests.js
+++ b/services/web/test/unit/src/Spelling/SpellingHandlerTests.js
@@ -11,10 +11,10 @@ const TIMEOUT = 1000 * 10
const SPELLING_HOST = 'http://spelling.service.test'
const SPELLING_URL = 'http://spelling.service.test'
-describe('SpellingHandler', function() {
+describe('SpellingHandler', function () {
let userId, word, dictionary, dictionaryString, request, SpellingHandler
- beforeEach(function() {
+ beforeEach(function () {
userId = 'wombat'
word = 'potato'
dictionary = ['wombaat', 'woombat']
@@ -37,8 +37,8 @@ describe('SpellingHandler', function() {
})
})
- describe('getUserDictionary', function() {
- it('calls the spelling API', function(done) {
+ describe('getUserDictionary', function () {
+ it('calls the spelling API', function (done) {
SpellingHandler.getUserDictionary(userId, () => {
expect(request.get).to.have.been.calledWith({
url: 'http://spelling.service.test/user/wombat',
@@ -48,7 +48,7 @@ describe('SpellingHandler', function() {
})
})
- it('returns the dictionary', function(done) {
+ it('returns the dictionary', function (done) {
SpellingHandler.getUserDictionary(userId, (err, dictionary) => {
expect(err).not.to.exist
expect(dictionary).to.deep.equal(dictionary)
@@ -56,7 +56,7 @@ describe('SpellingHandler', function() {
})
})
- it('returns an error when the request fails', function(done) {
+ it('returns an error when the request fails', function (done) {
request.get = sinon.stub().yields(new Error('ugh'))
SpellingHandler.getUserDictionary(userId, err => {
expect(err).to.exist
@@ -65,8 +65,8 @@ describe('SpellingHandler', function() {
})
})
- describe('deleteWordFromUserDictionary', function() {
- it('calls the spelling API', function(done) {
+ describe('deleteWordFromUserDictionary', function () {
+ it('calls the spelling API', function (done) {
SpellingHandler.deleteWordFromUserDictionary(userId, word, () => {
expect(request.post).to.have.been.calledWith({
url: 'http://spelling.service.test/user/wombat/unlearn',
@@ -79,14 +79,14 @@ describe('SpellingHandler', function() {
})
})
- it('does not return an error', function(done) {
+ it('does not return an error', function (done) {
SpellingHandler.deleteWordFromUserDictionary(userId, word, err => {
expect(err).not.to.exist
done()
})
})
- it('returns an error when the request fails', function(done) {
+ it('returns an error when the request fails', function (done) {
request.post = sinon.stub().yields(new Error('ugh'))
SpellingHandler.deleteWordFromUserDictionary(userId, word, err => {
expect(err).to.exist
@@ -95,8 +95,8 @@ describe('SpellingHandler', function() {
})
})
- describe('deleteUserDictionary', function() {
- it('calls the spelling API', function(done) {
+ describe('deleteUserDictionary', function () {
+ it('calls the spelling API', function (done) {
SpellingHandler.deleteUserDictionary(userId, () => {
expect(request.delete).to.have.been.calledWith({
url: 'http://spelling.service.test/user/wombat',
@@ -106,14 +106,14 @@ describe('SpellingHandler', function() {
})
})
- it('does not return an error', function(done) {
+ it('does not return an error', function (done) {
SpellingHandler.deleteUserDictionary(userId, err => {
expect(err).not.to.exist
done()
})
})
- it('returns an error when the request fails', function(done) {
+ it('returns an error when the request fails', function (done) {
request.delete = sinon.stub().yields(new Error('ugh'))
SpellingHandler.deleteUserDictionary(userId, err => {
expect(err).to.exist
diff --git a/services/web/test/unit/src/Subscription/FeaturesUpdaterTests.js b/services/web/test/unit/src/Subscription/FeaturesUpdaterTests.js
index 3737376603..fed0e0a56c 100644
--- a/services/web/test/unit/src/Subscription/FeaturesUpdaterTests.js
+++ b/services/web/test/unit/src/Subscription/FeaturesUpdaterTests.js
@@ -4,8 +4,8 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/Subscription/FeaturesUpdater'
const { ObjectId } = require('mongodb')
-describe('FeaturesUpdater', function() {
- beforeEach(function() {
+describe('FeaturesUpdater', function () {
+ beforeEach(function () {
this.user_id = ObjectId().toString()
this.FeaturesUpdater = SandboxedModule.require(modulePath, {
@@ -25,8 +25,8 @@ describe('FeaturesUpdater', function() {
})
})
- describe('refreshFeatures', function() {
- beforeEach(function() {
+ describe('refreshFeatures', function () {
+ beforeEach(function () {
this.user = {
_id: this.user_id,
features: {}
@@ -56,7 +56,7 @@ describe('FeaturesUpdater', function() {
this.callback = sinon.stub()
})
- it('should return features and featuresChanged', function() {
+ it('should return features and featuresChanged', function () {
this.FeaturesUpdater.refreshFeatures(
this.user_id,
(err, features, featuresChanged) => {
@@ -67,54 +67,54 @@ describe('FeaturesUpdater', function() {
)
})
- describe('normally', function() {
- beforeEach(function() {
+ describe('normally', function () {
+ beforeEach(function () {
this.FeaturesUpdater.refreshFeatures(this.user_id, this.callback)
})
- it('should get the individual features', function() {
+ it('should get the individual features', function () {
this.FeaturesUpdater._getIndividualFeatures
.calledWith(this.user_id)
.should.equal(true)
})
- it('should get the group features', function() {
+ it('should get the group features', function () {
this.FeaturesUpdater._getGroupFeatureSets
.calledWith(this.user_id)
.should.equal(true)
})
- it('should get the institution features', function() {
+ it('should get the institution features', function () {
this.InstitutionsFeatures.getInstitutionsFeatures
.calledWith(this.user_id)
.should.equal(true)
})
- it('should get the v1 features', function() {
+ it('should get the v1 features', function () {
this.FeaturesUpdater._getV1Features
.calledWith(this.user_id)
.should.equal(true)
})
- it('should get the bonus features', function() {
+ it('should get the bonus features', function () {
this.ReferalFeatures.getBonusFeatures
.calledWith(this.user_id)
.should.equal(true)
})
- it('should merge from the default features', function() {
+ it('should merge from the default features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(this.Settings.defaultFeatures)
.should.equal(true)
})
- it('should merge the individual features', function() {
+ it('should merge the individual features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { individual: 'features' })
.should.equal(true)
})
- it('should merge the group features', function() {
+ it('should merge the group features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { group: 'features' })
.should.equal(true)
@@ -123,32 +123,32 @@ describe('FeaturesUpdater', function() {
.should.equal(true)
})
- it('should merge the institutions features', function() {
+ it('should merge the institutions features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { institutions: 'features' })
.should.equal(true)
})
- it('should merge the v1 features', function() {
+ it('should merge the v1 features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { v1: 'features' })
.should.equal(true)
})
- it('should merge the bonus features', function() {
+ it('should merge the bonus features', function () {
this.FeaturesUpdater._mergeFeatures
.calledWith(sinon.match.any, { bonus: 'features' })
.should.equal(true)
})
- it('should update the user with the merged features', function() {
+ it('should update the user with the merged features', function () {
this.UserFeaturesUpdater.updateFeatures
.calledWith(this.user_id, { merged: 'features' })
.should.equal(true)
})
})
- describe('when losing dropbox feature', function() {
- beforeEach(function() {
+ describe('when losing dropbox feature', function () {
+ beforeEach(function () {
this.user = {
_id: this.user_id,
features: { dropbox: true }
@@ -159,7 +159,7 @@ describe('FeaturesUpdater', function() {
.returns({ dropbox: false })
this.FeaturesUpdater.refreshFeatures(this.user_id, this.callback)
})
- it('should fire module hook to unlink dropbox', function() {
+ it('should fire module hook to unlink dropbox', function () {
this.Modules.hooks.fire
.calledWith('removeDropbox', this.user._id)
.should.equal(true)
@@ -167,8 +167,8 @@ describe('FeaturesUpdater', function() {
})
})
- describe('_mergeFeatures', function() {
- it('should prefer priority over standard for compileGroup', function() {
+ describe('_mergeFeatures', function () {
+ it('should prefer priority over standard for compileGroup', function () {
expect(
this.FeaturesUpdater._mergeFeatures(
{
@@ -219,7 +219,7 @@ describe('FeaturesUpdater', function() {
})
})
- it('should prefer -1 over any other for collaborators', function() {
+ it('should prefer -1 over any other for collaborators', function () {
expect(
this.FeaturesUpdater._mergeFeatures(
{
@@ -258,7 +258,7 @@ describe('FeaturesUpdater', function() {
})
})
- it('should prefer the higher of compileTimeout', function() {
+ it('should prefer the higher of compileTimeout', function () {
expect(
this.FeaturesUpdater._mergeFeatures(
{
@@ -285,7 +285,7 @@ describe('FeaturesUpdater', function() {
})
})
- it('should prefer the true over false for other keys', function() {
+ it('should prefer the true over false for other keys', function () {
expect(
this.FeaturesUpdater._mergeFeatures(
{
@@ -337,8 +337,8 @@ describe('FeaturesUpdater', function() {
})
})
- describe('doSyncFromV1', function() {
- beforeEach(function() {
+ describe('doSyncFromV1', function () {
+ beforeEach(function () {
this.v1UserId = 1
this.user = {
_id: this.user_id,
@@ -355,8 +355,8 @@ describe('FeaturesUpdater', function() {
}
})
- describe('when all goes well', function() {
- it('should call getUser', function(done) {
+ describe('when all goes well', function () {
+ it('should call getUser', function (done) {
this.call(() => {
expect(this.UserGetter.getUser.callCount).to.equal(1)
expect(
@@ -366,7 +366,7 @@ describe('FeaturesUpdater', function() {
})
})
- it('should call refreshFeatures', function(done) {
+ it('should call refreshFeatures', function (done) {
this.call(() => {
expect(this.FeaturesUpdater.refreshFeatures.callCount).to.equal(1)
expect(
@@ -376,7 +376,7 @@ describe('FeaturesUpdater', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
this.call(err => {
expect(err).to.not.exist
done()
@@ -384,18 +384,18 @@ describe('FeaturesUpdater', function() {
})
})
- describe('when getUser produces an error', function() {
- beforeEach(function() {
+ describe('when getUser produces an error', function () {
+ beforeEach(function () {
this.UserGetter.getUser = sinon
.stub()
.callsArgWith(2, new Error('woops'))
})
- it('should not call refreshFeatures', function() {
+ it('should not call refreshFeatures', function () {
expect(this.FeaturesUpdater.refreshFeatures.callCount).to.equal(0)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
this.call(err => {
expect(err).to.exist
done()
@@ -403,19 +403,19 @@ describe('FeaturesUpdater', function() {
})
})
- describe('when getUser does not find a user', function() {
- beforeEach(function() {
+ describe('when getUser does not find a user', function () {
+ beforeEach(function () {
this.UserGetter.getUser = sinon.stub().callsArgWith(2, null, null)
})
- it('should not call refreshFeatures', function(done) {
+ it('should not call refreshFeatures', function (done) {
this.call(() => {
expect(this.FeaturesUpdater.refreshFeatures.callCount).to.equal(0)
done()
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
this.call(err => {
expect(err).to.not.exist
done()
diff --git a/services/web/test/unit/src/Subscription/LimitationsManagerTests.js b/services/web/test/unit/src/Subscription/LimitationsManagerTests.js
index 1e4e4f949c..d16feb0e06 100644
--- a/services/web/test/unit/src/Subscription/LimitationsManagerTests.js
+++ b/services/web/test/unit/src/Subscription/LimitationsManagerTests.js
@@ -19,8 +19,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Subscription/LimitationsManager'
)
-describe('LimitationsManager', function() {
- beforeEach(function() {
+describe('LimitationsManager', function () {
+ beforeEach(function () {
this.project = { _id: (this.project_id = 'project-id') }
this.user = { _id: (this.user_id = 'user-id'), features: {} }
this.ProjectGetter = {
@@ -60,9 +60,9 @@ describe('LimitationsManager', function() {
}))
})
- describe('allowedNumberOfCollaboratorsInProject', function() {
- describe('when the project is owned by a user without a subscription', function() {
- beforeEach(function() {
+ describe('allowedNumberOfCollaboratorsInProject', function () {
+ describe('when the project is owned by a user without a subscription', function () {
+ beforeEach(function () {
this.Settings.defaultFeatures = { collaborators: 23 }
this.project.owner_ref = this.user_id
delete this.user.features
@@ -73,15 +73,15 @@ describe('LimitationsManager', function() {
)
})
- it('should return the default number', function() {
+ it('should return the default number', function () {
return this.callback
.calledWith(null, this.Settings.defaultFeatures.collaborators)
.should.equal(true)
})
})
- describe('when the project is owned by a user with a subscription', function() {
- beforeEach(function() {
+ describe('when the project is owned by a user with a subscription', function () {
+ beforeEach(function () {
this.project.owner_ref = this.user_id
this.user.features = { collaborators: 21 }
this.callback = sinon.stub()
@@ -91,7 +91,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return the number of collaborators the user is allowed', function() {
+ it('should return the number of collaborators the user is allowed', function () {
return this.callback
.calledWith(null, this.user.features.collaborators)
.should.equal(true)
@@ -99,9 +99,9 @@ describe('LimitationsManager', function() {
})
})
- describe('allowedNumberOfCollaboratorsForUser', function() {
- describe('when the user has no features', function() {
- beforeEach(function() {
+ describe('allowedNumberOfCollaboratorsForUser', function () {
+ describe('when the user has no features', function () {
+ beforeEach(function () {
this.Settings.defaultFeatures = { collaborators: 23 }
delete this.user.features
this.callback = sinon.stub()
@@ -111,15 +111,15 @@ describe('LimitationsManager', function() {
)
})
- it('should return the default number', function() {
+ it('should return the default number', function () {
return this.callback
.calledWith(null, this.Settings.defaultFeatures.collaborators)
.should.equal(true)
})
})
- describe('when the user has features', function() {
- beforeEach(function() {
+ describe('when the user has features', function () {
+ beforeEach(function () {
this.user.features = { collaborators: 21 }
this.callback = sinon.stub()
return this.LimitationsManager.allowedNumberOfCollaboratorsForUser(
@@ -128,7 +128,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return the number of collaborators the user is allowed', function() {
+ it('should return the number of collaborators the user is allowed', function () {
return this.callback
.calledWith(null, this.user.features.collaborators)
.should.equal(true)
@@ -136,9 +136,9 @@ describe('LimitationsManager', function() {
})
})
- describe('canAddXCollaborators', function() {
- describe('when the project has fewer collaborators than allowed', function() {
- beforeEach(function() {
+ describe('canAddXCollaborators', function () {
+ describe('when the project has fewer collaborators than allowed', function () {
+ beforeEach(function () {
this.current_number = 1
this.allowed_number = 2
this.invite_count = 0
@@ -166,13 +166,13 @@ describe('LimitationsManager', function() {
)
})
- it('should return true', function() {
+ it('should return true', function () {
return this.callback.calledWith(null, true).should.equal(true)
})
})
- describe('when the project has fewer collaborators and invites than allowed', function() {
- beforeEach(function() {
+ describe('when the project has fewer collaborators and invites than allowed', function () {
+ beforeEach(function () {
this.current_number = 1
this.allowed_number = 4
this.invite_count = 1
@@ -200,13 +200,13 @@ describe('LimitationsManager', function() {
)
})
- it('should return true', function() {
+ it('should return true', function () {
return this.callback.calledWith(null, true).should.equal(true)
})
})
- describe('when the project has fewer collaborators than allowed but I want to add more than allowed', function() {
- beforeEach(function() {
+ describe('when the project has fewer collaborators than allowed but I want to add more than allowed', function () {
+ beforeEach(function () {
this.current_number = 1
this.allowed_number = 2
this.invite_count = 0
@@ -234,13 +234,13 @@ describe('LimitationsManager', function() {
)
})
- it('should return false', function() {
+ it('should return false', function () {
return this.callback.calledWith(null, false).should.equal(true)
})
})
- describe('when the project has more collaborators than allowed', function() {
- beforeEach(function() {
+ describe('when the project has more collaborators than allowed', function () {
+ beforeEach(function () {
this.current_number = 3
this.allowed_number = 2
this.invite_count = 0
@@ -268,13 +268,13 @@ describe('LimitationsManager', function() {
)
})
- it('should return false', function() {
+ it('should return false', function () {
return this.callback.calledWith(null, false).should.equal(true)
})
})
- describe('when the project has infinite collaborators', function() {
- beforeEach(function() {
+ describe('when the project has infinite collaborators', function () {
+ beforeEach(function () {
this.current_number = 100
this.allowed_number = -1
this.invite_count = 0
@@ -302,13 +302,13 @@ describe('LimitationsManager', function() {
)
})
- it('should return true', function() {
+ it('should return true', function () {
return this.callback.calledWith(null, true).should.equal(true)
})
})
- describe('when the project has more invites than allowed', function() {
- beforeEach(function() {
+ describe('when the project has more invites than allowed', function () {
+ beforeEach(function () {
this.current_number = 0
this.allowed_number = 2
this.invite_count = 2
@@ -336,13 +336,13 @@ describe('LimitationsManager', function() {
)
})
- it('should return false', function() {
+ it('should return false', function () {
return this.callback.calledWith(null, false).should.equal(true)
})
})
- describe('when the project has more invites and collaborators than allowed', function() {
- beforeEach(function() {
+ describe('when the project has more invites and collaborators than allowed', function () {
+ beforeEach(function () {
this.current_number = 1
this.allowed_number = 2
this.invite_count = 1
@@ -370,18 +370,18 @@ describe('LimitationsManager', function() {
)
})
- it('should return false', function() {
+ it('should return false', function () {
return this.callback.calledWith(null, false).should.equal(true)
})
})
})
- describe('userHasV2Subscription', function() {
- beforeEach(function() {
+ describe('userHasV2Subscription', function () {
+ beforeEach(function () {
return (this.SubscriptionLocator.getUsersSubscription = sinon.stub())
})
- it('should return true if the recurly token is set', function(done) {
+ it('should return true if the recurly token is set', function (done) {
this.SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, {
recurlySubscription_id: '1234'
})
@@ -394,7 +394,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return false if the recurly token is not set', function(done) {
+ it('should return false if the recurly token is not set', function (done) {
this.SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, {})
this.subscription = {}
return this.LimitationsManager.userHasV2Subscription(
@@ -406,7 +406,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return false if the subscription is undefined', function(done) {
+ it('should return false if the subscription is undefined', function (done) {
this.SubscriptionLocator.getUsersSubscription.callsArgWith(1)
return this.LimitationsManager.userHasV2Subscription(
this.user,
@@ -417,7 +417,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return the subscription', function(done) {
+ it('should return the subscription', function (done) {
const stubbedSubscription = { freeTrial: {}, token: '' }
this.SubscriptionLocator.getUsersSubscription.callsArgWith(
1,
@@ -433,8 +433,8 @@ describe('LimitationsManager', function() {
)
})
- describe('when user has a custom account', function() {
- beforeEach(function() {
+ describe('when user has a custom account', function () {
+ beforeEach(function () {
this.fakeSubscription = { customAccount: true }
return this.SubscriptionLocator.getUsersSubscription.callsArgWith(
1,
@@ -443,7 +443,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return true', function(done) {
+ it('should return true', function (done) {
return this.LimitationsManager.userHasV2Subscription(
this.user,
(err, hasSubscription, subscription) => {
@@ -453,7 +453,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return the subscription', function(done) {
+ it('should return the subscription', function (done) {
return this.LimitationsManager.userHasV2Subscription(
this.user,
(err, hasSubscription, subscription) => {
@@ -465,12 +465,12 @@ describe('LimitationsManager', function() {
})
})
- describe('userIsMemberOfGroupSubscription', function() {
- beforeEach(function() {
+ describe('userIsMemberOfGroupSubscription', function () {
+ beforeEach(function () {
return (this.SubscriptionLocator.getMemberSubscriptions = sinon.stub())
})
- it('should return false if there are no groups subcriptions', function(done) {
+ it('should return false if there are no groups subcriptions', function (done) {
this.SubscriptionLocator.getMemberSubscriptions.callsArgWith(1, null, [])
return this.LimitationsManager.userIsMemberOfGroupSubscription(
this.user,
@@ -481,7 +481,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return true if there are no groups subcriptions', function(done) {
+ it('should return true if there are no groups subcriptions', function (done) {
let subscriptions
this.SubscriptionLocator.getMemberSubscriptions.callsArgWith(
1,
@@ -499,8 +499,8 @@ describe('LimitationsManager', function() {
})
})
- describe('hasPaidSubscription', function() {
- beforeEach(function() {
+ describe('hasPaidSubscription', function () {
+ beforeEach(function () {
this.LimitationsManager.userIsMemberOfGroupSubscription = sinon
.stub()
.yields(null, false)
@@ -512,7 +512,7 @@ describe('LimitationsManager', function() {
.yields(null, false))
})
- it('should return true if userIsMemberOfGroupSubscription', function(done) {
+ it('should return true if userIsMemberOfGroupSubscription', function (done) {
this.LimitationsManager.userIsMemberOfGroupSubscription = sinon
.stub()
.yields(null, true)
@@ -525,7 +525,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return true if userHasV2Subscription', function(done) {
+ it('should return true if userHasV2Subscription', function (done) {
this.LimitationsManager.userHasV2Subscription = sinon
.stub()
.yields(null, true)
@@ -538,7 +538,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return true if userHasV1Subscription', function(done) {
+ it('should return true if userHasV1Subscription', function (done) {
this.LimitationsManager.userHasV1Subscription = sinon
.stub()
.yields(null, true)
@@ -551,7 +551,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return false if none are true', function(done) {
+ it('should return false if none are true', function (done) {
return this.LimitationsManager.hasPaidSubscription(
this.user,
(err, hasSubOrIsGroupMember) => {
@@ -561,7 +561,7 @@ describe('LimitationsManager', function() {
)
})
- it('should have userHasSubscriptionOrIsGroupMember alias', function(done) {
+ it('should have userHasSubscriptionOrIsGroupMember alias', function (done) {
return this.LimitationsManager.userHasSubscriptionOrIsGroupMember(
this.user,
(err, hasSubOrIsGroupMember) => {
@@ -572,8 +572,8 @@ describe('LimitationsManager', function() {
})
})
- describe('userHasV1OrV2Subscription', function() {
- beforeEach(function() {
+ describe('userHasV1OrV2Subscription', function () {
+ beforeEach(function () {
this.LimitationsManager.userHasV2Subscription = sinon
.stub()
.yields(null, false)
@@ -582,7 +582,7 @@ describe('LimitationsManager', function() {
.yields(null, false))
})
- it('should return true if userHasV2Subscription', function(done) {
+ it('should return true if userHasV2Subscription', function (done) {
this.LimitationsManager.userHasV2Subscription = sinon
.stub()
.yields(null, true)
@@ -595,7 +595,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return true if userHasV1Subscription', function(done) {
+ it('should return true if userHasV1Subscription', function (done) {
this.LimitationsManager.userHasV1Subscription = sinon
.stub()
.yields(null, true)
@@ -608,7 +608,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return false if none are true', function(done) {
+ it('should return false if none are true', function (done) {
return this.LimitationsManager.userHasV1OrV2Subscription(
this.user,
(err, hasSub) => {
@@ -619,8 +619,8 @@ describe('LimitationsManager', function() {
})
})
- describe('hasGroupMembersLimitReached', function() {
- beforeEach(function() {
+ describe('hasGroupMembersLimitReached', function () {
+ beforeEach(function () {
this.subscriptionId = '12312'
return (this.subscription = {
membersLimit: 3,
@@ -631,7 +631,7 @@ describe('LimitationsManager', function() {
})
})
- it('should return true if the limit is hit (including members and invites)', function(done) {
+ it('should return true if the limit is hit (including members and invites)', function (done) {
this.SubscriptionLocator.getSubscription.callsArgWith(
1,
null,
@@ -646,7 +646,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return false if the limit is not hit (including members and invites)', function(done) {
+ it('should return false if the limit is not hit (including members and invites)', function (done) {
this.subscription.membersLimit = 4
this.SubscriptionLocator.getSubscription.callsArgWith(
1,
@@ -662,7 +662,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return true if the limit has been exceded (including members and invites)', function(done) {
+ it('should return true if the limit has been exceded (including members and invites)', function (done) {
this.subscription.membersLimit = 2
this.SubscriptionLocator.getSubscription.callsArgWith(
1,
@@ -679,8 +679,8 @@ describe('LimitationsManager', function() {
})
})
- describe('userHasV1Subscription', function() {
- it('should return true if v1 returns has_subscription = true', function(done) {
+ describe('userHasV1Subscription', function () {
+ it('should return true if v1 returns has_subscription = true', function (done) {
this.V1SubscriptionManager.getSubscriptionsFromV1 = sinon
.stub()
.yields(null, { has_subscription: true })
@@ -696,7 +696,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return false if v1 returns has_subscription = false', function(done) {
+ it('should return false if v1 returns has_subscription = false', function (done) {
this.V1SubscriptionManager.getSubscriptionsFromV1 = sinon
.stub()
.yields(null, { has_subscription: false })
@@ -712,7 +712,7 @@ describe('LimitationsManager', function() {
)
})
- it('should return false if v1 returns nothing', function(done) {
+ it('should return false if v1 returns nothing', function (done) {
this.V1SubscriptionManager.getSubscriptionsFromV1 = sinon
.stub()
.yields(null, null)
diff --git a/services/web/test/unit/src/Subscription/RecurlyClientTests.js b/services/web/test/unit/src/Subscription/RecurlyClientTests.js
index 8f5477e908..2ee9b99d4f 100644
--- a/services/web/test/unit/src/Subscription/RecurlyClientTests.js
+++ b/services/web/test/unit/src/Subscription/RecurlyClientTests.js
@@ -9,8 +9,8 @@ const recurly = require('recurly')
const modulePath = '../../../../app/src/Features/Subscription/RecurlyClient'
const SandboxedModule = require('sandboxed-module')
-describe('RecurlyClient', function() {
- beforeEach(function() {
+describe('RecurlyClient', function () {
+ beforeEach(function () {
this.settings = {
apis: {
recurly: {
@@ -40,7 +40,7 @@ describe('RecurlyClient', function() {
}
this.recurly = {
errors: recurly.errors,
- Client: function() {
+ Client: function () {
return client
}
}
@@ -64,8 +64,8 @@ describe('RecurlyClient', function() {
}))
})
- describe('initalizing recurly client with undefined API key parameter', function() {
- it('should create a client without error', function() {
+ describe('initalizing recurly client with undefined API key parameter', function () {
+ it('should create a client without error', function () {
let testClient
expect(() => {
testClient = new recurly.Client(undefined)
@@ -74,8 +74,8 @@ describe('RecurlyClient', function() {
})
})
- describe('getAccountForUserId', function() {
- it('should return an Account if one exists', async function() {
+ describe('getAccountForUserId', function () {
+ it('should return an Account if one exists', async function () {
this.client.getAccount = sinon.stub().resolves(this.recurlyAccount)
await expect(
this.RecurlyClient.promises.getAccountForUserId(this.user._id)
@@ -84,7 +84,7 @@ describe('RecurlyClient', function() {
.that.has.property('code', this.user._id)
})
- it('should return nothing if no account found', async function() {
+ it('should return nothing if no account found', async function () {
this.client.getAccount = sinon
.stub()
.throws(new recurly.errors.NotFoundError())
@@ -93,7 +93,7 @@ describe('RecurlyClient', function() {
).to.eventually.equal(undefined)
})
- it('should re-throw caught errors', async function() {
+ it('should re-throw caught errors', async function () {
this.client.getAccount = sinon.stub().throws()
await expect(
this.RecurlyClient.promises.getAccountForUserId(this.user._id)
@@ -101,8 +101,8 @@ describe('RecurlyClient', function() {
})
})
- describe('createAccountForUserId', function() {
- it('should return the Account as created by recurly', async function() {
+ describe('createAccountForUserId', function () {
+ it('should return the Account as created by recurly', async function () {
this.client.createAccount = sinon.stub().resolves(this.recurlyAccount)
await expect(
this.RecurlyClient.promises.createAccountForUserId(this.user._id)
@@ -111,7 +111,7 @@ describe('RecurlyClient', function() {
.that.has.property('code', this.user._id)
})
- it('should throw any API errors', async function() {
+ it('should throw any API errors', async function () {
this.client.createAccount = sinon.stub().throws()
await expect(
this.RecurlyClient.promises.createAccountForUserId(this.user._id)
diff --git a/services/web/test/unit/src/Subscription/RecurlyWrapperTests.js b/services/web/test/unit/src/Subscription/RecurlyWrapperTests.js
index 49e08006af..947b64543c 100644
--- a/services/web/test/unit/src/Subscription/RecurlyWrapperTests.js
+++ b/services/web/test/unit/src/Subscription/RecurlyWrapperTests.js
@@ -106,7 +106,7 @@ const fixtures = {
''
}
-const mockApiRequest = function(options, callback) {
+const mockApiRequest = function (options, callback) {
if (fixtures[options.url]) {
return callback(null, { statusCode: 200 }, fixtures[options.url])
} else {
@@ -114,8 +114,8 @@ const mockApiRequest = function(options, callback) {
}
}
-describe('RecurlyWrapper', function() {
- beforeEach(function() {
+describe('RecurlyWrapper', function () {
+ beforeEach(function () {
let RecurlyWrapper
this.settings = {
plans: [
@@ -153,13 +153,13 @@ describe('RecurlyWrapper', function() {
))
})
- afterEach(function() {
+ afterEach(function () {
return tk.reset()
})
- describe('getSubscription', function() {
- describe('with proper subscription id', function() {
- beforeEach(function() {
+ describe('getSubscription', function () {
+ describe('with proper subscription id', function () {
+ beforeEach(function () {
this.apiRequest = sinon
.stub(this.RecurlyWrapper, 'apiRequest')
.callsFake(mockApiRequest)
@@ -170,25 +170,25 @@ describe('RecurlyWrapper', function() {
}
)
})
- afterEach(function() {
+ afterEach(function () {
return this.RecurlyWrapper.apiRequest.restore()
})
- it('should look up the subscription at the normal API end point', function() {
+ it('should look up the subscription at the normal API end point', function () {
return this.apiRequest.args[0][0].url.should.equal(
'subscriptions/44f83d7cba354d5b84812419f923ea96'
)
})
- it('should return the subscription', function() {
+ it('should return the subscription', function () {
return this.recurlySubscription.uuid.should.equal(
'44f83d7cba354d5b84812419f923ea96'
)
})
})
- describe('with ReculyJS token', function() {
- beforeEach(function() {
+ describe('with ReculyJS token', function () {
+ beforeEach(function () {
this.apiRequest = sinon
.stub(this.RecurlyWrapper, 'apiRequest')
.callsFake(mockApiRequest)
@@ -200,25 +200,25 @@ describe('RecurlyWrapper', function() {
}
)
})
- afterEach(function() {
+ afterEach(function () {
return this.RecurlyWrapper.apiRequest.restore()
})
- it('should return the subscription', function() {
+ it('should return the subscription', function () {
return this.recurlySubscription.uuid.should.equal(
'44f83d7cba354d5b84812419f923ea96'
)
})
- it('should look up the subscription at the RecurlyJS API end point', function() {
+ it('should look up the subscription at the RecurlyJS API end point', function () {
return this.apiRequest.args[0][0].url.should.equal(
'recurly_js/result/70db44b10f5f4b238669480c9903f6f5'
)
})
})
- describe('with includeAccount', function() {
- beforeEach(function() {
+ describe('with includeAccount', function () {
+ beforeEach(function () {
this.apiRequest = sinon
.stub(this.RecurlyWrapper, 'apiRequest')
.callsFake(mockApiRequest)
@@ -230,22 +230,22 @@ describe('RecurlyWrapper', function() {
}
)
})
- afterEach(function() {
+ afterEach(function () {
return this.RecurlyWrapper.apiRequest.restore()
})
- it('should request the account from the API', function() {
+ it('should request the account from the API', function () {
return this.apiRequest.args[1][0].url.should.equal('accounts/104')
})
- it('should populate the account attribute', function() {
+ it('should populate the account attribute', function () {
return this.recurlySubscription.account.account_code.should.equal('104')
})
})
})
- describe('updateAccountEmailAddress', function() {
- beforeEach(function(done) {
+ describe('updateAccountEmailAddress', function () {
+ beforeEach(function (done) {
this.recurlyAccountId = 'account-id-123'
this.newEmail = 'example@overleaf.com'
this.apiRequest = sinon
@@ -265,11 +265,11 @@ describe('RecurlyWrapper', function() {
)
})
- afterEach(function() {
+ afterEach(function () {
return this.RecurlyWrapper.apiRequest.restore()
})
- it('sends correct XML', function() {
+ it('sends correct XML', function () {
this.apiRequest.called.should.equal(true)
const { body } = this.apiRequest.lastCall.args[0]
expect(body).to.equal(`\
@@ -281,14 +281,14 @@ describe('RecurlyWrapper', function() {
this.requestOptions.method.should.equal('PUT')
})
- it('should return the updated account', function() {
+ it('should return the updated account', function () {
expect(this.recurlyAccount).to.exist
this.recurlyAccount.account_code.should.equal('104')
})
})
- describe('updateSubscription', function() {
- beforeEach(function(done) {
+ describe('updateSubscription', function () {
+ beforeEach(function (done) {
this.recurlySubscriptionId = 'subscription-id-123'
this.apiRequest = sinon
.stub(this.RecurlyWrapper, 'apiRequest')
@@ -309,11 +309,11 @@ describe('RecurlyWrapper', function() {
}
)
})
- afterEach(function() {
+ afterEach(function () {
return this.RecurlyWrapper.apiRequest.restore()
})
- it('sends correct XML', function() {
+ it('sends correct XML', function () {
this.apiRequest.called.should.equal(true)
const { body } = this.apiRequest.lastCall.args[0]
expect(body).to.equal(`\
@@ -328,14 +328,14 @@ describe('RecurlyWrapper', function() {
return this.requestOptions.method.should.equal('put')
})
- it('should return the updated subscription', function() {
+ it('should return the updated subscription', function () {
expect(this.recurlySubscription).to.exist
return this.recurlySubscription.plan.plan_code.should.equal('gold')
})
})
- describe('cancelSubscription', function() {
- beforeEach(function(done) {
+ describe('cancelSubscription', function () {
+ beforeEach(function (done) {
this.recurlySubscriptionId = 'subscription-id-123'
this.apiRequest = sinon
.stub(this.RecurlyWrapper, 'apiRequest')
@@ -352,16 +352,16 @@ describe('RecurlyWrapper', function() {
)
})
- afterEach(function() {
+ afterEach(function () {
return this.RecurlyWrapper.apiRequest.restore()
})
- it('should send a cancel request to the API', function() {
+ it('should send a cancel request to the API', function () {
return this.apiRequest.called.should.equal(true)
})
- describe('when the subscription is already cancelled', function() {
- beforeEach(function() {
+ describe('when the subscription is already cancelled', function () {
+ beforeEach(function () {
this.RecurlyWrapper.apiRequest.restore()
this.recurlySubscriptionId = 'subscription-id-123'
return (this.apiRequest = sinon
@@ -375,7 +375,7 @@ describe('RecurlyWrapper', function() {
}))
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.RecurlyWrapper.cancelSubscription(
this.recurlySubscriptionId,
err => {
@@ -387,8 +387,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('reactivateSubscription', function() {
- beforeEach(function(done) {
+ describe('reactivateSubscription', function () {
+ beforeEach(function (done) {
this.recurlySubscriptionId = 'subscription-id-123'
this.apiRequest = sinon
.stub(this.RecurlyWrapper, 'apiRequest')
@@ -405,17 +405,17 @@ describe('RecurlyWrapper', function() {
)
})
- afterEach(function() {
+ afterEach(function () {
return this.RecurlyWrapper.apiRequest.restore()
})
- it('should send a cancel request to the API', function() {
+ it('should send a cancel request to the API', function () {
return this.apiRequest.called.should.equal(true)
})
})
- describe('redeemCoupon', function() {
- beforeEach(function(done) {
+ describe('redeemCoupon', function () {
+ beforeEach(function (done) {
this.recurlyAccountId = 'account-id-123'
this.coupon_code = '312321312'
this.apiRequest = sinon
@@ -432,11 +432,11 @@ describe('RecurlyWrapper', function() {
)
})
- afterEach(function() {
+ afterEach(function () {
return this.RecurlyWrapper.apiRequest.restore()
})
- it('sends correct XML', function() {
+ it('sends correct XML', function () {
this.apiRequest.called.should.equal(true)
const { body } = this.apiRequest.lastCall.args[0]
return expect(body).to.equal(`\
@@ -448,8 +448,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('createFixedAmmountCoupon', function() {
- beforeEach(function(done) {
+ describe('createFixedAmmountCoupon', function () {
+ beforeEach(function (done) {
this.couponCode = 'a-coupon-code'
this.couponName = 'a-coupon-name'
this.currencyCode = 'EUR'
@@ -470,11 +470,11 @@ describe('RecurlyWrapper', function() {
)
})
- afterEach(function() {
+ afterEach(function () {
return this.RecurlyWrapper.apiRequest.restore()
})
- it('sends correct XML', function() {
+ it('sends correct XML', function () {
this.apiRequest.called.should.equal(true)
const { body } = this.apiRequest.lastCall.args[0]
return expect(body).to.equal(`\
@@ -494,8 +494,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('createSubscription', function() {
- beforeEach(function() {
+ describe('createSubscription', function () {
+ beforeEach(function () {
this.user = {
_id: 'some_id',
email: 'user@example.com'
@@ -528,8 +528,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when paypal', function() {
- beforeEach(function() {
+ describe('when paypal', function () {
+ beforeEach(function () {
this.subscriptionDetails.isPaypal = true
this._createPaypalSubscription = sinon.stub(
this.RecurlyWrapper,
@@ -542,11 +542,11 @@ describe('RecurlyWrapper', function() {
)
})
- afterEach(function() {
+ afterEach(function () {
return this._createPaypalSubscription.restore()
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, sub) => {
expect(err).to.equal(null)
expect(err).to.not.be.instanceof(Error)
@@ -554,29 +554,29 @@ describe('RecurlyWrapper', function() {
})
})
- it('should produce a subscription object', function(done) {
+ it('should produce a subscription object', function (done) {
return this.call((err, sub) => {
expect(sub).to.deep.equal(this.subscription)
return done()
})
})
- it('should call _createPaypalSubscription', function(done) {
+ it('should call _createPaypalSubscription', function (done) {
return this.call((err, sub) => {
this._createPaypalSubscription.callCount.should.equal(1)
return done()
})
})
- describe('when _createPaypalSubscription produces an error', function() {
- beforeEach(function() {
+ describe('when _createPaypalSubscription produces an error', function () {
+ beforeEach(function () {
return this._createPaypalSubscription.callsArgWith(
3,
new Error('woops')
)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, sub) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -585,8 +585,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when not paypal', function() {
- beforeEach(function() {
+ describe('when not paypal', function () {
+ beforeEach(function () {
this.subscriptionDetails.isPaypal = false
this._createCreditCardSubscription = sinon.stub(
this.RecurlyWrapper,
@@ -599,11 +599,11 @@ describe('RecurlyWrapper', function() {
)
})
- afterEach(function() {
+ afterEach(function () {
return this._createCreditCardSubscription.restore()
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, sub) => {
expect(err).to.equal(null)
expect(err).to.not.be.instanceof(Error)
@@ -611,29 +611,29 @@ describe('RecurlyWrapper', function() {
})
})
- it('should produce a subscription object', function(done) {
+ it('should produce a subscription object', function (done) {
return this.call((err, sub) => {
expect(sub).to.deep.equal(this.subscription)
return done()
})
})
- it('should call _createCreditCardSubscription', function(done) {
+ it('should call _createCreditCardSubscription', function (done) {
return this.call((err, sub) => {
this._createCreditCardSubscription.callCount.should.equal(1)
return done()
})
})
- describe('when _createCreditCardSubscription produces an error', function() {
- beforeEach(function() {
+ describe('when _createCreditCardSubscription produces an error', function () {
+ beforeEach(function () {
return this._createCreditCardSubscription.callsArgWith(
3,
new Error('woops')
)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, sub) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -643,8 +643,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('_createCreditCardSubscription', function() {
- beforeEach(function() {
+ describe('_createCreditCardSubscription', function () {
+ beforeEach(function () {
this.user = {
_id: 'some_id',
email: 'user@example.com',
@@ -691,12 +691,12 @@ describe('RecurlyWrapper', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
this.apiRequest.restore()
return this._parseSubscriptionXml.restore()
})
- it('sends correct XML', function(done) {
+ it('sends correct XML', function (done) {
return this.call((err, result) => {
const { body } = this.apiRequest.lastCall.args[0]
expect(body).to.equal(`\
@@ -730,7 +730,7 @@ describe('RecurlyWrapper', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, sub) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -738,29 +738,29 @@ describe('RecurlyWrapper', function() {
})
})
- it('should produce a subscription', function(done) {
+ it('should produce a subscription', function (done) {
return this.call((err, sub) => {
expect(sub).to.equal(this.subscription)
return done()
})
})
- it('should call apiRequest', function(done) {
+ it('should call apiRequest', function (done) {
return this.call((err, sub) => {
this.apiRequest.callCount.should.equal(1)
return done()
})
})
- it('should call _parseSubscriptionXml', function(done) {
+ it('should call _parseSubscriptionXml', function (done) {
return this.call((err, sub) => {
this._parseSubscriptionXml.callCount.should.equal(1)
return done()
})
})
- describe('when api request returns 422', function() {
- beforeEach(function() {
+ describe('when api request returns 422', function () {
+ beforeEach(function () {
const body = `\
@@ -778,7 +778,7 @@ describe('RecurlyWrapper', function() {
this.apiRequest.yields(null, { statusCode: 422 }, body)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, sub) => {
expect(err).to.be.instanceof(
SubscriptionErrors.RecurlyTransactionError
@@ -794,26 +794,26 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when api request produces an error', function() {
- beforeEach(function() {
+ describe('when api request produces an error', function () {
+ beforeEach(function () {
return this.apiRequest.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, sub) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should call apiRequest', function(done) {
+ it('should call apiRequest', function (done) {
return this.call((err, sub) => {
this.apiRequest.callCount.should.equal(1)
return done()
})
})
- it('should not _parseSubscriptionXml', function(done) {
+ it('should not _parseSubscriptionXml', function (done) {
return this.call((err, sub) => {
this._parseSubscriptionXml.callCount.should.equal(0)
return done()
@@ -821,12 +821,12 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when parse xml produces an error', function() {
- beforeEach(function() {
+ describe('when parse xml produces an error', function () {
+ beforeEach(function () {
return this._parseSubscriptionXml.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, sub) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -835,8 +835,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('_createPaypalSubscription', function() {
- beforeEach(function() {
+ describe('_createPaypalSubscription', function () {
+ beforeEach(function () {
this.checkAccountExists = sinon.stub(
this.RecurlyWrapper._paypal,
'checkAccountExists'
@@ -935,7 +935,7 @@ describe('RecurlyWrapper', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
this.checkAccountExists.restore()
this.createAccount.restore()
this.createBillingInfo.restore()
@@ -943,14 +943,14 @@ describe('RecurlyWrapper', function() {
return this.createSubscription.restore()
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, sub) => {
expect(err).to.not.be.instanceof(Error)
return done()
})
})
- it('should produce a subscription object', function(done) {
+ it('should produce a subscription object', function (done) {
return this.call((err, sub) => {
expect(sub).to.not.equal(null)
expect(sub).to.equal(this.subscription)
@@ -958,7 +958,7 @@ describe('RecurlyWrapper', function() {
})
})
- it('should call each of the paypal stages', function(done) {
+ it('should call each of the paypal stages', function (done) {
return this.call((err, sub) => {
this.checkAccountExists.callCount.should.equal(1)
this.createAccount.callCount.should.equal(1)
@@ -969,19 +969,19 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when one of the paypal stages produces an error', function() {
- beforeEach(function() {
+ describe('when one of the paypal stages produces an error', function () {
+ beforeEach(function () {
return this.createAccount.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, sub) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should stop calling the paypal stages after the error', function(done) {
+ it('should stop calling the paypal stages after the error', function (done) {
return this.call((err, sub) => {
this.checkAccountExists.callCount.should.equal(1)
this.createAccount.callCount.should.equal(1)
@@ -994,8 +994,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('paypal actions', function() {
- beforeEach(function() {
+ describe('paypal actions', function () {
+ beforeEach(function () {
this.apiRequest = sinon.stub(this.RecurlyWrapper, 'apiRequest')
this._parseAccountXml = sinon.spy(this.RecurlyWrapper, '_parseAccountXml')
this._parseBillingInfoXml = sinon.spy(
@@ -1036,15 +1036,15 @@ describe('RecurlyWrapper', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
this.apiRequest.restore()
this._parseAccountXml.restore()
this._parseBillingInfoXml.restore()
return this._parseSubscriptionXml.restore()
})
- describe('_paypal.checkAccountExists', function() {
- beforeEach(function() {
+ describe('_paypal.checkAccountExists', function () {
+ beforeEach(function () {
return (this.call = callback => {
return this.RecurlyWrapper._paypal.checkAccountExists(
this.cache,
@@ -1053,8 +1053,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when the account exists', function() {
- beforeEach(function() {
+ describe('when the account exists', function () {
+ beforeEach(function () {
const resultXml =
'abc'
return this.apiRequest.callsArgWith(
@@ -1065,28 +1065,28 @@ describe('RecurlyWrapper', function() {
)
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.not.be.instanceof(Error)
return done()
})
})
- it('should call apiRequest', function(done) {
+ it('should call apiRequest', function (done) {
return this.call((err, result) => {
this.apiRequest.callCount.should.equal(1)
return done()
})
})
- it('should call _parseAccountXml', function(done) {
+ it('should call _parseAccountXml', function (done) {
return this.call((err, result) => {
this.RecurlyWrapper._parseAccountXml.callCount.should.equal(1)
return done()
})
})
- it('should add the account to the cumulative result', function(done) {
+ it('should add the account to the cumulative result', function (done) {
return this.call((err, result) => {
expect(result.account).to.not.equal(null)
expect(result.account).to.not.equal(undefined)
@@ -1097,7 +1097,7 @@ describe('RecurlyWrapper', function() {
})
})
- it('should set userExists to true', function(done) {
+ it('should set userExists to true', function (done) {
return this.call((err, result) => {
expect(result.userExists).to.equal(true)
return done()
@@ -1105,19 +1105,19 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when the account does not exist', function() {
- beforeEach(function() {
+ describe('when the account does not exist', function () {
+ beforeEach(function () {
return this.apiRequest.callsArgWith(1, null, { statusCode: 404 }, '')
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.not.be.instanceof(Error)
return done()
})
})
- it('should call apiRequest', function(done) {
+ it('should call apiRequest', function (done) {
return this.call((err, result) => {
this.apiRequest.callCount.should.equal(1)
this.apiRequest.firstCall.args[0].method.should.equal('GET')
@@ -1125,21 +1125,21 @@ describe('RecurlyWrapper', function() {
})
})
- it('should not call _parseAccountXml', function(done) {
+ it('should not call _parseAccountXml', function (done) {
return this.call((err, result) => {
this.RecurlyWrapper._parseAccountXml.callCount.should.equal(0)
return done()
})
})
- it('should not add the account to result', function(done) {
+ it('should not add the account to result', function (done) {
return this.call((err, result) => {
expect(result.account).to.equal(undefined)
return done()
})
})
- it('should set userExists to false', function(done) {
+ it('should set userExists to false', function (done) {
return this.call((err, result) => {
expect(result.userExists).to.equal(false)
return done()
@@ -1147,14 +1147,14 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when apiRequest produces an error', function() {
- beforeEach(function() {
+ describe('when apiRequest produces an error', function () {
+ beforeEach(function () {
return this.apiRequest.callsArgWith(1, new Error('woops'), {
statusCode: 500
})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -1163,19 +1163,19 @@ describe('RecurlyWrapper', function() {
})
})
- describe('_paypal.createAccount', function() {
- beforeEach(function() {
+ describe('_paypal.createAccount', function () {
+ beforeEach(function () {
return (this.call = callback => {
return this.RecurlyWrapper._paypal.createAccount(this.cache, callback)
})
})
- describe('when address is missing from subscriptionDetails', function() {
- beforeEach(function() {
+ describe('when address is missing from subscriptionDetails', function () {
+ beforeEach(function () {
return (this.cache.subscriptionDetails.address = null)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -1183,12 +1183,12 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when country is missing from address', function() {
- beforeEach(function() {
+ describe('when country is missing from address', function () {
+ beforeEach(function () {
return (this.cache.subscriptionDetails.address = {})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.be.instanceof(Errors.InvalidError)
return done()
@@ -1196,20 +1196,20 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when account already exists', function() {
- beforeEach(function() {
+ describe('when account already exists', function () {
+ beforeEach(function () {
this.cache.userExists = true
return (this.cache.account = { account_code: 'abc' })
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.not.be.instanceof(Error)
return done()
})
})
- it('should produce cache object', function(done) {
+ it('should produce cache object', function (done) {
return this.call((err, result) => {
expect(result).to.deep.equal(this.cache)
expect(result.account).to.deep.equal({
@@ -1219,14 +1219,14 @@ describe('RecurlyWrapper', function() {
})
})
- it('should not call apiRequest', function(done) {
+ it('should not call apiRequest', function (done) {
return this.call((err, result) => {
this.apiRequest.callCount.should.equal(0)
return done()
})
})
- it('should not call _parseAccountXml', function(done) {
+ it('should not call _parseAccountXml', function (done) {
return this.call((err, result) => {
this.RecurlyWrapper._parseAccountXml.callCount.should.equal(0)
return done()
@@ -1234,8 +1234,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when account does not exist', function() {
- beforeEach(function() {
+ describe('when account does not exist', function () {
+ beforeEach(function () {
this.cache.userExists = false
const resultXml =
'abc'
@@ -1247,7 +1247,7 @@ describe('RecurlyWrapper', function() {
)
})
- it('sends correct XML', function(done) {
+ it('sends correct XML', function (done) {
return this.call((err, result) => {
const { body } = this.apiRequest.lastCall.args[0]
expect(body).to.equal(`\
@@ -1270,14 +1270,14 @@ describe('RecurlyWrapper', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.not.be.instanceof(Error)
return done()
})
})
- it('should call apiRequest', function(done) {
+ it('should call apiRequest', function (done) {
return this.call((err, result) => {
this.apiRequest.callCount.should.equal(1)
this.apiRequest.firstCall.args[0].method.should.equal('POST')
@@ -1285,21 +1285,21 @@ describe('RecurlyWrapper', function() {
})
})
- it('should call _parseAccountXml', function(done) {
+ it('should call _parseAccountXml', function (done) {
return this.call((err, result) => {
this.RecurlyWrapper._parseAccountXml.callCount.should.equal(1)
return done()
})
})
- describe('when apiRequest produces an error', function() {
- beforeEach(function() {
+ describe('when apiRequest produces an error', function () {
+ beforeEach(function () {
return this.apiRequest.callsArgWith(1, new Error('woops'), {
statusCode: 500
})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -1309,8 +1309,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('_paypal.createBillingInfo', function() {
- beforeEach(function() {
+ describe('_paypal.createBillingInfo', function () {
+ beforeEach(function () {
this.cache.account = { account_code: 'abc' }
return (this.call = callback => {
return this.RecurlyWrapper._paypal.createBillingInfo(
@@ -1320,12 +1320,12 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when account_code is missing from cache', function() {
- beforeEach(function() {
+ describe('when account_code is missing from cache', function () {
+ beforeEach(function () {
return (this.cache.account.account_code = null)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -1333,8 +1333,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when all goes well', function() {
- beforeEach(function() {
+ describe('when all goes well', function () {
+ beforeEach(function () {
const resultXml = '1'
return this.apiRequest.callsArgWith(
1,
@@ -1344,7 +1344,7 @@ describe('RecurlyWrapper', function() {
)
})
- it('sends correct XML', function(done) {
+ it('sends correct XML', function (done) {
return this.call((err, result) => {
const { body } = this.apiRequest.lastCall.args[0]
expect(body).to.equal(`\
@@ -1356,14 +1356,14 @@ describe('RecurlyWrapper', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.not.be.instanceof(Error)
return done()
})
})
- it('should call apiRequest', function(done) {
+ it('should call apiRequest', function (done) {
return this.call((err, result) => {
this.apiRequest.callCount.should.equal(1)
this.apiRequest.firstCall.args[0].method.should.equal('POST')
@@ -1371,14 +1371,14 @@ describe('RecurlyWrapper', function() {
})
})
- it('should call _parseBillingInfoXml', function(done) {
+ it('should call _parseBillingInfoXml', function (done) {
return this.call((err, result) => {
this.RecurlyWrapper._parseBillingInfoXml.callCount.should.equal(1)
return done()
})
})
- it('should set billingInfo on cache', function(done) {
+ it('should set billingInfo on cache', function (done) {
return this.call((err, result) => {
expect(result.billingInfo).to.deep.equal({
a: '1'
@@ -1388,14 +1388,14 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when apiRequest produces an error', function() {
- beforeEach(function() {
+ describe('when apiRequest produces an error', function () {
+ beforeEach(function () {
return this.apiRequest.callsArgWith(1, new Error('woops'), {
statusCode: 500
})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -1404,8 +1404,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('_paypal.setAddressAndCompanyBillingInfo', function() {
- beforeEach(function() {
+ describe('_paypal.setAddressAndCompanyBillingInfo', function () {
+ beforeEach(function () {
this.cache.account = { account_code: 'abc' }
this.cache.billingInfo = {}
return (this.call = callback => {
@@ -1416,12 +1416,12 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when account_code is missing from cache', function() {
- beforeEach(function() {
+ describe('when account_code is missing from cache', function () {
+ beforeEach(function () {
return (this.cache.account.account_code = null)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -1429,12 +1429,12 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when country is missing', function() {
- beforeEach(function() {
+ describe('when country is missing', function () {
+ beforeEach(function () {
return (this.cache.subscriptionDetails.address = { country: '' })
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.be.instanceof(Errors.InvalidError)
return done()
@@ -1442,8 +1442,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when all goes well', function() {
- beforeEach(function() {
+ describe('when all goes well', function () {
+ beforeEach(function () {
const resultXml = 'London'
return this.apiRequest.callsArgWith(
1,
@@ -1453,7 +1453,7 @@ describe('RecurlyWrapper', function() {
)
})
- it('sends correct XML', function(done) {
+ it('sends correct XML', function (done) {
return this.call((err, result) => {
const { body } = this.apiRequest.lastCall.args[0]
expect(body).to.equal(`\
@@ -1470,14 +1470,14 @@ describe('RecurlyWrapper', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.not.be.instanceof(Error)
return done()
})
})
- it('should call apiRequest', function(done) {
+ it('should call apiRequest', function (done) {
return this.call((err, result) => {
this.apiRequest.callCount.should.equal(1)
this.apiRequest.firstCall.args[0].method.should.equal('PUT')
@@ -1485,14 +1485,14 @@ describe('RecurlyWrapper', function() {
})
})
- it('should call _parseBillingInfoXml', function(done) {
+ it('should call _parseBillingInfoXml', function (done) {
return this.call((err, result) => {
this.RecurlyWrapper._parseBillingInfoXml.callCount.should.equal(1)
return done()
})
})
- it('should set billingInfo on cache', function(done) {
+ it('should set billingInfo on cache', function (done) {
return this.call((err, result) => {
expect(result.billingInfo).to.deep.equal({
city: 'London'
@@ -1502,14 +1502,14 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when apiRequest produces an error', function() {
- beforeEach(function() {
+ describe('when apiRequest produces an error', function () {
+ beforeEach(function () {
return this.apiRequest.callsArgWith(1, new Error('woops'), {
statusCode: 500
})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -1518,8 +1518,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('_paypal.createSubscription', function() {
- beforeEach(function() {
+ describe('_paypal.createSubscription', function () {
+ beforeEach(function () {
this.cache.account = { account_code: 'abc' }
this.cache.billingInfo = {}
return (this.call = callback => {
@@ -1530,8 +1530,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when all goes well', function() {
- beforeEach(function() {
+ describe('when all goes well', function () {
+ beforeEach(function () {
const resultXml = '1'
return this.apiRequest.callsArgWith(
1,
@@ -1541,7 +1541,7 @@ describe('RecurlyWrapper', function() {
)
})
- it('sends correct XML', function(done) {
+ it('sends correct XML', function (done) {
return this.call((err, result) => {
const { body } = this.apiRequest.lastCall.args[0]
expect(body).to.equal(`\
@@ -1568,14 +1568,14 @@ describe('RecurlyWrapper', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.not.be.instanceof(Error)
return done()
})
})
- it('should call apiRequest', function(done) {
+ it('should call apiRequest', function (done) {
return this.call((err, result) => {
this.apiRequest.callCount.should.equal(1)
this.apiRequest.firstCall.args[0].method.should.equal('POST')
@@ -1583,14 +1583,14 @@ describe('RecurlyWrapper', function() {
})
})
- it('should call _parseSubscriptionXml', function(done) {
+ it('should call _parseSubscriptionXml', function (done) {
return this.call((err, result) => {
this.RecurlyWrapper._parseSubscriptionXml.callCount.should.equal(1)
return done()
})
})
- it('should set subscription on cache', function(done) {
+ it('should set subscription on cache', function (done) {
return this.call((err, result) => {
expect(result.subscription).to.deep.equal({
a: '1'
@@ -1600,14 +1600,14 @@ describe('RecurlyWrapper', function() {
})
})
- describe('when apiRequest produces an error', function() {
- beforeEach(function() {
+ describe('when apiRequest produces an error', function () {
+ beforeEach(function () {
return this.apiRequest.callsArgWith(1, new Error('woops'), {
statusCode: 500
})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, result) => {
expect(err).to.be.instanceof(Error)
return done()
@@ -1617,8 +1617,8 @@ describe('RecurlyWrapper', function() {
})
})
- describe('listAccountActiveSubscriptions', function() {
- beforeEach(function() {
+ describe('listAccountActiveSubscriptions', function () {
+ beforeEach(function () {
this.user_id = 'mock-user-id'
this.callback = sinon.stub()
this.RecurlyWrapper.apiRequest = sinon
@@ -1633,15 +1633,15 @@ describe('RecurlyWrapper', function() {
.yields(null, (this.subscriptions = ['mock', 'subscriptions'])))
})
- describe('with an account', function() {
- beforeEach(function() {
+ describe('with an account', function () {
+ beforeEach(function () {
return this.RecurlyWrapper.listAccountActiveSubscriptions(
this.user_id,
this.callback
)
})
- it('should send a request to Recurly', function() {
+ it('should send a request to Recurly', function () {
return this.RecurlyWrapper.apiRequest
.calledWith({
url: `accounts/${this.user_id}/subscriptions`,
@@ -1653,15 +1653,15 @@ describe('RecurlyWrapper', function() {
.should.equal(true)
})
- it('should return the subscriptions', function() {
+ it('should return the subscriptions', function () {
return this.callback
.calledWith(null, this.subscriptions)
.should.equal(true)
})
})
- describe('without an account', function() {
- beforeEach(function() {
+ describe('without an account', function () {
+ beforeEach(function () {
this.response.statusCode = 404
return this.RecurlyWrapper.listAccountActiveSubscriptions(
this.user_id,
@@ -1669,7 +1669,7 @@ describe('RecurlyWrapper', function() {
)
})
- it('should return an empty array of subscriptions', function() {
+ it('should return an empty array of subscriptions', function () {
return this.callback.calledWith(null, []).should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js b/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js
index 373c1146c5..85ae37633a 100644
--- a/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js
+++ b/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js
@@ -37,8 +37,8 @@ const mockSubscriptions = {
}
}
-describe('SubscriptionController', function() {
- beforeEach(function() {
+describe('SubscriptionController', function () {
+ beforeEach(function () {
this.user = {
email: 'tom@yahoo.com',
_id: 'one',
@@ -126,8 +126,8 @@ describe('SubscriptionController', function() {
return (this.stubbedCurrencyCode = 'GBP')
})
- describe('plansPage', function() {
- beforeEach(function() {
+ describe('plansPage', function () {
+ beforeEach(function () {
this.req.ip = '1234.3123.3131.333 313.133.445.666 653.5345.5345.534'
return this.GeoIpLookup.getCurrencyCode.callsArgWith(
1,
@@ -136,19 +136,19 @@ describe('SubscriptionController', function() {
)
})
- describe('when user is logged in', function(done) {
- beforeEach(function(done) {
+ describe('when user is logged in', function (done) {
+ beforeEach(function (done) {
this.res.callback = done
return this.SubscriptionController.plansPage(this.req, this.res)
})
- it('should fetch the current user', function(done) {
+ it('should fetch the current user', function (done) {
this.UserGetter.getUser.callCount.should.equal(1)
return done()
})
- describe('not dependant on logged in state', function(done) {
+ describe('not dependant on logged in state', function (done) {
// these could have been put in 'when user is not logged in' too
- it('should set the recommended currency from the geoiplookup', function(done) {
+ it('should set the recommended currency from the geoiplookup', function (done) {
this.res.renderedVariables.recomendedCurrency.should.equal(
this.stubbedCurrencyCode
)
@@ -157,15 +157,15 @@ describe('SubscriptionController', function() {
.should.equal(true)
return done()
})
- it('should include data for features table', function(done) {
+ it('should include data for features table', function (done) {
this.res.renderedVariables.planFeatures.length.should.not.equal(0)
return done()
})
})
})
- describe('when user is not logged in', function(done) {
- beforeEach(function(done) {
+ describe('when user is not logged in', function (done) {
+ beforeEach(function (done) {
this.res.callback = done
this.AuthenticationController.getLoggedInUserId = sinon
.stub()
@@ -173,15 +173,15 @@ describe('SubscriptionController', function() {
return this.SubscriptionController.plansPage(this.req, this.res)
})
- it('should not fetch the current user', function(done) {
+ it('should not fetch the current user', function (done) {
this.UserGetter.getUser.callCount.should.equal(0)
return done()
})
})
})
- describe('paymentPage', function() {
- beforeEach(function() {
+ describe('paymentPage', function () {
+ beforeEach(function () {
this.req.headers = {}
this.SubscriptionHandler.validateNoSubscriptionInRecurly = sinon
.stub()
@@ -193,8 +193,8 @@ describe('SubscriptionController', function() {
)
})
- describe('with a user without a subscription', function() {
- beforeEach(function() {
+ describe('with a user without a subscription', function () {
+ beforeEach(function () {
this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith(
1,
null,
@@ -203,8 +203,8 @@ describe('SubscriptionController', function() {
return this.PlansLocator.findLocalPlanInSettings.returns({})
})
- describe('with a valid plan code', function() {
- it('should render the new subscription page', function(done) {
+ describe('with a valid plan code', function () {
+ it('should render the new subscription page', function (done) {
this.res.render = (page, opts) => {
page.should.equal('subscriptions/new')
return done()
@@ -214,8 +214,8 @@ describe('SubscriptionController', function() {
})
})
- describe('with a user with subscription', function() {
- it('should redirect to the subscription dashboard', function(done) {
+ describe('with a user with subscription', function () {
+ it('should redirect to the subscription dashboard', function (done) {
this.PlansLocator.findLocalPlanInSettings.returns({})
this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith(
1,
@@ -230,8 +230,8 @@ describe('SubscriptionController', function() {
})
})
- describe('with an invalid plan code', function() {
- it('should return 422 error - Unprocessable Entity', function(done) {
+ describe('with an invalid plan code', function () {
+ it('should return 422 error - Unprocessable Entity', function (done) {
this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith(
1,
null,
@@ -254,8 +254,8 @@ describe('SubscriptionController', function() {
})
})
- describe('which currency to use', function() {
- beforeEach(function() {
+ describe('which currency to use', function () {
+ beforeEach(function () {
this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith(
1,
null,
@@ -264,7 +264,7 @@ describe('SubscriptionController', function() {
return this.PlansLocator.findLocalPlanInSettings.returns({})
})
- it('should use the set currency from the query string', function(done) {
+ it('should use the set currency from the query string', function (done) {
this.req.query.currency = 'EUR'
this.res.render = (page, opts) => {
opts.currency.should.equal('EUR')
@@ -274,7 +274,7 @@ describe('SubscriptionController', function() {
return this.SubscriptionController.paymentPage(this.req, this.res)
})
- it('should upercase the currency code', function(done) {
+ it('should upercase the currency code', function (done) {
this.req.query.currency = 'eur'
this.res.render = (page, opts) => {
opts.currency.should.equal('EUR')
@@ -283,7 +283,7 @@ describe('SubscriptionController', function() {
return this.SubscriptionController.paymentPage(this.req, this.res)
})
- it('should use the geo ip currency if non is provided', function(done) {
+ it('should use the geo ip currency if non is provided', function (done) {
this.req.query.currency = null
this.res.render = (page, opts) => {
opts.currency.should.equal(this.stubbedCurrencyCode)
@@ -293,8 +293,8 @@ describe('SubscriptionController', function() {
})
})
- describe('with a recurly subscription already', function() {
- it('should redirect to the subscription dashboard', function(done) {
+ describe('with a recurly subscription already', function () {
+ it('should redirect to the subscription dashboard', function (done) {
this.PlansLocator.findLocalPlanInSettings.returns({})
this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith(
1,
@@ -313,8 +313,8 @@ describe('SubscriptionController', function() {
})
})
- describe('successful_subscription', function() {
- beforeEach(function(done) {
+ describe('successful_subscription', function () {
+ beforeEach(function (done) {
this.SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel.callsArgWith(
1,
null,
@@ -328,8 +328,8 @@ describe('SubscriptionController', function() {
})
})
- describe('userSubscriptionPage', function() {
- beforeEach(function(done) {
+ describe('userSubscriptionPage', function () {
+ beforeEach(function (done) {
this.SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel.callsArgWith(
1,
null,
@@ -361,7 +361,7 @@ describe('SubscriptionController', function() {
)
})
- it('should load the personal, groups and v1 subscriptions', function() {
+ it('should load the personal, groups and v1 subscriptions', function () {
expect(this.data.personalSubscription).to.deep.equal(
this.personalSubscription
)
@@ -370,17 +370,17 @@ describe('SubscriptionController', function() {
)
})
- it('should load the user', function() {
+ it('should load the user', function () {
return expect(this.data.user).to.deep.equal(this.user)
})
- it('should load the plans', function() {
+ it('should load the plans', function () {
return expect(this.data.plans).to.deep.equal(this.plans)
})
})
- describe('createSubscription', function() {
- beforeEach(function(done) {
+ describe('createSubscription', function () {
+ beforeEach(function (done) {
this.res = {
sendStatus() {
return done()
@@ -402,7 +402,7 @@ describe('SubscriptionController', function() {
return this.SubscriptionController.createSubscription(this.req, this.res)
})
- it('should send the user and subscriptionId to the handler', function(done) {
+ it('should send the user and subscriptionId to the handler', function (done) {
this.SubscriptionHandler.createSubscription
.calledWithMatch(
this.user,
@@ -413,14 +413,14 @@ describe('SubscriptionController', function() {
return done()
})
- it('should redurect to the subscription page', function(done) {
+ it('should redurect to the subscription page', function (done) {
this.res.sendStatus.calledWith(201).should.equal(true)
return done()
})
})
- describe('createSubscription with errors', function() {
- it('should handle users with subscription', function(done) {
+ describe('createSubscription with errors', function () {
+ it('should handle users with subscription', function (done) {
this.LimitationsManager.userHasV1OrV2Subscription.yields(null, true)
this.SubscriptionController.createSubscription(this.req, {
sendStatus: status => {
@@ -432,7 +432,7 @@ describe('SubscriptionController', function() {
})
})
- it('should handle 3DSecure errors', function(done) {
+ it('should handle 3DSecure errors', function (done) {
this.next = sinon.stub()
this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false)
this.SubscriptionHandler.createSubscription.yields(
@@ -449,7 +449,7 @@ describe('SubscriptionController', function() {
this.SubscriptionController.createSubscription(this.req, this.res)
})
- it('should handle validation errors', function(done) {
+ it('should handle validation errors', function (done) {
this.next = sinon.stub()
this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false)
this.SubscriptionHandler.createSubscription.yields(
@@ -466,7 +466,7 @@ describe('SubscriptionController', function() {
this.SubscriptionController.createSubscription(this.req, this.res)
})
- it('should handle recurly errors', function(done) {
+ it('should handle recurly errors', function (done) {
this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false)
this.SubscriptionHandler.createSubscription.yields(
new SubscriptionErrors.RecurlyTransactionError({})
@@ -484,7 +484,7 @@ describe('SubscriptionController', function() {
return this.SubscriptionController.createSubscription(this.req, this.res)
})
- it('should handle invalid error', function(done) {
+ it('should handle invalid error', function (done) {
this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false)
this.SubscriptionHandler.createSubscription.yields(
new Errors.InvalidError({})
@@ -500,8 +500,8 @@ describe('SubscriptionController', function() {
})
})
- describe('updateSubscription via post', function() {
- beforeEach(function(done) {
+ describe('updateSubscription via post', function () {
+ beforeEach(function (done) {
this.res = {
redirect() {
return done()
@@ -513,21 +513,21 @@ describe('SubscriptionController', function() {
return this.SubscriptionController.updateSubscription(this.req, this.res)
})
- it('should send the user and subscriptionId to the handler', function(done) {
+ it('should send the user and subscriptionId to the handler', function (done) {
this.SubscriptionHandler.updateSubscription
.calledWith(this.user, this.plan_code)
.should.equal(true)
return done()
})
- it('should redurect to the subscription page', function(done) {
+ it('should redurect to the subscription page', function (done) {
this.res.redirect.calledWith('/user/subscription').should.equal(true)
return done()
})
})
- describe('updateAccountEmailAddress via put', function() {
- it('should send the user and subscriptionId to RecurlyWrapper', function() {
+ describe('updateAccountEmailAddress via put', function () {
+ it('should send the user and subscriptionId to RecurlyWrapper', function () {
this.res.sendStatus = sinon.spy()
this.SubscriptionController.updateAccountEmailAddress(this.req, this.res)
this.RecurlyWrapper.updateAccountEmailAddress
@@ -535,13 +535,13 @@ describe('SubscriptionController', function() {
.should.equal(true)
})
- it('should respond with 200', function() {
+ it('should respond with 200', function () {
this.res.sendStatus = sinon.spy()
this.SubscriptionController.updateAccountEmailAddress(this.req, this.res)
this.res.sendStatus.calledWith(200).should.equal(true)
})
- it('should send the error to the next handler when updating recurly account email fails', function(done) {
+ it('should send the error to the next handler when updating recurly account email fails', function (done) {
this.RecurlyWrapper.updateAccountEmailAddress.yields(new Error())
this.next = sinon.spy(error => {
expect(error).instanceOf(Error)
@@ -555,8 +555,8 @@ describe('SubscriptionController', function() {
})
})
- describe('reactivateSubscription', function() {
- beforeEach(function(done) {
+ describe('reactivateSubscription', function () {
+ beforeEach(function (done) {
this.res = {
redirect() {
return done()
@@ -569,21 +569,21 @@ describe('SubscriptionController', function() {
)
})
- it('should tell the handler to reactivate this user', function(done) {
+ it('should tell the handler to reactivate this user', function (done) {
this.SubscriptionHandler.reactivateSubscription
.calledWith(this.user)
.should.equal(true)
return done()
})
- it('should redurect to the subscription page', function(done) {
+ it('should redurect to the subscription page', function (done) {
this.res.redirect.calledWith('/user/subscription').should.equal(true)
return done()
})
})
- describe('cancelSubscription', function() {
- beforeEach(function(done) {
+ describe('cancelSubscription', function () {
+ beforeEach(function (done) {
this.res = {
redirect() {
return done()
@@ -593,14 +593,14 @@ describe('SubscriptionController', function() {
return this.SubscriptionController.cancelSubscription(this.req, this.res)
})
- it('should tell the handler to cancel this user', function(done) {
+ it('should tell the handler to cancel this user', function (done) {
this.SubscriptionHandler.cancelSubscription
.calledWith(this.user)
.should.equal(true)
return done()
})
- it('should redurect to the subscription page', function(done) {
+ it('should redurect to the subscription page', function (done) {
this.res.redirect
.calledWith('/user/subscription/canceled')
.should.equal(true)
@@ -608,9 +608,9 @@ describe('SubscriptionController', function() {
})
})
- describe('recurly callback', function() {
- describe('with a sync subscription request', function() {
- beforeEach(function(done) {
+ describe('recurly callback', function () {
+ describe('with a sync subscription request', function () {
+ beforeEach(function (done) {
this.req = {
body: {
expired_subscription_notification: {
@@ -629,19 +629,19 @@ describe('SubscriptionController', function() {
return this.SubscriptionController.recurlyCallback(this.req, this.res)
})
- it('should tell the SubscriptionHandler to process the recurly callback', function(done) {
+ it('should tell the SubscriptionHandler to process the recurly callback', function (done) {
this.SubscriptionHandler.syncSubscription.called.should.equal(true)
return done()
})
- it('should send a 200', function(done) {
+ it('should send a 200', function (done) {
this.res.sendStatus.calledWith(200)
return done()
})
})
- describe('with a billing info updated request', function() {
- beforeEach(function(done) {
+ describe('with a billing info updated request', function () {
+ beforeEach(function (done) {
this.req = {
body: {
billing_info_updated_notification: {
@@ -660,21 +660,21 @@ describe('SubscriptionController', function() {
this.SubscriptionController.recurlyCallback(this.req, this.res)
})
- it('should call attemptPaypalInvoiceCollection', function(done) {
+ it('should call attemptPaypalInvoiceCollection', function (done) {
this.SubscriptionHandler.attemptPaypalInvoiceCollection
.calledWith('mock-account-code')
.should.equal(true)
done()
})
- it('should send a 200', function(done) {
+ it('should send a 200', function (done) {
this.res.sendStatus.calledWith(200)
done()
})
})
- describe('with a non-actionable request', function() {
- beforeEach(function(done) {
+ describe('with a non-actionable request', function () {
+ beforeEach(function (done) {
this.user.id = this.activeRecurlySubscription.account.account_code
this.req = {
body: {
@@ -694,23 +694,23 @@ describe('SubscriptionController', function() {
return this.SubscriptionController.recurlyCallback(this.req, this.res)
})
- it('should not call the subscriptionshandler', function() {
+ it('should not call the subscriptionshandler', function () {
this.SubscriptionHandler.syncSubscription.called.should.equal(false)
this.SubscriptionHandler.attemptPaypalInvoiceCollection.called.should.equal(
false
)
})
- it('should respond with a 200 status', function() {
+ it('should respond with a 200 status', function () {
return this.res.sendStatus.calledWith(200)
})
})
})
- describe('renderUpgradeToAnnualPlanPage', function() {
- it('should redirect to the plans page if the user does not have a subscription', function(done) {
+ describe('renderUpgradeToAnnualPlanPage', function () {
+ it('should redirect to the plans page if the user does not have a subscription', function (done) {
this.LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false)
- this.res.redirect = function(url) {
+ this.res.redirect = function (url) {
url.should.equal('/user/subscription/plans')
return done()
}
@@ -720,14 +720,14 @@ describe('SubscriptionController', function() {
)
})
- it('should pass the plan code to the view - student', function(done) {
+ it('should pass the plan code to the view - student', function (done) {
this.LimitationsManager.userHasV2Subscription.callsArgWith(
1,
null,
true,
{ planCode: 'Student free trial 14 days' }
)
- this.res.render = function(view, opts) {
+ this.res.render = function (view, opts) {
view.should.equal('subscriptions/upgradeToAnnual')
opts.planName.should.equal('student')
return done()
@@ -738,14 +738,14 @@ describe('SubscriptionController', function() {
)
})
- it('should pass the plan code to the view - collaborator', function(done) {
+ it('should pass the plan code to the view - collaborator', function (done) {
this.LimitationsManager.userHasV2Subscription.callsArgWith(
1,
null,
true,
{ planCode: 'free trial for Collaborator free trial 14 days' }
)
- this.res.render = function(view, opts) {
+ this.res.render = function (view, opts) {
opts.planName.should.equal('collaborator')
return done()
}
@@ -755,14 +755,14 @@ describe('SubscriptionController', function() {
)
})
- it('should pass annual as the plan name if the user is already on an annual plan', function(done) {
+ it('should pass annual as the plan name if the user is already on an annual plan', function (done) {
this.LimitationsManager.userHasV2Subscription.callsArgWith(
1,
null,
true,
{ planCode: 'student annual with free trial' }
)
- this.res.render = function(view, opts) {
+ this.res.render = function (view, opts) {
opts.planName.should.equal('annual')
return done()
}
@@ -773,10 +773,10 @@ describe('SubscriptionController', function() {
})
})
- describe('processUpgradeToAnnualPlan', function() {
- beforeEach(function() {})
+ describe('processUpgradeToAnnualPlan', function () {
+ beforeEach(function () {})
- it('should tell the subscription handler to update the subscription with the annual plan and apply a coupon code', function(done) {
+ it('should tell the subscription handler to update the subscription with the annual plan and apply a coupon code', function (done) {
this.req.body = { planName: 'student' }
this.res.sendStatus = () => {
@@ -792,7 +792,7 @@ describe('SubscriptionController', function() {
)
})
- it('should get the collaborator coupon code', function(done) {
+ it('should get the collaborator coupon code', function (done) {
this.req.body = { planName: 'collaborator' }
this.res.sendStatus = url => {
diff --git a/services/web/test/unit/src/Subscription/SubscriptionGroupControllerTests.js b/services/web/test/unit/src/Subscription/SubscriptionGroupControllerTests.js
index b871f67362..c939113463 100644
--- a/services/web/test/unit/src/Subscription/SubscriptionGroupControllerTests.js
+++ b/services/web/test/unit/src/Subscription/SubscriptionGroupControllerTests.js
@@ -17,8 +17,8 @@ const modulePath =
'../../../../app/src/Features/Subscription/SubscriptionGroupController'
const MockResponse = require('../helpers/MockResponse')
-describe('SubscriptionGroupController', function() {
- beforeEach(function() {
+describe('SubscriptionGroupController', function () {
+ beforeEach(function () {
this.user = { _id: '!@312431', email: 'user@email.com' }
this.adminUserId = '123jlkj'
this.subscriptionId = '123434325412'
@@ -65,8 +65,8 @@ describe('SubscriptionGroupController', function() {
}))
})
- describe('removeUserFromGroup', function() {
- it('should use the subscription id for the logged in user and take the user id from the params', function(done) {
+ describe('removeUserFromGroup', function () {
+ it('should use the subscription id for the logged in user and take the user id from the params', function (done) {
const userIdToRemove = '31231'
this.req.params = { user_id: userIdToRemove }
this.req.entity = this.subscription
@@ -83,8 +83,8 @@ describe('SubscriptionGroupController', function() {
})
})
- describe('removeSelfFromGroup', function() {
- it('gets subscription and remove user', function(done) {
+ describe('removeSelfFromGroup', function () {
+ it('gets subscription and remove user', function (done) {
const userIdToRemove = '31231'
this.req.query = { subscriptionId: this.subscriptionId }
const memberUserIdToremove = 123456789
diff --git a/services/web/test/unit/src/Subscription/SubscriptionGroupHandlerTests.js b/services/web/test/unit/src/Subscription/SubscriptionGroupHandlerTests.js
index 62f4937a30..352ec2117b 100644
--- a/services/web/test/unit/src/Subscription/SubscriptionGroupHandlerTests.js
+++ b/services/web/test/unit/src/Subscription/SubscriptionGroupHandlerTests.js
@@ -18,8 +18,8 @@ const { assert, expect } = require('chai')
const modulePath =
'../../../../app/src/Features/Subscription/SubscriptionGroupHandler'
-describe('SubscriptionGroupHandler', function() {
- beforeEach(function() {
+describe('SubscriptionGroupHandler', function () {
+ beforeEach(function () {
this.adminUser_id = '12321'
this.newEmail = 'bob@smith.com'
this.user_id = '3121321'
@@ -105,8 +105,8 @@ describe('SubscriptionGroupHandler', function() {
}))
})
- describe('removeUserFromGroup', function() {
- it('should call the subscription updater to remove the user', function(done) {
+ describe('removeUserFromGroup', function () {
+ it('should call the subscription updater to remove the user', function (done) {
return this.Handler.removeUserFromGroup(
this.adminUser_id,
this.user._id,
@@ -120,8 +120,8 @@ describe('SubscriptionGroupHandler', function() {
})
})
- describe('replaceUserReferencesInGroups', function() {
- beforeEach(function(done) {
+ describe('replaceUserReferencesInGroups', function () {
+ beforeEach(function (done) {
this.oldId = 'ba5eba11'
this.newId = '5ca1ab1e'
return this.Handler.replaceUserReferencesInGroups(
@@ -131,13 +131,13 @@ describe('SubscriptionGroupHandler', function() {
)
})
- it('replaces the admin_id', function() {
+ it('replaces the admin_id', function () {
return this.Subscription.updateOne
.calledWith({ admin_id: this.oldId }, { admin_id: this.newId })
.should.equal(true)
})
- it('replaces the manager_ids', function() {
+ it('replaces the manager_ids', function () {
this.Subscription.updateMany
.calledWith(
{ manager_ids: 'ba5eba11' },
@@ -153,7 +153,7 @@ describe('SubscriptionGroupHandler', function() {
.should.equal(true)
})
- it('replaces the member ids', function() {
+ it('replaces the member ids', function () {
this.Subscription.updateMany
.calledWith(
{ member_ids: this.oldId },
@@ -170,12 +170,12 @@ describe('SubscriptionGroupHandler', function() {
})
})
- describe('isUserPartOfGroup', function() {
- beforeEach(function() {
+ describe('isUserPartOfGroup', function () {
+ beforeEach(function () {
return (this.subscription_id = '123ed13123')
})
- it('should return true when user is part of subscription', function(done) {
+ it('should return true when user is part of subscription', function (done) {
this.SubscriptionLocator.getSubscriptionByMemberIdAndId.callsArgWith(
2,
null,
@@ -191,7 +191,7 @@ describe('SubscriptionGroupHandler', function() {
)
})
- it('should return false when no subscription is found', function(done) {
+ it('should return false when no subscription is found', function (done) {
this.SubscriptionLocator.getSubscriptionByMemberIdAndId.callsArgWith(
2,
null
@@ -207,12 +207,12 @@ describe('SubscriptionGroupHandler', function() {
})
})
- describe('getTotalConfirmedUsersInGroup', function() {
- describe('for existing subscriptions', function() {
- beforeEach(function() {
+ describe('getTotalConfirmedUsersInGroup', function () {
+ describe('for existing subscriptions', function () {
+ beforeEach(function () {
return (this.subscription.member_ids = ['12321', '3121321'])
})
- it('should call the subscription locator and return 2 users', function(done) {
+ it('should call the subscription locator and return 2 users', function (done) {
return this.Handler.getTotalConfirmedUsersInGroup(
this.subscription_id,
(err, count) => {
@@ -225,8 +225,8 @@ describe('SubscriptionGroupHandler', function() {
)
})
})
- describe('for nonexistent subscriptions', function() {
- it('should return undefined', function(done) {
+ describe('for nonexistent subscriptions', function () {
+ it('should return undefined', function (done) {
return this.Handler.getTotalConfirmedUsersInGroup(
'fake-id',
(err, count) => {
diff --git a/services/web/test/unit/src/Subscription/SubscriptionHandlerTests.js b/services/web/test/unit/src/Subscription/SubscriptionHandlerTests.js
index 6f43f7a737..c39d7ddcda 100644
--- a/services/web/test/unit/src/Subscription/SubscriptionHandlerTests.js
+++ b/services/web/test/unit/src/Subscription/SubscriptionHandlerTests.js
@@ -19,8 +19,8 @@ const mockRecurlySubscriptions = {
}
}
-describe('SubscriptionHandler', function() {
- beforeEach(function() {
+describe('SubscriptionHandler', function () {
+ beforeEach(function () {
this.Settings = {
plans: [
{
@@ -92,8 +92,8 @@ describe('SubscriptionHandler', function() {
.callsArgWith(2)
})
- describe('createSubscription', function() {
- beforeEach(function() {
+ describe('createSubscription', function () {
+ beforeEach(function () {
this.callback = sinon.stub()
this.subscriptionDetails = {
cvv: '123',
@@ -105,8 +105,8 @@ describe('SubscriptionHandler', function() {
.yields(null, true)
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
this.SubscriptionHandler.createSubscription(
this.user,
this.subscriptionDetails,
@@ -115,13 +115,13 @@ describe('SubscriptionHandler', function() {
)
})
- it('should create the subscription with the wrapper', function() {
+ it('should create the subscription with the wrapper', function () {
this.RecurlyWrapper.createSubscription
.calledWith(this.user, this.subscriptionDetails, this.recurlyTokenIds)
.should.equal(true)
})
- it('should sync the subscription to the user', function() {
+ it('should sync the subscription to the user', function () {
this.SubscriptionUpdater.syncSubscription.calledOnce.should.equal(true)
this.SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal(
this.activeRecurlySubscription
@@ -132,8 +132,8 @@ describe('SubscriptionHandler', function() {
})
})
- describe('when there is already a subscription in Recurly', function() {
- beforeEach(function() {
+ describe('when there is already a subscription in Recurly', function () {
+ beforeEach(function () {
this.SubscriptionHandler.validateNoSubscriptionInRecurly = sinon
.stub()
.yields(null, false)
@@ -145,7 +145,7 @@ describe('SubscriptionHandler', function() {
)
})
- it('should an error', function() {
+ it('should an error', function () {
this.callback.calledWith(
new Error('user already has subscription in recurly')
)
@@ -153,10 +153,10 @@ describe('SubscriptionHandler', function() {
})
})
- describe('updateSubscription', function() {
- describe('with a user with a subscription', function() {
- describe('with a valid plan code', function() {
- beforeEach(function(done) {
+ describe('updateSubscription', function () {
+ describe('with a user with a subscription', function () {
+ describe('with a valid plan code', function () {
+ beforeEach(function (done) {
this.plan_code = 'collaborator'
this.LimitationsManager.userHasV2Subscription.callsArgWith(
1,
@@ -172,7 +172,7 @@ describe('SubscriptionHandler', function() {
)
})
- it('should update the subscription', function() {
+ it('should update the subscription', function () {
this.RecurlyWrapper.updateSubscription
.calledWith(this.subscription.recurlySubscription_id)
.should.equal(true)
@@ -181,13 +181,13 @@ describe('SubscriptionHandler', function() {
updateOptions.plan_code.should.equal(this.plan_code)
})
- it('should update immediately', function() {
+ it('should update immediately', function () {
const updateOptions = this.RecurlyWrapper.updateSubscription
.args[0][1]
updateOptions.timeframe.should.equal('now')
})
- it('should sync the new subscription to the user', function() {
+ it('should sync the new subscription to the user', function () {
this.SubscriptionUpdater.syncSubscription.calledOnce.should.equal(
true
)
@@ -201,8 +201,8 @@ describe('SubscriptionHandler', function() {
})
})
- describe('with a user without a subscription', function() {
- beforeEach(function(done) {
+ describe('with a user without a subscription', function () {
+ beforeEach(function (done) {
this.LimitationsManager.userHasV2Subscription.callsArgWith(
1,
null,
@@ -216,7 +216,7 @@ describe('SubscriptionHandler', function() {
)
})
- it('should redirect to the subscription dashboard', function() {
+ it('should redirect to the subscription dashboard', function () {
this.RecurlyWrapper.updateSubscription.called.should.equal(false)
this.SubscriptionHandler.syncSubscriptionToUser.called.should.equal(
false
@@ -224,8 +224,8 @@ describe('SubscriptionHandler', function() {
})
})
- describe('with a coupon code', function() {
- beforeEach(function(done) {
+ describe('with a coupon code', function () {
+ beforeEach(function (done) {
this.plan_code = 'collaborator'
this.coupon_code = '1231312'
this.LimitationsManager.userHasV2Subscription.callsArgWith(
@@ -242,13 +242,13 @@ describe('SubscriptionHandler', function() {
)
})
- it('should get the users account', function() {
+ it('should get the users account', function () {
this.RecurlyWrapper.getSubscription
.calledWith(this.activeRecurlySubscription.uuid)
.should.equal(true)
})
- it('should redeme the coupon', function(done) {
+ it('should redeme the coupon', function (done) {
this.RecurlyWrapper.redeemCoupon
.calledWith(
this.activeRecurlySubscription.account.account_code,
@@ -258,7 +258,7 @@ describe('SubscriptionHandler', function() {
done()
})
- it('should update the subscription', function() {
+ it('should update the subscription', function () {
this.RecurlyWrapper.updateSubscription
.calledWith(this.subscription.recurlySubscription_id)
.should.equal(true)
@@ -268,9 +268,9 @@ describe('SubscriptionHandler', function() {
})
})
- describe('cancelSubscription', function() {
- describe('with a user without a subscription', function() {
- beforeEach(function(done) {
+ describe('cancelSubscription', function () {
+ describe('with a user without a subscription', function () {
+ beforeEach(function (done) {
this.LimitationsManager.userHasV2Subscription.callsArgWith(
1,
null,
@@ -280,13 +280,13 @@ describe('SubscriptionHandler', function() {
this.SubscriptionHandler.cancelSubscription(this.user, done)
})
- it('should redirect to the subscription dashboard', function() {
+ it('should redirect to the subscription dashboard', function () {
this.RecurlyWrapper.cancelSubscription.called.should.equal(false)
})
})
- describe('with a user with a subscription', function() {
- beforeEach(function(done) {
+ describe('with a user with a subscription', function () {
+ beforeEach(function (done) {
this.LimitationsManager.userHasV2Subscription.callsArgWith(
1,
null,
@@ -296,7 +296,7 @@ describe('SubscriptionHandler', function() {
this.SubscriptionHandler.cancelSubscription(this.user, done)
})
- it('should cancel the subscription', function() {
+ it('should cancel the subscription', function () {
this.RecurlyWrapper.cancelSubscription.called.should.equal(true)
this.RecurlyWrapper.cancelSubscription
.calledWith(this.subscription.recurlySubscription_id)
@@ -305,9 +305,9 @@ describe('SubscriptionHandler', function() {
})
})
- describe('reactiveRecurlySubscription', function() {
- describe('with a user without a subscription', function() {
- beforeEach(function(done) {
+ describe('reactiveRecurlySubscription', function () {
+ describe('with a user without a subscription', function () {
+ beforeEach(function (done) {
this.LimitationsManager.userHasV2Subscription.callsArgWith(
1,
null,
@@ -317,17 +317,17 @@ describe('SubscriptionHandler', function() {
this.SubscriptionHandler.reactivateSubscription(this.user, done)
})
- it('should redirect to the subscription dashboard', function() {
+ it('should redirect to the subscription dashboard', function () {
this.RecurlyWrapper.reactivateSubscription.called.should.equal(false)
})
- it('should not send a notification email', function() {
+ it('should not send a notification email', function () {
sinon.assert.notCalled(this.EmailHandler.sendEmail)
})
})
- describe('with a user with a subscription', function() {
- beforeEach(function(done) {
+ describe('with a user with a subscription', function () {
+ beforeEach(function (done) {
this.LimitationsManager.userHasV2Subscription.callsArgWith(
1,
null,
@@ -337,14 +337,14 @@ describe('SubscriptionHandler', function() {
this.SubscriptionHandler.reactivateSubscription(this.user, done)
})
- it('should reactivate the subscription', function() {
+ it('should reactivate the subscription', function () {
this.RecurlyWrapper.reactivateSubscription.called.should.equal(true)
this.RecurlyWrapper.reactivateSubscription
.calledWith(this.subscription.recurlySubscription_id)
.should.equal(true)
})
- it('should send a notification email', function() {
+ it('should send a notification email', function () {
sinon.assert.calledWith(
this.EmailHandler.sendEmail,
'reactivatedSubscription'
@@ -353,9 +353,9 @@ describe('SubscriptionHandler', function() {
})
})
- describe('syncSubscription', function() {
- describe('with an actionable request', function() {
- beforeEach(function(done) {
+ describe('syncSubscription', function () {
+ describe('with an actionable request', function () {
+ beforeEach(function (done) {
this.user.id = this.activeRecurlySubscription.account.account_code
this.User.findById = (userId, projection, callback) => {
@@ -369,18 +369,18 @@ describe('SubscriptionHandler', function() {
)
})
- it('should request the affected subscription from the API', function() {
+ it('should request the affected subscription from the API', function () {
this.RecurlyWrapper.getSubscription
.calledWith(this.activeRecurlySubscription.uuid)
.should.equal(true)
})
- it('should request the account details of the subscription', function() {
+ it('should request the account details of the subscription', function () {
const options = this.RecurlyWrapper.getSubscription.args[0][1]
options.includeAccount.should.equal(true)
})
- it('should sync the subscription to the user', function() {
+ it('should sync the subscription to the user', function () {
this.SubscriptionUpdater.syncSubscription.calledOnce.should.equal(true)
this.SubscriptionUpdater.syncSubscription.args[0][0].should.deep.equal(
this.activeRecurlySubscription
@@ -392,9 +392,9 @@ describe('SubscriptionHandler', function() {
})
})
- describe('attemptPaypalInvoiceCollection', function() {
- describe('for credit card users', function() {
- beforeEach(function(done) {
+ describe('attemptPaypalInvoiceCollection', function () {
+ describe('for credit card users', function () {
+ beforeEach(function (done) {
this.RecurlyWrapper.getBillingInfo.yields(null, {
paypal_billing_agreement_id: null
})
@@ -404,20 +404,20 @@ describe('SubscriptionHandler', function() {
)
})
- it('gets billing infos', function() {
+ it('gets billing infos', function () {
sinon.assert.calledWith(
this.RecurlyWrapper.getBillingInfo,
this.activeRecurlySubscription.account.account_code
)
})
- it('skips user', function() {
+ it('skips user', function () {
sinon.assert.notCalled(this.RecurlyWrapper.getAccountPastDueInvoices)
})
})
- describe('for paypal users', function() {
- beforeEach(function(done) {
+ describe('for paypal users', function () {
+ beforeEach(function (done) {
this.RecurlyWrapper.getBillingInfo.yields(null, {
paypal_billing_agreement_id: 'mock-billing-agreement'
})
@@ -430,14 +430,14 @@ describe('SubscriptionHandler', function() {
)
})
- it('gets past due invoices', function() {
+ it('gets past due invoices', function () {
sinon.assert.calledWith(
this.RecurlyWrapper.getAccountPastDueInvoices,
this.activeRecurlySubscription.account.account_code
)
})
- it('calls attemptInvoiceCollection', function() {
+ it('calls attemptInvoiceCollection', function () {
sinon.assert.calledWith(
this.RecurlyWrapper.attemptInvoiceCollection,
'mock-invoice-number'
@@ -446,8 +446,8 @@ describe('SubscriptionHandler', function() {
})
})
- describe('validateNoSubscriptionInRecurly', function() {
- beforeEach(function() {
+ describe('validateNoSubscriptionInRecurly', function () {
+ beforeEach(function () {
this.subscriptions = []
this.RecurlyWrapper.listAccountActiveSubscriptions = sinon
.stub()
@@ -456,8 +456,8 @@ describe('SubscriptionHandler', function() {
this.callback = sinon.stub()
})
- describe('with no subscription in recurly', function() {
- beforeEach(function() {
+ describe('with no subscription in recurly', function () {
+ beforeEach(function () {
this.subscriptions.push((this.subscription = { mock: 'subscription' }))
this.SubscriptionHandler.validateNoSubscriptionInRecurly(
this.user_id,
@@ -465,36 +465,36 @@ describe('SubscriptionHandler', function() {
)
})
- it('should call RecurlyWrapper.listAccountActiveSubscriptions with the user id', function() {
+ it('should call RecurlyWrapper.listAccountActiveSubscriptions with the user id', function () {
this.RecurlyWrapper.listAccountActiveSubscriptions
.calledWith(this.user_id)
.should.equal(true)
})
- it('should sync the subscription', function() {
+ it('should sync the subscription', function () {
this.SubscriptionUpdater.syncSubscription
.calledWith(this.subscription, this.user_id)
.should.equal(true)
})
- it('should call the callback with valid == false', function() {
+ it('should call the callback with valid == false', function () {
this.callback.calledWith(null, false).should.equal(true)
})
})
- describe('with a subscription in recurly', function() {
- beforeEach(function() {
+ describe('with a subscription in recurly', function () {
+ beforeEach(function () {
this.SubscriptionHandler.validateNoSubscriptionInRecurly(
this.user_id,
this.callback
)
})
- it('should not sync the subscription', function() {
+ it('should not sync the subscription', function () {
this.SubscriptionUpdater.syncSubscription.called.should.equal(false)
})
- it('should call the callback with valid == true', function() {
+ it('should call the callback with valid == true', function () {
this.callback.calledWith(null, true).should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Subscription/SubscriptionLocatorTests.js b/services/web/test/unit/src/Subscription/SubscriptionLocatorTests.js
index d8da940b3a..4f236e223e 100644
--- a/services/web/test/unit/src/Subscription/SubscriptionLocatorTests.js
+++ b/services/web/test/unit/src/Subscription/SubscriptionLocatorTests.js
@@ -17,8 +17,8 @@ const modulePath =
'../../../../app/src/Features/Subscription/SubscriptionLocator'
const { assert } = require('chai')
-describe('Subscription Locator Tests', function() {
- beforeEach(function() {
+describe('Subscription Locator Tests', function () {
+ beforeEach(function () {
this.user = { _id: '5208dd34438842e2db333333' }
this.subscription = { hello: 'world' }
this.Subscription = {
@@ -42,8 +42,8 @@ describe('Subscription Locator Tests', function() {
}))
})
- describe('finding users subscription', function() {
- it('should send the users features', function(done) {
+ describe('finding users subscription', function () {
+ it('should send the users features', function (done) {
this.Subscription.findOne.callsArgWith(1, null, this.subscription)
return this.SubscriptionLocator.getUsersSubscription(
this.user,
@@ -57,7 +57,7 @@ describe('Subscription Locator Tests', function() {
)
})
- it('should error if not found', function(done) {
+ it('should error if not found', function (done) {
this.Subscription.findOne.callsArgWith(1, 'not found')
return this.SubscriptionLocator.getUsersSubscription(
this.user,
@@ -68,7 +68,7 @@ describe('Subscription Locator Tests', function() {
)
})
- it('should take a user id rather than the user object', function(done) {
+ it('should take a user id rather than the user object', function (done) {
this.Subscription.findOne.callsArgWith(1, null, this.subscription)
return this.SubscriptionLocator.getUsersSubscription(
this.user._id,
diff --git a/services/web/test/unit/src/Subscription/SubscriptionUpdaterTests.js b/services/web/test/unit/src/Subscription/SubscriptionUpdaterTests.js
index cfef9f34f0..db734da1a4 100644
--- a/services/web/test/unit/src/Subscription/SubscriptionUpdaterTests.js
+++ b/services/web/test/unit/src/Subscription/SubscriptionUpdaterTests.js
@@ -5,8 +5,8 @@ const modulePath =
const { assert, expect } = require('chai')
const { ObjectId } = require('mongodb')
-describe('SubscriptionUpdater', function() {
- beforeEach(function() {
+describe('SubscriptionUpdater', function () {
+ beforeEach(function () {
this.recurlySubscription = {
uuid: '1238uoijdasjhd',
plan: {
@@ -106,8 +106,8 @@ describe('SubscriptionUpdater', function() {
})
})
- describe('updateAdmin', function() {
- it('should update the subscription admin', function(done) {
+ describe('updateAdmin', function () {
+ it('should update the subscription admin', function (done) {
this.subscription.groupPlan = true
this.SubscriptionUpdater.updateAdmin(
this.subscription,
@@ -134,7 +134,7 @@ describe('SubscriptionUpdater', function() {
)
})
- it('should remove the manager for non-group subscriptions', function(done) {
+ it('should remove the manager for non-group subscriptions', function (done) {
this.SubscriptionUpdater.updateAdmin(
this.subscription,
this.otherUserId,
@@ -163,8 +163,8 @@ describe('SubscriptionUpdater', function() {
})
})
- describe('syncSubscription', function() {
- beforeEach(function() {
+ describe('syncSubscription', function () {
+ beforeEach(function () {
this.SubscriptionLocator.getUsersSubscription.callsArgWith(
1,
null,
@@ -175,7 +175,7 @@ describe('SubscriptionUpdater', function() {
.yields()
})
- it('should update the subscription if the user already is admin of one', function(done) {
+ it('should update the subscription if the user already is admin of one', function (done) {
this.SubscriptionUpdater._createNewSubscription = sinon.stub()
this.SubscriptionUpdater.syncSubscription(
@@ -199,7 +199,7 @@ describe('SubscriptionUpdater', function() {
)
})
- it('should not call updateFeatures with group subscription if recurly subscription is not expired', function(done) {
+ it('should not call updateFeatures with group subscription if recurly subscription is not expired', function (done) {
this.SubscriptionUpdater.syncSubscription(
this.recurlySubscription,
this.adminUser._id,
@@ -223,17 +223,17 @@ describe('SubscriptionUpdater', function() {
})
})
- describe('_updateSubscriptionFromRecurly', function() {
- beforeEach(function() {
+ describe('_updateSubscriptionFromRecurly', function () {
+ beforeEach(function () {
this.FeaturesUpdater.refreshFeatures = sinon.stub().callsArgWith(1)
this.SubscriptionUpdater.deleteSubscription = sinon.stub().yields()
})
- afterEach(function() {
+ afterEach(function () {
this.subscription.member_ids = []
})
- it('should update the subscription with token etc when not expired', function(done) {
+ it('should update the subscription with token etc when not expired', function (done) {
this.SubscriptionUpdater._updateSubscriptionFromRecurly(
this.recurlySubscription,
this.subscription,
@@ -257,7 +257,7 @@ describe('SubscriptionUpdater', function() {
)
})
- it('should remove the subscription when expired', function(done) {
+ it('should remove the subscription when expired', function (done) {
this.recurlySubscription.state = 'expired'
this.SubscriptionUpdater._updateSubscriptionFromRecurly(
this.recurlySubscription,
@@ -275,7 +275,7 @@ describe('SubscriptionUpdater', function() {
)
})
- it('should update all the users features', function(done) {
+ it('should update all the users features', function (done) {
this.subscription.member_ids = this.allUserIds
this.SubscriptionUpdater._updateSubscriptionFromRecurly(
this.recurlySubscription,
@@ -302,7 +302,7 @@ describe('SubscriptionUpdater', function() {
)
})
- it('should set group to true and save how many members can be added to group', function(done) {
+ it('should set group to true and save how many members can be added to group', function (done) {
this.PlansLocator.findLocalPlanInSettings
.withArgs(this.recurlySubscription.plan.plan_code)
.returns({ groupPlan: true, membersLimit: 5 })
@@ -324,7 +324,7 @@ describe('SubscriptionUpdater', function() {
)
})
- it('should not set group to true or set groupPlan', function(done) {
+ it('should not set group to true or set groupPlan', function (done) {
this.SubscriptionUpdater._updateSubscriptionFromRecurly(
this.recurlySubscription,
this.subscription,
@@ -340,8 +340,8 @@ describe('SubscriptionUpdater', function() {
)
})
- describe('when the plan allows adding more seats', function() {
- beforeEach(function() {
+ describe('when the plan allows adding more seats', function () {
+ beforeEach(function () {
this.membersLimitAddOn = 'add_on1'
this.PlansLocator.findLocalPlanInSettings
.withArgs(this.recurlySubscription.plan.plan_code)
@@ -353,7 +353,7 @@ describe('SubscriptionUpdater', function() {
})
function expectMembersLimit(limit) {
- it('should set the membersLimit accordingly', function(done) {
+ it('should set the membersLimit accordingly', function (done) {
this.SubscriptionUpdater._updateSubscriptionFromRecurly(
this.recurlySubscription,
this.subscription,
@@ -368,15 +368,15 @@ describe('SubscriptionUpdater', function() {
})
}
- describe('when the recurlySubscription does not have add ons', function() {
- beforeEach(function() {
+ describe('when the recurlySubscription does not have add ons', function () {
+ beforeEach(function () {
delete this.recurlySubscription.subscription_add_ons
})
expectMembersLimit(5)
})
- describe('when the recurlySubscription has non-matching add ons', function() {
- beforeEach(function() {
+ describe('when the recurlySubscription has non-matching add ons', function () {
+ beforeEach(function () {
this.recurlySubscription.subscription_add_ons = [
{ add_on_code: 'add_on_99', quantity: 3 }
]
@@ -384,8 +384,8 @@ describe('SubscriptionUpdater', function() {
expectMembersLimit(5)
})
- describe('when the recurlySubscription has a matching add on', function() {
- beforeEach(function() {
+ describe('when the recurlySubscription has a matching add on', function () {
+ beforeEach(function () {
this.recurlySubscription.subscription_add_ons = [
{ add_on_code: this.membersLimitAddOn, quantity: 10 }
]
@@ -394,8 +394,8 @@ describe('SubscriptionUpdater', function() {
})
// NOTE: This is unexpected, but we are going to support it anyways.
- describe('when the recurlySubscription has multiple matching add ons', function() {
- beforeEach(function() {
+ describe('when the recurlySubscription has multiple matching add ons', function () {
+ beforeEach(function () {
this.recurlySubscription.subscription_add_ons = [
{ add_on_code: this.membersLimitAddOn, quantity: 10 },
{ add_on_code: this.membersLimitAddOn, quantity: 3 }
@@ -406,8 +406,8 @@ describe('SubscriptionUpdater', function() {
})
})
- describe('_createNewSubscription', function() {
- it('should create a new subscription then update the subscription', function(done) {
+ describe('_createNewSubscription', function () {
+ it('should create a new subscription then update the subscription', function (done) {
this.SubscriptionUpdater._createNewSubscription(
this.adminUser._id,
() => {
@@ -420,12 +420,12 @@ describe('SubscriptionUpdater', function() {
})
})
- describe('addUserToGroup', function() {
- beforeEach(function() {
+ describe('addUserToGroup', function () {
+ beforeEach(function () {
this.SubscriptionUpdater.addUsersToGroup = sinon.stub().yields(null)
})
- it('delegates to addUsersToGroup', function(done) {
+ it('delegates to addUsersToGroup', function (done) {
this.SubscriptionUpdater.addUserToGroup(
this.subscription._id,
this.otherUserId,
@@ -439,12 +439,12 @@ describe('SubscriptionUpdater', function() {
})
})
- describe('addUsersToGroup', function() {
- beforeEach(function() {
+ describe('addUsersToGroup', function () {
+ beforeEach(function () {
this.FeaturesUpdater.refreshFeatures = sinon.stub().callsArgWith(1)
})
- it('should add the user ids to the group as a set', function(done) {
+ it('should add the user ids to the group as a set', function (done) {
this.SubscriptionUpdater.addUsersToGroup(
this.subscription._id,
[this.otherUserId],
@@ -461,7 +461,7 @@ describe('SubscriptionUpdater', function() {
)
})
- it('should update the users features', function(done) {
+ it('should update the users features', function (done) {
this.SubscriptionUpdater.addUserToGroup(
this.subscription._id,
this.otherUserId,
@@ -475,8 +475,8 @@ describe('SubscriptionUpdater', function() {
})
})
- describe('removeUserFromGroups', function() {
- beforeEach(function() {
+ describe('removeUserFromGroups', function () {
+ beforeEach(function () {
this.FeaturesUpdater.refreshFeatures = sinon.stub().callsArgWith(1)
this.UserGetter.getUser.yields(null, {})
this.fakeSubscriptions = [{ _id: 'fake-id-1' }, { _id: 'fake-id-2' }]
@@ -486,7 +486,7 @@ describe('SubscriptionUpdater', function() {
)
})
- it('should pull the users id from the group', function(done) {
+ it('should pull the users id from the group', function (done) {
this.SubscriptionUpdater.removeUserFromGroup(
this.subscription._id,
this.otherUserId,
@@ -501,7 +501,7 @@ describe('SubscriptionUpdater', function() {
)
})
- it('should pull the users id from all groups', function(done) {
+ it('should pull the users id from all groups', function (done) {
this.SubscriptionUpdater.removeUserFromAllGroups(this.otherUserId, () => {
const filter = { _id: ['fake-id-1', 'fake-id-2'] }
const removeOperation = { $pull: { member_ids: this.otherUserId } }
@@ -510,7 +510,7 @@ describe('SubscriptionUpdater', function() {
})
})
- it('should update the users features', function(done) {
+ it('should update the users features', function (done) {
this.SubscriptionUpdater.removeUserFromGroup(
this.subscription._id,
this.otherUserId,
@@ -524,8 +524,8 @@ describe('SubscriptionUpdater', function() {
})
})
- describe('deleteSubscription', function() {
- beforeEach(function(done) {
+ describe('deleteSubscription', function () {
+ beforeEach(function (done) {
this.subscription = {
_id: ObjectId().toString(),
mock: 'subscription',
@@ -539,19 +539,19 @@ describe('SubscriptionUpdater', function() {
this.SubscriptionUpdater.deleteSubscription(this.subscription, {}, done)
})
- it('should remove the subscription', function() {
+ it('should remove the subscription', function () {
this.SubscriptionModel.deleteOne
.calledWith({ _id: this.subscription._id })
.should.equal(true)
})
- it('should downgrade the admin_id', function() {
+ it('should downgrade the admin_id', function () {
this.FeaturesUpdater.refreshFeatures
.calledWith(this.subscription.admin_id)
.should.equal(true)
})
- it('should downgrade all of the members', function() {
+ it('should downgrade all of the members', function () {
for (const userId of this.subscription.member_ids) {
this.FeaturesUpdater.refreshFeatures
.calledWith(userId)
diff --git a/services/web/test/unit/src/Subscription/TeamInvitesHandlerTests.js b/services/web/test/unit/src/Subscription/TeamInvitesHandlerTests.js
index e147886868..a0d4b80aa1 100644
--- a/services/web/test/unit/src/Subscription/TeamInvitesHandlerTests.js
+++ b/services/web/test/unit/src/Subscription/TeamInvitesHandlerTests.js
@@ -7,8 +7,8 @@ const modulePath =
const { ObjectId } = require('mongodb')
const Errors = require('../../../../app/src/Features/Errors/Errors')
-describe('TeamInvitesHandler', function() {
- beforeEach(function() {
+describe('TeamInvitesHandler', function () {
+ beforeEach(function () {
this.manager = {
_id: '666666',
first_name: 'Daenerys',
@@ -98,8 +98,8 @@ describe('TeamInvitesHandler', function() {
})
})
- describe('getInvite', function() {
- it("returns the invite if there's one", function(done) {
+ describe('getInvite', function () {
+ it("returns the invite if there's one", function (done) {
this.TeamInvitesHandler.getInvite(
this.token,
(err, invite, subscription) => {
@@ -111,7 +111,7 @@ describe('TeamInvitesHandler', function() {
)
})
- it("returns teamNotFound if there's none", function(done) {
+ it("returns teamNotFound if there's none", function (done) {
this.Subscription.findOne = sinon.stub().yields(null, null)
this.TeamInvitesHandler.getInvite(
@@ -124,8 +124,8 @@ describe('TeamInvitesHandler', function() {
})
})
- describe('createInvite', function() {
- it('adds the team invite to the subscription', function(done) {
+ describe('createInvite', function () {
+ it('adds the team invite to the subscription', function (done) {
this.TeamInvitesHandler.createInvite(
this.manager._id,
this.subscription,
@@ -144,7 +144,7 @@ describe('TeamInvitesHandler', function() {
)
})
- it('sends an email', function(done) {
+ it('sends an email', function (done) {
this.TeamInvitesHandler.createInvite(
this.manager._id,
this.subscription,
@@ -165,7 +165,7 @@ describe('TeamInvitesHandler', function() {
)
})
- it('refreshes the existing invite if the email has already been invited', function(done) {
+ it('refreshes the existing invite if the email has already been invited', function (done) {
const originalInvite = Object.assign({}, this.teamInvite)
this.TeamInvitesHandler.createInvite(
@@ -188,7 +188,7 @@ describe('TeamInvitesHandler', function() {
)
})
- it('removes any legacy invite from the subscription', function(done) {
+ it('removes any legacy invite from the subscription', function (done) {
this.TeamInvitesHandler.createInvite(
this.manager._id,
this.subscription,
@@ -205,7 +205,7 @@ describe('TeamInvitesHandler', function() {
)
})
- it('add user to subscription if inviting self', function(done) {
+ it('add user to subscription if inviting self', function (done) {
this.TeamInvitesHandler.createInvite(
this.manager._id,
this.subscription,
@@ -228,12 +228,12 @@ describe('TeamInvitesHandler', function() {
})
})
- describe('importInvite', function() {
- beforeEach(function() {
+ describe('importInvite', function () {
+ beforeEach(function () {
this.sentAt = new Date()
})
- it('can imports an invite from v1', function() {
+ it('can imports an invite from v1', function () {
this.TeamInvitesHandler.importInvite(
this.subscription,
'A-Team',
@@ -255,8 +255,8 @@ describe('TeamInvitesHandler', function() {
})
})
- describe('acceptInvite', function() {
- beforeEach(function() {
+ describe('acceptInvite', function () {
+ beforeEach(function () {
this.user = {
id: '123456789',
first_name: 'Tyrion',
@@ -275,7 +275,7 @@ describe('TeamInvitesHandler', function() {
})
})
- it('adds the user to the team', function(done) {
+ it('adds the user to the team', function (done) {
this.TeamInvitesHandler.acceptInvite('dddddddd', this.user.id, () => {
this.SubscriptionUpdater.addUserToGroup
.calledWith(this.subscription._id, this.user.id)
@@ -284,7 +284,7 @@ describe('TeamInvitesHandler', function() {
})
})
- it('removes the invite from the subscription', function(done) {
+ it('removes the invite from the subscription', function (done) {
this.TeamInvitesHandler.acceptInvite('dddddddd', this.user.id, () => {
this.Subscription.updateOne
.calledWith(
@@ -297,8 +297,8 @@ describe('TeamInvitesHandler', function() {
})
})
- describe('revokeInvite', function() {
- it('removes the team invite from the subscription', function(done) {
+ describe('revokeInvite', function () {
+ it('removes the team invite from the subscription', function (done) {
this.TeamInvitesHandler.revokeInvite(
this.manager._id,
this.subscription,
@@ -323,8 +323,8 @@ describe('TeamInvitesHandler', function() {
})
})
- describe('createTeamInvitesForLegacyInvitedEmail', function(done) {
- beforeEach(function() {
+ describe('createTeamInvitesForLegacyInvitedEmail', function (done) {
+ beforeEach(function () {
this.subscription.invited_emails = [
'eddard@example.com',
'robert@example.com'
@@ -335,7 +335,7 @@ describe('TeamInvitesHandler', function() {
.yields(null, [this.subscription])
})
- it('sends an invitation email to addresses in the legacy invited_emails field', function(done) {
+ it('sends an invitation email to addresses in the legacy invited_emails field', function (done) {
this.TeamInvitesHandler.createTeamInvitesForLegacyInvitedEmail(
'eddard@example.com',
(err, invite) => {
@@ -357,8 +357,8 @@ describe('TeamInvitesHandler', function() {
})
})
- describe('validation', function() {
- it("doesn't create an invite if the team limit has been reached", function(done) {
+ describe('validation', function () {
+ it("doesn't create an invite if the team limit has been reached", function (done) {
this.LimitationsManager.teamHasReachedMemberLimit = sinon
.stub()
.returns(true)
@@ -373,7 +373,7 @@ describe('TeamInvitesHandler', function() {
)
})
- it("doesn't create an invite if the subscription is not in a group plan", function(done) {
+ it("doesn't create an invite if the subscription is not in a group plan", function (done) {
this.subscription.groupPlan = false
this.TeamInvitesHandler.createInvite(
this.manager._id,
@@ -386,7 +386,7 @@ describe('TeamInvitesHandler', function() {
)
})
- it("doesn't create an invite if the user is already part of the team", function(done) {
+ it("doesn't create an invite if the user is already part of the team", function (done) {
const member = {
id: '1a2b',
_id: '1a2b',
diff --git a/services/web/test/unit/src/Subscription/UserFeaturesUpdaterTests.js b/services/web/test/unit/src/Subscription/UserFeaturesUpdaterTests.js
index 3df246571b..f932c5f54e 100644
--- a/services/web/test/unit/src/Subscription/UserFeaturesUpdaterTests.js
+++ b/services/web/test/unit/src/Subscription/UserFeaturesUpdaterTests.js
@@ -18,8 +18,8 @@ const modulePath =
'../../../../app/src/Features/Subscription/UserFeaturesUpdater'
const { assert } = require('chai')
-describe('UserFeaturesUpdater', function() {
- beforeEach(function() {
+describe('UserFeaturesUpdater', function () {
+ beforeEach(function () {
this.User = { updateOne: sinon.stub().callsArgWith(2) }
return (this.UserFeaturesUpdater = SandboxedModule.require(modulePath, {
requires: {
@@ -30,8 +30,8 @@ describe('UserFeaturesUpdater', function() {
}))
})
- describe('updateFeatures', function() {
- it('should send the users features', function(done) {
+ describe('updateFeatures', function () {
+ it('should send the users features', function (done) {
const user_id = '5208dd34438842e2db000005'
this.features = { versioning: true, collaborators: 10 }
return this.UserFeaturesUpdater.updateFeatures(
diff --git a/services/web/test/unit/src/Subscription/V1SusbcriptionManagerTests.js b/services/web/test/unit/src/Subscription/V1SusbcriptionManagerTests.js
index 74aaa2aeea..dd2eb27180 100644
--- a/services/web/test/unit/src/Subscription/V1SusbcriptionManagerTests.js
+++ b/services/web/test/unit/src/Subscription/V1SusbcriptionManagerTests.js
@@ -22,8 +22,8 @@ const modulePath = path.join(
const sinon = require('sinon')
const { expect } = require('chai')
-describe('V1SubscriptionManager', function() {
- beforeEach(function() {
+describe('V1SubscriptionManager', function () {
+ beforeEach(function () {
this.V1SubscriptionManager = SandboxedModule.require(modulePath, {
requires: {
'../User/UserGetter': (this.UserGetter = {}),
@@ -54,8 +54,8 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('getPlanCodeFromV1', function() {
- beforeEach(function() {
+ describe('getPlanCodeFromV1', function () {
+ beforeEach(function () {
this.responseBody = {
id: 32,
plan_name: 'pro'
@@ -68,8 +68,8 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('when all goes well', function() {
- it('should call _v1Request', function(done) {
+ describe('when all goes well', function () {
+ it('should call _v1Request', function (done) {
return this.call((err, planCode) => {
expect(this.V1SubscriptionManager._v1Request.callCount).to.equal(1)
expect(
@@ -79,14 +79,14 @@ describe('V1SubscriptionManager', function() {
})
})
- it('should return the v1 user id', function(done) {
- return this.call(function(err, planCode, v1Id) {
+ it('should return the v1 user id', function (done) {
+ return this.call(function (err, planCode, v1Id) {
expect(v1Id).to.equal(this.v1UserId)
return done()
})
})
- it('should produce a plan-code without error', function(done) {
+ it('should produce a plan-code without error', function (done) {
return this.call((err, planCode) => {
expect(err).to.not.exist
expect(planCode).to.equal('v1_pro')
@@ -94,12 +94,12 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('when the plan_name from v1 is null', function() {
- beforeEach(function() {
+ describe('when the plan_name from v1 is null', function () {
+ beforeEach(function () {
return (this.responseBody.plan_name = null)
})
- it('should produce a null plan-code without error', function(done) {
+ it('should produce a null plan-code without error', function (done) {
return this.call((err, planCode) => {
expect(err).to.not.exist
expect(planCode).to.equal(null)
@@ -110,9 +110,9 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('getGrandfatheredFeaturesForV1User', function() {
- describe('when the user ID is greater than the cutoff', function() {
- it('should return an empty feature set', function(done) {
+ describe('getGrandfatheredFeaturesForV1User', function () {
+ describe('when the user ID is greater than the cutoff', function () {
+ it('should return an empty feature set', function (done) {
expect(
this.V1SubscriptionManager.getGrandfatheredFeaturesForV1User(100)
).to.eql({})
@@ -120,8 +120,8 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('when the user ID is less than the cutoff', function() {
- it('should return a feature set with grandfathered properties for github and mendeley', function(done) {
+ describe('when the user ID is less than the cutoff', function () {
+ it('should return a feature set with grandfathered properties for github and mendeley', function (done) {
expect(
this.V1SubscriptionManager.getGrandfatheredFeaturesForV1User(1)
).to.eql({
@@ -133,13 +133,13 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('_v1Request', function() {
- beforeEach(function() {
+ describe('_v1Request', function () {
+ beforeEach(function () {
return (this.UserGetter.getUser = sinon.stub().yields(null, this.user))
})
- describe('when v1IdForUser produces an error', function() {
- beforeEach(function() {
+ describe('when v1IdForUser produces an error', function () {
+ beforeEach(function () {
this.V1SubscriptionManager.v1IdForUser = sinon
.stub()
.yields(new Error('woops'))
@@ -156,14 +156,14 @@ describe('V1SubscriptionManager', function() {
})
})
- it('should not call request', function(done) {
+ it('should not call request', function (done) {
return this.call((err, planCode) => {
expect(this.request.callCount).to.equal(0)
return done()
})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, planCode) => {
expect(err).to.exist
return done()
@@ -171,8 +171,8 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('when v1IdForUser does not find a user', function() {
- beforeEach(function() {
+ describe('when v1IdForUser does not find a user', function () {
+ beforeEach(function () {
this.V1SubscriptionManager.v1IdForUser = sinon.stub().yields(null, null)
return (this.call = cb => {
return this.V1SubscriptionManager._v1Request(
@@ -187,14 +187,14 @@ describe('V1SubscriptionManager', function() {
})
})
- it('should not call request', function(done) {
+ it('should not call request', function (done) {
return this.call((err, planCode) => {
expect(this.request.callCount).to.equal(0)
return done()
})
})
- it('should not error', function(done) {
+ it('should not error', function (done) {
return this.call(err => {
expect(err).to.not.exist
return done()
@@ -202,8 +202,8 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('when the request to v1 fails', function() {
- beforeEach(function() {
+ describe('when the request to v1 fails', function () {
+ beforeEach(function () {
this.request.yields(new Error('woops'))
return (this.call = cb => {
return this.V1SubscriptionManager._v1Request(
@@ -218,7 +218,7 @@ describe('V1SubscriptionManager', function() {
})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.exist
return done()
@@ -226,8 +226,8 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('when the call succeeds', function() {
- beforeEach(function() {
+ describe('when the call succeeds', function () {
+ beforeEach(function () {
this.V1SubscriptionManager.v1IdForUser = sinon
.stub()
.yields(null, this.v1UserId)
@@ -245,21 +245,21 @@ describe('V1SubscriptionManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, body, v1Id) => {
expect(err).not.to.exist
return done()
})
})
- it('should return the v1 user id', function(done) {
+ it('should return the v1 user id', function (done) {
return this.call((err, body, v1Id) => {
expect(v1Id).to.equal(this.v1UserId)
return done()
})
})
- it('should return the http response body', function(done) {
+ it('should return the http response body', function (done) {
return this.call((err, body, v1Id) => {
expect(body).to.equal('{}')
return done()
@@ -267,8 +267,8 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('when the call returns an http error status code', function() {
- beforeEach(function() {
+ describe('when the call returns an http error status code', function () {
+ beforeEach(function () {
this.V1SubscriptionManager.v1IdForUser = sinon
.stub()
.yields(null, this.v1UserId)
@@ -286,7 +286,7 @@ describe('V1SubscriptionManager', function() {
})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, body, v1Id) => {
expect(err).to.exist
return done()
@@ -294,8 +294,8 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('when the call returns an http not-found status code', function() {
- beforeEach(function() {
+ describe('when the call returns an http not-found status code', function () {
+ beforeEach(function () {
this.V1SubscriptionManager.v1IdForUser = sinon
.stub()
.yields(null, this.v1UserId)
@@ -313,7 +313,7 @@ describe('V1SubscriptionManager', function() {
})
})
- it('should produce an not-found error', function(done) {
+ it('should produce an not-found error', function (done) {
return this.call((err, body, v1Id) => {
expect(err).to.exist
expect(err.name).to.equal('NotFoundError')
@@ -323,20 +323,20 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('v1IdForUser', function() {
- beforeEach(function() {
+ describe('v1IdForUser', function () {
+ beforeEach(function () {
return (this.UserGetter.getUser = sinon.stub().yields(null, this.user))
})
- describe('when getUser produces an error', function() {
- beforeEach(function() {
+ describe('when getUser produces an error', function () {
+ beforeEach(function () {
this.UserGetter.getUser = sinon.stub().yields(new Error('woops'))
return (this.call = cb => {
return this.V1SubscriptionManager.v1IdForUser(this.user_id, cb)
})
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.exist
return done()
@@ -344,15 +344,15 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('when getUser does not find a user', function() {
- beforeEach(function() {
+ describe('when getUser does not find a user', function () {
+ beforeEach(function () {
this.UserGetter.getUser = sinon.stub().yields(null, null)
return (this.call = cb => {
return this.V1SubscriptionManager.v1IdForUser(this.user_id, cb)
})
})
- it('should not error', function(done) {
+ it('should not error', function (done) {
return this.call((err, user_id) => {
expect(err).to.not.exist
return done()
@@ -360,21 +360,21 @@ describe('V1SubscriptionManager', function() {
})
})
- describe('when it works', function() {
- beforeEach(function() {
+ describe('when it works', function () {
+ beforeEach(function () {
return (this.call = cb => {
return this.V1SubscriptionManager.v1IdForUser(this.user_id, cb)
})
})
- it('should not error', function(done) {
+ it('should not error', function (done) {
return this.call((err, user_id) => {
expect(err).to.not.exist
return done()
})
})
- it('should return the v1 user id', function(done) {
+ it('should return the v1 user id', function (done) {
return this.call((err, user_id) => {
expect(user_id).to.eql(42)
return done()
diff --git a/services/web/test/unit/src/SystemMessages/SystemMessageManagerTests.js b/services/web/test/unit/src/SystemMessages/SystemMessageManagerTests.js
index 13ef25618d..794889f0c0 100644
--- a/services/web/test/unit/src/SystemMessages/SystemMessageManagerTests.js
+++ b/services/web/test/unit/src/SystemMessages/SystemMessageManagerTests.js
@@ -18,8 +18,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/SystemMessages/SystemMessageManager.js'
)
-describe('SystemMessageManager', function() {
- beforeEach(function() {
+describe('SystemMessageManager', function () {
+ beforeEach(function () {
this.messages = ['messages-stub']
this.SystemMessage = {
find: sinon.stub().yields(null, this.messages)
@@ -32,32 +32,32 @@ describe('SystemMessageManager', function() {
return (this.callback = sinon.stub())
})
- it('should look the messages up in the database on import', function() {
+ it('should look the messages up in the database on import', function () {
sinon.assert.called(this.SystemMessage.find)
})
- describe('getMessage', function() {
- beforeEach(function() {
+ describe('getMessage', function () {
+ beforeEach(function () {
this.SystemMessageManager._cachedMessages = this.messages
return this.SystemMessageManager.getMessages(this.callback)
})
- it('should return the messages', function() {
+ it('should return the messages', function () {
return this.callback.calledWith(null, this.messages).should.equal(true)
})
})
- describe('clearMessages', function() {
- beforeEach(function() {
+ describe('clearMessages', function () {
+ beforeEach(function () {
this.SystemMessage.deleteMany = sinon.stub().callsArg(1)
return this.SystemMessageManager.clearMessages(this.callback)
})
- it('should remove the messages from the database', function() {
+ it('should remove the messages from the database', function () {
return this.SystemMessage.deleteMany.calledWith({}).should.equal(true)
})
- it('should return the callback', function() {
+ it('should return the callback', function () {
return this.callback.called.should.equal(true)
})
})
diff --git a/services/web/test/unit/src/Tags/TagsControllerTests.js b/services/web/test/unit/src/Tags/TagsControllerTests.js
index 1831f13b20..73acb2da90 100644
--- a/services/web/test/unit/src/Tags/TagsControllerTests.js
+++ b/services/web/test/unit/src/Tags/TagsControllerTests.js
@@ -19,12 +19,12 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Tags/TagsController.js'
)
-describe('TagsController', function() {
+describe('TagsController', function () {
const userId = '123nd3ijdks'
const projectId = '123njdskj9jlk'
const tag = 'some_class101'
- beforeEach(function() {
+ beforeEach(function () {
this.handler = {
addProjectToTag: sinon.stub().callsArgWith(3),
removeProjectFromTag: sinon.stub().callsArgWith(3),
@@ -61,8 +61,8 @@ describe('TagsController', function() {
return (this.res.json = sinon.stub())
})
- describe('getAllTags', function() {
- it('should ask the handler for all tags', function(done) {
+ describe('getAllTags', function () {
+ it('should ask the handler for all tags', function (done) {
const allTags = [{ name: 'tag', projects: ['123423', '423423'] }]
this.handler.getAllTags = sinon.stub().callsArgWith(1, null, allTags)
return this.controller.getAllTags(this.req, {
@@ -75,119 +75,119 @@ describe('TagsController', function() {
})
})
- describe('createTag', function() {
- beforeEach(function() {
+ describe('createTag', function () {
+ beforeEach(function () {
this.handler.createTag.callsArgWith(2, null, (this.tag = { mock: 'tag' }))
this.req.session.user._id = this.userId = 'user-id-123'
this.req.body = { name: (this.name = 'tag-name') }
return this.controller.createTag(this.req, this.res)
})
- it('should create the tag in the backend', function() {
+ it('should create the tag in the backend', function () {
return this.handler.createTag
.calledWith(this.userId, this.name)
.should.equal(true)
})
- it('should return the tag', function() {
+ it('should return the tag', function () {
return this.res.json.calledWith(this.tag).should.equal(true)
})
})
- describe('deleteTag', function() {
- beforeEach(function() {
+ describe('deleteTag', function () {
+ beforeEach(function () {
this.req.params.tagId = this.tagId = 'tag-id-123'
this.req.session.user._id = this.userId = 'user-id-123'
return this.controller.deleteTag(this.req, this.res)
})
- it('should delete the tag in the backend', function() {
+ it('should delete the tag in the backend', function () {
return this.handler.deleteTag
.calledWith(this.userId, this.tagId)
.should.equal(true)
})
- it('should return 204 status code', function() {
+ it('should return 204 status code', function () {
this.res.status.calledWith(204).should.equal(true)
return this.res.end.called.should.equal(true)
})
})
- describe('renameTag', function() {
- beforeEach(function() {
+ describe('renameTag', function () {
+ beforeEach(function () {
this.req.params.tagId = this.tagId = 'tag-id-123'
return (this.req.session.user._id = this.userId = 'user-id-123')
})
- describe('with a name', function() {
- beforeEach(function() {
+ describe('with a name', function () {
+ beforeEach(function () {
this.req.body = { name: (this.name = 'new-name') }
return this.controller.renameTag(this.req, this.res)
})
- it('should delete the tag in the backend', function() {
+ it('should delete the tag in the backend', function () {
return this.handler.renameTag
.calledWith(this.userId, this.tagId, this.name)
.should.equal(true)
})
- it('should return 204 status code', function() {
+ it('should return 204 status code', function () {
this.res.status.calledWith(204).should.equal(true)
return this.res.end.called.should.equal(true)
})
})
- describe('without a name', function() {
- beforeEach(function() {
+ describe('without a name', function () {
+ beforeEach(function () {
return this.controller.renameTag(this.req, this.res)
})
- it('should not call the backend', function() {
+ it('should not call the backend', function () {
return this.handler.renameTag.called.should.equal(false)
})
- it('should return 400 (bad request) status code', function() {
+ it('should return 400 (bad request) status code', function () {
this.res.status.calledWith(400).should.equal(true)
return this.res.end.called.should.equal(true)
})
})
})
- describe('addProjectToTag', function() {
- beforeEach(function() {
+ describe('addProjectToTag', function () {
+ beforeEach(function () {
this.req.params.tagId = this.tagId = 'tag-id-123'
this.req.params.projectId = this.projectId = 'project-id-123'
this.req.session.user._id = this.userId = 'user-id-123'
return this.controller.addProjectToTag(this.req, this.res)
})
- it('should add the tag to the project in the backend', function() {
+ it('should add the tag to the project in the backend', function () {
return this.handler.addProjectToTag
.calledWith(this.userId, this.tagId, this.projectId)
.should.equal(true)
})
- it('should return 204 status code', function() {
+ it('should return 204 status code', function () {
this.res.status.calledWith(204).should.equal(true)
return this.res.end.called.should.equal(true)
})
})
- describe('removeProjectFromTag', function() {
- beforeEach(function() {
+ describe('removeProjectFromTag', function () {
+ beforeEach(function () {
this.req.params.tagId = this.tagId = 'tag-id-123'
this.req.params.projectId = this.projectId = 'project-id-123'
this.req.session.user._id = this.userId = 'user-id-123'
return this.controller.removeProjectFromTag(this.req, this.res)
})
- it('should remove the tag from the project in the backend', function() {
+ it('should remove the tag from the project in the backend', function () {
return this.handler.removeProjectFromTag
.calledWith(this.userId, this.tagId, this.projectId)
.should.equal(true)
})
- it('should return 204 status code', function() {
+ it('should return 204 status code', function () {
this.res.status.calledWith(204).should.equal(true)
return this.res.end.called.should.equal(true)
})
diff --git a/services/web/test/unit/src/Tags/TagsHandlerTests.js b/services/web/test/unit/src/Tags/TagsHandlerTests.js
index d88c7d1d0b..26223ef676 100644
--- a/services/web/test/unit/src/Tags/TagsHandlerTests.js
+++ b/services/web/test/unit/src/Tags/TagsHandlerTests.js
@@ -8,8 +8,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Tags/TagsHandler.js'
)
-describe('TagsHandler', function() {
- beforeEach(function() {
+describe('TagsHandler', function () {
+ beforeEach(function () {
this.userId = ObjectId().toString()
this.callback = sinon.stub()
@@ -28,8 +28,8 @@ describe('TagsHandler', function() {
})
})
- describe('finding users tags', function() {
- it('should find all the documents with that user id', function(done) {
+ describe('finding users tags', function () {
+ it('should find all the documents with that user id', function (done) {
const stubbedTags = [{ name: 'tag1' }, { name: 'tag2' }, { name: 'tag3' }]
this.TagMock.expects('find')
.once()
@@ -44,9 +44,9 @@ describe('TagsHandler', function() {
})
})
- describe('createTag', function() {
- describe('when insert succeeds', function() {
- it('should call insert in mongo', function(done) {
+ describe('createTag', function () {
+ describe('when insert succeeds', function () {
+ it('should call insert in mongo', function (done) {
this.TagMock.expects('create')
.withArgs(this.tag)
.once()
@@ -65,13 +65,13 @@ describe('TagsHandler', function() {
})
})
- describe('when insert has duplicate key error error', function() {
- beforeEach(function() {
+ describe('when insert has duplicate key error error', function () {
+ beforeEach(function () {
this.duplicateKeyError = new Error('Duplicate')
this.duplicateKeyError.code = 11000
})
- it('should get tag with findOne and return that tag', function(done) {
+ it('should get tag with findOne and return that tag', function (done) {
this.TagMock.expects('create')
.withArgs(this.tag)
.once()
@@ -95,11 +95,11 @@ describe('TagsHandler', function() {
})
})
- describe('addProjectToTag', function() {
- describe('with a valid tag_id', function() {
- beforeEach(function() {})
+ describe('addProjectToTag', function () {
+ describe('with a valid tag_id', function () {
+ beforeEach(function () {})
- it('should call update in mongo', function(done) {
+ it('should call update in mongo', function (done) {
this.TagMock.expects('findOneAndUpdate')
.once()
.withArgs(
@@ -121,8 +121,8 @@ describe('TagsHandler', function() {
})
})
- describe('addProjectToTagName', function() {
- it('should call update in mongo', function(done) {
+ describe('addProjectToTagName', function () {
+ it('should call update in mongo', function (done) {
this.TagMock.expects('updateOne')
.once()
.withArgs(
@@ -144,8 +144,8 @@ describe('TagsHandler', function() {
})
})
- describe('updateTagUserIds', function() {
- it('should call update in mongo', function(done) {
+ describe('updateTagUserIds', function () {
+ it('should call update in mongo', function (done) {
this.newUserId = ObjectId().toString()
this.TagMock.expects('updateMany')
.once()
@@ -162,9 +162,9 @@ describe('TagsHandler', function() {
})
})
- describe('removeProjectFromTag', function() {
- describe('with a valid tag_id', function() {
- it('should call update in mongo', function(done) {
+ describe('removeProjectFromTag', function () {
+ describe('with a valid tag_id', function () {
+ it('should call update in mongo', function (done) {
this.TagMock.expects('updateOne')
.once()
.withArgs(
@@ -191,8 +191,8 @@ describe('TagsHandler', function() {
})
})
- describe('removeProjectFromAllTags', function() {
- it('should pull the project id from the tag', function(done) {
+ describe('removeProjectFromAllTags', function () {
+ it('should pull the project id from the tag', function (done) {
this.TagMock.expects('updateMany')
.once()
.withArgs(
@@ -216,9 +216,9 @@ describe('TagsHandler', function() {
})
})
- describe('deleteTag', function() {
- describe('with a valid tag_id', function() {
- it('should call remove in mongo', function(done) {
+ describe('deleteTag', function () {
+ describe('with a valid tag_id', function () {
+ it('should call remove in mongo', function (done) {
this.TagMock.expects('deleteOne')
.once()
.withArgs({ _id: this.tagId, user_id: this.userId })
@@ -232,9 +232,9 @@ describe('TagsHandler', function() {
})
})
- describe('renameTag', function() {
- describe('with a valid tag_id', function() {
- it('should call remove in mongo', function(done) {
+ describe('renameTag', function () {
+ describe('with a valid tag_id', function () {
+ it('should call remove in mongo', function (done) {
this.newName = 'new name'
this.TagMock.expects('updateOne')
.once()
diff --git a/services/web/test/unit/src/Templates/TemplatesControllerTests.js b/services/web/test/unit/src/Templates/TemplatesControllerTests.js
index 037915d60a..b14d8151ee 100644
--- a/services/web/test/unit/src/Templates/TemplatesControllerTests.js
+++ b/services/web/test/unit/src/Templates/TemplatesControllerTests.js
@@ -18,8 +18,8 @@ const ProjectHelper = require('../../../../app/src/Features/Project/ProjectHelpe
const modulePath = '../../../../app/src/Features/Templates/TemplatesController'
-describe('TemplatesController', function() {
- beforeEach(function() {
+describe('TemplatesController', function () {
+ beforeEach(function () {
this.user_id = 'user-id'
this.TemplatesController = SandboxedModule.require(modulePath, {
requires: {
@@ -52,9 +52,9 @@ describe('TemplatesController', function() {
return (this.res = { redirect: sinon.stub() })
})
- describe('createProjectFromV1Template', function() {
- describe('on success', function() {
- beforeEach(function() {
+ describe('createProjectFromV1Template', function () {
+ describe('on success', function () {
+ beforeEach(function () {
this.project = { _id: 'project-id' }
this.TemplatesManager.createProjectFromV1Template.yields(
null,
@@ -67,7 +67,7 @@ describe('TemplatesController', function() {
)
})
- it('should call TemplatesManager', function() {
+ it('should call TemplatesManager', function () {
return this.TemplatesManager.createProjectFromV1Template.should.have.been.calledWithMatch(
'brand-variation-id',
'compiler',
@@ -79,19 +79,19 @@ describe('TemplatesController', function() {
)
})
- it('should redirect to project', function() {
+ it('should redirect to project', function () {
return this.res.redirect.should.have.been.calledWith(
'/project/project-id'
)
})
- it('should delete session', function() {
+ it('should delete session', function () {
return expect(this.req.session.templateData).to.be.undefined
})
})
- describe('on error', function() {
- beforeEach(function() {
+ describe('on error', function () {
+ beforeEach(function () {
this.TemplatesManager.createProjectFromV1Template.yields('error')
return this.TemplatesController.createProjectFromV1Template(
this.req,
@@ -100,11 +100,11 @@ describe('TemplatesController', function() {
)
})
- it('should call next with error', function() {
+ it('should call next with error', function () {
return this.next.should.have.been.calledWith('error')
})
- it('should not redirect', function() {
+ it('should not redirect', function () {
return this.res.redirect.called.should.equal(false)
})
})
diff --git a/services/web/test/unit/src/Templates/TemplatesManagerTests.js b/services/web/test/unit/src/Templates/TemplatesManagerTests.js
index 6d10fb94bf..92c52ab61b 100644
--- a/services/web/test/unit/src/Templates/TemplatesManagerTests.js
+++ b/services/web/test/unit/src/Templates/TemplatesManagerTests.js
@@ -16,8 +16,8 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/Templates/TemplatesManager'
-describe('TemplatesManager', function() {
- beforeEach(function() {
+describe('TemplatesManager', function () {
+ beforeEach(function () {
this.project_id = 'project-id'
this.brandVariationId = 'brand-variation-id'
this.compiler = 'pdflatex'
@@ -100,9 +100,9 @@ describe('TemplatesManager', function() {
'%2Ftemplates%2F52fb86a81ae1e566597a25f6%2Fv%2F4%2Fzip&templateName=Moderncv%20Banking&compiler=pdflatex')
})
- describe('createProjectFromV1Template', function() {
- describe('when all options passed', function() {
- beforeEach(function() {
+ describe('createProjectFromV1Template', function () {
+ describe('when all options passed', function () {
+ beforeEach(function () {
return this.TemplatesManager.createProjectFromV1Template(
this.brandVariationId,
this.compiler,
@@ -116,19 +116,19 @@ describe('TemplatesManager', function() {
)
})
- it('should fetch zip from v1 based on template id', function() {
+ it('should fetch zip from v1 based on template id', function () {
return this.request.should.have.been.calledWith(
`${this.v1Url}/api/v1/sharelatex/templates/${this.templateVersionId}`
)
})
- it('should save temporary file', function() {
+ it('should save temporary file', function () {
return this.fs.createWriteStream.should.have.been.calledWith(
this.dumpPath
)
})
- it('should create project', function() {
+ it('should create project', function () {
return this.ProjectUploadManager.createProjectFromZipArchiveWithName.should.have.been.calledWithMatch(
this.user_id,
this.templateName,
@@ -140,11 +140,11 @@ describe('TemplatesManager', function() {
)
})
- it('should unlink file', function() {
+ it('should unlink file', function () {
return this.fs.unlink.should.have.been.calledWith(this.dumpPath)
})
- it('should set project options when passed', function() {
+ it('should set project options when passed', function () {
this.ProjectOptionsHandler.setCompiler.should.have.been.calledWithMatch(
this.project_id,
this.compiler
@@ -163,7 +163,7 @@ describe('TemplatesManager', function() {
)
})
- it('should update project', function() {
+ it('should update project', function () {
return this.Project.updateOne.should.have.been.calledWithMatch(
{ _id: this.project_id },
{
@@ -173,13 +173,13 @@ describe('TemplatesManager', function() {
)
})
- it('should ensure that the dump folder exists', function() {
+ it('should ensure that the dump folder exists', function () {
return sinon.assert.called(this.FileWriter.ensureDumpFolderExists)
})
})
- describe('when some options not set', function() {
- beforeEach(function() {
+ describe('when some options not set', function () {
+ beforeEach(function () {
return this.TemplatesManager.createProjectFromV1Template(
null,
null,
@@ -193,7 +193,7 @@ describe('TemplatesManager', function() {
)
})
- it('should not set missing project options', function() {
+ it('should not set missing project options', function () {
this.ProjectOptionsHandler.setCompiler.called.should.equal(false)
this.ProjectRootDocManager.setRootDocFromName.called.should.equal(false)
this.ProjectOptionsHandler.setBrandVariationId.called.should.equal(
diff --git a/services/web/test/unit/src/ThirdPartyDataStore/TpdsControllerTests.js b/services/web/test/unit/src/ThirdPartyDataStore/TpdsControllerTests.js
index 0762e5d8bf..a623c71dc0 100644
--- a/services/web/test/unit/src/ThirdPartyDataStore/TpdsControllerTests.js
+++ b/services/web/test/unit/src/ThirdPartyDataStore/TpdsControllerTests.js
@@ -6,8 +6,8 @@ const modulePath = require('path').join(
'../../../../app/src/Features/ThirdPartyDataStore/TpdsController.js'
)
-describe('TpdsController', function() {
- beforeEach(function() {
+describe('TpdsController', function () {
+ beforeEach(function () {
this.TpdsUpdateHandler = {}
this.AuthenticationController = {
getLoggedInUserId: sinon.stub().returns('user-id')
@@ -36,8 +36,8 @@ describe('TpdsController', function() {
this.user_id = 'dsad29jlkjas'
})
- describe('getting an update', function() {
- it('should process the update with the update receiver', function(done) {
+ describe('getting an update', function () {
+ it('should process the update with the update receiver', function (done) {
const path = '/projectName/here.txt'
const req = {
pause() {},
@@ -67,7 +67,7 @@ describe('TpdsController', function() {
this.TpdsController.mergeUpdate(req, res)
})
- it('should return a 500 error when the update receiver fails', function() {
+ it('should return a 500 error when the update receiver fails', function () {
const path = '/projectName/here.txt'
const req = {
pause() {},
@@ -89,7 +89,7 @@ describe('TpdsController', function() {
res.sendStatus.calledWith(500).should.equal(true)
})
- it('should return a 400 error when the project is too big', function() {
+ it('should return a 400 error when the project is too big', function () {
const path = '/projectName/here.txt'
const req = {
pause() {},
@@ -114,7 +114,7 @@ describe('TpdsController', function() {
.should.equal(true)
})
- it('should return a 429 error when the update receiver fails due to too many requests error', function() {
+ it('should return a 429 error when the update receiver fails due to too many requests error', function () {
const path = '/projectName/here.txt'
const req = {
pause() {},
@@ -137,8 +137,8 @@ describe('TpdsController', function() {
})
})
- describe('getting a delete update', function() {
- it('should process the delete with the update receiver', function(done) {
+ describe('getting a delete update', function () {
+ it('should process the delete with the update receiver', function (done) {
const path = '/projectName/here.txt'
const req = {
params: { 0: path, user_id: this.user_id },
@@ -162,8 +162,8 @@ describe('TpdsController', function() {
})
})
- describe('parseParams', function() {
- it('should take the project name off the start and replace with slash', function() {
+ describe('parseParams', function () {
+ it('should take the project name off the start and replace with slash', function () {
const path = 'noSlashHere'
const req = { params: { 0: path, user_id: this.user_id } }
const result = this.TpdsController.parseParams(req)
@@ -172,7 +172,7 @@ describe('TpdsController', function() {
result.projectName.should.equal(path)
})
- it('should take the project name off the start and it with no slashes in', function() {
+ it('should take the project name off the start and it with no slashes in', function () {
const path = '/project/file.tex'
const req = { params: { 0: path, user_id: this.user_id } }
const result = this.TpdsController.parseParams(req)
@@ -181,7 +181,7 @@ describe('TpdsController', function() {
result.projectName.should.equal('project')
})
- it('should take the project name of and return a slash for the file path', function() {
+ it('should take the project name of and return a slash for the file path', function () {
const path = '/project_name'
const req = { params: { 0: path, user_id: this.user_id } }
const result = this.TpdsController.parseParams(req)
@@ -190,8 +190,8 @@ describe('TpdsController', function() {
})
})
- describe('updateProjectContents', function() {
- beforeEach(function() {
+ describe('updateProjectContents', function () {
+ beforeEach(function () {
this.UpdateMerger.mergeUpdate = sinon.stub().callsArg(5)
this.req = {
params: {
@@ -210,7 +210,7 @@ describe('TpdsController', function() {
this.TpdsController.updateProjectContents(this.req, this.res, this.next)
})
- it('should merge the update', function() {
+ it('should merge the update', function () {
this.UpdateMerger.mergeUpdate
.calledWith(
null,
@@ -222,13 +222,13 @@ describe('TpdsController', function() {
.should.equal(true)
})
- it('should return a success', function() {
+ it('should return a success', function () {
this.res.sendStatus.calledWith(200).should.equal(true)
})
})
- describe('deleteProjectContents', function() {
- beforeEach(function() {
+ describe('deleteProjectContents', function () {
+ beforeEach(function () {
this.UpdateMerger.deleteUpdate = sinon.stub().callsArg(4)
this.req = {
params: {
@@ -247,30 +247,30 @@ describe('TpdsController', function() {
this.TpdsController.deleteProjectContents(this.req, this.res, this.next)
})
- it('should delete the file', function() {
+ it('should delete the file', function () {
this.UpdateMerger.deleteUpdate
.calledWith(null, this.project_id, `/${this.path}`, this.source)
.should.equal(true)
})
- it('should return a success', function() {
+ it('should return a success', function () {
this.res.sendStatus.calledWith(200).should.equal(true)
})
})
- describe('getQueues', function() {
- beforeEach(function() {
+ describe('getQueues', function () {
+ beforeEach(function () {
this.req = {}
this.res = { json: sinon.stub() }
this.next = sinon.stub()
})
- describe('success', function() {
- beforeEach(async function() {
+ describe('success', function () {
+ beforeEach(async function () {
await this.TpdsController.getQueues(this.req, this.res, this.next)
})
- it('should use userId from session', function() {
+ it('should use userId from session', function () {
this.AuthenticationController.getLoggedInUserId.should.have.been
.calledOnce
this.TpdsQueueManager.promises.getQueues.should.have.been.calledWith(
@@ -278,14 +278,14 @@ describe('TpdsController', function() {
)
})
- it('should call json with response', function() {
+ it('should call json with response', function () {
this.res.json.should.have.been.calledWith('queues')
this.next.should.not.have.been.called
})
})
- describe('error', function() {
- beforeEach(async function() {
+ describe('error', function () {
+ beforeEach(async function () {
this.err = new Error()
this.TpdsQueueManager.promises.getQueues = sinon
.stub()
@@ -293,7 +293,7 @@ describe('TpdsController', function() {
await this.TpdsController.getQueues(this.req, this.res, this.next)
})
- it('should call next with error', function() {
+ it('should call next with error', function () {
this.res.json.should.not.have.been.called
this.next.should.have.been.calledWith(this.err)
})
diff --git a/services/web/test/unit/src/ThirdPartyDataStore/TpdsProjectFlusherTests.js b/services/web/test/unit/src/ThirdPartyDataStore/TpdsProjectFlusherTests.js
index c5218574f9..838b34fa18 100644
--- a/services/web/test/unit/src/ThirdPartyDataStore/TpdsProjectFlusherTests.js
+++ b/services/web/test/unit/src/ThirdPartyDataStore/TpdsProjectFlusherTests.js
@@ -7,8 +7,8 @@ const { Project } = require('../helpers/models/Project')
const MODULE_PATH =
'../../../../app/src/Features/ThirdPartyDataStore/TpdsProjectFlusher'
-describe('TpdsProjectFlusher', function() {
- beforeEach(function() {
+describe('TpdsProjectFlusher', function () {
+ beforeEach(function () {
this.project = { _id: ObjectId() }
this.docs = {
'/doc/one': { _id: 'mock-doc-1', lines: ['one'], rev: 5 },
@@ -30,10 +30,7 @@ describe('TpdsProjectFlusher', function() {
}
this.ProjectEntityHandler = {
promises: {
- getAllDocs: sinon
- .stub()
- .withArgs(this.project._id)
- .resolves(this.docs),
+ getAllDocs: sinon.stub().withArgs(this.project._id).resolves(this.docs),
getAllFiles: sinon
.stub()
.withArgs(this.project._id)
@@ -60,25 +57,25 @@ describe('TpdsProjectFlusher', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
this.ProjectMock.restore()
})
- describe('flushProjectToTpds', function() {
- describe('usually', function() {
- beforeEach(async function() {
+ describe('flushProjectToTpds', function () {
+ describe('usually', function () {
+ beforeEach(async function () {
await this.TpdsProjectFlusher.promises.flushProjectToTpds(
this.project._id
)
})
- it('should flush the project from the doc updater', function() {
+ it('should flush the project from the doc updater', function () {
expect(
this.DocumentUpdaterHandler.promises.flushProjectToMongo
).to.have.been.calledWith(this.project._id)
})
- it('should flush each doc to the TPDS', function() {
+ it('should flush each doc to the TPDS', function () {
for (const [path, doc] of Object.entries(this.docs)) {
expect(this.TpdsUpdateSender.promises.addDoc).to.have.been.calledWith(
{
@@ -92,7 +89,7 @@ describe('TpdsProjectFlusher', function() {
}
})
- it('should flush each file to the TPDS', function() {
+ it('should flush each file to the TPDS', function () {
for (const [path, file] of Object.entries(this.files)) {
expect(
this.TpdsUpdateSender.promises.addFile
@@ -107,8 +104,8 @@ describe('TpdsProjectFlusher', function() {
})
})
- describe('when a TPDS flush is pending', function() {
- beforeEach(async function() {
+ describe('when a TPDS flush is pending', function () {
+ beforeEach(async function () {
this.project.deferredTpdsFlushCounter = 2
this.ProjectMock.expects('updateOne')
.withArgs(
@@ -125,14 +122,14 @@ describe('TpdsProjectFlusher', function() {
)
})
- it('resets the deferred flush counter', function() {
+ it('resets the deferred flush counter', function () {
this.ProjectMock.verify()
})
})
})
- describe('deferProjectFlushToTpds', function() {
- beforeEach(async function() {
+ describe('deferProjectFlushToTpds', function () {
+ beforeEach(async function () {
this.ProjectMock.expects('updateOne')
.withArgs(
{
@@ -147,32 +144,32 @@ describe('TpdsProjectFlusher', function() {
)
})
- it('increments the deferred flush counter', function() {
+ it('increments the deferred flush counter', function () {
this.ProjectMock.verify()
})
})
- describe('flushProjectToTpdsIfNeeded', function() {
+ describe('flushProjectToTpdsIfNeeded', function () {
let cases = [0, undefined]
cases.forEach(counterValue => {
- describe(`when the deferred flush counter is ${counterValue}`, function() {
- beforeEach(async function() {
+ describe(`when the deferred flush counter is ${counterValue}`, function () {
+ beforeEach(async function () {
this.project.deferredTpdsFlushCounter = counterValue
await this.TpdsProjectFlusher.promises.flushProjectToTpdsIfNeeded(
this.project._id
)
})
- it("doesn't flush the project from the doc updater", function() {
+ it("doesn't flush the project from the doc updater", function () {
expect(this.DocumentUpdaterHandler.promises.flushProjectToMongo).not
.to.have.been.called
})
- it("doesn't flush any doc", function() {
+ it("doesn't flush any doc", function () {
expect(this.TpdsUpdateSender.promises.addDoc).not.to.have.been.called
})
- it("doesn't flush any file", function() {
+ it("doesn't flush any file", function () {
expect(this.TpdsUpdateSender.promises.addFile).not.to.have.been.called
})
})
@@ -180,8 +177,8 @@ describe('TpdsProjectFlusher', function() {
cases = [1, 2]
cases.forEach(counterValue => {
- describe(`when the deferred flush counter is ${counterValue}`, function() {
- beforeEach(async function() {
+ describe(`when the deferred flush counter is ${counterValue}`, function () {
+ beforeEach(async function () {
this.project.deferredTpdsFlushCounter = counterValue
this.ProjectMock.expects('updateOne')
.withArgs(
@@ -198,13 +195,13 @@ describe('TpdsProjectFlusher', function() {
)
})
- it('flushes the project from the doc updater', function() {
+ it('flushes the project from the doc updater', function () {
expect(
this.DocumentUpdaterHandler.promises.flushProjectToMongo
).to.have.been.calledWith(this.project._id)
})
- it('flushes each doc to the TPDS', function() {
+ it('flushes each doc to the TPDS', function () {
for (const [path, doc] of Object.entries(this.docs)) {
expect(
this.TpdsUpdateSender.promises.addDoc
@@ -218,7 +215,7 @@ describe('TpdsProjectFlusher', function() {
}
})
- it('flushes each file to the TPDS', function() {
+ it('flushes each file to the TPDS', function () {
for (const [path, file] of Object.entries(this.files)) {
expect(
this.TpdsUpdateSender.promises.addFile
@@ -232,7 +229,7 @@ describe('TpdsProjectFlusher', function() {
}
})
- it('resets the deferred flush counter', function() {
+ it('resets the deferred flush counter', function () {
this.ProjectMock.verify()
})
})
diff --git a/services/web/test/unit/src/ThirdPartyDataStore/TpdsUpdateHandlerTests.js b/services/web/test/unit/src/ThirdPartyDataStore/TpdsUpdateHandlerTests.js
index a14d41dae8..56c8c9a269 100644
--- a/services/web/test/unit/src/ThirdPartyDataStore/TpdsUpdateHandlerTests.js
+++ b/services/web/test/unit/src/ThirdPartyDataStore/TpdsUpdateHandlerTests.js
@@ -7,16 +7,16 @@ const Errors = require('../../../../app/src/Features/Errors/Errors')
const MODULE_PATH =
'../../../../app/src/Features/ThirdPartyDataStore/TpdsUpdateHandler.js'
-describe('TpdsUpdateHandler', function() {
- beforeEach(function() {
+describe('TpdsUpdateHandler', function () {
+ beforeEach(function () {
this.clock = sinon.useFakeTimers()
})
- afterEach(function() {
+ afterEach(function () {
this.clock.restore()
})
- beforeEach(function() {
+ beforeEach(function () {
this.projectName = 'My recipes'
this.projects = {
active1: { _id: new ObjectId(), name: this.projectName },
@@ -92,22 +92,22 @@ describe('TpdsUpdateHandler', function() {
})
})
- describe('getting an update', function() {
- describe('with no matching project', function() {
+ describe('getting an update', function () {
+ describe('with no matching project', function () {
setupMatchingProjects([])
receiveUpdate()
expectProjectCreated()
expectUpdateProcessed()
})
- describe('with one matching active project', function() {
+ describe('with one matching active project', function () {
setupMatchingProjects(['active1'])
receiveUpdate()
expectProjectNotCreated()
expectUpdateProcessed()
})
- describe('with one matching archived project', function() {
+ describe('with one matching archived project', function () {
setupMatchingProjects(['archived1'])
receiveUpdate()
expectProjectNotCreated()
@@ -115,7 +115,7 @@ describe('TpdsUpdateHandler', function() {
expectDropboxNotUnlinked()
})
- describe('with two matching active projects', function() {
+ describe('with two matching active projects', function () {
setupMatchingProjects(['active1', 'active2'])
receiveUpdate()
expectProjectNotCreated()
@@ -123,7 +123,7 @@ describe('TpdsUpdateHandler', function() {
expectDropboxUnlinked()
})
- describe('with two matching archived projects', function() {
+ describe('with two matching archived projects', function () {
setupMatchingProjects(['archived1', 'archived2'])
receiveUpdate()
expectProjectNotCreated()
@@ -131,7 +131,7 @@ describe('TpdsUpdateHandler', function() {
expectDropboxNotUnlinked()
})
- describe('with one matching active and one matching archived project', function() {
+ describe('with one matching active and one matching archived project', function () {
setupMatchingProjects(['active1', 'archived1'])
receiveUpdate()
expectProjectNotCreated()
@@ -139,9 +139,9 @@ describe('TpdsUpdateHandler', function() {
expectDropboxUnlinked()
})
- describe('update to a file that should be ignored', function(done) {
+ describe('update to a file that should be ignored', function (done) {
setupMatchingProjects(['active1'])
- beforeEach(function() {
+ beforeEach(function () {
this.FileTypeManager.shouldIgnore.yields(null, true)
})
receiveUpdate()
@@ -150,10 +150,10 @@ describe('TpdsUpdateHandler', function() {
expectDropboxNotUnlinked()
})
- describe('update to a project on cooldown', function(done) {
+ describe('update to a project on cooldown', function (done) {
setupMatchingProjects(['active1'])
setupProjectOnCooldown()
- beforeEach(function(done) {
+ beforeEach(function (done) {
this.TpdsUpdateHandler.newUpdate(
this.userId,
this.projectName,
@@ -170,29 +170,29 @@ describe('TpdsUpdateHandler', function() {
})
})
- describe('getting a file delete', function() {
- describe('with no matching project', function() {
+ describe('getting a file delete', function () {
+ describe('with no matching project', function () {
setupMatchingProjects([])
receiveFileDelete()
expectDeleteNotProcessed()
expectProjectNotDeleted()
})
- describe('with one matching active project', function() {
+ describe('with one matching active project', function () {
setupMatchingProjects(['active1'])
receiveFileDelete()
expectDeleteProcessed()
expectProjectNotDeleted()
})
- describe('with one matching archived project', function() {
+ describe('with one matching archived project', function () {
setupMatchingProjects(['archived1'])
receiveFileDelete()
expectDeleteNotProcessed()
expectProjectNotDeleted()
})
- describe('with two matching active projects', function() {
+ describe('with two matching active projects', function () {
setupMatchingProjects(['active1', 'active2'])
receiveFileDelete()
expectDeleteNotProcessed()
@@ -200,7 +200,7 @@ describe('TpdsUpdateHandler', function() {
expectDropboxUnlinked()
})
- describe('with two matching archived projects', function() {
+ describe('with two matching archived projects', function () {
setupMatchingProjects(['archived1', 'archived2'])
receiveFileDelete()
expectDeleteNotProcessed()
@@ -208,7 +208,7 @@ describe('TpdsUpdateHandler', function() {
expectDropboxNotUnlinked()
})
- describe('with one matching active and one matching archived project', function() {
+ describe('with one matching active and one matching archived project', function () {
setupMatchingProjects(['active1', 'archived1'])
receiveFileDelete()
expectDeleteNotProcessed()
@@ -217,29 +217,29 @@ describe('TpdsUpdateHandler', function() {
})
})
- describe('getting a project delete', function() {
- describe('with no matching project', function() {
+ describe('getting a project delete', function () {
+ describe('with no matching project', function () {
setupMatchingProjects([])
receiveProjectDelete()
expectDeleteNotProcessed()
expectProjectNotDeleted()
})
- describe('with one matching active project', function() {
+ describe('with one matching active project', function () {
setupMatchingProjects(['active1'])
receiveProjectDelete()
expectDeleteNotProcessed()
expectProjectDeleted()
})
- describe('with one matching archived project', function() {
+ describe('with one matching archived project', function () {
setupMatchingProjects(['archived1'])
receiveProjectDelete()
expectDeleteNotProcessed()
expectProjectNotDeleted()
})
- describe('with two matching active projects', function() {
+ describe('with two matching active projects', function () {
setupMatchingProjects(['active1', 'active2'])
receiveProjectDelete()
expectDeleteNotProcessed()
@@ -247,7 +247,7 @@ describe('TpdsUpdateHandler', function() {
expectDropboxUnlinked()
})
- describe('with two matching archived projects', function() {
+ describe('with two matching archived projects', function () {
setupMatchingProjects(['archived1', 'archived2'])
receiveProjectDelete()
expectDeleteNotProcessed()
@@ -255,7 +255,7 @@ describe('TpdsUpdateHandler', function() {
expectDropboxNotUnlinked()
})
- describe('with one matching active and one matching archived project', function() {
+ describe('with one matching active and one matching archived project', function () {
setupMatchingProjects(['active1', 'archived1'])
receiveProjectDelete()
expectDeleteNotProcessed()
@@ -268,7 +268,7 @@ describe('TpdsUpdateHandler', function() {
/* Setup helpers */
function setupMatchingProjects(projectKeys) {
- beforeEach(function() {
+ beforeEach(function () {
const projects = projectKeys.map(key => this.projects[key])
this.ProjectGetter.findUsersProjectsByName
.withArgs(this.userId, this.projectName)
@@ -277,7 +277,7 @@ function setupMatchingProjects(projectKeys) {
}
function setupProjectOnCooldown() {
- beforeEach(function() {
+ beforeEach(function () {
this.CooldownManager.isProjectOnCooldown
.withArgs(this.projects.active1._id)
.yields(null, true)
@@ -287,7 +287,7 @@ function setupProjectOnCooldown() {
/* Test helpers */
function receiveUpdate() {
- beforeEach(function(done) {
+ beforeEach(function (done) {
this.TpdsUpdateHandler.newUpdate(
this.userId,
this.projectName,
@@ -300,7 +300,7 @@ function receiveUpdate() {
}
function receiveFileDelete() {
- beforeEach(function(done) {
+ beforeEach(function (done) {
this.TpdsUpdateHandler.deleteUpdate(
this.userId,
this.projectName,
@@ -312,7 +312,7 @@ function receiveFileDelete() {
}
function receiveProjectDelete() {
- beforeEach(function(done) {
+ beforeEach(function (done) {
this.TpdsUpdateHandler.deleteUpdate(
this.userId,
this.projectName,
@@ -326,13 +326,13 @@ function receiveProjectDelete() {
/* Expectations */
function expectProjectCreated() {
- it('creates a project', function() {
+ it('creates a project', function () {
expect(
this.ProjectCreationHandler.createBlankProject
).to.have.been.calledWith(this.userId, this.projectName)
})
- it('sets the root doc', function() {
+ it('sets the root doc', function () {
// Fire pending timers
this.clock.runAll()
expect(this.RootDocManager.setRootDocAutomatically).to.have.been.calledWith(
@@ -342,12 +342,12 @@ function expectProjectCreated() {
}
function expectProjectNotCreated() {
- it('does not create a project', function() {
+ it('does not create a project', function () {
expect(this.ProjectCreationHandler.createBlankProject).not.to.have.been
.called
})
- it('does not set the root doc', function() {
+ it('does not set the root doc', function () {
// Fire pending timers
this.clock.runAll()
expect(this.RootDocManager.setRootDocAutomatically).not.to.have.been.called
@@ -355,7 +355,7 @@ function expectProjectNotCreated() {
}
function expectUpdateProcessed() {
- it('processes the update', function() {
+ it('processes the update', function () {
expect(this.UpdateMerger.mergeUpdate).to.have.been.calledWith(
this.userId,
this.projects.active1._id,
@@ -367,20 +367,20 @@ function expectUpdateProcessed() {
}
function expectUpdateNotProcessed() {
- it('does not process the update', function() {
+ it('does not process the update', function () {
expect(this.UpdateMerger.mergeUpdate).not.to.have.been.called
})
}
function expectDropboxUnlinked() {
- it('unlinks Dropbox', function() {
+ it('unlinks Dropbox', function () {
expect(this.Modules.hooks.fire).to.have.been.calledWith(
'removeDropbox',
this.userId
)
})
- it('creates a notification that dropbox was unlinked', function() {
+ it('creates a notification that dropbox was unlinked', function () {
expect(
this.NotificationsBuilder.dropboxDuplicateProjectNames
).to.have.been.calledWith(this.userId)
@@ -389,18 +389,18 @@ function expectDropboxUnlinked() {
}
function expectDropboxNotUnlinked() {
- it('does not unlink Dropbox', function() {
+ it('does not unlink Dropbox', function () {
expect(this.Modules.hooks.fire).not.to.have.been.called
})
- it('does not create a notification that dropbox was unlinked', function() {
+ it('does not create a notification that dropbox was unlinked', function () {
expect(this.NotificationsBuilder.dropboxDuplicateProjectNames).not.to.have
.been.called
})
}
function expectDeleteProcessed() {
- it('processes the delete', function() {
+ it('processes the delete', function () {
expect(this.UpdateMerger.deleteUpdate).to.have.been.calledWith(
this.userId,
this.projects.active1._id,
@@ -411,13 +411,13 @@ function expectDeleteProcessed() {
}
function expectDeleteNotProcessed() {
- it('does not process the delete', function() {
+ it('does not process the delete', function () {
expect(this.UpdateMerger.deleteUpdate).not.to.have.been.called
})
}
function expectProjectDeleted() {
- it('deletes the project', function() {
+ it('deletes the project', function () {
expect(
this.ProjectDeleter.markAsDeletedByExternalSource
).to.have.been.calledWith(this.projects.active1._id)
@@ -425,7 +425,7 @@ function expectProjectDeleted() {
}
function expectProjectNotDeleted() {
- it('does not delete the project', function() {
+ it('does not delete the project', function () {
expect(this.ProjectDeleter.markAsDeletedByExternalSource).not.to.have.been
.called
})
diff --git a/services/web/test/unit/src/ThirdPartyDataStore/TpdsUpdateSenderTests.js b/services/web/test/unit/src/ThirdPartyDataStore/TpdsUpdateSenderTests.js
index 7e483ed789..b46471628a 100644
--- a/services/web/test/unit/src/ThirdPartyDataStore/TpdsUpdateSenderTests.js
+++ b/services/web/test/unit/src/ThirdPartyDataStore/TpdsUpdateSenderTests.js
@@ -21,12 +21,12 @@ const siteUrl = 'http://www.localhost:3000'
const httpAuthSiteUrl = `http://${httpUsername}:${httpPass}@www.localhost:3000`
const filestoreUrl = 'filestore.sharelatex.com'
-describe('TpdsUpdateSender', function() {
- beforeEach(function() {
+describe('TpdsUpdateSender', function () {
+ beforeEach(function () {
this.fakeUser = {
_id: '12390i'
}
- this.requestQueuer = function(queue, meth, opts, callback) {}
+ this.requestQueuer = function (queue, meth, opts, callback) {}
const memberIds = [userId, collaberatorRef, readOnlyRef]
this.CollaboratorsGetter = {
promises: {
@@ -70,13 +70,13 @@ describe('TpdsUpdateSender', function() {
})
})
- describe('enqueue', function() {
- it('should not call request if there is no tpdsworker url', async function() {
+ describe('enqueue', function () {
+ it('should not call request if there is no tpdsworker url', async function () {
await this.updateSender.promises.enqueue(null, null, null)
this.request.should.not.have.been.called
})
- it('should post the message to the tpdsworker', async function() {
+ it('should post the message to the tpdsworker', async function () {
this.settings.apis.tpdsworker = { url: 'www.tpdsworker.env' }
const group0 = 'myproject'
const method0 = 'somemethod0'
@@ -92,12 +92,12 @@ describe('TpdsUpdateSender', function() {
})
})
- describe('sending updates', function() {
- beforeEach(function() {
+ describe('sending updates', function () {
+ beforeEach(function () {
this.settings.apis.tpdsworker = { url: 'www.tpdsworker.env' }
})
- it('queues a post the file with user and file id', async function() {
+ it('queues a post the file with user and file id', async function () {
const fileId = '4545345'
const path = '/some/path/here.jpg'
@@ -149,7 +149,7 @@ describe('TpdsUpdateSender', function() {
)
})
- it('post doc with stream origin of docstore', async function() {
+ it('post doc with stream origin of docstore', async function () {
const docId = '4545345'
const path = '/some/path/here.tex'
const lines = ['line1', 'line2', 'line3']
@@ -201,7 +201,7 @@ describe('TpdsUpdateSender', function() {
)
})
- it('deleting entity', async function() {
+ it('deleting entity', async function () {
const path = '/path/here/t.tex'
await this.updateSender.promises.deleteEntity({
@@ -246,7 +246,7 @@ describe('TpdsUpdateSender', function() {
)
})
- it('moving entity', async function() {
+ it('moving entity', async function () {
const startPath = 'staring/here/file.tex'
const endPath = 'ending/here/file.tex'
@@ -294,7 +294,7 @@ describe('TpdsUpdateSender', function() {
)
})
- it('should be able to rename a project using the move entity func', async function() {
+ it('should be able to rename a project using the move entity func', async function () {
const oldProjectName = '/oldProjectName/'
const newProjectName = '/newProjectName/'
@@ -341,7 +341,7 @@ describe('TpdsUpdateSender', function() {
)
})
- it('pollDropboxForUser', async function() {
+ it('pollDropboxForUser', async function () {
await this.updateSender.promises.pollDropboxForUser(userId)
const {
diff --git a/services/web/test/unit/src/ThirdPartyDataStore/UpdateMergerTests.js b/services/web/test/unit/src/ThirdPartyDataStore/UpdateMergerTests.js
index 97ba619d7a..b9f18be50b 100644
--- a/services/web/test/unit/src/ThirdPartyDataStore/UpdateMergerTests.js
+++ b/services/web/test/unit/src/ThirdPartyDataStore/UpdateMergerTests.js
@@ -6,8 +6,8 @@ const modulePath = require('path').join(
)
const BufferedStream = require('bufferedstream')
-describe('UpdateMerger :', function() {
- beforeEach(function() {
+describe('UpdateMerger :', function () {
+ beforeEach(function () {
this.updateMerger = SandboxedModule.require(modulePath, {
requires: {
fs: (this.fs = { unlink: sinon.stub().callsArgWith(1) }),
@@ -42,9 +42,9 @@ describe('UpdateMerger :', function() {
this.callback = sinon.stub()
})
- describe('mergeUpdate', function() {
- describe('doc updates for a new doc', function() {
- beforeEach(function() {
+ describe('mergeUpdate', function () {
+ describe('doc updates for a new doc', function () {
+ beforeEach(function () {
this.FileTypeManager.getType = sinon
.stub()
.yields(null, { binary: false, encoding: 'utf-8' })
@@ -59,11 +59,11 @@ describe('UpdateMerger :', function() {
)
})
- it('should look at the file contents', function() {
+ it('should look at the file contents', function () {
this.FileTypeManager.getType.called.should.equal(true)
})
- it('should process update as doc', function() {
+ it('should process update as doc', function () {
this.updateMerger.p.processDoc
.calledWith(
this.project_id,
@@ -75,13 +75,13 @@ describe('UpdateMerger :', function() {
.should.equal(true)
})
- it('removes the temp file from disk', function() {
+ it('removes the temp file from disk', function () {
this.fs.unlink.calledWith(this.fsPath).should.equal(true)
})
})
- describe('file updates for a new file ', function() {
- beforeEach(function() {
+ describe('file updates for a new file ', function () {
+ beforeEach(function () {
this.FileTypeManager.getType = sinon
.stub()
.yields(null, { binary: true })
@@ -96,11 +96,11 @@ describe('UpdateMerger :', function() {
)
})
- it('should look at the file contents', function() {
+ it('should look at the file contents', function () {
this.FileTypeManager.getType.called.should.equal(true)
})
- it('should process update as file', function() {
+ it('should process update as file', function () {
this.updateMerger.p.processFile
.calledWith(
this.project_id,
@@ -112,13 +112,13 @@ describe('UpdateMerger :', function() {
.should.equal(true)
})
- it('removes the temp file from disk', function() {
+ it('removes the temp file from disk', function () {
this.fs.unlink.calledWith(this.fsPath).should.equal(true)
})
})
- describe('doc updates for an existing doc', function() {
- beforeEach(function() {
+ describe('doc updates for an existing doc', function () {
+ beforeEach(function () {
this.FileTypeManager.getType = sinon
.stub()
.yields(null, { binary: false, encoding: 'utf-8' })
@@ -133,11 +133,11 @@ describe('UpdateMerger :', function() {
)
})
- it('should look at the file contents', function() {
+ it('should look at the file contents', function () {
this.FileTypeManager.getType.called.should.equal(true)
})
- it('should process update as doc', function() {
+ it('should process update as doc', function () {
this.updateMerger.p.processDoc
.calledWith(
this.project_id,
@@ -149,13 +149,13 @@ describe('UpdateMerger :', function() {
.should.equal(true)
})
- it('removes the temp file from disk', function() {
+ it('removes the temp file from disk', function () {
this.fs.unlink.calledWith(this.fsPath).should.equal(true)
})
})
- describe('file updates for an existing file', function() {
- beforeEach(function() {
+ describe('file updates for an existing file', function () {
+ beforeEach(function () {
this.FileTypeManager.getType = sinon
.stub()
.yields(null, { binary: true })
@@ -170,11 +170,11 @@ describe('UpdateMerger :', function() {
)
})
- it('should look at the file contents', function() {
+ it('should look at the file contents', function () {
this.FileTypeManager.getType.called.should.equal(true)
})
- it('should process update as file', function() {
+ it('should process update as file', function () {
this.updateMerger.p.processFile
.calledWith(
this.project_id,
@@ -186,14 +186,14 @@ describe('UpdateMerger :', function() {
.should.equal(true)
})
- it('removes the temp file from disk', function() {
+ it('removes the temp file from disk', function () {
this.fs.unlink.calledWith(this.fsPath).should.equal(true)
})
})
})
- describe('file updates for an existing doc', function() {
- beforeEach(function() {
+ describe('file updates for an existing doc', function () {
+ beforeEach(function () {
this.FileTypeManager.getType = sinon.stub().yields(null, { binary: true })
this.updateMerger.deleteUpdate = sinon.stub().yields()
this.updateMerger.p.processFile = sinon.stub().yields()
@@ -207,11 +207,11 @@ describe('UpdateMerger :', function() {
)
})
- it('should look at the file contents', function() {
+ it('should look at the file contents', function () {
this.FileTypeManager.getType.called.should.equal(true)
})
- it('should delete the existing doc', function() {
+ it('should delete the existing doc', function () {
this.updateMerger.deleteUpdate
.calledWith(
this.user_id,
@@ -222,7 +222,7 @@ describe('UpdateMerger :', function() {
.should.equal(true)
})
- it('should process update as file', function() {
+ it('should process update as file', function () {
this.updateMerger.p.processFile
.calledWith(
this.project_id,
@@ -234,13 +234,13 @@ describe('UpdateMerger :', function() {
.should.equal(true)
})
- it('removes the temp file from disk', function() {
+ it('removes the temp file from disk', function () {
this.fs.unlink.calledWith(this.fsPath).should.equal(true)
})
})
- describe('doc updates for an existing file', function() {
- beforeEach(function() {
+ describe('doc updates for an existing file', function () {
+ beforeEach(function () {
this.FileTypeManager.getType = sinon.stub().yields(null, { binary: true })
this.updateMerger.deleteUpdate = sinon.stub().yields()
this.updateMerger.p.processFile = sinon.stub().yields()
@@ -254,15 +254,15 @@ describe('UpdateMerger :', function() {
)
})
- it('should look at the file contents', function() {
+ it('should look at the file contents', function () {
this.FileTypeManager.getType.called.should.equal(true)
})
- it('should not delete the existing file', function() {
+ it('should not delete the existing file', function () {
this.updateMerger.deleteUpdate.called.should.equal(false)
})
- it('should process update as file', function() {
+ it('should process update as file', function () {
this.updateMerger.p.processFile
.calledWith(
this.project_id,
@@ -274,13 +274,13 @@ describe('UpdateMerger :', function() {
.should.equal(true)
})
- it('removes the temp file from disk', function() {
+ it('removes the temp file from disk', function () {
this.fs.unlink.calledWith(this.fsPath).should.equal(true)
})
})
- describe('deleteUpdate', function() {
- beforeEach(function() {
+ describe('deleteUpdate', function () {
+ beforeEach(function () {
this.EditorController.deleteEntityWithPath = sinon.stub().yields()
this.updateMerger.deleteUpdate(
this.user_id,
@@ -291,16 +291,16 @@ describe('UpdateMerger :', function() {
)
})
- it('should delete the entity in the editor controller', function() {
+ it('should delete the entity in the editor controller', function () {
this.EditorController.deleteEntityWithPath
.calledWith(this.project_id, this.docPath, this.source, this.user_id)
.should.equal(true)
})
})
- describe('private methods', function() {
- describe('processDoc', function() {
- beforeEach(function() {
+ describe('private methods', function () {
+ describe('processDoc', function () {
+ beforeEach(function () {
this.docLines =
'\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\n\\title{42}\n\\author{Jane Doe}\n\\date{June 2011}'
this.updateMerger.p.readFileIntoTextArray = sinon
@@ -318,13 +318,13 @@ describe('UpdateMerger :', function() {
)
})
- it('reads the temp file from disk', function() {
+ it('reads the temp file from disk', function () {
this.updateMerger.p.readFileIntoTextArray
.calledWith(this.fsPath)
.should.equal(true)
})
- it('should upsert the doc in the editor controller', function() {
+ it('should upsert the doc in the editor controller', function () {
this.EditorController.upsertDocWithPath
.calledWith(
this.project_id,
@@ -337,8 +337,8 @@ describe('UpdateMerger :', function() {
})
})
- describe('processFile', function() {
- beforeEach(function() {
+ describe('processFile', function () {
+ beforeEach(function () {
this.EditorController.upsertFileWithPath = sinon.stub().yields()
this.updateMerger.p.processFile(
this.project_id,
@@ -350,7 +350,7 @@ describe('UpdateMerger :', function() {
)
})
- it('should upsert the file in the editor controller', function() {
+ it('should upsert the file in the editor controller', function () {
this.EditorController.upsertFileWithPath
.calledWith(
this.project_id,
diff --git a/services/web/test/unit/src/TokenAccess/TokenAccessHandlerTests.js b/services/web/test/unit/src/TokenAccess/TokenAccessHandlerTests.js
index 8717bd8a70..aa3cfae4d5 100644
--- a/services/web/test/unit/src/TokenAccess/TokenAccessHandlerTests.js
+++ b/services/web/test/unit/src/TokenAccess/TokenAccessHandlerTests.js
@@ -22,8 +22,8 @@ const modulePath = path.join(
const { expect } = require('chai')
const { ObjectId } = require('mongodb')
-describe('TokenAccessHandler', function() {
- beforeEach(function() {
+describe('TokenAccessHandler', function () {
+ beforeEach(function () {
this.token = 'abcdefabcdef'
this.projectId = ObjectId()
this.project = {
@@ -50,8 +50,8 @@ describe('TokenAccessHandler', function() {
}))
})
- describe('getTokenType', function() {
- it('should determine tokens correctly', function() {
+ describe('getTokenType', function () {
+ it('should determine tokens correctly', function () {
const specs = {
abcdefabcdef: 'readOnly',
aaaaaabbbbbb: 'readOnly',
@@ -68,13 +68,13 @@ describe('TokenAccessHandler', function() {
})
})
- describe('getProjectByReadOnlyToken', function() {
- beforeEach(function() {
+ describe('getProjectByReadOnlyToken', function () {
+ beforeEach(function () {
this.token = 'abcdefabcdef'
this.Project.findOne = sinon.stub().callsArgWith(2, null, this.project)
})
- it('should get the project', function(done) {
+ it('should get the project', function (done) {
this.TokenAccessHandler.getProjectByReadOnlyToken(
this.token,
(err, project) => {
@@ -87,8 +87,8 @@ describe('TokenAccessHandler', function() {
})
})
- describe('getProjectByReadAndWriteToken', function() {
- beforeEach(function() {
+ describe('getProjectByReadAndWriteToken', function () {
+ beforeEach(function () {
sinon.spy(this.Crypto, 'timingSafeEqual')
this.token = '1234abcdefabcdef'
this.project.tokens = {
@@ -98,11 +98,11 @@ describe('TokenAccessHandler', function() {
this.Project.findOne = sinon.stub().callsArgWith(2, null, this.project)
})
- afterEach(function() {
+ afterEach(function () {
this.Crypto.timingSafeEqual.restore()
})
- it('should get the project and do timing-safe comparison', function(done) {
+ it('should get the project and do timing-safe comparison', function (done) {
this.TokenAccessHandler.getProjectByReadAndWriteToken(
this.token,
(err, project) => {
@@ -119,12 +119,12 @@ describe('TokenAccessHandler', function() {
})
})
- describe('addReadOnlyUserToProject', function() {
- beforeEach(function() {
+ describe('addReadOnlyUserToProject', function () {
+ beforeEach(function () {
return (this.Project.updateOne = sinon.stub().callsArgWith(2, null))
})
- it('should call Project.updateOne', function(done) {
+ it('should call Project.updateOne', function (done) {
return this.TokenAccessHandler.addReadOnlyUserToProject(
this.userId,
this.projectId,
@@ -149,7 +149,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.TokenAccessHandler.addReadOnlyUserToProject(
this.userId,
this.projectId,
@@ -160,14 +160,14 @@ describe('TokenAccessHandler', function() {
)
})
- describe('when Project.updateOne produces an error', function() {
- beforeEach(function() {
+ describe('when Project.updateOne produces an error', function () {
+ beforeEach(function () {
return (this.Project.updateOne = sinon
.stub()
.callsArgWith(2, new Error('woops')))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.TokenAccessHandler.addReadOnlyUserToProject(
this.userId,
this.projectId,
@@ -180,12 +180,12 @@ describe('TokenAccessHandler', function() {
})
})
- describe('addReadAndWriteUserToProject', function() {
- beforeEach(function() {
+ describe('addReadAndWriteUserToProject', function () {
+ beforeEach(function () {
return (this.Project.updateOne = sinon.stub().callsArgWith(2, null))
})
- it('should call Project.updateOne', function(done) {
+ it('should call Project.updateOne', function (done) {
return this.TokenAccessHandler.addReadAndWriteUserToProject(
this.userId,
this.projectId,
@@ -210,7 +210,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.TokenAccessHandler.addReadAndWriteUserToProject(
this.userId,
this.projectId,
@@ -221,14 +221,14 @@ describe('TokenAccessHandler', function() {
)
})
- describe('when Project.updateOne produces an error', function() {
- beforeEach(function() {
+ describe('when Project.updateOne produces an error', function () {
+ beforeEach(function () {
return (this.Project.updateOne = sinon
.stub()
.callsArgWith(2, new Error('woops')))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.TokenAccessHandler.addReadAndWriteUserToProject(
this.userId,
this.projectId,
@@ -241,12 +241,12 @@ describe('TokenAccessHandler', function() {
})
})
- describe('grantSessionTokenAccess', function() {
- beforeEach(function() {
+ describe('grantSessionTokenAccess', function () {
+ beforeEach(function () {
return (this.req = { session: {}, headers: {} })
})
- it('should add the token to the session', function(done) {
+ it('should add the token to the session', function (done) {
this.TokenAccessHandler.grantSessionTokenAccess(
this.req,
this.projectId,
@@ -259,16 +259,16 @@ describe('TokenAccessHandler', function() {
})
})
- describe('validateTokenForAnonymousAccess', function() {
- describe('when a read-only project is found', function() {
- beforeEach(function() {
+ describe('validateTokenForAnonymousAccess', function () {
+ describe('when a read-only project is found', function () {
+ beforeEach(function () {
this.TokenAccessHandler.getTokenType = sinon.stub().returns('readOnly')
this.TokenAccessHandler.getProjectByToken = sinon
.stub()
.callsArgWith(2, null, this.project)
})
- it('should try to find projects with both kinds of token', function(done) {
+ it('should try to find projects with both kinds of token', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -281,7 +281,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should allow read-only access', function(done) {
+ it('should allow read-only access', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -295,8 +295,8 @@ describe('TokenAccessHandler', function() {
})
})
- describe('when a read-and-write project is found', function() {
- beforeEach(function() {
+ describe('when a read-and-write project is found', function () {
+ beforeEach(function () {
this.TokenAccessHandler.getTokenType = sinon
.stub()
.returns('readAndWrite')
@@ -305,12 +305,12 @@ describe('TokenAccessHandler', function() {
.callsArgWith(2, null, this.project)
})
- describe('when Anonymous token access is not enabled', function(done) {
- beforeEach(function() {
+ describe('when Anonymous token access is not enabled', function (done) {
+ beforeEach(function () {
this.TokenAccessHandler.ANONYMOUS_READ_AND_WRITE_ENABLED = false
})
- it('should try to find projects with both kinds of token', function(done) {
+ it('should try to find projects with both kinds of token', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -323,7 +323,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should not allow read-and-write access', function(done) {
+ it('should not allow read-and-write access', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -337,12 +337,12 @@ describe('TokenAccessHandler', function() {
})
})
- describe('when anonymous token access is enabled', function(done) {
- beforeEach(function() {
+ describe('when anonymous token access is enabled', function (done) {
+ beforeEach(function () {
this.TokenAccessHandler.ANONYMOUS_READ_AND_WRITE_ENABLED = true
})
- it('should try to find projects with both kinds of token', function(done) {
+ it('should try to find projects with both kinds of token', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -355,7 +355,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should allow read-and-write access', function(done) {
+ it('should allow read-and-write access', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -370,14 +370,14 @@ describe('TokenAccessHandler', function() {
})
})
- describe('when no project is found', function() {
- beforeEach(function() {
+ describe('when no project is found', function () {
+ beforeEach(function () {
this.TokenAccessHandler.getProjectByToken = sinon
.stub()
.callsArgWith(2, null, null, null)
})
- it('should try to find projects with both kinds of token', function(done) {
+ it('should try to find projects with both kinds of token', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -390,7 +390,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should not allow any access', function(done) {
+ it('should not allow any access', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -404,14 +404,14 @@ describe('TokenAccessHandler', function() {
})
})
- describe('when findProject produces an error', function() {
- beforeEach(function() {
+ describe('when findProject produces an error', function () {
+ beforeEach(function () {
this.TokenAccessHandler.getProjectByToken = sinon
.stub()
.callsArgWith(2, new Error('woops'))
})
- it('should try to find projects with both kinds of token', function(done) {
+ it('should try to find projects with both kinds of token', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -424,7 +424,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should produce an error and not allow access', function(done) {
+ it('should produce an error and not allow access', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -439,13 +439,13 @@ describe('TokenAccessHandler', function() {
})
})
- describe('when project is not set to token-based access', function() {
- beforeEach(function() {
+ describe('when project is not set to token-based access', function () {
+ beforeEach(function () {
return (this.project.publicAccesLevel = 'private')
})
- describe('for read-and-write project', function() {
- beforeEach(function() {
+ describe('for read-and-write project', function () {
+ beforeEach(function () {
this.TokenAccessHandler.getTokenType = sinon
.stub()
.returns('readAndWrite')
@@ -454,7 +454,7 @@ describe('TokenAccessHandler', function() {
.callsArgWith(2, null, this.project)
})
- it('should not allow any access', function(done) {
+ it('should not allow any access', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -468,8 +468,8 @@ describe('TokenAccessHandler', function() {
})
})
- describe('for read-only project', function() {
- beforeEach(function() {
+ describe('for read-only project', function () {
+ beforeEach(function () {
this.TokenAccessHandler.getTokenType = sinon
.stub()
.returns('readOnly')
@@ -478,7 +478,7 @@ describe('TokenAccessHandler', function() {
.callsArgWith(2, null, this.project)
})
- it('should not allow any access', function(done) {
+ it('should not allow any access', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
this.token,
@@ -492,14 +492,14 @@ describe('TokenAccessHandler', function() {
})
})
- describe('with nothing', function() {
- beforeEach(function() {
+ describe('with nothing', function () {
+ beforeEach(function () {
this.TokenAccessHandler.getProjectByToken = sinon
.stub()
.callsArgWith(1, null, null, null)
})
- it('should not allow any access', function(done) {
+ it('should not allow any access', function (done) {
return this.TokenAccessHandler.validateTokenForAnonymousAccess(
this.projectId,
null,
@@ -515,8 +515,8 @@ describe('TokenAccessHandler', function() {
})
})
- describe('protectTokens', function() {
- beforeEach(function() {
+ describe('protectTokens', function () {
+ beforeEach(function () {
return (this.project = {
tokens: {
readAndWrite: 'rw',
@@ -526,33 +526,33 @@ describe('TokenAccessHandler', function() {
})
})
- it('should hide write token from read-only user', function() {
+ it('should hide write token from read-only user', function () {
this.TokenAccessHandler.protectTokens(this.project, 'readOnly')
expect(this.project.tokens.readAndWrite).to.equal('')
expect(this.project.tokens.readAndWritePrefix).to.equal('')
return expect(this.project.tokens.readOnly).to.equal('ro')
})
- it('should hide read token from read-write user', function() {
+ it('should hide read token from read-write user', function () {
this.TokenAccessHandler.protectTokens(this.project, 'readAndWrite')
expect(this.project.tokens.readAndWrite).to.equal('rw')
return expect(this.project.tokens.readOnly).to.equal('')
})
- it('should leave tokens in place for owner', function() {
+ it('should leave tokens in place for owner', function () {
this.TokenAccessHandler.protectTokens(this.project, 'owner')
expect(this.project.tokens.readAndWrite).to.equal('rw')
return expect(this.project.tokens.readOnly).to.equal('ro')
})
})
- describe('getDocPublishedInfo', function() {
- beforeEach(function() {
+ describe('getDocPublishedInfo', function () {
+ beforeEach(function () {
return (this.callback = sinon.stub())
})
- describe('when v1 api not set', function() {
- beforeEach(function() {
+ describe('when v1 api not set', function () {
+ beforeEach(function () {
this.settings.apis = { v1: undefined }
return this.TokenAccessHandler.getV1DocPublishedInfo(
this.token,
@@ -560,7 +560,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should not check access and return default info', function() {
+ it('should not check access and return default info', function () {
expect(this.V1Api.request.called).to.equal(false)
return expect(
this.callback.calledWith(null, {
@@ -570,13 +570,13 @@ describe('TokenAccessHandler', function() {
})
})
- describe('when v1 api is set', function() {
- beforeEach(function() {
+ describe('when v1 api is set', function () {
+ beforeEach(function () {
return (this.settings.apis = { v1: { url: 'v1Url' } })
})
- describe('on V1Api.request success', function() {
- beforeEach(function() {
+ describe('on V1Api.request success', function () {
+ beforeEach(function () {
this.V1Api.request = sinon
.stub()
.callsArgWith(1, null, null, 'mock-data')
@@ -586,7 +586,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should return response body', function() {
+ it('should return response body', function () {
expect(
this.V1Api.request.calledWith({
url: `/api/v1/sharelatex/docs/${this.token}/is_published`
@@ -598,8 +598,8 @@ describe('TokenAccessHandler', function() {
})
})
- describe('on V1Api.request error', function() {
- beforeEach(function() {
+ describe('on V1Api.request error', function () {
+ beforeEach(function () {
this.V1Api.request = sinon.stub().callsArgWith(1, 'error')
return this.TokenAccessHandler.getV1DocPublishedInfo(
this.token,
@@ -607,21 +607,21 @@ describe('TokenAccessHandler', function() {
)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.calledWith('error')).to.equal(true)
})
})
})
})
- describe('getV1DocInfo', function() {
- beforeEach(function() {
+ describe('getV1DocInfo', function () {
+ beforeEach(function () {
this.v2UserId = 123
return (this.callback = sinon.stub())
})
- describe('when v1 api not set', function() {
- beforeEach(function() {
+ describe('when v1 api not set', function () {
+ beforeEach(function () {
return this.TokenAccessHandler.getV1DocInfo(
this.token,
this.v2UserId,
@@ -629,7 +629,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should not check access and return default info', function() {
+ it('should not check access and return default info', function () {
expect(this.V1Api.request.called).to.equal(false)
return expect(
this.callback.calledWith(null, {
@@ -640,13 +640,13 @@ describe('TokenAccessHandler', function() {
})
})
- describe('when v1 api is set', function() {
- beforeEach(function() {
+ describe('when v1 api is set', function () {
+ beforeEach(function () {
return (this.settings.apis = { v1: 'v1' })
})
- describe('on UserGetter.getUser success', function() {
- beforeEach(function() {
+ describe('on UserGetter.getUser success', function () {
+ beforeEach(function () {
this.UserGetter.getUser = sinon.stub().yields(null, {
overleaf: { id: 1 }
})
@@ -657,15 +657,15 @@ describe('TokenAccessHandler', function() {
)
})
- it('should get user', function() {
+ it('should get user', function () {
return expect(
this.UserGetter.getUser.calledWith(this.v2UserId)
).to.equal(true)
})
})
- describe('on UserGetter.getUser error', function() {
- beforeEach(function() {
+ describe('on UserGetter.getUser error', function () {
+ beforeEach(function () {
this.error = new Error('failed to get user')
this.UserGetter.getUser = sinon.stub().yields(this.error)
return this.TokenAccessHandler.getV1DocInfo(
@@ -675,13 +675,13 @@ describe('TokenAccessHandler', function() {
)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.calledWith(this.error)).to.equal(true)
})
})
- describe('on V1Api.request success', function() {
- beforeEach(function() {
+ describe('on V1Api.request success', function () {
+ beforeEach(function () {
this.v1UserId = 1
this.UserGetter.getUser = sinon.stub().yields(null, {
overleaf: { id: this.v1UserId }
@@ -696,7 +696,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should return response body', function() {
+ it('should return response body', function () {
expect(
this.V1Api.request.calledWith({
url: `/api/v1/sharelatex/users/${this.v1UserId}/docs/${this.token}/info`
@@ -708,8 +708,8 @@ describe('TokenAccessHandler', function() {
})
})
- describe('on V1Api.request error', function() {
- beforeEach(function() {
+ describe('on V1Api.request error', function () {
+ beforeEach(function () {
this.UserGetter.getUser = sinon.stub().yields(null, {
overleaf: { id: 1 }
})
@@ -721,7 +721,7 @@ describe('TokenAccessHandler', function() {
)
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
return expect(this.callback.calledWith('error')).to.equal(true)
})
})
diff --git a/services/web/test/unit/src/Uploads/ArchiveManagerTests.js b/services/web/test/unit/src/Uploads/ArchiveManagerTests.js
index 2722226861..7cbc61afb8 100644
--- a/services/web/test/unit/src/Uploads/ArchiveManagerTests.js
+++ b/services/web/test/unit/src/Uploads/ArchiveManagerTests.js
@@ -19,11 +19,11 @@ const ArchiveErrors = require('../../../../app/src/Features/Uploads/ArchiveError
const SandboxedModule = require('sandboxed-module')
const events = require('events')
-describe('ArchiveManager', function() {
- beforeEach(function() {
+describe('ArchiveManager', function () {
+ beforeEach(function () {
let Timer
this.metrics = {
- Timer: (Timer = (function() {
+ Timer: (Timer = (function () {
Timer = class Timer {
static initClass() {
this.prototype.done = sinon.stub()
@@ -52,8 +52,8 @@ describe('ArchiveManager', function() {
return (this.callback = sinon.stub())
})
- describe('extractZipArchive', function() {
- beforeEach(function() {
+ describe('extractZipArchive', function () {
+ beforeEach(function () {
this.source = '/path/to/zip/source.zip'
this.destination = '/path/to/zip/destination'
return (this.ArchiveManager._isZipTooLarge = sinon
@@ -61,8 +61,8 @@ describe('ArchiveManager', function() {
.callsArgWith(1, null, false))
})
- describe('successfully', function() {
- beforeEach(function(done) {
+ describe('successfully', function () {
+ beforeEach(function (done) {
this.readStream = new events.EventEmitter()
this.readStream.pipe = sinon.stub()
this.zipfile.openReadStream = sinon
@@ -83,17 +83,17 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should run yauzl', function() {
+ it('should run yauzl', function () {
return this.yauzl.open.calledWith(this.source).should.equal(true)
})
- it('should time the unzip', function() {
+ it('should time the unzip', function () {
return this.metrics.Timer.prototype.done.called.should.equal(true)
})
})
- describe('with a zipfile containing an empty directory', function() {
- beforeEach(function(done) {
+ describe('with a zipfile containing an empty directory', function () {
+ beforeEach(function (done) {
this.readStream = new events.EventEmitter()
this.readStream.pipe = sinon.stub()
this.zipfile.openReadStream = sinon
@@ -117,7 +117,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
return sinon.assert.calledWithExactly(
this.callback,
sinon.match.instanceOf(ArchiveErrors.EmptyZipFileError)
@@ -125,8 +125,8 @@ describe('ArchiveManager', function() {
})
})
- describe('with an empty zipfile', function() {
- beforeEach(function(done) {
+ describe('with an empty zipfile', function () {
+ beforeEach(function (done) {
this.ArchiveManager.extractZipArchive(
this.source,
this.destination,
@@ -138,7 +138,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
return sinon.assert.calledWithExactly(
this.callback,
sinon.match.instanceOf(ArchiveErrors.EmptyZipFileError)
@@ -146,8 +146,8 @@ describe('ArchiveManager', function() {
})
})
- describe('with an error in the zip file header', function() {
- beforeEach(function(done) {
+ describe('with an error in the zip file header', function () {
+ beforeEach(function (done) {
this.yauzl.open = sinon
.stub()
.callsArgWith(2, new ArchiveErrors.InvalidZipFileError())
@@ -161,7 +161,7 @@ describe('ArchiveManager', function() {
)
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
return sinon.assert.calledWithExactly(
this.callback,
sinon.match.instanceOf(ArchiveErrors.InvalidZipFileError)
@@ -169,8 +169,8 @@ describe('ArchiveManager', function() {
})
})
- describe('with a zip that is too large', function() {
- beforeEach(function(done) {
+ describe('with a zip that is too large', function () {
+ beforeEach(function (done) {
this.ArchiveManager._isZipTooLarge = sinon
.stub()
.callsArgWith(1, null, true)
@@ -184,20 +184,20 @@ describe('ArchiveManager', function() {
)
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
return sinon.assert.calledWithExactly(
this.callback,
sinon.match.instanceOf(ArchiveErrors.ZipContentsTooLargeError)
)
})
- it('should not call yauzl.open', function() {
+ it('should not call yauzl.open', function () {
return this.yauzl.open.called.should.equal(false)
})
})
- describe('with an error in the extracted files', function() {
- beforeEach(function(done) {
+ describe('with an error in the extracted files', function () {
+ beforeEach(function (done) {
this.ArchiveManager.extractZipArchive(
this.source,
this.destination,
@@ -209,7 +209,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('error', new Error('Something went wrong'))
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
return this.callback.should.have.been.calledWithExactly(
sinon.match
.instanceOf(Error)
@@ -218,8 +218,8 @@ describe('ArchiveManager', function() {
})
})
- describe('with a relative extracted file path', function() {
- beforeEach(function(done) {
+ describe('with a relative extracted file path', function () {
+ beforeEach(function (done) {
this.zipfile.openReadStream = sinon.stub()
this.ArchiveManager.extractZipArchive(
this.source,
@@ -233,13 +233,13 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should not write try to read the file entry', function() {
+ it('should not write try to read the file entry', function () {
return this.zipfile.openReadStream.called.should.equal(false)
})
})
- describe('with an unnormalized extracted file path', function() {
- beforeEach(function(done) {
+ describe('with an unnormalized extracted file path', function () {
+ beforeEach(function (done) {
this.zipfile.openReadStream = sinon.stub()
this.ArchiveManager.extractZipArchive(
this.source,
@@ -253,13 +253,13 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should not try to read the file entry', function() {
+ it('should not try to read the file entry', function () {
return this.zipfile.openReadStream.called.should.equal(false)
})
})
- describe('with backslashes in the path', function() {
- beforeEach(function(done) {
+ describe('with backslashes in the path', function () {
+ beforeEach(function (done) {
this.readStream = new events.EventEmitter()
this.readStream.pipe = sinon.stub()
this.writeStream = new events.EventEmitter()
@@ -281,7 +281,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should read the file entry with its original path', function() {
+ it('should read the file entry with its original path', function () {
this.zipfile.openReadStream.should.be.calledWith({
fileName: 'wombat\\foo.tex'
})
@@ -290,14 +290,14 @@ describe('ArchiveManager', function() {
})
})
- it('should treat the backslashes as a directory separator when creating the directory', function() {
+ it('should treat the backslashes as a directory separator when creating the directory', function () {
this.fse.ensureDir.should.be.calledWith(`${this.destination}/wombat`)
return this.fse.ensureDir.should.be.calledWith(
`${this.destination}/potato`
)
})
- it('should treat the backslashes as a directory separator when creating the file', function() {
+ it('should treat the backslashes as a directory separator when creating the file', function () {
this.fs.createWriteStream.should.be.calledWith(
`${this.destination}/wombat/foo.tex`
)
@@ -307,8 +307,8 @@ describe('ArchiveManager', function() {
})
})
- describe('with a directory entry', function() {
- beforeEach(function(done) {
+ describe('with a directory entry', function () {
+ beforeEach(function (done) {
this.zipfile.openReadStream = sinon.stub()
this.ArchiveManager.extractZipArchive(
this.source,
@@ -322,13 +322,13 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should not try to read the entry', function() {
+ it('should not try to read the entry', function () {
return this.zipfile.openReadStream.called.should.equal(false)
})
})
- describe('with an error opening the file read stream', function() {
- beforeEach(function(done) {
+ describe('with an error opening the file read stream', function () {
+ beforeEach(function (done) {
this.zipfile.openReadStream = sinon
.stub()
.callsArgWith(1, new Error('Something went wrong'))
@@ -345,7 +345,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
return this.callback.should.have.been.calledWithExactly(
sinon.match
.instanceOf(Error)
@@ -353,13 +353,13 @@ describe('ArchiveManager', function() {
)
})
- it('should close the zipfile', function() {
+ it('should close the zipfile', function () {
return this.zipfile.close.called.should.equal(true)
})
})
- describe('with an error in the file read stream', function() {
- beforeEach(function(done) {
+ describe('with an error in the file read stream', function () {
+ beforeEach(function (done) {
this.readStream = new events.EventEmitter()
this.readStream.pipe = sinon.stub()
this.zipfile.openReadStream = sinon
@@ -381,7 +381,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
return this.callback.should.have.been.calledWithExactly(
sinon.match
.instanceOf(Error)
@@ -389,13 +389,13 @@ describe('ArchiveManager', function() {
)
})
- it('should close the zipfile', function() {
+ it('should close the zipfile', function () {
return this.zipfile.close.called.should.equal(true)
})
})
- describe('with an error in the file write stream', function() {
- beforeEach(function(done) {
+ describe('with an error in the file write stream', function () {
+ beforeEach(function (done) {
this.readStream = new events.EventEmitter()
this.readStream.pipe = sinon.stub()
this.readStream.unpipe = sinon.stub()
@@ -419,7 +419,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
return this.callback.should.have.been.calledWithExactly(
sinon.match
.instanceOf(Error)
@@ -427,22 +427,22 @@ describe('ArchiveManager', function() {
)
})
- it('should unpipe from the readstream', function() {
+ it('should unpipe from the readstream', function () {
return this.readStream.unpipe.called.should.equal(true)
})
- it('should destroy the readstream', function() {
+ it('should destroy the readstream', function () {
return this.readStream.destroy.called.should.equal(true)
})
- it('should close the zipfile', function() {
+ it('should close the zipfile', function () {
return this.zipfile.close.called.should.equal(true)
})
})
})
- describe('_isZipTooLarge', function() {
- it('should return false with small output', function(done) {
+ describe('_isZipTooLarge', function () {
+ it('should return false with small output', function (done) {
this.ArchiveManager._isZipTooLarge(this.source, (error, isTooLarge) => {
isTooLarge.should.equal(false)
return done()
@@ -451,7 +451,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should return true with large bytes', function(done) {
+ it('should return true with large bytes', function (done) {
this.ArchiveManager._isZipTooLarge(this.source, (error, isTooLarge) => {
isTooLarge.should.equal(true)
return done()
@@ -460,7 +460,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should return error on no data', function(done) {
+ it('should return error on no data', function (done) {
this.ArchiveManager._isZipTooLarge(this.source, (error, isTooLarge) => {
expect(error).to.exist
return done()
@@ -469,7 +469,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it("should return error if it didn't get a number", function(done) {
+ it("should return error if it didn't get a number", function (done) {
this.ArchiveManager._isZipTooLarge(this.source, (error, isTooLarge) => {
expect(error).to.exist
return done()
@@ -478,7 +478,7 @@ describe('ArchiveManager', function() {
return this.zipfile.emit('end')
})
- it('should return error if there is no data', function(done) {
+ it('should return error if there is no data', function (done) {
this.ArchiveManager._isZipTooLarge(this.source, (error, isTooLarge) => {
expect(error).to.exist
return done()
@@ -487,15 +487,15 @@ describe('ArchiveManager', function() {
})
})
- describe('findTopLevelDirectory', function() {
- beforeEach(function() {
+ describe('findTopLevelDirectory', function () {
+ beforeEach(function () {
this.fs.readdir = sinon.stub()
this.fs.stat = sinon.stub()
return (this.directory = 'test/directory')
})
- describe('with multiple files', function() {
- beforeEach(function() {
+ describe('with multiple files', function () {
+ beforeEach(function () {
this.fs.readdir.callsArgWith(1, null, ['multiple', 'files'])
return this.ArchiveManager.findTopLevelDirectory(
this.directory,
@@ -503,17 +503,17 @@ describe('ArchiveManager', function() {
)
})
- it('should find the files in the directory', function() {
+ it('should find the files in the directory', function () {
return this.fs.readdir.calledWith(this.directory).should.equal(true)
})
- it('should return the original directory', function() {
+ it('should return the original directory', function () {
return this.callback.calledWith(null, this.directory).should.equal(true)
})
})
- describe('with a single file (not folder)', function() {
- beforeEach(function() {
+ describe('with a single file (not folder)', function () {
+ beforeEach(function () {
this.fs.readdir.callsArgWith(1, null, ['foo.tex'])
this.fs.stat.callsArgWith(1, null, {
isDirectory() {
@@ -526,19 +526,19 @@ describe('ArchiveManager', function() {
)
})
- it('should check if the file is a directory', function() {
+ it('should check if the file is a directory', function () {
return this.fs.stat
.calledWith(this.directory + '/foo.tex')
.should.equal(true)
})
- it('should return the original directory', function() {
+ it('should return the original directory', function () {
return this.callback.calledWith(null, this.directory).should.equal(true)
})
})
- describe('with a single top-level folder', function() {
- beforeEach(function() {
+ describe('with a single top-level folder', function () {
+ beforeEach(function () {
this.fs.readdir.callsArgWith(1, null, ['folder'])
this.fs.stat.callsArgWith(1, null, {
isDirectory() {
@@ -551,13 +551,13 @@ describe('ArchiveManager', function() {
)
})
- it('should check if the file is a directory', function() {
+ it('should check if the file is a directory', function () {
return this.fs.stat
.calledWith(this.directory + '/folder')
.should.equal(true)
})
- it('should return the child directory', function() {
+ it('should return the child directory', function () {
return this.callback
.calledWith(null, this.directory + '/folder')
.should.equal(true)
diff --git a/services/web/test/unit/src/Uploads/FileSystemImportManagerTests.js b/services/web/test/unit/src/Uploads/FileSystemImportManagerTests.js
index 6a93da1dcd..c17e8291a1 100644
--- a/services/web/test/unit/src/Uploads/FileSystemImportManagerTests.js
+++ b/services/web/test/unit/src/Uploads/FileSystemImportManagerTests.js
@@ -7,8 +7,8 @@ const { ObjectId } = require('mongodb')
const MODULE_PATH =
'../../../../app/src/Features/Uploads/FileSystemImportManager.js'
-describe('FileSystemImportManager', function() {
- beforeEach(function() {
+describe('FileSystemImportManager', function () {
+ beforeEach(function () {
this.projectId = new ObjectId()
this.folderId = new ObjectId()
this.newFolderId = new ObjectId()
@@ -30,8 +30,8 @@ describe('FileSystemImportManager', function() {
})
})
- describe('importDir', function() {
- beforeEach(async function() {
+ describe('importDir', function () {
+ beforeEach(async function () {
mockFs({
'import-test': {
'main.tex': 'My thesis',
@@ -59,11 +59,11 @@ describe('FileSystemImportManager', function() {
this.projectPaths = this.entries.map(x => x.projectPath)
})
- afterEach(function() {
+ afterEach(function () {
mockFs.restore()
})
- it('should import regular docs', function() {
+ it('should import regular docs', function () {
expect(this.entries).to.deep.include({
type: 'doc',
projectPath: '/main.tex',
@@ -71,15 +71,15 @@ describe('FileSystemImportManager', function() {
})
})
- it('should skip symlinks inside the import folder', function() {
+ it('should skip symlinks inside the import folder', function () {
expect(this.projectPaths).not.to.include('/link-to-main.tex')
})
- it('should skip ignored files', function() {
+ it('should skip ignored files', function () {
expect(this.projectPaths).not.to.include('/.DS_Store')
})
- it('should import binary files', function() {
+ it('should import binary files', function () {
expect(this.entries).to.deep.include({
type: 'file',
projectPath: '/images/cat.jpg',
@@ -87,7 +87,7 @@ describe('FileSystemImportManager', function() {
})
})
- it('should deal with Mac/Windows/Unix line endings', function() {
+ it('should deal with Mac/Windows/Unix line endings', function () {
expect(this.entries).to.deep.include({
type: 'doc',
projectPath: '/line-endings/unix.txt',
@@ -110,7 +110,7 @@ describe('FileSystemImportManager', function() {
})
})
- it('should import documents with latin1 encoding', function() {
+ it('should import documents with latin1 encoding', function () {
expect(this.entries).to.deep.include({
type: 'doc',
projectPath: '/encodings/latin1.txt',
@@ -118,7 +118,7 @@ describe('FileSystemImportManager', function() {
})
})
- it('should import documents with utf16-le encoding', function() {
+ it('should import documents with utf16-le encoding', function () {
expect(this.entries).to.deep.include({
type: 'doc',
projectPath: '/encodings/utf16le.txt',
@@ -126,15 +126,15 @@ describe('FileSystemImportManager', function() {
})
})
- it('should error when the root folder is a symlink', async function() {
+ it('should error when the root folder is a symlink', async function () {
await expect(this.FileSystemImportManager.promises.importDir('symlink'))
.to.be.rejected
})
})
- describe('addEntity', function() {
- describe('with directory', function() {
- beforeEach(async function() {
+ describe('addEntity', function () {
+ describe('with directory', function () {
+ beforeEach(async function () {
mockFs({
path: {
to: {
@@ -156,11 +156,11 @@ describe('FileSystemImportManager', function() {
)
})
- afterEach(function() {
+ afterEach(function () {
mockFs.restore()
})
- it('should add a folder to the project', function() {
+ it('should add a folder to the project', function () {
this.EditorController.promises.addFolder.should.have.been.calledWith(
this.projectId,
this.folderId,
@@ -169,7 +169,7 @@ describe('FileSystemImportManager', function() {
)
})
- it("should add the folder's contents", function() {
+ it("should add the folder's contents", function () {
this.EditorController.promises.addDoc.should.have.been.calledWith(
this.projectId,
this.newFolderId,
@@ -190,17 +190,17 @@ describe('FileSystemImportManager', function() {
})
})
- describe('with binary file', function() {
- beforeEach(function() {
+ describe('with binary file', function () {
+ beforeEach(function () {
mockFs({ 'uploaded-file': Buffer.from([1, 2, 3, 4]) })
})
- afterEach(function() {
+ afterEach(function () {
mockFs.restore()
})
- describe('with replace set to false', function() {
- beforeEach(async function() {
+ describe('with replace set to false', function () {
+ beforeEach(async function () {
await this.FileSystemImportManager.promises.addEntity(
this.userId,
this.projectId,
@@ -211,7 +211,7 @@ describe('FileSystemImportManager', function() {
)
})
- it('should add the file', function() {
+ it('should add the file', function () {
this.EditorController.promises.addFile.should.have.been.calledWith(
this.projectId,
this.folderId,
@@ -224,8 +224,8 @@ describe('FileSystemImportManager', function() {
})
})
- describe('with replace set to true', function() {
- beforeEach(async function() {
+ describe('with replace set to true', function () {
+ beforeEach(async function () {
await this.FileSystemImportManager.promises.addEntity(
this.userId,
this.projectId,
@@ -236,7 +236,7 @@ describe('FileSystemImportManager', function() {
)
})
- it('should add the file', function() {
+ it('should add the file', function () {
this.EditorController.promises.upsertFile.should.have.been.calledWith(
this.projectId,
this.folderId,
@@ -255,8 +255,8 @@ describe('FileSystemImportManager', function() {
['Mac', '\r'],
['Windows', '\r\n']
]) {
- describe(`with text file (${lineEndingDescription} line endings)`, function() {
- beforeEach(function() {
+ describe(`with text file (${lineEndingDescription} line endings)`, function () {
+ beforeEach(function () {
mockFs({
path: {
to: { 'uploaded-file': `one${lineEnding}two${lineEnding}three` }
@@ -264,12 +264,12 @@ describe('FileSystemImportManager', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
mockFs.restore()
})
- describe('with replace set to false', function() {
- beforeEach(async function() {
+ describe('with replace set to false', function () {
+ beforeEach(async function () {
await this.FileSystemImportManager.promises.addEntity(
this.userId,
this.projectId,
@@ -280,7 +280,7 @@ describe('FileSystemImportManager', function() {
)
})
- it('should insert the doc', function() {
+ it('should insert the doc', function () {
this.EditorController.promises.addDoc.should.have.been.calledWith(
this.projectId,
this.folderId,
@@ -292,8 +292,8 @@ describe('FileSystemImportManager', function() {
})
})
- describe('with replace set to true', function() {
- beforeEach(async function() {
+ describe('with replace set to true', function () {
+ beforeEach(async function () {
await this.FileSystemImportManager.promises.addEntity(
this.userId,
this.projectId,
@@ -304,7 +304,7 @@ describe('FileSystemImportManager', function() {
)
})
- it('should upsert the doc', function() {
+ it('should upsert the doc', function () {
this.EditorController.promises.upsertDoc.should.have.been.calledWith(
this.projectId,
this.folderId,
@@ -318,18 +318,18 @@ describe('FileSystemImportManager', function() {
})
}
- describe('with symlink', function() {
- beforeEach(function() {
+ describe('with symlink', function () {
+ beforeEach(function () {
mockFs({
path: { to: { symlink: mockFs.symlink({ path: '/etc/passwd' }) } }
})
})
- afterEach(function() {
+ afterEach(function () {
mockFs.restore()
})
- it('should stop with an error', async function() {
+ it('should stop with an error', async function () {
await expect(
this.FileSystemImportManager.promises.addEntity(
this.userId,
diff --git a/services/web/test/unit/src/Uploads/FileTypeManagerTests.js b/services/web/test/unit/src/Uploads/FileTypeManagerTests.js
index edcede8759..72517600e8 100644
--- a/services/web/test/unit/src/Uploads/FileTypeManagerTests.js
+++ b/services/web/test/unit/src/Uploads/FileTypeManagerTests.js
@@ -5,8 +5,8 @@ const isUtf8 = require('utf-8-validate')
const Settings = require('settings-sharelatex')
const modulePath = '../../../../app/src/Features/Uploads/FileTypeManager.js'
-describe('FileTypeManager', function() {
- beforeEach(function() {
+describe('FileTypeManager', function () {
+ beforeEach(function () {
this.isUtf8 = sinon.spy(isUtf8)
this.stats = {
isDirectory: sinon.stub().returns(false),
@@ -49,32 +49,32 @@ describe('FileTypeManager', function() {
})
})
- describe('isDirectory', function() {
- describe('when it is a directory', function() {
- beforeEach(function() {
+ describe('isDirectory', function () {
+ describe('when it is a directory', function () {
+ beforeEach(function () {
this.stats.isDirectory.returns(true)
this.FileTypeManager.isDirectory('/some/path', this.callback)
})
- it('should return true', function() {
+ it('should return true', function () {
this.callback.should.have.been.calledWith(null, true)
})
})
- describe('when it is not a directory', function() {
- beforeEach(function() {
+ describe('when it is not a directory', function () {
+ beforeEach(function () {
this.stats.isDirectory.returns(false)
this.FileTypeManager.isDirectory('/some/path', this.callback)
})
- it('should return false', function() {
+ it('should return false', function () {
this.callback.should.have.been.calledWith(null, false)
})
})
})
- describe('getType', function() {
- describe('when the file extension is text', function() {
+ describe('getType', function () {
+ describe('when the file extension is text', function () {
const TEXT_FILENAMES = [
'file.tex',
'file.bib',
@@ -90,7 +90,7 @@ describe('FileTypeManager', function() {
'file.TEX'
]
TEXT_FILENAMES.forEach(filename => {
- it(`should classify ${filename} as text`, function(done) {
+ it(`should classify ${filename} as text`, function (done) {
this.FileTypeManager.getType(
'file.tex',
'utf8.tex',
@@ -105,7 +105,7 @@ describe('FileTypeManager', function() {
})
})
- it('should classify large text files as binary', function(done) {
+ it('should classify large text files as binary', function (done) {
this.stats.size = 2 * 1024 * 1024 // 2Mb
this.FileTypeManager.getType(
'file.tex',
@@ -120,7 +120,7 @@ describe('FileTypeManager', function() {
)
})
- it('should not try to determine the encoding of large files', function(done) {
+ it('should not try to determine the encoding of large files', function (done) {
this.stats.size = 2 * 1024 * 1024 // 2Mb
this.FileTypeManager.getType('file.tex', 'utf8.tex', err => {
if (err) {
@@ -131,7 +131,7 @@ describe('FileTypeManager', function() {
})
})
- it('should detect the encoding of a utf8 file', function(done) {
+ it('should detect the encoding of a utf8 file', function (done) {
this.FileTypeManager.getType(
'file.tex',
'utf8.tex',
@@ -147,7 +147,7 @@ describe('FileTypeManager', function() {
)
})
- it("should return 'latin1' for non-unicode encodings", function(done) {
+ it("should return 'latin1' for non-unicode encodings", function (done) {
this.FileTypeManager.getType(
'file.tex',
'latin1.tex',
@@ -163,7 +163,7 @@ describe('FileTypeManager', function() {
)
})
- it('should classify utf16 with BOM as utf-16', function(done) {
+ it('should classify utf16 with BOM as utf-16', function (done) {
this.FileTypeManager.getType(
'file.tex',
'utf16.tex',
@@ -179,7 +179,7 @@ describe('FileTypeManager', function() {
)
})
- it('should classify latin1 files with a null char as binary', function(done) {
+ it('should classify latin1 files with a null char as binary', function (done) {
this.FileTypeManager.getType(
'file.tex',
'latin1-null.tex',
@@ -193,7 +193,7 @@ describe('FileTypeManager', function() {
)
})
- it('should classify utf8 files with a null char as binary', function(done) {
+ it('should classify utf8 files with a null char as binary', function (done) {
this.FileTypeManager.getType(
'file.tex',
'utf8-null.tex',
@@ -207,7 +207,7 @@ describe('FileTypeManager', function() {
)
})
- it('should classify utf8 files with non-BMP chars as binary', function(done) {
+ it('should classify utf8 files with non-BMP chars as binary', function (done) {
this.FileTypeManager.getType(
'file.tex',
'utf8-non-bmp.tex',
@@ -221,7 +221,7 @@ describe('FileTypeManager', function() {
)
})
- it('should classify utf8 files with ascii control chars as utf-8', function(done) {
+ it('should classify utf8 files with ascii control chars as utf-8', function (done) {
this.FileTypeManager.getType(
'file.tex',
'utf8-control-chars.tex',
@@ -237,10 +237,10 @@ describe('FileTypeManager', function() {
})
})
- describe('when the file extension is non-text', function() {
+ describe('when the file extension is non-text', function () {
const BINARY_FILENAMES = ['file.eps', 'file.dvi', 'file.png', 'tex']
BINARY_FILENAMES.forEach(filename => {
- it(`should classify ${filename} as binary`, function(done) {
+ it(`should classify ${filename} as binary`, function (done) {
this.FileTypeManager.getType(
'file.tex',
'utf8.tex',
@@ -255,7 +255,7 @@ describe('FileTypeManager', function() {
})
})
- it('should not try to get the character encoding', function(done) {
+ it('should not try to get the character encoding', function (done) {
this.FileTypeManager.getType('file.png', 'utf8.tex', err => {
if (err) {
return done(err)
@@ -267,8 +267,8 @@ describe('FileTypeManager', function() {
})
})
- describe('shouldIgnore', function() {
- it('should ignore tex auxiliary files', function(done) {
+ describe('shouldIgnore', function () {
+ it('should ignore tex auxiliary files', function (done) {
this.FileTypeManager.shouldIgnore('file.aux', (err, ignore) => {
if (err) {
return done(err)
@@ -278,7 +278,7 @@ describe('FileTypeManager', function() {
})
})
- it('should ignore dotfiles', function(done) {
+ it('should ignore dotfiles', function (done) {
this.FileTypeManager.shouldIgnore('path/.git', (err, ignore) => {
if (err) {
return done(err)
@@ -288,7 +288,7 @@ describe('FileTypeManager', function() {
})
})
- it('should not ignore .latexmkrc dotfile', function(done) {
+ it('should not ignore .latexmkrc dotfile', function (done) {
this.FileTypeManager.shouldIgnore('path/.latexmkrc', (err, ignore) => {
if (err) {
return done(err)
@@ -298,7 +298,7 @@ describe('FileTypeManager', function() {
})
})
- it('should ignore __MACOSX', function(done) {
+ it('should ignore __MACOSX', function (done) {
this.FileTypeManager.shouldIgnore('path/__MACOSX', (err, ignore) => {
if (err) {
return done(err)
@@ -308,7 +308,7 @@ describe('FileTypeManager', function() {
})
})
- it('should not ignore .tex files', function(done) {
+ it('should not ignore .tex files', function (done) {
this.FileTypeManager.shouldIgnore('file.tex', (err, ignore) => {
if (err) {
return done(err)
@@ -318,7 +318,7 @@ describe('FileTypeManager', function() {
})
})
- it('should ignore the case of the extension', function(done) {
+ it('should ignore the case of the extension', function (done) {
this.FileTypeManager.shouldIgnore('file.AUX', (err, ignore) => {
if (err) {
return done(err)
@@ -328,7 +328,7 @@ describe('FileTypeManager', function() {
})
})
- it('should not ignore files with an ignored extension as full name', function(done) {
+ it('should not ignore files with an ignored extension as full name', function (done) {
this.FileTypeManager.shouldIgnore('dvi', (err, ignore) => {
if (err) {
return done(err)
@@ -338,7 +338,7 @@ describe('FileTypeManager', function() {
})
})
- it('should not ignore directories with an ignored extension as full name', function(done) {
+ it('should not ignore directories with an ignored extension as full name', function (done) {
this.stats.isDirectory.returns(true)
this.FileTypeManager.shouldIgnore('dvi', (err, ignore) => {
if (err) {
diff --git a/services/web/test/unit/src/Uploads/ProjectUploadControllerTests.js b/services/web/test/unit/src/Uploads/ProjectUploadControllerTests.js
index 6fe9607ea6..1f06df3e5e 100644
--- a/services/web/test/unit/src/Uploads/ProjectUploadControllerTests.js
+++ b/services/web/test/unit/src/Uploads/ProjectUploadControllerTests.js
@@ -20,14 +20,14 @@ const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
const ArchiveErrors = require('../../../../app/src/Features/Uploads/ArchiveErrors')
-describe('ProjectUploadController', function() {
- beforeEach(function() {
+describe('ProjectUploadController', function () {
+ beforeEach(function () {
let Timer
this.req = new MockRequest()
this.res = new MockResponse()
this.user_id = 'user-id-123'
this.metrics = {
- Timer: (Timer = (function() {
+ Timer: (Timer = (function () {
Timer = class Timer {
static initClass() {
this.prototype.done = sinon.stub()
@@ -56,8 +56,8 @@ describe('ProjectUploadController', function() {
}))
})
- describe('uploadProject', function() {
- beforeEach(function() {
+ describe('uploadProject', function () {
+ beforeEach(function () {
this.path = '/path/to/file/on/disk.zip'
this.name = 'filename.zip'
this.req.file = {
@@ -74,65 +74,65 @@ describe('ProjectUploadController', function() {
return (this.fs.unlink = sinon.stub())
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
this.ProjectUploadManager.createProjectFromZipArchive = sinon
.stub()
.callsArgWith(3, null, this.project)
return this.ProjectUploadController.uploadProject(this.req, this.res)
})
- it('should create a project owned by the logged in user', function() {
+ it('should create a project owned by the logged in user', function () {
return this.ProjectUploadManager.createProjectFromZipArchive
.calledWith(this.user_id)
.should.equal(true)
})
- it('should create a project with the same name as the zip archive', function() {
+ it('should create a project with the same name as the zip archive', function () {
return this.ProjectUploadManager.createProjectFromZipArchive
.calledWith(sinon.match.any, 'filename', sinon.match.any)
.should.equal(true)
})
- it('should create a project from the zip archive', function() {
+ it('should create a project from the zip archive', function () {
return this.ProjectUploadManager.createProjectFromZipArchive
.calledWith(sinon.match.any, sinon.match.any, this.path)
.should.equal(true)
})
- it('should return a successful response to the FileUploader client', function() {
+ it('should return a successful response to the FileUploader client', function () {
return expect(this.res.body).to.deep.equal({
success: true,
project_id: this.project_id
})
})
- it('should record the time taken to do the upload', function() {
+ it('should record the time taken to do the upload', function () {
return this.metrics.Timer.prototype.done.called.should.equal(true)
})
- it('should remove the uploaded file', function() {
+ it('should remove the uploaded file', function () {
return this.fs.unlink.calledWith(this.path).should.equal(true)
})
})
- describe('when ProjectUploadManager.createProjectFromZipArchive fails', function() {
- beforeEach(function() {
+ describe('when ProjectUploadManager.createProjectFromZipArchive fails', function () {
+ beforeEach(function () {
this.ProjectUploadManager.createProjectFromZipArchive = sinon
.stub()
.callsArgWith(3, new Error('Something went wrong'), this.project)
return this.ProjectUploadController.uploadProject(this.req, this.res)
})
- it('should return a failed response to the FileUploader client', function() {
+ it('should return a failed response to the FileUploader client', function () {
return expect(this.res.body).to.deep.equal(
JSON.stringify({ success: false, error: 'upload_failed' })
)
})
})
- describe('when ProjectUploadManager.createProjectFromZipArchive reports the file as invalid', function() {
- beforeEach(function() {
+ describe('when ProjectUploadManager.createProjectFromZipArchive reports the file as invalid', function () {
+ beforeEach(function () {
this.ProjectUploadManager.createProjectFromZipArchive = sinon
.stub()
.callsArgWith(
@@ -143,21 +143,21 @@ describe('ProjectUploadController', function() {
return this.ProjectUploadController.uploadProject(this.req, this.res)
})
- it('should return the reported error to the FileUploader client', function() {
+ it('should return the reported error to the FileUploader client', function () {
expect(JSON.parse(this.res.body)).to.deep.equal({
success: false,
error: 'zip_contents_too_large'
})
})
- it("should return an 'unprocessable entity' status code", function() {
+ it("should return an 'unprocessable entity' status code", function () {
return expect(this.res.statusCode).to.equal(422)
})
})
})
- describe('uploadFile', function() {
- beforeEach(function() {
+ describe('uploadFile', function () {
+ beforeEach(function () {
this.project_id = 'project-id-123'
this.folder_id = 'folder-id-123'
this.path = '/path/to/file/on/disk.png'
@@ -176,8 +176,8 @@ describe('ProjectUploadController', function() {
return (this.fs.unlink = sinon.stub())
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
this.entity = {
_id: '1234',
type: 'file'
@@ -188,7 +188,7 @@ describe('ProjectUploadController', function() {
return this.ProjectUploadController.uploadFile(this.req, this.res)
})
- it('should insert the file', function() {
+ it('should insert the file', function () {
return this.FileSystemImportManager.addEntity
.calledWith(
this.user_id,
@@ -200,7 +200,7 @@ describe('ProjectUploadController', function() {
.should.equal(true)
})
- it('should return a successful response to the FileUploader client', function() {
+ it('should return a successful response to the FileUploader client', function () {
return expect(this.res.body).to.deep.equal({
success: true,
entity_id: this.entity._id,
@@ -208,39 +208,39 @@ describe('ProjectUploadController', function() {
})
})
- it('should time the request', function() {
+ it('should time the request', function () {
return this.metrics.Timer.prototype.done.called.should.equal(true)
})
- it('should remove the uploaded file', function() {
+ it('should remove the uploaded file', function () {
return this.fs.unlink.calledWith(this.path).should.equal(true)
})
})
- describe('when FileSystemImportManager.addEntity returns a generic error', function() {
- beforeEach(function() {
+ describe('when FileSystemImportManager.addEntity returns a generic error', function () {
+ beforeEach(function () {
this.FileSystemImportManager.addEntity = sinon
.stub()
.callsArgWith(6, new Error('Sorry something went wrong'))
return this.ProjectUploadController.uploadFile(this.req, this.res)
})
- it('should return an unsuccessful response to the FileUploader client', function() {
+ it('should return an unsuccessful response to the FileUploader client', function () {
return expect(this.res.body).to.deep.equal({
success: false
})
})
})
- describe('when FileSystemImportManager.addEntity returns a too many files error', function() {
- beforeEach(function() {
+ describe('when FileSystemImportManager.addEntity returns a too many files error', function () {
+ beforeEach(function () {
this.FileSystemImportManager.addEntity = sinon
.stub()
.callsArgWith(6, new Error('project_has_too_many_files'))
return this.ProjectUploadController.uploadFile(this.req, this.res)
})
- it('should return an unsuccessful response to the FileUploader client', function() {
+ it('should return an unsuccessful response to the FileUploader client', function () {
return expect(this.res.body).to.deep.equal({
success: false,
error: 'project_has_too_many_files'
@@ -248,13 +248,13 @@ describe('ProjectUploadController', function() {
})
})
- describe('with a bad request', function() {
- beforeEach(function() {
+ describe('with a bad request', function () {
+ beforeEach(function () {
this.req.file.originalname = ''
return this.ProjectUploadController.uploadFile(this.req, this.res)
})
- it('should return a a non success response', function() {
+ it('should return a a non success response', function () {
return expect(this.res.body).to.deep.equal({
success: false
})
diff --git a/services/web/test/unit/src/Uploads/ProjectUploadManagerTests.js b/services/web/test/unit/src/Uploads/ProjectUploadManagerTests.js
index aa854c0d19..2abe4b45c0 100644
--- a/services/web/test/unit/src/Uploads/ProjectUploadManagerTests.js
+++ b/services/web/test/unit/src/Uploads/ProjectUploadManagerTests.js
@@ -7,8 +7,8 @@ const { ObjectId } = require('mongodb')
const MODULE_PATH =
'../../../../app/src/Features/Uploads/ProjectUploadManager.js'
-describe('ProjectUploadManager', function() {
- beforeEach(function() {
+describe('ProjectUploadManager', function () {
+ beforeEach(function () {
this.now = Date.now()
timekeeper.freeze(this.now)
this.rootFolderId = new ObjectId()
@@ -166,13 +166,13 @@ describe('ProjectUploadManager', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
timekeeper.reset()
})
- describe('createProjectFromZipArchive', function() {
- describe('when the title can be read from the root document', function() {
- beforeEach(async function() {
+ describe('createProjectFromZipArchive', function () {
+ describe('when the title can be read from the root document', function () {
+ beforeEach(async function () {
await this.ProjectUploadManager.promises.createProjectFromZipArchive(
this.ownerId,
this.projectName,
@@ -180,21 +180,21 @@ describe('ProjectUploadManager', function() {
)
})
- it('should extract the archive', function() {
+ it('should extract the archive', function () {
this.ArchiveManager.promises.extractZipArchive.should.have.been.calledWith(
this.zipPath,
this.extractedZipPath
)
})
- it('should create a project', function() {
+ it('should create a project', function () {
this.ProjectCreationHandler.promises.createBlankProject.should.have.been.calledWith(
this.ownerId,
this.uniqueProjectName
)
})
- it('should initialize the file tree', function() {
+ it('should initialize the file tree', function () {
this.ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure.should.have.been.calledWith(
this.project._id,
this.docEntries,
@@ -202,7 +202,7 @@ describe('ProjectUploadManager', function() {
)
})
- it('should notify document updater', function() {
+ it('should notify document updater', function () {
this.DocumentUpdaterHandler.promises.updateProjectStructure.should.have.been.calledWith(
this.project._id,
this.project.overleaf.history.id,
@@ -215,26 +215,26 @@ describe('ProjectUploadManager', function() {
)
})
- it('should flush the project to TPDS', function() {
+ it('should flush the project to TPDS', function () {
this.TpdsProjectFlusher.promises.flushProjectToTpds.should.have.been.calledWith(
this.project._id
)
})
- it('should set the root document', function() {
+ it('should set the root document', function () {
this.ProjectRootDocManager.promises.setRootDocFromName.should.have.been.calledWith(
this.project._id,
'main.tex'
)
})
- it('should remove the destination directory afterwards', function() {
+ it('should remove the destination directory afterwards', function () {
this.fs.remove.should.have.been.calledWith(this.extractedZipPath)
})
})
- describe("when the root document can't be determined", function() {
- beforeEach(async function() {
+ describe("when the root document can't be determined", function () {
+ beforeEach(async function () {
this.ProjectRootDocManager.promises.findRootDocFileFromDirectory.resolves(
{}
)
@@ -245,15 +245,15 @@ describe('ProjectUploadManager', function() {
)
})
- it('should not try to set the root doc', function() {
+ it('should not try to set the root doc', function () {
this.ProjectRootDocManager.promises.setRootDocFromName.should.not.have
.been.called
})
})
})
- describe('createProjectFromZipArchiveWithName', function() {
- beforeEach(async function() {
+ describe('createProjectFromZipArchiveWithName', function () {
+ beforeEach(async function () {
await this.ProjectUploadManager.promises.createProjectFromZipArchiveWithName(
this.ownerId,
this.projectName,
@@ -261,27 +261,27 @@ describe('ProjectUploadManager', function() {
)
})
- it('should extract the archive', function() {
+ it('should extract the archive', function () {
this.ArchiveManager.promises.extractZipArchive.should.have.been.calledWith(
this.zipPath,
this.extractedZipPath
)
})
- it('should create a project owned by the owner_id', function() {
+ it('should create a project owned by the owner_id', function () {
this.ProjectCreationHandler.promises.createBlankProject.should.have.been.calledWith(
this.ownerId,
this.uniqueProjectName
)
})
- it('should automatically set the root doc', function() {
+ it('should automatically set the root doc', function () {
this.ProjectRootDocManager.promises.setRootDocAutomatically.should.have.been.calledWith(
this.project._id
)
})
- it('should initialize the file tree', function() {
+ it('should initialize the file tree', function () {
this.ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure.should.have.been.calledWith(
this.project._id,
this.docEntries,
@@ -289,7 +289,7 @@ describe('ProjectUploadManager', function() {
)
})
- it('should notify document updater', function() {
+ it('should notify document updater', function () {
this.DocumentUpdaterHandler.promises.updateProjectStructure.should.have.been.calledWith(
this.project._id,
this.project.overleaf.history.id,
@@ -302,18 +302,18 @@ describe('ProjectUploadManager', function() {
)
})
- it('should flush the project to TPDS', function() {
+ it('should flush the project to TPDS', function () {
this.TpdsProjectFlusher.promises.flushProjectToTpds.should.have.been.calledWith(
this.project._id
)
})
- it('should remove the destination directory afterwards', function() {
+ it('should remove the destination directory afterwards', function () {
this.fs.remove.should.have.been.calledWith(this.extractedZipPath)
})
- describe('when initializing the folder structure fails', function() {
- beforeEach(async function() {
+ describe('when initializing the folder structure fails', function () {
+ beforeEach(async function () {
this.ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure.rejects()
await expect(
this.ProjectUploadManager.promises.createProjectFromZipArchiveWithName(
@@ -324,15 +324,15 @@ describe('ProjectUploadManager', function() {
).to.be.rejected
})
- it('should cleanup the blank project created', async function() {
+ it('should cleanup the blank project created', async function () {
this.ProjectDeleter.promises.deleteProject.should.have.been.calledWith(
this.project._id
)
})
})
- describe('when setting automatically the root doc fails', function() {
- beforeEach(async function() {
+ describe('when setting automatically the root doc fails', function () {
+ beforeEach(async function () {
this.ProjectRootDocManager.promises.setRootDocAutomatically.rejects()
await expect(
this.ProjectUploadManager.promises.createProjectFromZipArchiveWithName(
@@ -343,7 +343,7 @@ describe('ProjectUploadManager', function() {
).to.be.rejected
})
- it('should cleanup the blank project created', function() {
+ it('should cleanup the blank project created', function () {
this.ProjectDeleter.promises.deleteProject.should.have.been.calledWith(
this.project._id
)
diff --git a/services/web/test/unit/src/User/SAMLIdentityManagerTests.js b/services/web/test/unit/src/User/SAMLIdentityManagerTests.js
index 2ba8c677b8..969169e87b 100644
--- a/services/web/test/unit/src/User/SAMLIdentityManagerTests.js
+++ b/services/web/test/unit/src/User/SAMLIdentityManagerTests.js
@@ -5,10 +5,10 @@ const SandboxedModule = require('sandboxed-module')
const Errors = require('../../../../app/src/Features/Errors/Errors')
const modulePath = '../../../../app/src/Features/User/SAMLIdentityManager.js'
-describe('SAMLIdentityManager', function() {
+describe('SAMLIdentityManager', function () {
const linkedEmail = 'another@example.com'
- beforeEach(function() {
+ beforeEach(function () {
this.userId = '6005c75b12cbcaf771f4a105'
this.user = {
_id: this.userId,
@@ -97,8 +97,8 @@ describe('SAMLIdentityManager', function() {
})
})
- describe('getUser', function() {
- it('should throw an error if missing provider ID and/or external user ID', async function() {
+ describe('getUser', function () {
+ it('should throw an error if missing provider ID and/or external user ID', async function () {
let error
try {
await this.SAMLIdentityManager.getUser(null, null)
@@ -110,15 +110,15 @@ describe('SAMLIdentityManager', function() {
})
})
- describe('linkAccounts', function() {
- describe('errors', function() {
- beforeEach(function() {
+ describe('linkAccounts', function () {
+ describe('errors', function () {
+ beforeEach(function () {
// first call is to get userWithProvider; should be falsy
this.UserGetter.promises.getUser.onFirstCall().resolves()
this.UserGetter.promises.getUser.onSecondCall().resolves(this.user)
})
- it('should throw an error if missing data', async function() {
+ it('should throw an error if missing data', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
@@ -135,14 +135,14 @@ describe('SAMLIdentityManager', function() {
}
})
- describe('when email is already associated with another Overleaf account', function() {
- beforeEach(function() {
+ describe('when email is already associated with another Overleaf account', function () {
+ beforeEach(function () {
this.UserGetter.promises.getUserByAnyEmail.resolves(
this.userEmailExists
)
})
- it('should throw an EmailExistsError error', async function() {
+ it('should throw an EmailExistsError error', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
@@ -166,8 +166,8 @@ describe('SAMLIdentityManager', function() {
})
})
- describe('when email is not affiliated', function() {
- beforeEach(function() {
+ describe('when email is not affiliated', function () {
+ beforeEach(function () {
this.UserGetter.promises.getUserByAnyEmail.resolves(this.user)
this.UserGetter.promises.getUserFullEmails.resolves([
{
@@ -176,7 +176,7 @@ describe('SAMLIdentityManager', function() {
])
})
- it('should throw SAMLEmailNotAffiliatedError', async function() {
+ it('should throw SAMLEmailNotAffiliatedError', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
@@ -200,8 +200,8 @@ describe('SAMLIdentityManager', function() {
})
})
- describe('when email is affiliated with another institution', function() {
- beforeEach(function() {
+ describe('when email is affiliated with another institution', function () {
+ beforeEach(function () {
this.UserGetter.promises.getUserByAnyEmail.resolves(this.user)
this.UserGetter.promises.getUserFullEmails.resolves([
{
@@ -211,7 +211,7 @@ describe('SAMLIdentityManager', function() {
])
})
- it('should throw SAMLEmailAffiliatedWithAnotherInstitutionError', async function() {
+ it('should throw SAMLEmailAffiliatedWithAnotherInstitutionError', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
@@ -237,14 +237,14 @@ describe('SAMLIdentityManager', function() {
})
})
- describe('when institution identifier is already associated with another Overleaf account', function() {
- beforeEach(function() {
+ describe('when institution identifier is already associated with another Overleaf account', function () {
+ beforeEach(function () {
this.UserGetter.promises.getUserByAnyEmail.resolves(
this.userAlreadyLinked
)
})
- it('should throw an SAMLIdentityExistsError error', async function() {
+ it('should throw an SAMLIdentityExistsError error', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
@@ -268,13 +268,13 @@ describe('SAMLIdentityManager', function() {
})
})
- describe('when institution provider is already associated with the user', function() {
- beforeEach(function() {
+ describe('when institution provider is already associated with the user', function () {
+ beforeEach(function () {
// first call is to get userWithProvider; resolves with any user
this.UserGetter.promises.getUser.onFirstCall().resolves(this.user)
})
- it('should throw an SAMLAlreadyLinkedError error', async function() {
+ it('should throw an SAMLAlreadyLinkedError error', async function () {
let error
try {
await this.SAMLIdentityManager.linkAccounts(
@@ -304,7 +304,7 @@ describe('SAMLIdentityManager', function() {
})
})
- it('should pass back errors via UserAuditLogHandler', async function() {
+ it('should pass back errors via UserAuditLogHandler', async function () {
let error
const anError = new Error('oops')
this.UserAuditLogHandler.promises.addEntry.rejects(anError)
@@ -332,14 +332,14 @@ describe('SAMLIdentityManager', function() {
})
})
- describe('success', function() {
- beforeEach(function() {
+ describe('success', function () {
+ beforeEach(function () {
// first call is to get userWithProvider; should be falsy
this.UserGetter.promises.getUser.onFirstCall().resolves()
this.UserGetter.promises.getUser.onSecondCall().resolves(this.user)
})
- it('should update the user audit log', function() {
+ it('should update the user audit log', function () {
const auditLog = {
intiatorId: '6005c75b12cbcaf771f4a105',
ip: '0:0:0:0'
@@ -370,7 +370,7 @@ describe('SAMLIdentityManager', function() {
)
})
- it('should send an email notification', function() {
+ it('should send an email notification', function () {
this.SAMLIdentityManager.linkAccounts(
this.user._id,
'externalUserId',
@@ -397,8 +397,8 @@ describe('SAMLIdentityManager', function() {
})
})
- describe('unlinkAccounts', function() {
- it('should update the audit log', async function() {
+ describe('unlinkAccounts', function () {
+ it('should update the audit log', async function () {
await this.SAMLIdentityManager.unlinkAccounts(
this.user._id,
linkedEmail,
@@ -421,7 +421,7 @@ describe('SAMLIdentityManager', function() {
}
)
})
- it('should remove the identifier', async function() {
+ it('should remove the identifier', async function () {
await this.SAMLIdentityManager.unlinkAccounts(
this.user._id,
linkedEmail,
@@ -445,7 +445,7 @@ describe('SAMLIdentityManager', function() {
update
)
})
- it('should send an email notification', async function() {
+ it('should send an email notification', async function () {
await this.SAMLIdentityManager.unlinkAccounts(
this.user._id,
linkedEmail,
@@ -464,8 +464,8 @@ describe('SAMLIdentityManager', function() {
expect(emailArgs[1].message[0]).to.contain(linkedEmail)
})
- describe('errors', function() {
- it('should pass back errors via UserAuditLogHandler', async function() {
+ describe('errors', function () {
+ it('should pass back errors via UserAuditLogHandler', async function () {
let error
const anError = new Error('oops')
this.UserAuditLogHandler.promises.addEntry.rejects(anError)
@@ -490,43 +490,43 @@ describe('SAMLIdentityManager', function() {
})
})
- describe('entitlementAttributeMatches', function() {
- it('should return true when entitlement matches on string', function() {
+ describe('entitlementAttributeMatches', function () {
+ it('should return true when entitlement matches on string', function () {
this.SAMLIdentityManager.entitlementAttributeMatches(
'foo bar',
'bar'
).should.equal(true)
})
- it('should return false when entitlement does not match on string', function() {
+ it('should return false when entitlement does not match on string', function () {
this.SAMLIdentityManager.entitlementAttributeMatches(
'foo bar',
'bam'
).should.equal(false)
})
- it('should return false on an invalid matcher', function() {
+ it('should return false on an invalid matcher', function () {
this.SAMLIdentityManager.entitlementAttributeMatches(
'foo bar',
'('
).should.equal(false)
})
- it('should log error on an invalid matcher', function() {
+ it('should log error on an invalid matcher', function () {
this.SAMLIdentityManager.entitlementAttributeMatches('foo bar', '(')
this.logger.error.firstCall.args[0].err.message.should.equal(
'Invalid regular expression: /(/: Unterminated group'
)
})
- it('should return true when entitlement matches on array', function() {
+ it('should return true when entitlement matches on array', function () {
this.SAMLIdentityManager.entitlementAttributeMatches(
['foo', 'bar'],
'bar'
).should.equal(true)
})
- it('should return false when entitlement does not match array', function() {
+ it('should return false when entitlement does not match array', function () {
this.SAMLIdentityManager.entitlementAttributeMatches(
['foo', 'bar'],
'bam'
@@ -534,19 +534,19 @@ describe('SAMLIdentityManager', function() {
})
})
- describe('redundantSubscription', function() {
+ describe('redundantSubscription', function () {
const userId = '1bv'
const providerId = 123
const providerName = 'University Name'
- describe('with a personal subscription', function() {
- beforeEach(function() {
+ describe('with a personal subscription', function () {
+ beforeEach(function () {
this.SubscriptionLocator.promises.getUserIndividualSubscription.resolves(
{
planCode: 'professional'
}
)
})
- it('should create redundant personal subscription notification ', async function() {
+ it('should create redundant personal subscription notification ', async function () {
try {
await this.SAMLIdentityManager.redundantSubscription(
userId,
@@ -560,8 +560,8 @@ describe('SAMLIdentityManager', function() {
.to.have.been.calledOnce
})
})
- describe('without a personal subscription', function() {
- it('should create redundant personal subscription notification ', async function() {
+ describe('without a personal subscription', function () {
+ it('should create redundant personal subscription notification ', async function () {
try {
await this.SAMLIdentityManager.redundantSubscription(
userId,
diff --git a/services/web/test/unit/src/User/ThirdPartyIdentityManagerTests.js b/services/web/test/unit/src/User/ThirdPartyIdentityManagerTests.js
index cdef2b2182..317bbceea2 100644
--- a/services/web/test/unit/src/User/ThirdPartyIdentityManagerTests.js
+++ b/services/web/test/unit/src/User/ThirdPartyIdentityManagerTests.js
@@ -4,8 +4,8 @@ const SandboxedModule = require('sandboxed-module')
const modulePath =
'../../../../app/src/Features/User/ThirdPartyIdentityManager.js'
-describe('ThirdPartyIdentityManager', function() {
- beforeEach(function() {
+describe('ThirdPartyIdentityManager', function () {
+ beforeEach(function () {
this.userId = 'a1b2c3'
this.user = {
_id: this.userId,
@@ -41,8 +41,8 @@ describe('ThirdPartyIdentityManager', function() {
}
})
})
- describe('getUser', function() {
- it('should an error when missing providerId or externalUserId', function(done) {
+ describe('getUser', function () {
+ it('should an error when missing providerId or externalUserId', function (done) {
this.ThirdPartyIdentityManager.getUser(
undefined,
undefined,
@@ -57,12 +57,12 @@ describe('ThirdPartyIdentityManager', function() {
}
)
})
- describe('when user linked', function() {
- beforeEach(function() {
+ describe('when user linked', function () {
+ beforeEach(function () {
this.User.findOne.yields(undefined, this.user)
})
- it('should return the user', async function() {
+ it('should return the user', async function () {
this.User.findOne.returns(undefined, this.user)
const user = await this.ThirdPartyIdentityManager.promises.getUser(
'google',
@@ -71,7 +71,7 @@ describe('ThirdPartyIdentityManager', function() {
expect(user).to.deep.equal(this.user)
})
})
- it('should return ThirdPartyUserNotFoundError when no user linked', function(done) {
+ it('should return ThirdPartyUserNotFoundError when no user linked', function (done) {
this.ThirdPartyIdentityManager.getUser(
'google',
'an-id-not-linked',
@@ -83,8 +83,8 @@ describe('ThirdPartyIdentityManager', function() {
)
})
})
- describe('link', function() {
- it('should send email alert', async function() {
+ describe('link', function () {
+ it('should send email alert', async function () {
await this.ThirdPartyIdentityManager.promises.link(
this.userId,
'google',
@@ -99,7 +99,7 @@ describe('ThirdPartyIdentityManager', function() {
)
})
- it('should update user audit log', async function() {
+ it('should update user audit log', async function () {
await this.ThirdPartyIdentityManager.promises.link(
this.userId,
'google',
@@ -117,9 +117,9 @@ describe('ThirdPartyIdentityManager', function() {
}
)
})
- describe('errors', function() {
+ describe('errors', function () {
const anError = new Error('oops')
- it('should not unlink if the UserAuditLogHandler throws an error', function(done) {
+ it('should not unlink if the UserAuditLogHandler throws an error', function (done) {
this.UserAuditLogHandler.addEntry.yields(anError)
this.ThirdPartyIdentityManager.link(
this.userId,
@@ -135,11 +135,11 @@ describe('ThirdPartyIdentityManager', function() {
}
)
})
- describe('EmailHandler', function() {
- beforeEach(function() {
+ describe('EmailHandler', function () {
+ beforeEach(function () {
this.EmailHandler.sendEmail.yields(anError)
})
- it('should log but not return the error', function(done) {
+ it('should log but not return the error', function (done) {
this.ThirdPartyIdentityManager.link(
this.userId,
'google',
@@ -162,8 +162,8 @@ describe('ThirdPartyIdentityManager', function() {
})
})
})
- describe('unlink', function() {
- it('should send email alert', async function() {
+ describe('unlink', function () {
+ it('should send email alert', async function () {
await this.ThirdPartyIdentityManager.promises.unlink(
this.userId,
'orcid',
@@ -175,7 +175,7 @@ describe('ThirdPartyIdentityManager', function() {
'an Orcid account was unlinked from'
)
})
- it('should update user audit log', async function() {
+ it('should update user audit log', async function () {
await this.ThirdPartyIdentityManager.promises.unlink(
this.userId,
'orcid',
@@ -191,9 +191,9 @@ describe('ThirdPartyIdentityManager', function() {
}
)
})
- describe('errors', function() {
+ describe('errors', function () {
const anError = new Error('oops')
- it('should not unlink if the UserAuditLogHandler throws an error', function(done) {
+ it('should not unlink if the UserAuditLogHandler throws an error', function (done) {
this.UserAuditLogHandler.addEntry.yields(anError)
this.ThirdPartyIdentityManager.unlink(
this.userId,
@@ -208,11 +208,11 @@ describe('ThirdPartyIdentityManager', function() {
)
expect(this.User.findOneAndUpdate).to.not.have.been.called
})
- describe('EmailHandler', function() {
- beforeEach(function() {
+ describe('EmailHandler', function () {
+ beforeEach(function () {
this.EmailHandler.sendEmail.yields(anError)
})
- it('should log but not return the error', function(done) {
+ it('should log but not return the error', function (done) {
this.ThirdPartyIdentityManager.unlink(
this.userId,
'google',
diff --git a/services/web/test/unit/src/User/UserAuditLogHandlerTests.js b/services/web/test/unit/src/User/UserAuditLogHandlerTests.js
index 0fb707d650..d37ab18337 100644
--- a/services/web/test/unit/src/User/UserAuditLogHandlerTests.js
+++ b/services/web/test/unit/src/User/UserAuditLogHandlerTests.js
@@ -6,8 +6,8 @@ const { User } = require('../helpers/models/User')
const MODULE_PATH = '../../../../app/src/Features/User/UserAuditLogHandler'
-describe('UserAuditLogHandler', function() {
- beforeEach(function() {
+describe('UserAuditLogHandler', function () {
+ beforeEach(function () {
this.userId = ObjectId()
this.initiatorId = ObjectId()
this.action = {
@@ -31,18 +31,18 @@ describe('UserAuditLogHandler', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
this.UserMock.restore()
})
- describe('addEntry', function() {
- describe('success', function() {
- beforeEach(function() {
+ describe('addEntry', function () {
+ describe('success', function () {
+ beforeEach(function () {
this.dbUpdate = this.UserMock.expects('updateOne')
.chain('exec')
.resolves({ nModified: 1 })
})
- it('writes a log', async function() {
+ it('writes a log', async function () {
await this.UserAuditLogHandler.promises.addEntry(
this.userId,
this.action.operation,
@@ -53,7 +53,7 @@ describe('UserAuditLogHandler', function() {
this.UserMock.verify()
})
- it('updates the log for password reset operation witout a initiatorId', async function() {
+ it('updates the log for password reset operation witout a initiatorId', async function () {
await expect(
this.UserAuditLogHandler.promises.addEntry(
this.userId,
@@ -67,15 +67,15 @@ describe('UserAuditLogHandler', function() {
})
})
- describe('errors', function() {
- describe('when the user does not exist', function() {
- beforeEach(function() {
+ describe('errors', function () {
+ describe('when the user does not exist', function () {
+ beforeEach(function () {
this.UserMock.expects('updateOne')
.chain('exec')
.resolves({ nModified: 0 })
})
- it('throws an error', async function() {
+ it('throws an error', async function () {
await expect(
this.UserAuditLogHandler.promises.addEntry(
this.userId,
@@ -88,8 +88,8 @@ describe('UserAuditLogHandler', function() {
})
})
- describe('missing parameters', function() {
- it('throws an error when no operation', async function() {
+ describe('missing parameters', function () {
+ it('throws an error when no operation', async function () {
await expect(
this.UserAuditLogHandler.promises.addEntry(
this.userId,
@@ -101,7 +101,7 @@ describe('UserAuditLogHandler', function() {
).to.be.rejected
})
- it('throws an error when no IP', async function() {
+ it('throws an error when no IP', async function () {
await expect(
this.UserAuditLogHandler.promises.addEntry(
this.userId,
@@ -113,7 +113,7 @@ describe('UserAuditLogHandler', function() {
).to.be.rejected
})
- it('throws an error when no initiatorId and not a password reset operation', async function() {
+ it('throws an error when no initiatorId and not a password reset operation', async function () {
await expect(
this.UserAuditLogHandler.promises.addEntry(
this.userId,
diff --git a/services/web/test/unit/src/User/UserControllerTests.js b/services/web/test/unit/src/User/UserControllerTests.js
index 9ef829f4db..7c1a57e437 100644
--- a/services/web/test/unit/src/User/UserControllerTests.js
+++ b/services/web/test/unit/src/User/UserControllerTests.js
@@ -5,8 +5,8 @@ const SandboxedModule = require('sandboxed-module')
const OError = require('@overleaf/o-error')
const Errors = require('../../../../app/src/Features/Errors/Errors')
-describe('UserController', function() {
- beforeEach(function() {
+describe('UserController', function () {
+ beforeEach(function () {
this.user_id = '323123'
this.user = {
@@ -137,8 +137,8 @@ describe('UserController', function() {
this.callback = sinon.stub()
})
- describe('tryDeleteUser', function() {
- beforeEach(function() {
+ describe('tryDeleteUser', function () {
+ beforeEach(function () {
this.req.body.password = 'wat'
this.req.logout = sinon.stub()
this.req.session.destroy = sinon.stub().callsArgWith(0, null)
@@ -150,7 +150,7 @@ describe('UserController', function() {
.callsArgWith(2, null, this.user)
})
- it('should send 200', function(done) {
+ it('should send 200', function (done) {
this.res.sendStatus = code => {
code.should.equal(200)
done()
@@ -158,7 +158,7 @@ describe('UserController', function() {
this.UserController.tryDeleteUser(this.req, this.res, this.next)
})
- it('should try to authenticate user', function(done) {
+ it('should try to authenticate user', function (done) {
this.res.sendStatus = code => {
this.AuthenticationManager.authenticate.callCount.should.equal(1)
this.AuthenticationManager.authenticate
@@ -169,7 +169,7 @@ describe('UserController', function() {
this.UserController.tryDeleteUser(this.req, this.res, this.next)
})
- it('should delete the user', function(done) {
+ it('should delete the user', function (done) {
this.res.sendStatus = code => {
this.UserDeleter.deleteUser.callCount.should.equal(1)
this.UserDeleter.deleteUser.calledWith(this.user._id).should.equal(true)
@@ -178,12 +178,12 @@ describe('UserController', function() {
this.UserController.tryDeleteUser(this.req, this.res, this.next)
})
- describe('when no password is supplied', function() {
- beforeEach(function() {
+ describe('when no password is supplied', function () {
+ beforeEach(function () {
this.req.body.password = ''
})
- it('should return 403', function(done) {
+ it('should return 403', function (done) {
this.res.sendStatus = code => {
code.should.equal(403)
done()
@@ -192,14 +192,14 @@ describe('UserController', function() {
})
})
- describe('when authenticate produces an error', function() {
- beforeEach(function() {
+ describe('when authenticate produces an error', function () {
+ beforeEach(function () {
this.AuthenticationManager.authenticate = sinon
.stub()
.callsArgWith(2, new Error('woops'))
})
- it('should call next with an error', function(done) {
+ it('should call next with an error', function (done) {
this.next = err => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -209,14 +209,14 @@ describe('UserController', function() {
})
})
- describe('when authenticate does not produce a user', function() {
- beforeEach(function() {
+ describe('when authenticate does not produce a user', function () {
+ beforeEach(function () {
this.AuthenticationManager.authenticate = sinon
.stub()
.callsArgWith(2, null, null)
})
- it('should return 403', function(done) {
+ it('should return 403', function (done) {
this.res.sendStatus = code => {
code.should.equal(403)
done()
@@ -225,12 +225,12 @@ describe('UserController', function() {
})
})
- describe('when deleteUser produces an error', function() {
- beforeEach(function() {
+ describe('when deleteUser produces an error', function () {
+ beforeEach(function () {
this.UserDeleter.deleteUser = sinon.stub().yields(new Error('woops'))
})
- it('should call next with an error', function(done) {
+ it('should call next with an error', function (done) {
this.next = err => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -240,14 +240,14 @@ describe('UserController', function() {
})
})
- describe('when deleteUser produces a known error', function() {
- beforeEach(function() {
+ describe('when deleteUser produces a known error', function () {
+ beforeEach(function () {
this.UserDeleter.deleteUser = sinon
.stub()
.yields(new Errors.SubscriptionAdminDeletionError())
})
- it('should return a HTTP Unprocessable Entity error', function(done) {
+ it('should return a HTTP Unprocessable Entity error', function (done) {
this.HttpErrorHandler.unprocessableEntity = sinon.spy(
(req, res, message, info) => {
expect(req).to.exist
@@ -263,14 +263,14 @@ describe('UserController', function() {
})
})
- describe('when session.destroy produces an error', function() {
- beforeEach(function() {
+ describe('when session.destroy produces an error', function () {
+ beforeEach(function () {
this.req.session.destroy = sinon
.stub()
.callsArgWith(0, new Error('woops'))
})
- it('should call next with an error', function(done) {
+ it('should call next with an error', function (done) {
this.next = err => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -281,8 +281,8 @@ describe('UserController', function() {
})
})
- describe('unsubscribe', function() {
- it('should send the user to unsubscribe', function(done) {
+ describe('unsubscribe', function () {
+ it('should send the user to unsubscribe', function (done) {
this.res.sendStatus = () => {
this.NewsLetterManager.unsubscribe
.calledWith(this.user)
@@ -293,14 +293,14 @@ describe('UserController', function() {
})
})
- describe('updateUserSettings', function() {
- beforeEach(function() {
+ describe('updateUserSettings', function () {
+ beforeEach(function () {
this.auditLog = { initiatorId: this.user_id, ipAddress: this.req.ip }
this.newEmail = 'hello@world.com'
this.req.externalAuthenticationSystemUsed = sinon.stub().returns(false)
})
- it('should call save', function(done) {
+ it('should call save', function (done) {
this.req.body = {}
this.res.sendStatus = code => {
this.user.save.called.should.equal(true)
@@ -309,7 +309,7 @@ describe('UserController', function() {
this.UserController.updateUserSettings(this.req, this.res)
})
- it('should set the first name', function(done) {
+ it('should set the first name', function (done) {
this.req.body = { first_name: 'bobby ' }
this.res.sendStatus = code => {
this.user.first_name.should.equal('bobby')
@@ -318,7 +318,7 @@ describe('UserController', function() {
this.UserController.updateUserSettings(this.req, this.res)
})
- it('should set the role', function(done) {
+ it('should set the role', function (done) {
this.req.body = { role: 'student' }
this.res.sendStatus = code => {
this.user.role.should.equal('student')
@@ -327,7 +327,7 @@ describe('UserController', function() {
this.UserController.updateUserSettings(this.req, this.res)
})
- it('should set the institution', function(done) {
+ it('should set the institution', function (done) {
this.req.body = { institution: 'MIT' }
this.res.sendStatus = code => {
this.user.institution.should.equal('MIT')
@@ -336,7 +336,7 @@ describe('UserController', function() {
this.UserController.updateUserSettings(this.req, this.res)
})
- it('should set some props on ace', function(done) {
+ it('should set some props on ace', function (done) {
this.req.body = { editorTheme: 'something' }
this.res.sendStatus = code => {
this.user.ace.theme.should.equal('something')
@@ -345,7 +345,7 @@ describe('UserController', function() {
this.UserController.updateUserSettings(this.req, this.res)
})
- it('should set the overall theme', function(done) {
+ it('should set the overall theme', function (done) {
this.req.body = { overallTheme: 'green-ish' }
this.res.sendStatus = code => {
this.user.ace.overallTheme.should.equal('green-ish')
@@ -354,25 +354,25 @@ describe('UserController', function() {
this.UserController.updateUserSettings(this.req, this.res)
})
- it('should send an error if the email is 0 len', function(done) {
+ it('should send an error if the email is 0 len', function (done) {
this.req.body.email = ''
- this.res.sendStatus = function(code) {
+ this.res.sendStatus = function (code) {
code.should.equal(400)
done()
}
this.UserController.updateUserSettings(this.req, this.res)
})
- it('should send an error if the email does not contain an @', function(done) {
+ it('should send an error if the email does not contain an @', function (done) {
this.req.body.email = 'bob at something dot com'
- this.res.sendStatus = function(code) {
+ this.res.sendStatus = function (code) {
code.should.equal(400)
done()
}
this.UserController.updateUserSettings(this.req, this.res)
})
- it('should call the user updater with the new email and user _id', function(done) {
+ it('should call the user updater with the new email and user _id', function (done) {
this.req.body.email = this.newEmail.toUpperCase()
this.UserUpdater.changeEmailAddress.callsArgWith(3)
this.res.sendStatus = code => {
@@ -385,7 +385,7 @@ describe('UserController', function() {
this.UserController.updateUserSettings(this.req, this.res)
})
- it('should update the email on the session', function(done) {
+ it('should update the email on the session', function (done) {
this.req.body.email = this.newEmail.toUpperCase()
this.UserUpdater.changeEmailAddress.callsArgWith(3)
let callcount = 0
@@ -409,7 +409,7 @@ describe('UserController', function() {
this.UserController.updateUserSettings(this.req, this.res)
})
- it('should call populateTeamInvites', function(done) {
+ it('should call populateTeamInvites', function (done) {
this.req.body.email = this.newEmail.toUpperCase()
this.UserUpdater.changeEmailAddress.callsArgWith(3)
this.res.sendStatus = code => {
@@ -422,8 +422,8 @@ describe('UserController', function() {
this.UserController.updateUserSettings(this.req, this.res)
})
- describe('when changeEmailAddress yields an error', function() {
- it('should pass on an error and not send a success status', function(done) {
+ describe('when changeEmailAddress yields an error', function () {
+ it('should pass on an error and not send a success status', function (done) {
this.req.body.email = this.newEmail.toUpperCase()
this.UserUpdater.changeEmailAddress.callsArgWith(3, new OError())
this.HttpErrorHandler.legacyInternal = sinon.spy(
@@ -438,7 +438,7 @@ describe('UserController', function() {
this.UserController.updateUserSettings(this.req, this.res, this.next)
})
- it('should call the HTTP conflict error handler when the email already exists', function(done) {
+ it('should call the HTTP conflict error handler when the email already exists', function (done) {
this.HttpErrorHandler.conflict = sinon.spy((req, res, message) => {
expect(req).to.exist
expect(req).to.exist
@@ -454,14 +454,14 @@ describe('UserController', function() {
})
})
- describe('when using an external auth source', function() {
- beforeEach(function() {
+ describe('when using an external auth source', function () {
+ beforeEach(function () {
this.UserUpdater.changeEmailAddress.callsArgWith(2)
this.newEmail = 'someone23@example.com'
this.req.externalAuthenticationSystemUsed = sinon.stub().returns(true)
})
- it('should not set a new email', function(done) {
+ it('should not set a new email', function (done) {
this.req.body.email = this.newEmail
this.res.sendStatus = code => {
code.should.equal(200)
@@ -475,8 +475,8 @@ describe('UserController', function() {
})
})
- describe('logout', function() {
- it('should destroy the session', function(done) {
+ describe('logout', function () {
+ it('should destroy the session', function (done) {
this.req.session.destroy = sinon.stub().callsArgWith(0)
this.res.redirect = url => {
url.should.equal('/login')
@@ -487,7 +487,7 @@ describe('UserController', function() {
this.UserController.logout(this.req, this.res)
})
- it('should untrack session', function(done) {
+ it('should untrack session', function (done) {
this.req.session.destroy = sinon.stub().callsArgWith(0)
this.res.redirect = url => {
url.should.equal('/login')
@@ -501,7 +501,7 @@ describe('UserController', function() {
this.UserController.logout(this.req, this.res)
})
- it('should redirect after logout', function(done) {
+ it('should redirect after logout', function (done) {
this.req.body.redirect = '/institutional-login'
this.req.session.destroy = sinon.stub().callsArgWith(0)
this.res.redirect = url => {
@@ -511,7 +511,7 @@ describe('UserController', function() {
this.UserController.logout(this.req, this.res)
})
- it('should redirect after logout, but not to evil.com', function(done) {
+ it('should redirect after logout, but not to evil.com', function (done) {
this.req.body.redirect = 'https://evil.com'
this.req.session.destroy = sinon.stub().callsArgWith(0)
this.res.redirect = url => {
@@ -521,7 +521,7 @@ describe('UserController', function() {
this.UserController.logout(this.req, this.res)
})
- it('should redirect to login after logout when no redirect set', function(done) {
+ it('should redirect to login after logout when no redirect set', function (done) {
this.req.session.destroy = sinon.stub().callsArgWith(0)
this.res.redirect = url => {
url.should.equal('/login')
@@ -531,8 +531,8 @@ describe('UserController', function() {
})
})
- describe('register', function() {
- beforeEach(function() {
+ describe('register', function () {
+ beforeEach(function () {
this.UserRegistrationHandler.registerNewUserAndSendActivationEmail = sinon
.stub()
.callsArgWith(1, null, this.user, (this.url = 'mock/url'))
@@ -540,13 +540,13 @@ describe('UserController', function() {
this.UserController.register(this.req, this.res)
})
- it('should register the user and send them an email', function() {
+ it('should register the user and send them an email', function () {
this.UserRegistrationHandler.registerNewUserAndSendActivationEmail
.calledWith(this.email)
.should.equal(true)
})
- it('should return the user and activation url', function() {
+ it('should return the user and activation url', function () {
this.res.json
.calledWith({
email: this.email,
@@ -556,9 +556,9 @@ describe('UserController', function() {
})
})
- describe('clearSessions', function() {
- describe('success', function() {
- it('should call revokeAllUserSessions', function(done) {
+ describe('clearSessions', function () {
+ describe('success', function () {
+ it('should call revokeAllUserSessions', function (done) {
this.res.sendStatus.callsFake(() => {
this.UserSessionsManager.promises.revokeAllUserSessions.callCount.should.equal(
1
@@ -568,7 +568,7 @@ describe('UserController', function() {
this.UserController.clearSessions(this.req, this.res)
})
- it('send a 201 response', function(done) {
+ it('send a 201 response', function (done) {
this.res.sendStatus.callsFake(status => {
status.should.equal(201)
done()
@@ -577,7 +577,7 @@ describe('UserController', function() {
this.UserController.clearSessions(this.req, this.res)
})
- it('sends a security alert email', function(done) {
+ it('sends a security alert email', function (done) {
this.res.sendStatus.callsFake(status => {
this.EmailHandler.promises.sendEmail.callCount.should.equal(1)
const expectedArg = {
@@ -595,9 +595,9 @@ describe('UserController', function() {
})
})
- describe('errors', function() {
- describe('when getAllUserSessions produces an error', function() {
- it('should return an error', function(done) {
+ describe('errors', function () {
+ describe('when getAllUserSessions produces an error', function () {
+ it('should return an error', function (done) {
this.UserSessionsManager.promises.getAllUserSessions.rejects(
new Error('woops')
)
@@ -608,8 +608,8 @@ describe('UserController', function() {
})
})
- describe('when audit log addEntry produces an error', function() {
- it('should call next with an error', function(done) {
+ describe('when audit log addEntry produces an error', function () {
+ it('should call next with an error', function (done) {
this.UserAuditLogHandler.promises.addEntry.rejects(new Error('woops'))
this.UserController.clearSessions(this.req, this.res, error => {
expect(error).to.be.instanceof(Error)
@@ -618,8 +618,8 @@ describe('UserController', function() {
})
})
- describe('when revokeAllUserSessions produces an error', function() {
- it('should call next with an error', function(done) {
+ describe('when revokeAllUserSessions produces an error', function () {
+ it('should call next with an error', function (done) {
this.UserSessionsManager.promises.revokeAllUserSessions.rejects(
new Error('woops')
)
@@ -630,9 +630,9 @@ describe('UserController', function() {
})
})
- describe('when EmailHandler produces an error', function() {
+ describe('when EmailHandler produces an error', function () {
const anError = new Error('oops')
- it('send a 201 response but log error', function(done) {
+ it('send a 201 response but log error', function (done) {
this.EmailHandler.promises.sendEmail.rejects(anError)
this.res.sendStatus.callsFake(status => {
status.should.equal(201)
@@ -653,9 +653,9 @@ describe('UserController', function() {
})
})
- describe('changePassword', function() {
- describe('success', function() {
- beforeEach(function() {
+ describe('changePassword', function () {
+ describe('success', function () {
+ beforeEach(function () {
this.AuthenticationManager.promises.authenticate.resolves(this.user)
this.AuthenticationManager.promises.setUserPassword.resolves()
this.req.body = {
@@ -663,7 +663,7 @@ describe('UserController', function() {
newPassword2: 'newpass'
}
})
- it('should set the new password if they do match', function(done) {
+ it('should set the new password if they do match', function (done) {
this.res.json.callsFake(() => {
this.AuthenticationManager.promises.setUserPassword.should.have.been.calledWith(
this.user,
@@ -674,7 +674,7 @@ describe('UserController', function() {
this.UserController.changePassword(this.req, this.res)
})
- it('should log the update', function(done) {
+ it('should log the update', function (done) {
this.res.json.callsFake(() => {
this.UserAuditLogHandler.promises.addEntry.should.have.been.calledWith(
this.user._id,
@@ -690,7 +690,7 @@ describe('UserController', function() {
this.UserController.changePassword(this.req, this.res)
})
- it('should send security alert email', function(done) {
+ it('should send security alert email', function (done) {
this.res.json.callsFake(() => {
const expectedArg = {
to: this.user.email,
@@ -706,8 +706,8 @@ describe('UserController', function() {
})
})
- describe('errors', function() {
- it('should check the old password is the current one at the moment', function(done) {
+ describe('errors', function () {
+ it('should check the old password is the current one at the moment', function (done) {
this.AuthenticationManager.promises.authenticate.resolves()
this.req.body = { currentPassword: 'oldpasshere' }
this.HttpErrorHandler.badRequest.callsFake(() => {
@@ -728,7 +728,7 @@ describe('UserController', function() {
this.UserController.changePassword(this.req, this.res)
})
- it('it should not set the new password if they do not match', function(done) {
+ it('it should not set the new password if they do not match', function (done) {
this.AuthenticationManager.promises.authenticate.resolves({})
this.req.body = {
newPassword1: '1',
@@ -748,7 +748,7 @@ describe('UserController', function() {
this.UserController.changePassword(this.req, this.res)
})
- it('it should not set the new password if it is invalid', function(done) {
+ it('it should not set the new password if it is invalid', function (done) {
// this.AuthenticationManager.validatePassword = sinon
// .stub()
// .returns({ message: 'validation-error' })
@@ -774,8 +774,8 @@ describe('UserController', function() {
this.UserController.changePassword(this.req, this.res)
})
- describe('UserAuditLogHandler error', function() {
- it('should return error and not update password', function(done) {
+ describe('UserAuditLogHandler error', function () {
+ it('should return error and not update password', function (done) {
this.UserAuditLogHandler.promises.addEntry.rejects(new Error('oops'))
this.AuthenticationManager.promises.authenticate.resolves(this.user)
this.AuthenticationManager.promises.setUserPassword.resolves()
@@ -794,9 +794,9 @@ describe('UserController', function() {
})
})
- describe('EmailHandler error', function() {
+ describe('EmailHandler error', function () {
const anError = new Error('oops')
- beforeEach(function() {
+ beforeEach(function () {
this.AuthenticationManager.promises.authenticate.resolves(this.user)
this.AuthenticationManager.promises.setUserPassword.resolves()
this.req.body = {
@@ -805,7 +805,7 @@ describe('UserController', function() {
}
this.EmailHandler.sendEmail.yields(anError)
})
- it('should not return error but should log it', function(done) {
+ it('should not return error but should log it', function (done) {
this.res.json.callsFake(result => {
expect(result.message.type).to.equal('success')
this.logger.error.callCount.should.equal(1)
@@ -824,27 +824,27 @@ describe('UserController', function() {
})
})
- describe('ensureAffiliationMiddleware', function() {
- describe('without affiliations feature', function() {
- beforeEach(async function() {
+ describe('ensureAffiliationMiddleware', function () {
+ describe('without affiliations feature', function () {
+ beforeEach(async function () {
await this.UserController.promises.ensureAffiliationMiddleware(
this.req,
this.res,
this.next
)
})
- it('should not run affiliation check', function() {
+ it('should not run affiliation check', function () {
expect(this.UserGetter.promises.getUser).to.not.have.been.called
expect(this.UserUpdater.promises.confirmEmail).to.not.have.been.called
expect(this.UserUpdater.promises.addAffiliationForNewUser).to.not.have
.been.called
})
- it('should not return an error', function() {
+ it('should not return an error', function () {
expect(this.next).to.be.calledWith()
})
})
- describe('without ensureAffiliation query parameter', function() {
- beforeEach(async function() {
+ describe('without ensureAffiliation query parameter', function () {
+ beforeEach(async function () {
this.Features.hasFeature.withArgs('affiliations').returns(true)
await this.UserController.promises.ensureAffiliationMiddleware(
this.req,
@@ -852,18 +852,18 @@ describe('UserController', function() {
this.next
)
})
- it('should not run middleware', function() {
+ it('should not run middleware', function () {
expect(this.UserGetter.promises.getUser).to.not.have.been.called
expect(this.UserUpdater.promises.confirmEmail).to.not.have.been.called
expect(this.UserUpdater.promises.addAffiliationForNewUser).to.not.have
.been.called
})
- it('should not return an error', function() {
+ it('should not return an error', function () {
expect(this.next).to.be.calledWith()
})
})
- describe('no flagged email', function() {
- beforeEach(async function() {
+ describe('no flagged email', function () {
+ beforeEach(async function () {
const email = 'unit-test@overleaf.com'
this.user.email = email
this.user.emails = [
@@ -879,22 +879,22 @@ describe('UserController', function() {
this.next
)
})
- it('should get the user', function() {
+ it('should get the user', function () {
expect(this.UserGetter.promises.getUser).to.have.been.calledWith(
this.user._id
)
})
- it('should not try to add affiliation or update user', function() {
+ it('should not try to add affiliation or update user', function () {
expect(this.UserUpdater.promises.addAffiliationForNewUser).to.not.have
.been.called
})
- it('should not return an error', function() {
+ it('should not return an error', function () {
expect(this.next).to.be.calledWith()
})
})
- describe('flagged non-SSO email', function() {
+ describe('flagged non-SSO email', function () {
let emailFlagged
- beforeEach(async function() {
+ beforeEach(async function () {
emailFlagged = 'flagged@overleaf.com'
this.user.email = emailFlagged
this.user.emails = [
@@ -911,7 +911,7 @@ describe('UserController', function() {
this.next
)
})
- it('should unflag the emails but not confirm', function() {
+ it('should unflag the emails but not confirm', function () {
expect(
this.UserUpdater.promises.addAffiliationForNewUser
).to.have.been.calledWith(this.user._id, emailFlagged)
@@ -919,13 +919,13 @@ describe('UserController', function() {
this.UserUpdater.promises.confirmEmail
).to.not.have.been.calledWith(this.user._id, emailFlagged)
})
- it('should not return an error', function() {
+ it('should not return an error', function () {
expect(this.next).to.be.calledWith()
})
})
- describe('flagged SSO email', function() {
+ describe('flagged SSO email', function () {
let emailFlagged
- beforeEach(async function() {
+ beforeEach(async function () {
emailFlagged = 'flagged@overleaf.com'
this.user.email = emailFlagged
this.user.emails = [
@@ -943,7 +943,7 @@ describe('UserController', function() {
this.next
)
})
- it('should add affiliation to v1, unflag and confirm on v2', function() {
+ it('should add affiliation to v1, unflag and confirm on v2', function () {
expect(this.UserUpdater.promises.addAffiliationForNewUser).to.have.not
.been.called
expect(this.UserUpdater.promises.confirmEmail).to.have.been.calledWith(
@@ -951,13 +951,13 @@ describe('UserController', function() {
emailFlagged
)
})
- it('should not return an error', function() {
+ it('should not return an error', function () {
expect(this.next).to.be.calledWith()
})
})
- describe('when v1 returns an error', function() {
+ describe('when v1 returns an error', function () {
let emailFlagged
- beforeEach(async function() {
+ beforeEach(async function () {
this.UserUpdater.promises.addAffiliationForNewUser.rejects()
emailFlagged = 'flagged@overleaf.com'
this.user.email = emailFlagged
@@ -975,7 +975,7 @@ describe('UserController', function() {
this.next
)
})
- it('should return the error', function() {
+ it('should return the error', function () {
expect(this.next).to.be.calledWith(sinon.match.instanceOf(Error))
})
})
diff --git a/services/web/test/unit/src/User/UserCreatorTests.js b/services/web/test/unit/src/User/UserCreatorTests.js
index 55a8d6c2dc..9059911203 100644
--- a/services/web/test/unit/src/User/UserCreatorTests.js
+++ b/services/web/test/unit/src/User/UserCreatorTests.js
@@ -4,8 +4,8 @@ const { assert } = require('chai')
const modulePath = '../../../../app/src/Features/User/UserCreator.js'
-describe('UserCreator', function() {
- beforeEach(function() {
+describe('UserCreator', function () {
+ beforeEach(function () {
const self = this
this.user = { _id: '12390i', ace: {} }
this.user.save = sinon.stub().resolves(self.user)
@@ -53,9 +53,9 @@ describe('UserCreator', function() {
this.email = 'bob.oswald@gmail.com'
})
- describe('createNewUser', function() {
- describe('with callbacks', function() {
- it('should take the opts and put them in the model', async function() {
+ describe('createNewUser', function () {
+ describe('with callbacks', function () {
+ it('should take the opts and put them in the model', async function () {
const user = await this.UserCreator.promises.createNewUser({
email: this.email,
holdingAccount: true
@@ -65,7 +65,7 @@ describe('UserCreator', function() {
assert.equal(user.first_name, 'bob.oswald')
})
- it('should use the start of the email if the first name is empty string', async function() {
+ it('should use the start of the email if the first name is empty string', async function () {
const user = await this.UserCreator.promises.createNewUser({
email: this.email,
holdingAccount: true,
@@ -76,7 +76,7 @@ describe('UserCreator', function() {
assert.equal(user.first_name, 'bob.oswald')
})
- it('should use the first name if passed', async function() {
+ it('should use the first name if passed', async function () {
const user = await this.UserCreator.promises.createNewUser({
email: this.email,
holdingAccount: true,
@@ -87,7 +87,7 @@ describe('UserCreator', function() {
assert.equal(user.first_name, 'fiiirstname')
})
- it('should use the last name if passed', async function() {
+ it('should use the last name if passed', async function () {
const user = await this.UserCreator.promises.createNewUser({
email: this.email,
holdingAccount: true,
@@ -98,7 +98,7 @@ describe('UserCreator', function() {
assert.equal(user.last_name, 'lastNammmmeee')
})
- it('should set emails attribute', async function() {
+ it('should set emails attribute', async function () {
const user = await this.UserCreator.promises.createNewUser({
email: this.email
})
@@ -109,9 +109,9 @@ describe('UserCreator', function() {
user.emails[0].reversedHostname.should.equal('moc.liamg')
})
- describe('with affiliations feature', function() {
+ describe('with affiliations feature', function () {
let attributes, user
- beforeEach(function() {
+ beforeEach(function () {
attributes = { email: this.email }
this.Features.hasFeature = sinon
.stub()
@@ -119,16 +119,16 @@ describe('UserCreator', function() {
.returns(true)
})
- describe('when v1 affiliations API does not return an error', function() {
- beforeEach(async function() {
+ describe('when v1 affiliations API does not return an error', function () {
+ beforeEach(async function () {
user = await this.UserCreator.promises.createNewUser(attributes)
})
- it('should flag that affiliation is unchecked', function() {
+ it('should flag that affiliation is unchecked', function () {
user.emails[0].affiliationUnchecked.should.equal(true)
})
- it('should try to add affiliation to v1', function() {
+ it('should try to add affiliation to v1', function () {
sinon.assert.calledOnce(
this.UserUpdater.promises.addAffiliationForNewUser
)
@@ -139,22 +139,22 @@ describe('UserCreator', function() {
)
})
- it('should query for updated user data', function() {
+ it('should query for updated user data', function () {
sinon.assert.calledOnce(this.UserGetter.promises.getUser)
})
})
- describe('when v1 affiliations API does return an error', function() {
- beforeEach(async function() {
+ describe('when v1 affiliations API does return an error', function () {
+ beforeEach(async function () {
this.UserUpdater.promises.addAffiliationForNewUser.rejects()
user = await this.UserCreator.promises.createNewUser(attributes)
})
- it('should flag that affiliation is unchecked', function() {
+ it('should flag that affiliation is unchecked', function () {
user.emails[0].affiliationUnchecked.should.equal(true)
})
- it('should try to add affiliation to v1', function() {
+ it('should try to add affiliation to v1', function () {
sinon.assert.calledOnce(
this.UserUpdater.promises.addAffiliationForNewUser
)
@@ -165,26 +165,26 @@ describe('UserCreator', function() {
)
})
- it('should not query for updated user data', function() {
+ it('should not query for updated user data', function () {
sinon.assert.notCalled(this.UserGetter.promises.getUser)
})
- it('should log error', function() {
+ it('should log error', function () {
sinon.assert.calledOnce(this.logger.error)
})
})
- describe('when v1 affiliations API returns an error and requireAffiliation=true', function() {
- beforeEach(async function() {
+ describe('when v1 affiliations API returns an error and requireAffiliation=true', function () {
+ beforeEach(async function () {
this.UserUpdater.promises.addAffiliationForNewUser.rejects()
user = await this.UserCreator.promises.createNewUser(attributes)
})
- it('should flag that affiliation is unchecked', function() {
+ it('should flag that affiliation is unchecked', function () {
user.emails[0].affiliationUnchecked.should.equal(true)
})
- it('should try to add affiliation to v1', function() {
+ it('should try to add affiliation to v1', function () {
sinon.assert.calledOnce(
this.UserUpdater.promises.addAffiliationForNewUser
)
@@ -195,17 +195,17 @@ describe('UserCreator', function() {
)
})
- it('should not query for updated user data', function() {
+ it('should not query for updated user data', function () {
sinon.assert.notCalled(this.UserGetter.promises.getUser)
})
- it('should log error', function() {
+ it('should log error', function () {
sinon.assert.calledOnce(this.logger.error)
})
})
})
- it('should not add affiliation when without affiliation feature', async function() {
+ it('should not add affiliation when without affiliation feature', async function () {
const attributes = { email: this.email }
await this.UserCreator.promises.createNewUser(attributes)
sinon.assert.notCalled(
@@ -214,8 +214,8 @@ describe('UserCreator', function() {
})
})
- describe('with promises', function() {
- it('should take the opts and put them in the model', async function() {
+ describe('with promises', function () {
+ it('should take the opts and put them in the model', async function () {
const opts = {
email: this.email,
holdingAccount: true
@@ -226,7 +226,7 @@ describe('UserCreator', function() {
assert.equal(user.first_name, 'bob.oswald')
})
- it('should add affiliation when with affiliation feature', async function() {
+ it('should add affiliation when with affiliation feature', async function () {
this.Features.hasFeature = sinon
.stub()
.withArgs('affiliations')
@@ -243,7 +243,7 @@ describe('UserCreator', function() {
)
})
- it('should not add affiliation when without affiliation feature', async function() {
+ it('should not add affiliation when without affiliation feature', async function () {
this.Features.hasFeature = sinon.stub().returns(false)
const attributes = { email: this.email }
await this.UserCreator.promises.createNewUser(attributes)
@@ -252,7 +252,7 @@ describe('UserCreator', function() {
)
})
- it('should include SAML provider ID with email', async function() {
+ it('should include SAML provider ID with email', async function () {
const attributes = {
email: this.email,
samlIdentifiers: [{ email: this.email, providerId: '1' }]
@@ -261,7 +261,7 @@ describe('UserCreator', function() {
assert.equal(user.emails[0].samlProviderId, '1')
})
- it('should fire an analytics event on registration', async function() {
+ it('should fire an analytics event on registration', async function () {
const user = await this.UserCreator.promises.createNewUser({
email: this.email
})
@@ -273,7 +273,7 @@ describe('UserCreator', function() {
)
})
- it('should schedule an onboarding email on registration', async function() {
+ it('should schedule an onboarding email on registration', async function () {
const user = await this.UserCreator.promises.createNewUser({
email: this.email
})
diff --git a/services/web/test/unit/src/User/UserDeleterTests.js b/services/web/test/unit/src/User/UserDeleterTests.js
index 3675faa3d5..3da498ab8e 100644
--- a/services/web/test/unit/src/User/UserDeleterTests.js
+++ b/services/web/test/unit/src/User/UserDeleterTests.js
@@ -10,8 +10,8 @@ const { DeletedUser } = require('../helpers/models/DeletedUser')
const modulePath = '../../../../app/src/Features/User/UserDeleter.js'
-describe('UserDeleter', function() {
- beforeEach(function() {
+describe('UserDeleter', function () {
+ beforeEach(function () {
tk.freeze(Date.now())
this.userId = ObjectId()
@@ -100,22 +100,22 @@ describe('UserDeleter', function() {
})
})
- afterEach(function() {
+ afterEach(function () {
this.DeletedUserMock.restore()
this.UserMock.restore()
this.mockedUser.restore()
})
- describe('deleteUser', function() {
- beforeEach(function() {
+ describe('deleteUser', function () {
+ beforeEach(function () {
this.UserMock.expects('findById')
.withArgs(this.userId)
.chain('exec')
.resolves(this.user)
})
- describe('when the user can be deleted', function() {
- beforeEach(function() {
+ describe('when the user can be deleted', function () {
+ beforeEach(function () {
this.deletedUser = {
user: this.user,
deleterData: {
@@ -134,8 +134,8 @@ describe('UserDeleter', function() {
}
})
- describe('when no options are passed', function() {
- beforeEach(function() {
+ describe('when no options are passed', function () {
+ beforeEach(function () {
this.DeletedUserMock.expects('updateOne')
.withArgs(
{ 'deleterData.deletedUserId': this.userId },
@@ -146,69 +146,69 @@ describe('UserDeleter', function() {
.resolves()
})
- describe('when unsubscribing in Mailchimp succeeds', function() {
- beforeEach(function() {
+ describe('when unsubscribing in Mailchimp succeeds', function () {
+ beforeEach(function () {
this.UserMock.expects('deleteOne')
.withArgs({ _id: this.userId })
.chain('exec')
.resolves()
})
- it('should find and the user in mongo by its id', async function() {
+ it('should find and the user in mongo by its id', async function () {
await this.UserDeleter.promises.deleteUser(this.userId)
this.UserMock.verify()
})
- it('should delete the user from mailchimp', async function() {
+ it('should delete the user from mailchimp', async function () {
await this.UserDeleter.promises.deleteUser(this.userId)
expect(
this.NewsletterManager.promises.unsubscribe
).to.have.been.calledWith(this.user, { delete: true })
})
- it('should delete all the projects of a user', async function() {
+ it('should delete all the projects of a user', async function () {
await this.UserDeleter.promises.deleteUser(this.userId)
expect(
this.ProjectDeleter.promises.deleteUsersProjects
).to.have.been.calledWith(this.userId)
})
- it("should cancel the user's subscription", async function() {
+ it("should cancel the user's subscription", async function () {
await this.UserDeleter.promises.deleteUser(this.userId)
expect(
this.SubscriptionHandler.promises.cancelSubscription
).to.have.been.calledWith(this.user)
})
- it('should delete user affiliations', async function() {
+ it('should delete user affiliations', async function () {
await this.UserDeleter.promises.deleteUser(this.userId)
expect(
this.InstitutionsApi.promises.deleteAffiliations
).to.have.been.calledWith(this.userId)
})
- it('should stop the user sessions', async function() {
+ it('should stop the user sessions', async function () {
await this.UserDeleter.promises.deleteUser(this.userId)
expect(
this.UserSessionsManager.promises.revokeAllUserSessions
).to.have.been.calledWith(this.userId, [])
})
- it('should remove user from group subscriptions', async function() {
+ it('should remove user from group subscriptions', async function () {
await this.UserDeleter.promises.deleteUser(this.userId)
expect(
this.SubscriptionUpdater.promises.removeUserFromAllGroups
).to.have.been.calledWith(this.userId)
})
- it('should remove user memberships', async function() {
+ it('should remove user memberships', async function () {
await this.UserDeleter.promises.deleteUser(this.userId)
expect(
this.UserMembershipsHandler.promises.removeUserFromAllEntities
).to.have.been.calledWith(this.userId)
})
- it('rejects if the user is a subscription admin', async function() {
+ it('rejects if the user is a subscription admin', async function () {
this.SubscriptionLocator.promises.getUsersSubscription.rejects({
_id: 'some-subscription'
})
@@ -216,35 +216,35 @@ describe('UserDeleter', function() {
.be.rejected
})
- it('should create a deletedUser', async function() {
+ it('should create a deletedUser', async function () {
await this.UserDeleter.promises.deleteUser(this.userId)
this.DeletedUserMock.verify()
})
})
- describe('when unsubscribing from mailchimp fails', function() {
- beforeEach(function() {
+ describe('when unsubscribing from mailchimp fails', function () {
+ beforeEach(function () {
this.NewsletterManager.promises.unsubscribe.rejects(
new Error('something went wrong')
)
})
- it('should return an error and not delete the user', async function() {
+ it('should return an error and not delete the user', async function () {
await expect(this.UserDeleter.promises.deleteUser(this.userId)).to
.be.rejected
this.UserMock.verify()
})
})
- describe('when called as a callback', function() {
- beforeEach(function() {
+ describe('when called as a callback', function () {
+ beforeEach(function () {
this.UserMock.expects('deleteOne')
.withArgs({ _id: this.userId })
.chain('exec')
.resolves()
})
- it('should delete the user', function(done) {
+ it('should delete the user', function (done) {
this.UserDeleter.deleteUser(this.userId, err => {
expect(err).not.to.exist
this.UserMock.verify()
@@ -255,8 +255,8 @@ describe('UserDeleter', function() {
})
})
- describe('when a user and IP address are specified', function() {
- beforeEach(function() {
+ describe('when a user and IP address are specified', function () {
+ beforeEach(function () {
this.ipAddress = '1.2.3.4'
this.deleterId = ObjectId()
@@ -277,7 +277,7 @@ describe('UserDeleter', function() {
.resolves()
})
- it('should add the deleted user id and ip address to the deletedUser', async function() {
+ it('should add the deleted user id and ip address to the deletedUser', async function () {
await this.UserDeleter.promises.deleteUser(this.userId, {
deleterUser: { _id: this.deleterId },
ipAddress: this.ipAddress
@@ -285,8 +285,8 @@ describe('UserDeleter', function() {
this.DeletedUserMock.verify()
})
- describe('when called as a callback', function() {
- it('should delete the user', function(done) {
+ describe('when called as a callback', function () {
+ it('should delete the user', function (done) {
this.UserDeleter.deleteUser(
this.userId,
{
@@ -305,26 +305,26 @@ describe('UserDeleter', function() {
})
})
- describe('when the user cannot be deleted because they are a subscription admin', function() {
- beforeEach(function() {
+ describe('when the user cannot be deleted because they are a subscription admin', function () {
+ beforeEach(function () {
this.SubscriptionLocator.promises.getUsersSubscription.resolves({
_id: 'some-subscription'
})
})
- it('fails with a SubscriptionAdminDeletionError', async function() {
+ it('fails with a SubscriptionAdminDeletionError', async function () {
await expect(
this.UserDeleter.promises.deleteUser(this.userId)
).to.be.rejectedWith(Errors.SubscriptionAdminDeletionError)
})
- it('should not create a deletedUser', async function() {
+ it('should not create a deletedUser', async function () {
await expect(this.UserDeleter.promises.deleteUser(this.userId)).to.be
.rejected
this.DeletedUserMock.verify()
})
- it('should not remove the user from mongo', async function() {
+ it('should not remove the user from mongo', async function () {
await expect(this.UserDeleter.promises.deleteUser(this.userId)).to.be
.rejected
this.UserMock.verify()
@@ -332,8 +332,8 @@ describe('UserDeleter', function() {
})
})
- describe('ensureCanDeleteUser', function() {
- it('should not return error when user can be deleted', async function() {
+ describe('ensureCanDeleteUser', function () {
+ it('should not return error when user can be deleted', async function () {
this.SubscriptionLocator.promises.getUsersSubscription.resolves(null)
let error
try {
@@ -345,7 +345,7 @@ describe('UserDeleter', function() {
}
})
- it('should return custom error when user is group admin', async function() {
+ it('should return custom error when user is group admin', async function () {
this.SubscriptionLocator.promises.getUsersSubscription.resolves({
_id: '123abc'
})
@@ -359,7 +359,7 @@ describe('UserDeleter', function() {
}
})
- it('propagates errors', async function() {
+ it('propagates errors', async function () {
this.SubscriptionLocator.promises.getUsersSubscription.rejects(
new Error('Some error')
)
@@ -374,11 +374,11 @@ describe('UserDeleter', function() {
})
})
- describe('expireDeletedUsersAfterDuration', function() {
+ describe('expireDeletedUsersAfterDuration', function () {
const userId1 = new ObjectId()
const userId2 = new ObjectId()
- beforeEach(function() {
+ beforeEach(function () {
this.deletedUsers = [
{
user: { _id: userId1 },
@@ -413,7 +413,7 @@ describe('UserDeleter', function() {
}
})
- it('clears data from all deleted users', async function() {
+ it('clears data from all deleted users', async function () {
await this.UserDeleter.promises.expireDeletedUsersAfterDuration()
for (const deletedUser of this.deletedUsers) {
expect(deletedUser.user).to.be.undefined
@@ -422,8 +422,8 @@ describe('UserDeleter', function() {
})
})
- describe('expireDeletedUser', function() {
- beforeEach(function() {
+ describe('expireDeletedUser', function () {
+ beforeEach(function () {
this.mockedDeletedUser = sinon.mock(
new DeletedUser({
user: this.user,
@@ -443,37 +443,37 @@ describe('UserDeleter', function() {
.resolves(this.deletedUser)
})
- afterEach(function() {
+ afterEach(function () {
this.mockedDeletedUser.restore()
})
- it('should find the user by user ID', async function() {
+ it('should find the user by user ID', async function () {
await this.UserDeleter.promises.expireDeletedUser('giraffe')
this.DeletedUserMock.verify()
})
- it('should remove the user data from mongo', async function() {
+ it('should remove the user data from mongo', async function () {
await this.UserDeleter.promises.expireDeletedUser('giraffe')
expect(this.deletedUser.user).not.to.exist
})
- it('should remove the IP address from mongo', async function() {
+ it('should remove the IP address from mongo', async function () {
await this.UserDeleter.promises.expireDeletedUser('giraffe')
expect(this.deletedUser.deleterData.ipAddress).not.to.exist
})
- it('should not delete other deleterData fields', async function() {
+ it('should not delete other deleterData fields', async function () {
await this.UserDeleter.promises.expireDeletedUser('giraffe')
expect(this.deletedUser.deleterData.deletedUserId).to.equal(this.userId)
})
- it('should save the record to mongo', async function() {
+ it('should save the record to mongo', async function () {
await this.UserDeleter.promises.expireDeletedUser('giraffe')
this.mockedDeletedUser.verify()
})
- describe('when called as a callback', function() {
- it('should expire the user', function(done) {
+ describe('when called as a callback', function () {
+ it('should expire the user', function (done) {
this.UserDeleter.expireDeletedUser('giraffe', err => {
expect(err).not.to.exist
this.DeletedUserMock.verify()
diff --git a/services/web/test/unit/src/User/UserEmailsConfirmationHandlerTests.js b/services/web/test/unit/src/User/UserEmailsConfirmationHandlerTests.js
index 1694c22ad5..c7f4e292ca 100644
--- a/services/web/test/unit/src/User/UserEmailsConfirmationHandlerTests.js
+++ b/services/web/test/unit/src/User/UserEmailsConfirmationHandlerTests.js
@@ -22,8 +22,8 @@ const { expect } = require('chai')
const Errors = require('../../../../app/src/Features/Errors/Errors')
const EmailHelper = require('../../../../app/src/Features/Helpers/EmailHelper')
-describe('UserEmailsConfirmationHandler', function() {
- beforeEach(function() {
+describe('UserEmailsConfirmationHandler', function () {
+ beforeEach(function () {
this.UserEmailsConfirmationHandler = SandboxedModule.require(modulePath, {
requires: {
'settings-sharelatex': (this.settings = {
@@ -48,16 +48,16 @@ describe('UserEmailsConfirmationHandler', function() {
return (this.callback = sinon.stub())
})
- describe('sendConfirmationEmail', function() {
- beforeEach(function() {
+ describe('sendConfirmationEmail', function () {
+ beforeEach(function () {
this.OneTimeTokenHandler.getNewToken = sinon
.stub()
.yields(null, (this.token = 'new-token'))
return (this.EmailHandler.sendEmail = sinon.stub().yields())
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
return this.UserEmailsConfirmationHandler.sendConfirmationEmail(
this.user_id,
this.email,
@@ -65,7 +65,7 @@ describe('UserEmailsConfirmationHandler', function() {
)
})
- it('should generate a token for the user which references their id and email', function() {
+ it('should generate a token for the user which references their id and email', function () {
return this.OneTimeTokenHandler.getNewToken
.calledWith(
'email_confirmation',
@@ -75,7 +75,7 @@ describe('UserEmailsConfirmationHandler', function() {
.should.equal(true)
})
- it('should send an email to the user', function() {
+ it('should send an email to the user', function () {
return this.EmailHandler.sendEmail
.calledWith('confirmEmail', {
to: this.email,
@@ -86,13 +86,13 @@ describe('UserEmailsConfirmationHandler', function() {
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('with invalid email', function() {
- beforeEach(function() {
+ describe('with invalid email', function () {
+ beforeEach(function () {
return this.UserEmailsConfirmationHandler.sendConfirmationEmail(
this.user_id,
'!"£$%^&*()',
@@ -100,15 +100,15 @@ describe('UserEmailsConfirmationHandler', function() {
)
})
- it('should return an error', function() {
+ it('should return an error', function () {
return this.callback
.calledWith(sinon.match.instanceOf(Error))
.should.equal(true)
})
})
- describe('a custom template', function() {
- beforeEach(function() {
+ describe('a custom template', function () {
+ beforeEach(function () {
return this.UserEmailsConfirmationHandler.sendConfirmationEmail(
this.user_id,
this.email,
@@ -117,7 +117,7 @@ describe('UserEmailsConfirmationHandler', function() {
)
})
- it('should send an email with the given template', function() {
+ it('should send an email with the given template', function () {
return this.EmailHandler.sendEmail
.calledWith('myCustomTemplate')
.should.equal(true)
@@ -125,41 +125,41 @@ describe('UserEmailsConfirmationHandler', function() {
})
})
- describe('confirmEmailFromToken', function() {
- beforeEach(function() {
+ describe('confirmEmailFromToken', function () {
+ beforeEach(function () {
this.OneTimeTokenHandler.getValueFromTokenAndExpire = sinon
.stub()
.yields(null, { user_id: this.user_id, email: this.email })
return (this.UserUpdater.confirmEmail = sinon.stub().yields())
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
return this.UserEmailsConfirmationHandler.confirmEmailFromToken(
(this.token = 'mock-token'),
this.callback
)
})
- it('should call getValueFromTokenAndExpire', function() {
+ it('should call getValueFromTokenAndExpire', function () {
return this.OneTimeTokenHandler.getValueFromTokenAndExpire
.calledWith('email_confirmation', this.token)
.should.equal(true)
})
- it('should confirm the email of the user_id', function() {
+ it('should confirm the email of the user_id', function () {
return this.UserUpdater.confirmEmail
.calledWith(this.user_id, this.email)
.should.equal(true)
})
- it('should call the callback', function() {
+ it('should call the callback', function () {
return this.callback.called.should.equal(true)
})
})
- describe('with an expired token', function() {
- beforeEach(function() {
+ describe('with an expired token', function () {
+ beforeEach(function () {
this.OneTimeTokenHandler.getValueFromTokenAndExpire = sinon
.stub()
.yields(null, null)
@@ -169,15 +169,15 @@ describe('UserEmailsConfirmationHandler', function() {
)
})
- it('should call the callback with a NotFoundError', function() {
+ it('should call the callback with a NotFoundError', function () {
return this.callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
})
})
- describe('with no user_id in the token', function() {
- beforeEach(function() {
+ describe('with no user_id in the token', function () {
+ beforeEach(function () {
this.OneTimeTokenHandler.getValueFromTokenAndExpire = sinon
.stub()
.yields(null, { email: this.email })
@@ -187,15 +187,15 @@ describe('UserEmailsConfirmationHandler', function() {
)
})
- it('should call the callback with a NotFoundError', function() {
+ it('should call the callback with a NotFoundError', function () {
return this.callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
})
})
- describe('with no email in the token', function() {
- beforeEach(function() {
+ describe('with no email in the token', function () {
+ beforeEach(function () {
this.OneTimeTokenHandler.getValueFromTokenAndExpire = sinon
.stub()
.yields(null, { user_id: this.user_id })
@@ -205,15 +205,15 @@ describe('UserEmailsConfirmationHandler', function() {
)
})
- it('should call the callback with a NotFoundError', function() {
+ it('should call the callback with a NotFoundError', function () {
return this.callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
})
})
- describe('with no user found', function() {
- beforeEach(function() {
+ describe('with no user found', function () {
+ beforeEach(function () {
this.UserGetter.getUser.yields(null, null)
return this.UserEmailsConfirmationHandler.confirmEmailFromToken(
(this.token = 'mock-token'),
@@ -221,15 +221,15 @@ describe('UserEmailsConfirmationHandler', function() {
)
})
- it('should call the callback with a NotFoundError', function() {
+ it('should call the callback with a NotFoundError', function () {
return this.callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
})
})
- describe('with secondary email missing on user', function() {
- beforeEach(function() {
+ describe('with secondary email missing on user', function () {
+ beforeEach(function () {
this.OneTimeTokenHandler.getValueFromTokenAndExpire = sinon
.stub()
.yields(null, { user_id: this.user_id, email: 'deleted@email.com' })
@@ -239,7 +239,7 @@ describe('UserEmailsConfirmationHandler', function() {
)
})
- it('should call the callback with a NotFoundError', function() {
+ it('should call the callback with a NotFoundError', function () {
return this.callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal(true)
diff --git a/services/web/test/unit/src/User/UserEmailsControllerTests.js b/services/web/test/unit/src/User/UserEmailsControllerTests.js
index 44f68de6e5..a59f89e66c 100644
--- a/services/web/test/unit/src/User/UserEmailsControllerTests.js
+++ b/services/web/test/unit/src/User/UserEmailsControllerTests.js
@@ -8,8 +8,8 @@ const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
const Errors = require('../../../../app/src/Features/Errors/Errors')
-describe('UserEmailsController', function() {
- beforeEach(function() {
+describe('UserEmailsController', function () {
+ beforeEach(function () {
this.req = new MockRequest()
this.req.sessionID = Math.random().toString()
this.res = new MockResponse()
@@ -79,10 +79,10 @@ describe('UserEmailsController', function() {
})
})
- describe('List', function() {
- beforeEach(function() {})
+ describe('List', function () {
+ beforeEach(function () {})
- it('lists emails', function(done) {
+ it('lists emails', function (done) {
const fullEmails = [{ some: 'data' }]
this.UserGetter.getUserFullEmails.callsArgWith(1, null, fullEmails)
@@ -96,8 +96,8 @@ describe('UserEmailsController', function() {
})
})
- describe('Add', function() {
- beforeEach(function() {
+ describe('Add', function () {
+ beforeEach(function () {
this.newEmail = 'new_email@baz.com'
this.req.body = {
email: this.newEmail,
@@ -111,7 +111,7 @@ describe('UserEmailsController', function() {
.yields()
})
- it('passed audit log to addEmailAddress', function(done) {
+ it('passed audit log to addEmailAddress', function (done) {
this.res.sendStatus = sinon.stub()
this.res.sendStatus.callsFake(() => {
const addCall = this.UserUpdater.promises.addEmailAddress.lastCall
@@ -124,7 +124,7 @@ describe('UserEmailsController', function() {
this.UserEmailsController.add(this.req, this.res)
})
- it('adds new email', function(done) {
+ it('adds new email', function (done) {
this.UserEmailsController.add(
this.req,
{
@@ -151,7 +151,7 @@ describe('UserEmailsController', function() {
)
})
- it('sends a security alert email', function(done) {
+ it('sends a security alert email', function (done) {
this.res.sendStatus = sinon.stub()
this.res.sendStatus.callsFake(() => {
const emailCall = this.EmailHandler.promises.sendEmail.getCall(0)
@@ -168,7 +168,7 @@ describe('UserEmailsController', function() {
this.UserEmailsController.add(this.req, this.res)
})
- it('sends an email confirmation', function(done) {
+ it('sends an email confirmation', function (done) {
this.UserEmailsController.add(
this.req,
{
@@ -186,7 +186,7 @@ describe('UserEmailsController', function() {
)
})
- it('handles email parse error', function(done) {
+ it('handles email parse error', function (done) {
this.EmailHelper.parseEmail.returns(null)
this.UserEmailsController.add(
this.req,
@@ -201,7 +201,7 @@ describe('UserEmailsController', function() {
)
})
- it('should pass the error to the next handler when adding the email fails', function(done) {
+ it('should pass the error to the next handler when adding the email fails', function (done) {
this.UserUpdater.promises.addEmailAddress.rejects(new Error())
this.UserEmailsController.add(this.req, this.res, error => {
expect(error).to.be.instanceof(Error)
@@ -209,7 +209,7 @@ describe('UserEmailsController', function() {
})
})
- it('should call the HTTP conflict handler when the email already exists', function(done) {
+ it('should call the HTTP conflict handler when the email already exists', function (done) {
this.UserUpdater.promises.addEmailAddress.rejects(
new Errors.EmailExistsError()
)
@@ -222,7 +222,7 @@ describe('UserEmailsController', function() {
this.UserEmailsController.add(this.req, this.res, this.next)
})
- it("should call the HTTP conflict handler when there's a domain matching error", function(done) {
+ it("should call the HTTP conflict handler when there's a domain matching error", function (done) {
this.UserUpdater.promises.addEmailAddress.rejects(
new Error('422: Email does not belong to university')
)
@@ -236,14 +236,14 @@ describe('UserEmailsController', function() {
})
})
- describe('remove', function() {
- beforeEach(function() {
+ describe('remove', function () {
+ beforeEach(function () {
this.email = 'email_to_remove@bar.com'
this.req.body.email = this.email
this.EmailHelper.parseEmail.returns(this.email)
})
- it('removes email', function(done) {
+ it('removes email', function (done) {
this.UserUpdater.removeEmailAddress.callsArgWith(2, null)
this.UserEmailsController.remove(this.req, {
@@ -260,7 +260,7 @@ describe('UserEmailsController', function() {
})
})
- it('handles email parse error', function(done) {
+ it('handles email parse error', function (done) {
this.EmailHelper.parseEmail.returns(null)
this.UserEmailsController.remove(this.req, {
@@ -273,15 +273,15 @@ describe('UserEmailsController', function() {
})
})
- describe('setDefault', function() {
- beforeEach(function() {
+ describe('setDefault', function () {
+ beforeEach(function () {
this.email = 'email_to_set_default@bar.com'
this.req.body.email = this.email
this.EmailHelper.parseEmail.returns(this.email)
this.AuthenticationController.setInSessionUser.returns(null)
})
- it('sets default email', function(done) {
+ it('sets default email', function (done) {
this.UserUpdater.setDefaultEmailAddress.yields()
this.UserEmailsController.setDefault(this.req, {
@@ -303,7 +303,7 @@ describe('UserEmailsController', function() {
})
})
- it('handles email parse error', function(done) {
+ it('handles email parse error', function (done) {
this.EmailHelper.parseEmail.returns(null)
this.UserEmailsController.setDefault(this.req, {
@@ -315,7 +315,7 @@ describe('UserEmailsController', function() {
})
})
- it('should reset the users other sessions', function(done) {
+ it('should reset the users other sessions', function (done) {
this.UserUpdater.setDefaultEmailAddress.yields()
this.res.callback = () => {
@@ -328,7 +328,7 @@ describe('UserEmailsController', function() {
this.UserEmailsController.setDefault(this.req, this.res, done)
})
- it('handles error from revoking sessions and returns 200', function(done) {
+ it('handles error from revoking sessions and returns 200', function (done) {
this.UserUpdater.setDefaultEmailAddress.yields()
const redisError = new Error('redis error')
this.UserSessionsManager.revokeAllUserSessions = sinon
@@ -352,14 +352,14 @@ describe('UserEmailsController', function() {
})
})
- describe('endorse', function() {
- beforeEach(function() {
+ describe('endorse', function () {
+ beforeEach(function () {
this.email = 'email_to_endorse@bar.com'
this.req.body.email = this.email
this.EmailHelper.parseEmail.returns(this.email)
})
- it('endorses affiliation', function(done) {
+ it('endorses affiliation', function (done) {
this.req.body.role = 'Role'
this.req.body.department = 'Department'
@@ -379,8 +379,8 @@ describe('UserEmailsController', function() {
})
})
- describe('confirm', function() {
- beforeEach(function() {
+ describe('confirm', function () {
+ beforeEach(function () {
this.UserEmailsConfirmationHandler.confirmEmailFromToken = sinon
.stub()
.yields()
@@ -394,42 +394,42 @@ describe('UserEmailsController', function() {
this.req.body = { token: this.token }
})
- describe('successfully', function() {
- beforeEach(function() {
+ describe('successfully', function () {
+ beforeEach(function () {
this.UserEmailsController.confirm(this.req, this.res, this.next)
})
- it('should confirm the email from the token', function() {
+ it('should confirm the email from the token', function () {
this.UserEmailsConfirmationHandler.confirmEmailFromToken
.calledWith(this.token)
.should.equal(true)
})
- it('should return a 200 status', function() {
+ it('should return a 200 status', function () {
this.res.sendStatus.calledWith(200).should.equal(true)
})
})
- describe('without a token', function() {
- beforeEach(function() {
+ describe('without a token', function () {
+ beforeEach(function () {
this.req.body.token = null
this.UserEmailsController.confirm(this.req, this.res, this.next)
})
- it('should return a 422 status', function() {
+ it('should return a 422 status', function () {
this.res.status.calledWith(422).should.equal(true)
})
})
- describe('when confirming fails', function() {
- beforeEach(function() {
+ describe('when confirming fails', function () {
+ beforeEach(function () {
this.UserEmailsConfirmationHandler.confirmEmailFromToken = sinon
.stub()
.yields(new Errors.NotFoundError('not found'))
this.UserEmailsController.confirm(this.req, this.res, this.next)
})
- it('should return a 404 error code with a message', function() {
+ it('should return a 404 error code with a message', function () {
this.res.status.calledWith(404).should.equal(true)
this.res.json
.calledWith({
@@ -439,8 +439,8 @@ describe('UserEmailsController', function() {
})
})
})
- describe('resendConfirmation', function() {
- beforeEach(function() {
+ describe('resendConfirmation', function () {
+ beforeEach(function () {
this.req = {
body: {}
}
@@ -452,15 +452,15 @@ describe('UserEmailsController', function() {
.stub()
.yields()
})
- describe('when institution SSO is released', function() {
- beforeEach(function() {
+ describe('when institution SSO is released', function () {
+ beforeEach(function () {
this.Features.hasFeature.withArgs('saml').returns(true)
})
- describe('for an institution SSO email', function() {
- beforeEach(function() {
+ describe('for an institution SSO email', function () {
+ beforeEach(function () {
this.req.body.email = 'with-sso@overleaf.com'
})
- it('should not send the email', function() {
+ it('should not send the email', function () {
this.UserEmailsController.resendConfirmation(
this.req,
this.res,
@@ -471,11 +471,11 @@ describe('UserEmailsController', function() {
)
})
})
- describe('for a non-institution SSO email', function() {
- beforeEach(function() {
+ describe('for a non-institution SSO email', function () {
+ beforeEach(function () {
this.req.body.email = 'without-sso@example.com'
})
- it('should send the email', function() {
+ it('should send the email', function () {
this.UserEmailsController.resendConfirmation(
this.req,
this.res,
@@ -487,15 +487,15 @@ describe('UserEmailsController', function() {
})
})
})
- describe('when institution SSO is not released', function() {
- beforeEach(function() {
+ describe('when institution SSO is not released', function () {
+ beforeEach(function () {
this.Features.hasFeature.withArgs('saml').returns(false)
})
- describe('for an institution SSO email', function() {
- beforeEach(function() {
+ describe('for an institution SSO email', function () {
+ beforeEach(function () {
this.req.body.email = 'with-sso@overleaf.com'
})
- it('should send the email', function() {
+ it('should send the email', function () {
this.UserEmailsController.resendConfirmation(
this.req,
this.res,
@@ -506,11 +506,11 @@ describe('UserEmailsController', function() {
)
})
})
- describe('for a non-institution SSO email', function() {
- beforeEach(function() {
+ describe('for a non-institution SSO email', function () {
+ beforeEach(function () {
this.req.body.email = 'without-sso@example.com'
})
- it('should send the email', function() {
+ it('should send the email', function () {
this.UserEmailsController.resendConfirmation(
this.req,
this.res,
diff --git a/services/web/test/unit/src/User/UserGetterTests.js b/services/web/test/unit/src/User/UserGetterTests.js
index 73898d0263..03bd01c5bf 100644
--- a/services/web/test/unit/src/User/UserGetterTests.js
+++ b/services/web/test/unit/src/User/UserGetterTests.js
@@ -15,8 +15,8 @@ const {
normalizeMultiQuery
} = require('../../../../app/src/Features/Helpers/Mongo')
-describe('UserGetter', function() {
- beforeEach(function() {
+describe('UserGetter', function () {
+ beforeEach(function () {
this.fakeUser = {
_id: '12390i',
email: 'email2@foo.bar',
@@ -65,8 +65,8 @@ describe('UserGetter', function() {
})
})
- describe('getUser', function() {
- it('should get user', function(done) {
+ describe('getUser', function () {
+ it('should get user', function (done) {
const query = { _id: '000000000000000000000000' }
const projection = { email: 1 }
this.UserGetter.getUser(query, projection, (error, user) => {
@@ -78,7 +78,7 @@ describe('UserGetter', function() {
})
})
- it('should not allow null query', function(done) {
+ it('should not allow null query', function (done) {
this.UserGetter.getUser(null, {}, error => {
error.should.exist
error.message.should.equal('no query provided')
@@ -87,8 +87,8 @@ describe('UserGetter', function() {
})
})
- describe('getUsers', function() {
- it('should get users with array of userIds', function(done) {
+ describe('getUsers', function () {
+ it('should get users with array of userIds', function (done) {
const query = [new ObjectId()]
const projection = { email: 1 }
this.UserGetter.getUsers(query, projection, (error, users) => {
@@ -102,7 +102,7 @@ describe('UserGetter', function() {
})
})
- it('should not allow null query', function(done) {
+ it('should not allow null query', function (done) {
this.UserGetter.getUser(null, {}, error => {
error.should.exist
error.message.should.equal('no query provided')
@@ -111,8 +111,8 @@ describe('UserGetter', function() {
})
})
- describe('getUserFullEmails', function() {
- it('should get user', function(done) {
+ describe('getUserFullEmails', function () {
+ it('should get user', function (done) {
this.UserGetter.promises.getUser = sinon.stub().resolves(this.fakeUser)
const projection = { email: 1, emails: 1, samlIdentifiers: 1 }
this.UserGetter.getUserFullEmails(
@@ -128,7 +128,7 @@ describe('UserGetter', function() {
)
})
- it('should fetch emails data', function(done) {
+ it('should fetch emails data', function (done) {
this.UserGetter.promises.getUser = sinon.stub().resolves(this.fakeUser)
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
@@ -154,7 +154,7 @@ describe('UserGetter', function() {
)
})
- it('should merge affiliation data', function(done) {
+ it('should merge affiliation data', function (done) {
this.UserGetter.promises.getUser = sinon.stub().resolves(this.fakeUser)
const affiliationsData = [
{
@@ -207,7 +207,7 @@ describe('UserGetter', function() {
)
})
- it('should merge SAML identifier', function(done) {
+ it('should merge SAML identifier', function (done) {
const fakeSamlIdentifiers = [
{ providerId: 'saml_id', exteranlUserId: 'whatever' }
]
@@ -242,7 +242,7 @@ describe('UserGetter', function() {
)
})
- it('should get user when it has no emails field', function(done) {
+ it('should get user when it has no emails field', function (done) {
this.fakeUser = {
_id: '12390i',
email: 'email2@foo.bar'
@@ -263,7 +263,7 @@ describe('UserGetter', function() {
)
})
- describe('affiliation reconfirmation', function() {
+ describe('affiliation reconfirmation', function () {
const institutionNonSSO = {
id: 1,
name: 'University Name',
@@ -283,7 +283,7 @@ describe('UserGetter', function() {
ssoEnabled: true,
maxConfirmationMonths: 12
}
- describe('non-SSO institutions', function() {
+ describe('non-SSO institutions', function () {
const email1 = 'leonard@example-affiliation.com'
const email2 = 'mccoy@example-affiliation.com'
const affiliationsData = [
@@ -304,7 +304,7 @@ describe('UserGetter', function() {
institution: institutionNonSSO
}
]
- it('should flag inReconfirmNotificationPeriod for all affiliations in period', function(done) {
+ it('should flag inReconfirmNotificationPeriod for all affiliations in period', function (done) {
const user = {
_id: '12390i',
email: email1,
@@ -348,7 +348,7 @@ describe('UserGetter', function() {
}
)
})
- it('should not flag affiliations outside of notification period', function(done) {
+ it('should not flag affiliations outside of notification period', function (done) {
const aboutToBeWithinPeriod = moment()
.subtract(institutionNonSSO.maxConfirmationMonths, 'months')
.add(15, 'days')
@@ -388,8 +388,8 @@ describe('UserGetter', function() {
})
})
- describe('SSO institutions', function() {
- it('should flag only linked email, if in notification period', function(done) {
+ describe('SSO institutions', function () {
+ it('should flag only linked email, if in notification period', function (done) {
const email1 = 'email1@sso.bar'
const email2 = 'email2@sso.bar'
const email3 = 'email3@sso.bar'
@@ -474,8 +474,8 @@ describe('UserGetter', function() {
})
})
- describe('multiple institution affiliations', function() {
- it('should flag each institution', function(done) {
+ describe('multiple institution affiliations', function () {
+ it('should flag each institution', function (done) {
const email1 = 'email1@sso.bar'
const email2 = 'email2@sso.bar'
const email3 = 'email3@foo.bar'
@@ -573,8 +573,8 @@ describe('UserGetter', function() {
})
})
- describe('reconfirmedAt', function() {
- it('only use confirmedAt when no reconfirmedAt', function(done) {
+ describe('reconfirmedAt', function () {
+ it('only use confirmedAt when no reconfirmedAt', function (done) {
const email1 = 'email1@foo.bar'
const email2 = 'email2@foo.bar'
const email3 = 'email3@foo.bar'
@@ -669,9 +669,9 @@ describe('UserGetter', function() {
})
})
- describe('before reconfirmation period expires and within reconfirmation notification period', function() {
+ describe('before reconfirmation period expires and within reconfirmation notification period', function () {
const email = 'leonard@example-affiliation.com'
- it('should flag the email', function(done) {
+ it('should flag the email', function (done) {
const confirmedAt = moment()
.subtract(institutionNonSSO.maxConfirmationMonths, 'months')
.subtract(14, 'days')
@@ -712,8 +712,8 @@ describe('UserGetter', function() {
})
})
- describe('when no Settings.reconfirmNotificationDays', function() {
- it('should always return inReconfirmNotificationPeriod:false', function(done) {
+ describe('when no Settings.reconfirmNotificationDays', function () {
+ it('should always return inReconfirmNotificationPeriod:false', function (done) {
const email1 = 'email1@sso.bar'
const email2 = 'email2@foo.bar'
const email3 = 'email3@foo.bar'
@@ -786,8 +786,8 @@ describe('UserGetter', function() {
})
})
- describe('getUserbyMainEmail', function() {
- it('query user by main email', function(done) {
+ describe('getUserbyMainEmail', function () {
+ it('query user by main email', function (done) {
const email = 'hello@world.com'
const projection = { emails: 1 }
this.UserGetter.getUserByMainEmail(email, projection, (error, user) => {
@@ -798,7 +798,7 @@ describe('UserGetter', function() {
})
})
- it('return user if found', function(done) {
+ it('return user if found', function (done) {
const email = 'hello@world.com'
this.UserGetter.getUserByMainEmail(email, (error, user) => {
expect(error).to.not.exist
@@ -807,7 +807,7 @@ describe('UserGetter', function() {
})
})
- it('trim email', function(done) {
+ it('trim email', function (done) {
const email = 'hello@world.com'
this.UserGetter.getUserByMainEmail(` ${email} `, (error, user) => {
expect(error).to.not.exist
@@ -818,8 +818,8 @@ describe('UserGetter', function() {
})
})
- describe('getUserByAnyEmail', function() {
- it('query user for any email', function(done) {
+ describe('getUserByAnyEmail', function () {
+ it('query user for any email', function (done) {
const email = 'hello@world.com'
const expectedQuery = {
emails: { $exists: true },
@@ -840,7 +840,7 @@ describe('UserGetter', function() {
)
})
- it('query contains $exists:true so partial index is used', function(done) {
+ it('query contains $exists:true so partial index is used', function (done) {
const expectedQuery = {
emails: { $exists: true },
'emails.email': ''
@@ -854,7 +854,7 @@ describe('UserGetter', function() {
})
})
- it('checks main email as well', function(done) {
+ it('checks main email as well', function (done) {
this.findOne.callsArgWith(2, null, null)
const email = 'hello@world.com'
const projection = { emails: 1 }
@@ -871,15 +871,12 @@ describe('UserGetter', function() {
})
})
- describe('getUsersByHostname', function() {
- it('should find user by hostname', function(done) {
+ describe('getUsersByHostname', function () {
+ it('should find user by hostname', function (done) {
const hostname = 'bar.foo'
const expectedQuery = {
emails: { $exists: true },
- 'emails.reversedHostname': hostname
- .split('')
- .reverse()
- .join('')
+ 'emails.reversedHostname': hostname.split('').reverse().join('')
}
const projection = { emails: 1 }
this.UserGetter.getUsersByHostname(
@@ -895,8 +892,8 @@ describe('UserGetter', function() {
})
})
- describe('getUsersByAnyConfirmedEmail', function() {
- it('should find users by confirmed email', function(done) {
+ describe('getUsersByAnyConfirmedEmail', function () {
+ it('should find users by confirmed email', function (done) {
const emails = ['confirmed@example.com']
this.UserGetter.getUsersByAnyConfirmedEmail(emails, (error, users) => {
@@ -919,8 +916,8 @@ describe('UserGetter', function() {
})
})
- describe('getUsersByV1Id', function() {
- it('should find users by list of v1 ids', function(done) {
+ describe('getUsersByV1Id', function () {
+ it('should find users by list of v1 ids', function (done) {
const v1Ids = [501]
const expectedQuery = {
'overleaf.id': { $in: v1Ids }
@@ -935,12 +932,12 @@ describe('UserGetter', function() {
})
})
- describe('ensureUniqueEmailAddress', function() {
- beforeEach(function() {
+ describe('ensureUniqueEmailAddress', function () {
+ beforeEach(function () {
this.UserGetter.getUserByAnyEmail = sinon.stub()
})
- it('should return error if existing user is found', function(done) {
+ it('should return error if existing user is found', function (done) {
this.UserGetter.getUserByAnyEmail.callsArgWith(1, null, this.fakeUser)
this.UserGetter.ensureUniqueEmailAddress(this.newEmail, err => {
expect(err).to.exist
@@ -949,7 +946,7 @@ describe('UserGetter', function() {
})
})
- it('should return null if no user is found', function(done) {
+ it('should return null if no user is found', function (done) {
this.UserGetter.getUserByAnyEmail.callsArgWith(1)
this.UserGetter.ensureUniqueEmailAddress(this.newEmail, err => {
expect(err).not.to.exist
diff --git a/services/web/test/unit/src/User/UserHandlerTests.js b/services/web/test/unit/src/User/UserHandlerTests.js
index 5dd4e90e8e..ddd54e6550 100644
--- a/services/web/test/unit/src/User/UserHandlerTests.js
+++ b/services/web/test/unit/src/User/UserHandlerTests.js
@@ -2,8 +2,8 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/Features/User/UserHandler.js'
const SandboxedModule = require('sandboxed-module')
-describe('UserHandler', function() {
- beforeEach(function() {
+describe('UserHandler', function () {
+ beforeEach(function () {
this.user = {
_id: '12390i',
email: 'bob@bob.com',
@@ -21,12 +21,12 @@ describe('UserHandler', function() {
})
})
- describe('populateTeamInvites', function() {
- beforeEach(function(done) {
+ describe('populateTeamInvites', function () {
+ beforeEach(function (done) {
this.UserHandler.populateTeamInvites(this.user, done)
})
- it('notifies the user about legacy team invites', function() {
+ it('notifies the user about legacy team invites', function () {
this.TeamInvitesHandler.createTeamInvitesForLegacyInvitedEmail
.calledWith(this.user.email)
.should.eq(true)
diff --git a/services/web/test/unit/src/User/UserInfoControllerTests.js b/services/web/test/unit/src/User/UserInfoControllerTests.js
index a537a64021..e34c773fe5 100644
--- a/services/web/test/unit/src/User/UserInfoControllerTests.js
+++ b/services/web/test/unit/src/User/UserInfoControllerTests.js
@@ -19,8 +19,8 @@ const MockResponse = require('../helpers/MockResponse')
const MockRequest = require('../helpers/MockRequest')
const { ObjectId } = require('mongodb')
-describe('UserInfoController', function() {
- beforeEach(function() {
+describe('UserInfoController', function () {
+ beforeEach(function () {
this.UserDeleter = { deleteUser: sinon.stub().callsArgWith(1) }
this.UserUpdater = { updatePersonalInfo: sinon.stub() }
this.sanitizer = {
@@ -49,8 +49,8 @@ describe('UserInfoController', function() {
return (this.next = sinon.stub())
})
- describe('getLoggedInUsersPersonalInfo', function() {
- beforeEach(function() {
+ describe('getLoggedInUsersPersonalInfo', function () {
+ beforeEach(function () {
this.user = { _id: ObjectId() }
this.req.user = this.user
this.req.session.user = this.user
@@ -66,16 +66,16 @@ describe('UserInfoController', function() {
)
})
- it('should call sendFormattedPersonalInfo', function() {
+ it('should call sendFormattedPersonalInfo', function () {
return this.UserInfoController.sendFormattedPersonalInfo
.calledWith(this.user, this.res, this.next)
.should.equal(true)
})
})
- describe('getPersonalInfo', function() {
- describe('when the user exists with sharelatex id', function() {
- beforeEach(function() {
+ describe('getPersonalInfo', function () {
+ describe('when the user exists with sharelatex id', function () {
+ beforeEach(function () {
this.user_id = ObjectId().toString()
this.user = { _id: ObjectId(this.user_id) }
this.req.params = { user_id: this.user_id }
@@ -88,7 +88,7 @@ describe('UserInfoController', function() {
)
})
- it('should look up the user in the database', function() {
+ it('should look up the user in the database', function () {
return this.UserGetter.getUser
.calledWith(
{ _id: ObjectId(this.user_id) },
@@ -97,15 +97,15 @@ describe('UserInfoController', function() {
.should.equal(true)
})
- it('should send the formatted details back to the client', function() {
+ it('should send the formatted details back to the client', function () {
return this.UserInfoController.sendFormattedPersonalInfo
.calledWith(this.user, this.res, this.next)
.should.equal(true)
})
})
- describe('when the user exists with overleaf id', function() {
- beforeEach(function() {
+ describe('when the user exists with overleaf id', function () {
+ beforeEach(function () {
this.user_id = 12345
this.user = {
_id: ObjectId(),
@@ -123,7 +123,7 @@ describe('UserInfoController', function() {
)
})
- it('should look up the user in the database', function() {
+ it('should look up the user in the database', function () {
return this.UserGetter.getUser
.calledWith(
{ 'overleaf.id': this.user_id },
@@ -132,15 +132,15 @@ describe('UserInfoController', function() {
.should.equal(true)
})
- it('should send the formatted details back to the client', function() {
+ it('should send the formatted details back to the client', function () {
return this.UserInfoController.sendFormattedPersonalInfo
.calledWith(this.user, this.res, this.next)
.should.equal(true)
})
})
- describe('when the user does not exist', function() {
- beforeEach(function() {
+ describe('when the user does not exist', function () {
+ beforeEach(function () {
this.user_id = ObjectId().toString()
this.req.params = { user_id: this.user_id }
this.UserGetter.getUser = sinon.stub().callsArgWith(2, null, null)
@@ -151,13 +151,13 @@ describe('UserInfoController', function() {
)
})
- it('should return 404 to the client', function() {
+ it('should return 404 to the client', function () {
return this.res.statusCode.should.equal(404)
})
})
- describe('when the user id is invalid', function() {
- beforeEach(function() {
+ describe('when the user id is invalid', function () {
+ beforeEach(function () {
this.user_id = 'invalid'
this.req.params = { user_id: this.user_id }
this.UserGetter.getUser = sinon.stub().callsArgWith(2, null, null)
@@ -168,14 +168,14 @@ describe('UserInfoController', function() {
)
})
- it('should return 400 to the client', function() {
+ it('should return 400 to the client', function () {
return this.res.statusCode.should.equal(400)
})
})
})
- describe('sendFormattedPersonalInfo', function() {
- beforeEach(function() {
+ describe('sendFormattedPersonalInfo', function () {
+ beforeEach(function () {
this.user = {
_id: ObjectId(),
first_name: 'Douglas',
@@ -197,19 +197,19 @@ describe('UserInfoController', function() {
)
})
- it('should format the user details for the response', function() {
+ it('should format the user details for the response', function () {
return this.UserInfoController.formatPersonalInfo
.calledWith(this.user)
.should.equal(true)
})
- it('should send the formatted details back to the client', function() {
+ it('should send the formatted details back to the client', function () {
return this.res.body.should.equal(JSON.stringify(this.formattedInfo))
})
})
- describe('formatPersonalInfo', function() {
- it('should return the correctly formatted data', function() {
+ describe('formatPersonalInfo', function () {
+ it('should return the correctly formatted data', function () {
this.user = {
_id: ObjectId(),
first_name: 'Douglas',
diff --git a/services/web/test/unit/src/User/UserOnboardingEmailManagerTests.js b/services/web/test/unit/src/User/UserOnboardingEmailManagerTests.js
index 09fb3bddbc..9e1f8933ba 100644
--- a/services/web/test/unit/src/User/UserOnboardingEmailManagerTests.js
+++ b/services/web/test/unit/src/User/UserOnboardingEmailManagerTests.js
@@ -7,8 +7,8 @@ const MODULE_PATH = path.join(
'../../../../app/src/Features/User/UserOnboardingEmailManager'
)
-describe('UserOnboardingEmailManager', function() {
- beforeEach(function() {
+describe('UserOnboardingEmailManager', function () {
+ beforeEach(function () {
this.fakeUserId = '123abc'
this.fakeUserEmail = 'frog@overleaf.com'
this.onboardingEmailsQueue = {
@@ -55,8 +55,8 @@ describe('UserOnboardingEmailManager', function() {
})
})
- describe('schedule email', function() {
- it('should schedule delayed job on queue', function() {
+ describe('schedule email', function () {
+ it('should schedule delayed job on queue', function () {
this.UserOnboardingEmailManager.scheduleOnboardingEmail({
_id: this.fakeUserId
})
@@ -67,7 +67,7 @@ describe('UserOnboardingEmailManager', function() {
)
})
- it('queue process callback should send onboarding email and update user', async function() {
+ it('queue process callback should send onboarding email and update user', async function () {
await this.queueProcessFunction({ data: { userId: this.fakeUserId } })
sinon.assert.calledWith(
this.UserGetter.promises.getUser,
@@ -90,7 +90,7 @@ describe('UserOnboardingEmailManager', function() {
)
})
- it('queue process callback should stop if user is not found', async function() {
+ it('queue process callback should stop if user is not found', async function () {
this.UserGetter.promises.getUser = sinon.stub().resolves()
await this.queueProcessFunction({ data: { userId: 'deleted-user' } })
sinon.assert.calledWith(
diff --git a/services/web/test/unit/src/User/UserPagesControllerTests.js b/services/web/test/unit/src/User/UserPagesControllerTests.js
index 5cbfd15c51..86d14d359a 100644
--- a/services/web/test/unit/src/User/UserPagesControllerTests.js
+++ b/services/web/test/unit/src/User/UserPagesControllerTests.js
@@ -20,8 +20,8 @@ const modulePath = path.join(
)
const { expect } = require('chai')
-describe('UserPagesController', function() {
- beforeEach(function() {
+describe('UserPagesController', function () {
+ beforeEach(function () {
this.settings = {
apis: {
v1: {
@@ -73,8 +73,8 @@ describe('UserPagesController', function() {
return (this.res = {})
})
- describe('registerPage', function() {
- it('should render the register page', function(done) {
+ describe('registerPage', function () {
+ it('should render the register page', function (done) {
this.res.render = page => {
page.should.equal('user/register')
return done()
@@ -82,7 +82,7 @@ describe('UserPagesController', function() {
return this.UserPagesController.registerPage(this.req, this.res)
})
- it('should set sharedProjectData', function(done) {
+ it('should set sharedProjectData', function (done) {
this.req.query.project_name = 'myProject'
this.req.query.user_first_name = 'user_first_name_here'
@@ -96,7 +96,7 @@ describe('UserPagesController', function() {
return this.UserPagesController.registerPage(this.req, this.res)
})
- it('should set newTemplateData', function(done) {
+ it('should set newTemplateData', function (done) {
this.req.session.templateData = { templateName: 'templateName' }
this.res.render = (page, opts) => {
@@ -106,7 +106,7 @@ describe('UserPagesController', function() {
return this.UserPagesController.registerPage(this.req, this.res)
})
- it('should not set the newTemplateData if there is nothing in the session', function(done) {
+ it('should not set the newTemplateData if there is nothing in the session', function (done) {
this.res.render = (page, opts) => {
assert.equal(opts.newTemplateData.templateName, undefined)
return done()
@@ -115,8 +115,8 @@ describe('UserPagesController', function() {
})
})
- describe('loginForm', function() {
- it('should render the login page', function(done) {
+ describe('loginForm', function () {
+ it('should render the login page', function (done) {
this.res.render = page => {
page.should.equal('user/login')
return done()
@@ -124,8 +124,8 @@ describe('UserPagesController', function() {
return this.UserPagesController.loginPage(this.req, this.res)
})
- describe('when an explicit redirect is set via query string', function() {
- beforeEach(function() {
+ describe('when an explicit redirect is set via query string', function () {
+ beforeEach(function () {
this.AuthenticationController._getRedirectFromSession = sinon
.stub()
.returns(null)
@@ -133,7 +133,7 @@ describe('UserPagesController', function() {
return (this.req.query.redir = '/somewhere/in/particular')
})
- it('should set a redirect', function(done) {
+ it('should set a redirect', function (done) {
this.res.render = page => {
this.AuthenticationController.setRedirectInSession.callCount.should.equal(
1
@@ -148,8 +148,8 @@ describe('UserPagesController', function() {
})
})
- describe('sessionsPage', function() {
- beforeEach(function() {
+ describe('sessionsPage', function () {
+ beforeEach(function () {
return this.UserSessionsManager.getAllUserSessions.callsArgWith(
2,
null,
@@ -157,15 +157,15 @@ describe('UserPagesController', function() {
)
})
- it('should render user/sessions', function(done) {
- this.res.render = function(page) {
+ it('should render user/sessions', function (done) {
+ this.res.render = function (page) {
page.should.equal('user/sessions')
return done()
}
return this.UserPagesController.sessionsPage(this.req, this.res)
})
- it('should have called getAllUserSessions', function(done) {
+ it('should have called getAllUserSessions', function (done) {
this.res.render = page => {
this.UserSessionsManager.getAllUserSessions.callCount.should.equal(1)
return done()
@@ -173,15 +173,15 @@ describe('UserPagesController', function() {
return this.UserPagesController.sessionsPage(this.req, this.res)
})
- describe('when getAllUserSessions produces an error', function() {
- beforeEach(function() {
+ describe('when getAllUserSessions produces an error', function () {
+ beforeEach(function () {
return this.UserSessionsManager.getAllUserSessions.callsArgWith(
2,
new Error('woops')
)
})
- it('should call next with an error', function(done) {
+ it('should call next with an error', function (done) {
this.next = err => {
assert(err !== null)
assert(err instanceof Error)
@@ -196,8 +196,8 @@ describe('UserPagesController', function() {
})
})
- describe('settingsPage', function() {
- beforeEach(function() {
+ describe('settingsPage', function () {
+ beforeEach(function () {
this.request.get = sinon
.stub()
.callsArgWith(1, null, { statusCode: 200 }, { has_password: true })
@@ -206,15 +206,15 @@ describe('UserPagesController', function() {
.callsArgWith(1, null, this.user))
})
- it('should render user/settings', function(done) {
- this.res.render = function(page) {
+ it('should render user/settings', function (done) {
+ this.res.render = function (page) {
page.should.equal('user/settings')
return done()
}
return this.UserPagesController.settingsPage(this.req, this.res)
})
- it('should send user', function(done) {
+ it('should send user', function (done) {
this.res.render = (page, opts) => {
opts.user.should.equal(this.user)
return done()
@@ -222,7 +222,7 @@ describe('UserPagesController', function() {
return this.UserPagesController.settingsPage(this.req, this.res)
})
- it("should set 'shouldAllowEditingDetails' to true", function(done) {
+ it("should set 'shouldAllowEditingDetails' to true", function (done) {
this.res.render = (page, opts) => {
opts.shouldAllowEditingDetails.should.equal(true)
return done()
@@ -230,7 +230,7 @@ describe('UserPagesController', function() {
return this.UserPagesController.settingsPage(this.req, this.res)
})
- it('should restructure thirdPartyIdentifiers data for template use', function(done) {
+ it('should restructure thirdPartyIdentifiers data for template use', function (done) {
const expectedResult = {
google: 'testId'
}
@@ -241,16 +241,16 @@ describe('UserPagesController', function() {
return this.UserPagesController.settingsPage(this.req, this.res)
})
- describe('when ldap.updateUserDetailsOnLogin is true', function() {
- beforeEach(function() {
+ describe('when ldap.updateUserDetailsOnLogin is true', function () {
+ beforeEach(function () {
return (this.settings.ldap = { updateUserDetailsOnLogin: true })
})
- afterEach(function() {
+ afterEach(function () {
return delete this.settings.ldap
})
- it('should set "shouldAllowEditingDetails" to false', function(done) {
+ it('should set "shouldAllowEditingDetails" to false', function (done) {
this.res.render = (page, opts) => {
opts.shouldAllowEditingDetails.should.equal(false)
return done()
@@ -259,16 +259,16 @@ describe('UserPagesController', function() {
})
})
- describe('when saml.updateUserDetailsOnLogin is true', function() {
- beforeEach(function() {
+ describe('when saml.updateUserDetailsOnLogin is true', function () {
+ beforeEach(function () {
return (this.settings.saml = { updateUserDetailsOnLogin: true })
})
- afterEach(function() {
+ afterEach(function () {
return delete this.settings.saml
})
- it('should set "shouldAllowEditingDetails" to false', function(done) {
+ it('should set "shouldAllowEditingDetails" to false', function (done) {
this.res.render = (page, opts) => {
opts.shouldAllowEditingDetails.should.equal(false)
return done()
diff --git a/services/web/test/unit/src/User/UserRegistrationHandlerTests.js b/services/web/test/unit/src/User/UserRegistrationHandlerTests.js
index a1a8455589..2ea25598e7 100644
--- a/services/web/test/unit/src/User/UserRegistrationHandlerTests.js
+++ b/services/web/test/unit/src/User/UserRegistrationHandlerTests.js
@@ -22,8 +22,8 @@ const sinon = require('sinon')
const { expect } = require('chai')
const EmailHelper = require('../../../../app/src/Features/Helpers/EmailHelper')
-describe('UserRegistrationHandler', function() {
- beforeEach(function() {
+describe('UserRegistrationHandler', function () {
+ beforeEach(function () {
this.user = { _id: (this.user_id = '31j2lk21kjl') }
this.User = { updateOne: sinon.stub().callsArgWith(2) }
this.UserGetter = { getUserByAnyEmail: sinon.stub() }
@@ -64,22 +64,22 @@ describe('UserRegistrationHandler', function() {
})
})
- describe('validate Register Request', function() {
- it('allows passing validation through', function() {
+ describe('validate Register Request', function () {
+ it('allows passing validation through', function () {
const result = this.handler._registrationRequestIsValid(
this.passingRequest
)
return result.should.equal(true)
})
- describe('failing email validation', function() {
- beforeEach(function() {
+ describe('failing email validation', function () {
+ beforeEach(function () {
return this.AuthenticationManager.validateEmail.returns({
message: 'email not set'
})
})
- it('does not allow through', function() {
+ it('does not allow through', function () {
const result = this.handler._registrationRequestIsValid(
this.passingRequest
)
@@ -87,14 +87,14 @@ describe('UserRegistrationHandler', function() {
})
})
- describe('failing password validation', function() {
- beforeEach(function() {
+ describe('failing password validation', function () {
+ beforeEach(function () {
return this.AuthenticationManager.validatePassword.returns({
message: 'password is too short'
})
})
- it('does not allow through', function() {
+ it('does not allow through', function () {
const result = this.handler._registrationRequestIsValid(
this.passingRequest
)
@@ -103,9 +103,9 @@ describe('UserRegistrationHandler', function() {
})
})
- describe('registerNewUser', function() {
- describe('holdingAccount', function(done) {
- beforeEach(function() {
+ describe('registerNewUser', function () {
+ describe('holdingAccount', function (done) {
+ beforeEach(function () {
this.user.holdingAccount = true
this.handler._registrationRequestIsValid = sinon.stub().returns(true)
return this.UserGetter.getUserByAnyEmail.callsArgWith(
@@ -115,14 +115,14 @@ describe('UserRegistrationHandler', function() {
)
})
- it('should not create a new user if there is a holding account there', function(done) {
+ it('should not create a new user if there is a holding account there', function (done) {
return this.handler.registerNewUser(this.passingRequest, err => {
this.UserCreator.createNewUser.called.should.equal(false)
return done()
})
})
- it('should set holding account to false', function(done) {
+ it('should set holding account to false', function (done) {
return this.handler.registerNewUser(this.passingRequest, err => {
const update = this.User.updateOne.args[0]
assert.deepEqual(update[0], { _id: this.user._id })
@@ -132,8 +132,8 @@ describe('UserRegistrationHandler', function() {
})
})
- describe('invalidRequest', function() {
- it('should not create a new user if the the request is not valid', function(done) {
+ describe('invalidRequest', function () {
+ it('should not create a new user if the the request is not valid', function (done) {
this.handler._registrationRequestIsValid = sinon.stub().returns(false)
return this.handler.registerNewUser(this.passingRequest, err => {
expect(err).to.exist
@@ -142,7 +142,7 @@ describe('UserRegistrationHandler', function() {
})
})
- it('should return email registered in the error if there is a non holdingAccount there', function(done) {
+ it('should return email registered in the error if there is a non holdingAccount there', function (done) {
this.UserGetter.getUserByAnyEmail.callsArgWith(
1,
null,
@@ -160,13 +160,13 @@ describe('UserRegistrationHandler', function() {
})
})
- describe('validRequest', function() {
- beforeEach(function() {
+ describe('validRequest', function () {
+ beforeEach(function () {
this.handler._registrationRequestIsValid = sinon.stub().returns(true)
return this.UserGetter.getUserByAnyEmail.callsArgWith(1)
})
- it('should create a new user', function(done) {
+ it('should create a new user', function (done) {
return this.handler.registerNewUser(this.passingRequest, err => {
this.UserCreator.createNewUser
.calledWith({
@@ -180,7 +180,7 @@ describe('UserRegistrationHandler', function() {
})
})
- it('lower case email', function(done) {
+ it('lower case email', function (done) {
this.passingRequest.email = 'soMe@eMail.cOm'
return this.handler.registerNewUser(this.passingRequest, err => {
this.UserCreator.createNewUser.args[0][0].email.should.equal(
@@ -190,7 +190,7 @@ describe('UserRegistrationHandler', function() {
})
})
- it('trim white space from email', function(done) {
+ it('trim white space from email', function (done) {
this.passingRequest.email = ' some@email.com '
return this.handler.registerNewUser(this.passingRequest, err => {
this.UserCreator.createNewUser.args[0][0].email.should.equal(
@@ -200,7 +200,7 @@ describe('UserRegistrationHandler', function() {
})
})
- it('should set the password', function(done) {
+ it('should set the password', function (done) {
return this.handler.registerNewUser(this.passingRequest, err => {
this.AuthenticationManager.setUserPassword
.calledWith(this.user, this.passingRequest.password)
@@ -209,7 +209,7 @@ describe('UserRegistrationHandler', function() {
})
})
- it('should add the user to the newsletter if accepted terms', function(done) {
+ it('should add the user to the newsletter if accepted terms', function (done) {
this.passingRequest.subscribeToNewsletter = 'true'
return this.handler.registerNewUser(this.passingRequest, err => {
this.NewsLetterManager.subscribe
@@ -219,7 +219,7 @@ describe('UserRegistrationHandler', function() {
})
})
- it('should not add the user to the newsletter if not accepted terms', function(done) {
+ it('should not add the user to the newsletter if not accepted terms', function (done) {
return this.handler.registerNewUser(this.passingRequest, err => {
this.NewsLetterManager.subscribe
.calledWith(this.user)
@@ -228,7 +228,7 @@ describe('UserRegistrationHandler', function() {
})
})
- it('should track the registration event', function(done) {
+ it('should track the registration event', function (done) {
return this.handler.registerNewUser(this.passingRequest, err => {
this.AnalyticsManager.recordEvent
.calledWith(this.user._id, 'user-registered')
@@ -238,13 +238,13 @@ describe('UserRegistrationHandler', function() {
})
})
- it('should call the ReferalAllocator', function(done) {
+ it('should call the ReferalAllocator', function (done) {
return done()
})
})
- describe('registerNewUserAndSendActivationEmail', function() {
- beforeEach(function() {
+ describe('registerNewUserAndSendActivationEmail', function () {
+ beforeEach(function () {
this.email = 'Email@example.com'
this.crypto.randomBytes = sinon.stub().returns({
toString: () => {
@@ -259,8 +259,8 @@ describe('UserRegistrationHandler', function() {
return (this.callback = sinon.stub())
})
- describe('with a new user', function() {
- beforeEach(function() {
+ describe('with a new user', function () {
+ beforeEach(function () {
this.user.email = this.email.toLowerCase()
this.handler.registerNewUser.callsArgWith(1, null, this.user)
return this.handler.registerNewUserAndSendActivationEmail(
@@ -269,7 +269,7 @@ describe('UserRegistrationHandler', function() {
)
})
- it('should ask the UserRegistrationHandler to register user', function() {
+ it('should ask the UserRegistrationHandler to register user', function () {
return this.handler.registerNewUser
.calledWith({
email: this.email,
@@ -278,7 +278,7 @@ describe('UserRegistrationHandler', function() {
.should.equal(true)
})
- it('should generate a new password reset token', function() {
+ it('should generate a new password reset token', function () {
const data = {
user_id: this.user._id.toString(),
email: this.user.email
@@ -288,7 +288,7 @@ describe('UserRegistrationHandler', function() {
.should.equal(true)
})
- it('should send a registered email', function() {
+ it('should send a registered email', function () {
return this.EmailHandler.sendEmail
.calledWith('registered', {
to: this.user.email,
@@ -297,7 +297,7 @@ describe('UserRegistrationHandler', function() {
.should.equal(true)
})
- it('should return the user', function() {
+ it('should return the user', function () {
return this.callback
.calledWith(
null,
@@ -308,8 +308,8 @@ describe('UserRegistrationHandler', function() {
})
})
- describe('with a user that already exists', function() {
- beforeEach(function() {
+ describe('with a user that already exists', function () {
+ beforeEach(function () {
this.handler.registerNewUser.callsArgWith(
1,
new Error('EmailAlreadyRegistered'),
@@ -321,7 +321,7 @@ describe('UserRegistrationHandler', function() {
)
})
- it('should still generate a new password token and email', function() {
+ it('should still generate a new password token and email', function () {
this.OneTimeTokenHandler.getNewToken.called.should.equal(true)
return this.EmailHandler.sendEmail.called.should.equal(true)
})
diff --git a/services/web/test/unit/src/User/UserSessionsManagerTests.js b/services/web/test/unit/src/User/UserSessionsManagerTests.js
index 0721e02b33..d4265de440 100644
--- a/services/web/test/unit/src/User/UserSessionsManagerTests.js
+++ b/services/web/test/unit/src/User/UserSessionsManagerTests.js
@@ -16,8 +16,8 @@ const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/User/UserSessionsManager.js'
const SandboxedModule = require('sandboxed-module')
-describe('UserSessionsManager', function() {
- beforeEach(function() {
+describe('UserSessionsManager', function () {
+ beforeEach(function () {
this.user = {
_id: 'abcd',
email: 'user@example.com'
@@ -61,15 +61,15 @@ describe('UserSessionsManager', function() {
}))
})
- describe('_sessionKey', function() {
- it('should build the correct key', function() {
+ describe('_sessionKey', function () {
+ it('should build the correct key', function () {
const result = this.UserSessionsManager._sessionKey(this.sessionId)
return result.should.equal('sess:some_session_id')
})
})
- describe('trackSession', function() {
- beforeEach(function() {
+ describe('trackSession', function () {
+ beforeEach(function () {
this.call = callback => {
return this.UserSessionsManager.trackSession(
this.user,
@@ -83,18 +83,18 @@ describe('UserSessionsManager', function() {
.returns(null))
})
- afterEach(function() {
+ afterEach(function () {
return this._checkSessions.restore()
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
return done()
})
})
- it('should call the appropriate redis methods', function(done) {
+ it('should call the appropriate redis methods', function (done) {
return this.call(err => {
this.rclient.multi.callCount.should.equal(1)
this.rclient.sadd.callCount.should.equal(1)
@@ -104,26 +104,26 @@ describe('UserSessionsManager', function() {
})
})
- it('should call _checkSessions', function(done) {
+ it('should call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(1)
return done()
})
})
- describe('when rclient produces an error', function() {
- beforeEach(function() {
+ describe('when rclient produces an error', function () {
+ beforeEach(function () {
return this.rclient.exec.callsArgWith(0, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should not call _checkSessions', function(done) {
+ it('should not call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
@@ -131,8 +131,8 @@ describe('UserSessionsManager', function() {
})
})
- describe('when no user is supplied', function() {
- beforeEach(function() {
+ describe('when no user is supplied', function () {
+ beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.trackSession(
null,
@@ -142,7 +142,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -150,7 +150,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call the appropriate redis methods', function(done) {
+ it('should not call the appropriate redis methods', function (done) {
return this.call(err => {
this.rclient.multi.callCount.should.equal(0)
this.rclient.sadd.callCount.should.equal(0)
@@ -160,7 +160,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call _checkSessions', function(done) {
+ it('should not call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
@@ -168,8 +168,8 @@ describe('UserSessionsManager', function() {
})
})
- describe('when no sessionId is supplied', function() {
- beforeEach(function() {
+ describe('when no sessionId is supplied', function () {
+ beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.trackSession(
this.user,
@@ -179,7 +179,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -187,7 +187,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call the appropriate redis methods', function(done) {
+ it('should not call the appropriate redis methods', function (done) {
return this.call(err => {
this.rclient.multi.callCount.should.equal(0)
this.rclient.sadd.callCount.should.equal(0)
@@ -197,7 +197,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call _checkSessions', function(done) {
+ it('should not call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
@@ -206,8 +206,8 @@ describe('UserSessionsManager', function() {
})
})
- describe('untrackSession', function() {
- beforeEach(function() {
+ describe('untrackSession', function () {
+ beforeEach(function () {
this.call = callback => {
return this.UserSessionsManager.untrackSession(
this.user,
@@ -221,11 +221,11 @@ describe('UserSessionsManager', function() {
.returns(null))
})
- afterEach(function() {
+ afterEach(function () {
return this._checkSessions.restore()
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(undefined)
@@ -233,7 +233,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should call the appropriate redis methods', function(done) {
+ it('should call the appropriate redis methods', function (done) {
return this.call(err => {
this.rclient.multi.callCount.should.equal(1)
this.rclient.srem.callCount.should.equal(1)
@@ -243,26 +243,26 @@ describe('UserSessionsManager', function() {
})
})
- it('should call _checkSessions', function(done) {
+ it('should call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(1)
return done()
})
})
- describe('when rclient produces an error', function() {
- beforeEach(function() {
+ describe('when rclient produces an error', function () {
+ beforeEach(function () {
return this.rclient.exec.callsArgWith(0, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should not call _checkSessions', function(done) {
+ it('should not call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
@@ -270,8 +270,8 @@ describe('UserSessionsManager', function() {
})
})
- describe('when no user is supplied', function() {
- beforeEach(function() {
+ describe('when no user is supplied', function () {
+ beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.untrackSession(
null,
@@ -281,7 +281,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -289,7 +289,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call the appropriate redis methods', function(done) {
+ it('should not call the appropriate redis methods', function (done) {
return this.call(err => {
this.rclient.multi.callCount.should.equal(0)
this.rclient.srem.callCount.should.equal(0)
@@ -299,7 +299,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call _checkSessions', function(done) {
+ it('should not call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
@@ -307,8 +307,8 @@ describe('UserSessionsManager', function() {
})
})
- describe('when no sessionId is supplied', function() {
- beforeEach(function() {
+ describe('when no sessionId is supplied', function () {
+ beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.untrackSession(
this.user,
@@ -318,7 +318,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -326,7 +326,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call the appropriate redis methods', function(done) {
+ it('should not call the appropriate redis methods', function (done) {
return this.call(err => {
this.rclient.multi.callCount.should.equal(0)
this.rclient.srem.callCount.should.equal(0)
@@ -336,7 +336,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call _checkSessions', function(done) {
+ it('should not call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
@@ -345,8 +345,8 @@ describe('UserSessionsManager', function() {
})
})
- describe('revokeAllUserSessions', function() {
- beforeEach(function() {
+ describe('revokeAllUserSessions', function () {
+ beforeEach(function () {
this.sessionKeys = ['sess:one', 'sess:two']
this.retain = []
this.rclient.smembers.callsArgWith(1, null, this.sessionKeys)
@@ -361,7 +361,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -369,7 +369,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should call the appropriate redis methods', function(done) {
+ it('should call the appropriate redis methods', function (done) {
return this.call(err => {
this.rclient.smembers.callCount.should.equal(1)
@@ -390,8 +390,8 @@ describe('UserSessionsManager', function() {
})
})
- describe('when a session is retained', function() {
- beforeEach(function() {
+ describe('when a session is retained', function () {
+ beforeEach(function () {
this.sessionKeys = ['sess:one', 'sess:two', 'sess:three', 'sess:four']
this.retain = ['two']
this.rclient.smembers.callsArgWith(1, null, this.sessionKeys)
@@ -405,7 +405,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -413,7 +413,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should call the appropriate redis methods', function(done) {
+ it('should call the appropriate redis methods', function (done) {
return this.call(err => {
this.rclient.smembers.callCount.should.equal(1)
this.rclient.del.callCount.should.equal(this.sessionKeys.length - 1)
@@ -422,7 +422,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should remove all sessions except for the retained one', function(done) {
+ it('should remove all sessions except for the retained one', function (done) {
return this.call(err => {
expect(this.rclient.del.firstCall.args[0]).to.deep.equal('sess:one')
expect(this.rclient.del.secondCall.args[0]).to.deep.equal(
@@ -439,21 +439,21 @@ describe('UserSessionsManager', function() {
})
})
- describe('when rclient produces an error', function() {
- beforeEach(function() {
+ describe('when rclient produces an error', function () {
+ beforeEach(function () {
return (this.rclient.del = sinon
.stub()
.callsArgWith(1, new Error('woops')))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should not call rclient.srem', function(done) {
+ it('should not call rclient.srem', function (done) {
return this.call(err => {
this.rclient.srem.callCount.should.equal(0)
return done()
@@ -461,8 +461,8 @@ describe('UserSessionsManager', function() {
})
})
- describe('when no user is supplied', function() {
- beforeEach(function() {
+ describe('when no user is supplied', function () {
+ beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.revokeAllUserSessions(
null,
@@ -472,7 +472,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -480,7 +480,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call the appropriate redis methods', function(done) {
+ it('should not call the appropriate redis methods', function (done) {
return this.call(err => {
this.rclient.smembers.callCount.should.equal(0)
this.rclient.del.callCount.should.equal(0)
@@ -490,12 +490,12 @@ describe('UserSessionsManager', function() {
})
})
- describe('when there are no keys to delete', function() {
- beforeEach(function() {
+ describe('when there are no keys to delete', function () {
+ beforeEach(function () {
return this.rclient.smembers.callsArgWith(1, null, [])
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -503,7 +503,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not do the delete operation', function(done) {
+ it('should not do the delete operation', function (done) {
return this.call(err => {
this.rclient.smembers.callCount.should.equal(1)
this.rclient.del.callCount.should.equal(0)
@@ -514,15 +514,15 @@ describe('UserSessionsManager', function() {
})
})
- describe('touch', function() {
- beforeEach(function() {
+ describe('touch', function () {
+ beforeEach(function () {
this.rclient.pexpire.callsArgWith(2, null)
return (this.call = callback => {
return this.UserSessionsManager.touch(this.user, callback)
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -530,19 +530,19 @@ describe('UserSessionsManager', function() {
})
})
- it('should call rclient.pexpire', function(done) {
+ it('should call rclient.pexpire', function (done) {
return this.call(err => {
this.rclient.pexpire.callCount.should.equal(1)
return done()
})
})
- describe('when rclient produces an error', function() {
- beforeEach(function() {
+ describe('when rclient produces an error', function () {
+ beforeEach(function () {
return this.rclient.pexpire.callsArgWith(2, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
@@ -550,14 +550,14 @@ describe('UserSessionsManager', function() {
})
})
- describe('when no user is supplied', function() {
- beforeEach(function() {
+ describe('when no user is supplied', function () {
+ beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.touch(null, callback)
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -565,7 +565,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call pexpire', function(done) {
+ it('should not call pexpire', function (done) {
return this.call(err => {
this.rclient.pexpire.callCount.should.equal(0)
return done()
@@ -574,8 +574,8 @@ describe('UserSessionsManager', function() {
})
})
- describe('getAllUserSessions', function() {
- beforeEach(function() {
+ describe('getAllUserSessions', function () {
+ beforeEach(function () {
this.sessionKeys = ['sess:one', 'sess:two', 'sess:three']
this.sessions = [
'{"user": {"ip_address": "a", "session_created": "b"}}',
@@ -596,14 +596,14 @@ describe('UserSessionsManager', function() {
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, sessions) => {
expect(err).to.equal(null)
return done()
})
})
- it('should get sessions', function(done) {
+ it('should get sessions', function (done) {
return this.call((err, sessions) => {
expect(sessions).to.deep.equal([
{ ip_address: 'a', session_created: 'b' },
@@ -613,48 +613,48 @@ describe('UserSessionsManager', function() {
})
})
- it('should have called rclient.smembers', function(done) {
+ it('should have called rclient.smembers', function (done) {
return this.call((err, sessions) => {
this.rclient.smembers.callCount.should.equal(1)
return done()
})
})
- it('should have called rclient.get', function(done) {
+ it('should have called rclient.get', function (done) {
return this.call((err, sessions) => {
this.rclient.get.callCount.should.equal(this.sessionKeys.length - 1)
return done()
})
})
- describe('when there are no other sessions', function() {
- beforeEach(function() {
+ describe('when there are no other sessions', function () {
+ beforeEach(function () {
this.sessionKeys = ['sess:two']
return this.rclient.smembers.callsArgWith(1, null, this.sessionKeys)
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call((err, sessions) => {
expect(err).to.equal(null)
return done()
})
})
- it('should produce an empty list of sessions', function(done) {
+ it('should produce an empty list of sessions', function (done) {
return this.call((err, sessions) => {
expect(sessions).to.deep.equal([])
return done()
})
})
- it('should have called rclient.smembers', function(done) {
+ it('should have called rclient.smembers', function (done) {
return this.call((err, sessions) => {
this.rclient.smembers.callCount.should.equal(1)
return done()
})
})
- it('should not have called rclient.mget', function(done) {
+ it('should not have called rclient.mget', function (done) {
return this.call((err, sessions) => {
this.rclient.mget.callCount.should.equal(0)
return done()
@@ -662,12 +662,12 @@ describe('UserSessionsManager', function() {
})
})
- describe('when smembers produces an error', function() {
- beforeEach(function() {
+ describe('when smembers produces an error', function () {
+ beforeEach(function () {
return this.rclient.smembers.callsArgWith(1, new Error('woops'))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, sessions) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -675,7 +675,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not have called rclient.mget', function(done) {
+ it('should not have called rclient.mget', function (done) {
return this.call((err, sessions) => {
this.rclient.mget.callCount.should.equal(0)
return done()
@@ -683,14 +683,14 @@ describe('UserSessionsManager', function() {
})
})
- describe('when get produces an error', function() {
- beforeEach(function() {
+ describe('when get produces an error', function () {
+ beforeEach(function () {
return (this.rclient.get = sinon
.stub()
.callsArgWith(1, new Error('woops')))
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call((err, sessions) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
@@ -700,8 +700,8 @@ describe('UserSessionsManager', function() {
})
})
- describe('_checkSessions', function() {
- beforeEach(function() {
+ describe('_checkSessions', function () {
+ beforeEach(function () {
this.call = callback => {
return this.UserSessionsManager._checkSessions(this.user, callback)
}
@@ -711,7 +711,7 @@ describe('UserSessionsManager', function() {
return this.rclient.srem.callsArgWith(2, null, {})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(undefined)
@@ -719,7 +719,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should call the appropriate redis methods', function(done) {
+ it('should call the appropriate redis methods', function (done) {
return this.call(err => {
this.rclient.smembers.callCount.should.equal(1)
this.rclient.get.callCount.should.equal(2)
@@ -728,13 +728,13 @@ describe('UserSessionsManager', function() {
})
})
- describe('when one of the keys is not present in redis', function() {
- beforeEach(function() {
+ describe('when one of the keys is not present in redis', function () {
+ beforeEach(function () {
this.rclient.get.onCall(0).callsArgWith(1, null, 'some-val')
return this.rclient.get.onCall(1).callsArgWith(1, null, null)
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(undefined)
@@ -742,7 +742,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should remove that key from the set', function(done) {
+ it('should remove that key from the set', function (done) {
return this.call(err => {
this.rclient.smembers.callCount.should.equal(1)
this.rclient.get.callCount.should.equal(2)
@@ -753,14 +753,14 @@ describe('UserSessionsManager', function() {
})
})
- describe('when no user is supplied', function() {
- beforeEach(function() {
+ describe('when no user is supplied', function () {
+ beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager._checkSessions(null, callback)
})
})
- it('should not produce an error', function(done) {
+ it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
@@ -768,7 +768,7 @@ describe('UserSessionsManager', function() {
})
})
- it('should not call redis methods', function(done) {
+ it('should not call redis methods', function (done) {
return this.call(err => {
this.rclient.smembers.callCount.should.equal(0)
this.rclient.get.callCount.should.equal(0)
@@ -777,20 +777,20 @@ describe('UserSessionsManager', function() {
})
})
- describe('when one of the get operations produces an error', function() {
- beforeEach(function() {
+ describe('when one of the get operations produces an error', function () {
+ beforeEach(function () {
this.rclient.get.onCall(0).callsArgWith(1, new Error('woops'), null)
return this.rclient.get.onCall(1).callsArgWith(1, null, null)
})
- it('should produce an error', function(done) {
+ it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
- it('should call the right redis methods, bailing out early', function(done) {
+ it('should call the right redis methods, bailing out early', function (done) {
return this.call(err => {
this.rclient.smembers.callCount.should.equal(1)
this.rclient.get.callCount.should.equal(1)
diff --git a/services/web/test/unit/src/User/UserUpdaterTests.js b/services/web/test/unit/src/User/UserUpdaterTests.js
index 1dee14fefe..b0e4707d60 100644
--- a/services/web/test/unit/src/User/UserUpdaterTests.js
+++ b/services/web/test/unit/src/User/UserUpdaterTests.js
@@ -9,8 +9,8 @@ const tk = require('timekeeper')
const { expect } = require('chai')
const { normalizeQuery } = require('../../../../app/src/Features/Helpers/Mongo')
-describe('UserUpdater', function() {
- beforeEach(function() {
+describe('UserUpdater', function () {
+ beforeEach(function () {
tk.freeze(Date.now())
this.mongodb = {
db: {},
@@ -95,17 +95,17 @@ describe('UserUpdater', function() {
this.callback = sinon.stub()
})
- afterEach(function() {
+ afterEach(function () {
return tk.reset()
})
- describe('addAffiliationForNewUser', function(done) {
- beforeEach(function() {
+ describe('addAffiliationForNewUser', function (done) {
+ beforeEach(function () {
this.UserUpdater.updateUser = sinon
.stub()
.callsArgWith(2, null, { n: 1, nModified: 1, ok: 1 })
})
- it('should not remove affiliationUnchecked flag if v1 returns an error', function(done) {
+ it('should not remove affiliationUnchecked flag if v1 returns an error', function (done) {
this.addAffiliation.yields(true)
this.UserUpdater.addAffiliationForNewUser(
this.stubbedUser._id,
@@ -118,7 +118,7 @@ describe('UserUpdater', function() {
}
)
})
- it('should remove affiliationUnchecked flag if v1 does not return an error', function(done) {
+ it('should remove affiliationUnchecked flag if v1 does not return an error', function (done) {
this.addAffiliation.yields()
this.UserUpdater.addAffiliationForNewUser(
this.stubbedUser._id,
@@ -137,8 +137,8 @@ describe('UserUpdater', function() {
})
})
- describe('changeEmailAddress', function() {
- beforeEach(function() {
+ describe('changeEmailAddress', function () {
+ beforeEach(function () {
this.auditLog = {
initiatorId: 'abc123',
ipAddress: '0:0:0:0'
@@ -149,7 +149,7 @@ describe('UserUpdater', function() {
this.UserUpdater.removeEmailAddress = sinon.stub().callsArgWith(2)
})
- it('change email', function(done) {
+ it('change email', function (done) {
this.UserUpdater.changeEmailAddress(
this.stubbedUser._id,
this.newEmail,
@@ -176,7 +176,7 @@ describe('UserUpdater', function() {
)
})
- it('validates email', function(done) {
+ it('validates email', function (done) {
this.UserUpdater.changeEmailAddress(
this.stubbedUser._id,
'foo',
@@ -188,7 +188,7 @@ describe('UserUpdater', function() {
)
})
- it('handle error', function(done) {
+ it('handle error', function (done) {
this.UserUpdater.removeEmailAddress.callsArgWith(2, new Error('nope'))
this.UserUpdater.changeEmailAddress(
this.stubbedUser._id,
@@ -202,15 +202,15 @@ describe('UserUpdater', function() {
})
})
- describe('addEmailAddress', function() {
- beforeEach(function() {
+ describe('addEmailAddress', function () {
+ beforeEach(function () {
this.UserGetter.promises.ensureUniqueEmailAddress = sinon
.stub()
.resolves()
this.UserUpdater.promises.updateUser = sinon.stub().resolves()
})
- it('add email', function(done) {
+ it('add email', function (done) {
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
this.newEmail,
@@ -242,7 +242,7 @@ describe('UserUpdater', function() {
)
})
- it('add affiliation', function(done) {
+ it('add affiliation', function (done) {
const affiliationOptions = {
university: { id: 1 },
role: 'Prof',
@@ -267,7 +267,7 @@ describe('UserUpdater', function() {
)
})
- it('handle affiliation error', function(done) {
+ it('handle affiliation error', function (done) {
this.InstitutionsAPI.promises.addAffiliation.rejects(new Error('nope'))
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
@@ -282,7 +282,7 @@ describe('UserUpdater', function() {
)
})
- it('validates email', function(done) {
+ it('validates email', function (done) {
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
'bar',
@@ -295,7 +295,7 @@ describe('UserUpdater', function() {
)
})
- it('updates the audit log', function(done) {
+ it('updates the audit log', function (done) {
this.ip = '127:0:0:0'
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
@@ -320,13 +320,13 @@ describe('UserUpdater', function() {
)
})
- describe('errors', function() {
- describe('via UserAuditLogHandler', function() {
+ describe('errors', function () {
+ describe('via UserAuditLogHandler', function () {
const anError = new Error('oops')
- beforeEach(function() {
+ beforeEach(function () {
this.UserAuditLogHandler.promises.addEntry.throws(anError)
})
- it('should not add email and should return error', function(done) {
+ it('should not add email and should return error', function (done) {
this.UserUpdater.addEmailAddress(
this.stubbedUser._id,
this.newEmail,
@@ -345,14 +345,14 @@ describe('UserUpdater', function() {
})
})
- describe('removeEmailAddress', function() {
- beforeEach(function() {
+ describe('removeEmailAddress', function () {
+ beforeEach(function () {
this.UserUpdater.updateUser = sinon
.stub()
.callsArgWith(2, null, { nMatched: 1 })
})
- it('remove email', function(done) {
+ it('remove email', function (done) {
this.UserUpdater.removeEmailAddress(
this.stubbedUser._id,
this.newEmail,
@@ -369,7 +369,7 @@ describe('UserUpdater', function() {
)
})
- it('remove affiliation', function(done) {
+ it('remove affiliation', function (done) {
this.UserUpdater.removeEmailAddress(
this.stubbedUser._id,
this.newEmail,
@@ -384,7 +384,7 @@ describe('UserUpdater', function() {
)
})
- it('refresh features', function(done) {
+ it('refresh features', function (done) {
this.UserUpdater.removeEmailAddress(
this.stubbedUser._id,
this.newEmail,
@@ -396,7 +396,7 @@ describe('UserUpdater', function() {
)
})
- it('handle error', function(done) {
+ it('handle error', function (done) {
this.UserUpdater.updateUser = sinon
.stub()
.callsArgWith(2, new Error('nope'))
@@ -411,7 +411,7 @@ describe('UserUpdater', function() {
)
})
- it('handle missed update', function(done) {
+ it('handle missed update', function (done) {
this.UserUpdater.updateUser = sinon.stub().callsArgWith(2, null, { n: 0 })
this.UserUpdater.removeEmailAddress(
@@ -424,7 +424,7 @@ describe('UserUpdater', function() {
)
})
- it('handle affiliation error', function(done) {
+ it('handle affiliation error', function (done) {
this.removeAffiliation.callsArgWith(2, new Error('nope'))
this.UserUpdater.removeEmailAddress(
this.stubbedUser._id,
@@ -437,7 +437,7 @@ describe('UserUpdater', function() {
)
})
- it('validates email', function(done) {
+ it('validates email', function (done) {
this.UserUpdater.removeEmailAddress(this.stubbedUser._id, 'baz', err => {
expect(err).to.exist
done()
@@ -445,8 +445,8 @@ describe('UserUpdater', function() {
})
})
- describe('setDefaultEmailAddress', function() {
- beforeEach(function() {
+ describe('setDefaultEmailAddress', function () {
+ beforeEach(function () {
this.auditLog = {
initiatorId: this.stubbedUser,
ipAddress: '0:0:0:0'
@@ -462,7 +462,7 @@ describe('UserUpdater', function() {
this.RecurlyWrapper.promises.updateAccountEmailAddress.resolves()
})
- it('set default', function(done) {
+ it('set default', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 1 })
this.UserUpdater.setDefaultEmailAddress(
@@ -483,7 +483,7 @@ describe('UserUpdater', function() {
)
})
- it('set changed the email in newsletter', function(done) {
+ it('set changed the email in newsletter', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 1 })
this.UserUpdater.setDefaultEmailAddress(
@@ -504,7 +504,7 @@ describe('UserUpdater', function() {
)
})
- it('handle error', function(done) {
+ it('handle error', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().rejects(Error('nope'))
this.UserUpdater.setDefaultEmailAddress(
@@ -519,7 +519,7 @@ describe('UserUpdater', function() {
)
})
- it('handle missed update', function(done) {
+ it('handle missed update', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 0 })
this.UserUpdater.setDefaultEmailAddress(
@@ -534,7 +534,7 @@ describe('UserUpdater', function() {
)
})
- it('validates email', function(done) {
+ it('validates email', function (done) {
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
'.edu',
@@ -547,7 +547,7 @@ describe('UserUpdater', function() {
)
})
- it('updates audit log', function(done) {
+ it('updates audit log', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 1 })
this.UserUpdater.setDefaultEmailAddress(
@@ -574,7 +574,7 @@ describe('UserUpdater', function() {
)
})
- it('blocks email update if audit log returns an error', function(done) {
+ it('blocks email update if audit log returns an error', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub()
this.UserAuditLogHandler.promises.addEntry.rejects(new Error('oops'))
this.UserUpdater.setDefaultEmailAddress(
@@ -590,8 +590,8 @@ describe('UserUpdater', function() {
)
})
- describe('when email not confirmed', function() {
- beforeEach(function() {
+ describe('when email not confirmed', function () {
+ beforeEach(function () {
this.stubbedUser.emails = [
{
email: this.newEmail,
@@ -601,7 +601,7 @@ describe('UserUpdater', function() {
this.UserUpdater.promises.updateUser = sinon.stub()
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
@@ -619,14 +619,14 @@ describe('UserUpdater', function() {
})
})
- describe('when email does not belong to user', function() {
- beforeEach(function() {
+ describe('when email does not belong to user', function () {
+ beforeEach(function () {
this.stubbedUser.emails = []
this.UserGetter.promises.getUser.resolves(this.stubbedUser)
this.UserUpdater.promises.updateUser = sinon.stub()
})
- it('should callback with error', function() {
+ it('should callback with error', function () {
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
@@ -644,8 +644,8 @@ describe('UserUpdater', function() {
})
})
- describe('security alert', function() {
- it('should be sent to old and new email when sendSecurityAlert=true', function(done) {
+ describe('security alert', function () {
+ it('should be sent to old and new email when sendSecurityAlert=true', function (done) {
// this.UserGetter.promises.getUser.resolves(this.stubbedUser)
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 1 })
@@ -670,16 +670,16 @@ describe('UserUpdater', function() {
}
)
})
- describe('errors', function() {
+ describe('errors', function () {
const anError = new Error('oops')
- describe('EmailHandler', function() {
- beforeEach(function() {
+ describe('EmailHandler', function () {
+ beforeEach(function () {
this.EmailHandler.promises.sendEmail.rejects(anError)
this.UserUpdater.promises.updateUser = sinon
.stub()
.resolves({ n: 1 })
})
- it('should log but not pass back the error', function(done) {
+ it('should log but not pass back the error', function (done) {
this.UserUpdater.setDefaultEmailAddress(
this.stubbedUser._id,
this.newEmail,
@@ -705,12 +705,12 @@ describe('UserUpdater', function() {
})
})
- describe('confirmEmail', function() {
- beforeEach(function() {
+ describe('confirmEmail', function () {
+ beforeEach(function () {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 1 })
})
- it('should update the email record', function(done) {
+ it('should update the email record', function (done) {
this.UserUpdater.confirmEmail(
this.stubbedUser._id,
this.stubbedUserEmail,
@@ -737,7 +737,7 @@ describe('UserUpdater', function() {
)
})
- it('add affiliation', function(done) {
+ it('add affiliation', function (done) {
this.UserUpdater.confirmEmail(
this.stubbedUser._id,
this.newEmail,
@@ -757,7 +757,7 @@ describe('UserUpdater', function() {
)
})
- it('handle error', function(done) {
+ it('handle error', function (done) {
this.UserUpdater.promises.updateUser = sinon
.stub()
.throws(new Error('nope'))
@@ -772,7 +772,7 @@ describe('UserUpdater', function() {
)
})
- it('handle missed update', function(done) {
+ it('handle missed update', function (done) {
this.UserUpdater.promises.updateUser = sinon.stub().resolves({ n: 0 })
this.UserUpdater.confirmEmail(
@@ -785,14 +785,14 @@ describe('UserUpdater', function() {
)
})
- it('validates email', function(done) {
+ it('validates email', function (done) {
this.UserUpdater.confirmEmail(this.stubbedUser._id, '@', err => {
expect(err).to.exist
done()
})
})
- it('handle affiliation error', function(done) {
+ it('handle affiliation error', function (done) {
this.InstitutionsAPI.promises.addAffiliation.throws(Error('nope'))
this.UserUpdater.confirmEmail(
this.stubbedUser._id,
@@ -805,7 +805,7 @@ describe('UserUpdater', function() {
)
})
- it('refresh features', function(done) {
+ it('refresh features', function (done) {
this.UserUpdater.confirmEmail(
this.stubbedUser._id,
this.newEmail,
diff --git a/services/web/test/unit/src/UserMembership/UserMembershipControllerTests.js b/services/web/test/unit/src/UserMembership/UserMembershipControllerTests.js
index 427628204a..80f4cf0c72 100644
--- a/services/web/test/unit/src/UserMembership/UserMembershipControllerTests.js
+++ b/services/web/test/unit/src/UserMembership/UserMembershipControllerTests.js
@@ -22,8 +22,8 @@ const MockResponse = require('../helpers/MockResponse')
const EntityConfigs = require('../../../../app/src/Features/UserMembership/UserMembershipEntityConfigs')
const Errors = require('../../../../app/src/Features/Errors/Errors')
-describe('UserMembershipController', function() {
- beforeEach(function() {
+describe('UserMembershipController', function () {
+ beforeEach(function () {
this.req = new MockRequest()
this.req.params.id = 'mock-entity-id'
this.user = { _id: 'mock-user-id' }
@@ -77,13 +77,13 @@ describe('UserMembershipController', function() {
))
})
- describe('index', function() {
- beforeEach(function() {
+ describe('index', function () {
+ beforeEach(function () {
this.req.entity = this.subscription
return (this.req.entityConfig = EntityConfigs.group)
})
- it('get users', function(done) {
+ it('get users', function (done) {
return this.UserMembershipController.index(this.req, {
render: () => {
sinon.assert.calledWithMatch(
@@ -96,7 +96,7 @@ describe('UserMembershipController', function() {
})
})
- it('render group view', function(done) {
+ it('render group view', function (done) {
return this.UserMembershipController.index(this.req, {
render: (viewPath, viewParams) => {
expect(viewPath).to.equal('user_membership/index')
@@ -111,7 +111,7 @@ describe('UserMembershipController', function() {
})
})
- it('render group managers view', function(done) {
+ it('render group managers view', function (done) {
this.req.entityConfig = EntityConfigs.groupManagers
return this.UserMembershipController.index(this.req, {
render: (viewPath, viewParams) => {
@@ -127,7 +127,7 @@ describe('UserMembershipController', function() {
})
})
- it('render institution view', function(done) {
+ it('render institution view', function (done) {
this.req.entity = this.institution
this.req.entityConfig = EntityConfigs.institution
return this.UserMembershipController.index(this.req, {
@@ -143,14 +143,14 @@ describe('UserMembershipController', function() {
})
})
- describe('add', function() {
- beforeEach(function() {
+ describe('add', function () {
+ beforeEach(function () {
this.req.body.email = this.newUser.email
this.req.entity = this.subscription
return (this.req.entityConfig = EntityConfigs.groupManagers)
})
- it('add user', function(done) {
+ it('add user', function (done) {
return this.UserMembershipController.add(this.req, {
json: () => {
sinon.assert.calledWithMatch(
@@ -164,7 +164,7 @@ describe('UserMembershipController', function() {
})
})
- it('return user object', function(done) {
+ it('return user object', function (done) {
return this.UserMembershipController.add(this.req, {
json: payload => {
payload.user.should.equal(this.newUser)
@@ -173,7 +173,7 @@ describe('UserMembershipController', function() {
})
})
- it('handle readOnly entity', function(done) {
+ it('handle readOnly entity', function (done) {
this.req.entityConfig = EntityConfigs.group
return this.UserMembershipController.add(this.req, null, error => {
expect(error).to.exist
@@ -182,7 +182,7 @@ describe('UserMembershipController', function() {
})
})
- it('handle user already added', function(done) {
+ it('handle user already added', function (done) {
this.UserMembershipHandler.addUser.yields({ alreadyAdded: true })
return this.UserMembershipController.add(this.req, {
status: () => ({
@@ -194,7 +194,7 @@ describe('UserMembershipController', function() {
})
})
- it('handle user not found', function(done) {
+ it('handle user not found', function (done) {
this.UserMembershipHandler.addUser.yields({ userNotFound: true })
return this.UserMembershipController.add(this.req, {
status: () => ({
@@ -206,7 +206,7 @@ describe('UserMembershipController', function() {
})
})
- it('handle invalid email', function(done) {
+ it('handle invalid email', function (done) {
this.req.body.email = 'not_valid_email'
return this.UserMembershipController.add(this.req, {
status: () => ({
@@ -219,14 +219,14 @@ describe('UserMembershipController', function() {
})
})
- describe('remove', function() {
- beforeEach(function() {
+ describe('remove', function () {
+ beforeEach(function () {
this.req.params.userId = this.newUser._id
this.req.entity = this.subscription
return (this.req.entityConfig = EntityConfigs.groupManagers)
})
- it('remove user', function(done) {
+ it('remove user', function (done) {
return this.UserMembershipController.remove(this.req, {
sendStatus: () => {
sinon.assert.calledWithMatch(
@@ -240,7 +240,7 @@ describe('UserMembershipController', function() {
})
})
- it('handle readOnly entity', function(done) {
+ it('handle readOnly entity', function (done) {
this.req.entityConfig = EntityConfigs.group
return this.UserMembershipController.remove(this.req, null, error => {
expect(error).to.exist
@@ -249,7 +249,7 @@ describe('UserMembershipController', function() {
})
})
- it('prevent self removal', function(done) {
+ it('prevent self removal', function (done) {
this.req.params.userId = this.user._id
return this.UserMembershipController.remove(this.req, {
status: () => ({
@@ -261,7 +261,7 @@ describe('UserMembershipController', function() {
})
})
- it('prevent admin removal', function(done) {
+ it('prevent admin removal', function (done) {
this.UserMembershipHandler.removeUser.yields({ isAdmin: true })
return this.UserMembershipController.remove(this.req, {
status: () => ({
@@ -274,8 +274,8 @@ describe('UserMembershipController', function() {
})
})
- describe('exportCsv', function() {
- beforeEach(function() {
+ describe('exportCsv', function () {
+ beforeEach(function () {
this.req.entity = this.subscription
this.req.entityConfig = EntityConfigs.groupManagers
this.res = new MockResponse()
@@ -285,7 +285,7 @@ describe('UserMembershipController', function() {
return this.UserMembershipController.exportCsv(this.req, this.res)
})
- it('get users', function() {
+ it('get users', function () {
return sinon.assert.calledWithMatch(
this.UserMembershipHandler.getUsers,
this.subscription,
@@ -293,11 +293,11 @@ describe('UserMembershipController', function() {
)
})
- it('should set the correct content type on the request', function() {
+ it('should set the correct content type on the request', function () {
return assertCalledWith(this.res.contentType, 'text/csv')
})
- it('should name the exported csv file', function() {
+ it('should name the exported csv file', function () {
return assertCalledWith(
this.res.header,
'Content-Disposition',
@@ -305,7 +305,7 @@ describe('UserMembershipController', function() {
)
})
- it('should export the correct csv', function() {
+ it('should export the correct csv', function () {
return assertCalledWith(
this.res.send,
'"email","last_logged_in_at"\n"mock-email-1@foo.com","2020-08-09T12:43:11.467Z"\n"mock-email-2@foo.com","2020-05-20T10:41:11.407Z"'
@@ -313,13 +313,13 @@ describe('UserMembershipController', function() {
})
})
- describe('new', function() {
- beforeEach(function() {
+ describe('new', function () {
+ beforeEach(function () {
this.req.params.name = 'publisher'
return (this.req.params.id = 'abc')
})
- it('renders view', function(done) {
+ it('renders view', function (done) {
return this.UserMembershipController.new(this.req, {
render: (viewPath, data) => {
expect(data.entityName).to.eq('publisher')
@@ -330,14 +330,14 @@ describe('UserMembershipController', function() {
})
})
- describe('create', function() {
- beforeEach(function() {
+ describe('create', function () {
+ beforeEach(function () {
this.req.params.name = 'institution'
this.req.entityConfig = EntityConfigs.institution
return (this.req.params.id = 123)
})
- it('creates institution', function(done) {
+ it('creates institution', function (done) {
return this.UserMembershipController.create(this.req, {
redirect: path => {
expect(path).to.eq(EntityConfigs.institution.pathsFor(123).index)
diff --git a/services/web/test/unit/src/UserMembership/UserMembershipHandlerTests.js b/services/web/test/unit/src/UserMembership/UserMembershipHandlerTests.js
index ddca4fd3d4..6f93e7def7 100644
--- a/services/web/test/unit/src/UserMembership/UserMembershipHandlerTests.js
+++ b/services/web/test/unit/src/UserMembership/UserMembershipHandlerTests.js
@@ -22,8 +22,8 @@ const SandboxedModule = require('sandboxed-module')
const Errors = require('../../../../app/src/Features/Errors/Errors')
const EntityConfigs = require('../../../../app/src/Features/UserMembership/UserMembershipEntityConfigs')
-describe('UserMembershipHandler', function() {
- beforeEach(function() {
+describe('UserMembershipHandler', function () {
+ beforeEach(function () {
this.user = { _id: ObjectId() }
this.newUser = { _id: ObjectId(), email: 'new-user-email@foo.bar' }
this.fakeEntityId = ObjectId()
@@ -83,8 +83,8 @@ describe('UserMembershipHandler', function() {
}))
})
- describe('getEntityWithoutAuthorizationCheck', function() {
- it('get publisher', function(done) {
+ describe('getEntityWithoutAuthorizationCheck', function () {
+ it('get publisher', function (done) {
return this.UserMembershipHandler.getEntityWithoutAuthorizationCheck(
this.fakeEntityId,
EntityConfigs.publisher,
@@ -99,9 +99,9 @@ describe('UserMembershipHandler', function() {
})
})
- describe('getUsers', function() {
- describe('group', function() {
- it('build view model for all users', function(done) {
+ describe('getUsers', function () {
+ describe('group', function () {
+ it('build view model for all users', function (done) {
return this.UserMembershipHandler.getUsers(
this.subscription,
EntityConfigs.group,
@@ -119,8 +119,8 @@ describe('UserMembershipHandler', function() {
})
})
- describe('group mamagers', function() {
- it('build view model for all managers', function(done) {
+ describe('group mamagers', function () {
+ it('build view model for all managers', function (done) {
return this.UserMembershipHandler.getUsers(
this.subscription,
EntityConfigs.groupManagers,
@@ -135,8 +135,8 @@ describe('UserMembershipHandler', function() {
})
})
- describe('institution', function() {
- it('build view model for all managers', function(done) {
+ describe('institution', function () {
+ it('build view model for all managers', function (done) {
return this.UserMembershipHandler.getUsers(
this.institution,
EntityConfigs.institution,
@@ -152,8 +152,8 @@ describe('UserMembershipHandler', function() {
})
})
- describe('createEntity', function() {
- it('creates publisher', function(done) {
+ describe('createEntity', function () {
+ it('creates publisher', function (done) {
return this.UserMembershipHandler.createEntity(
this.fakeEntityId,
EntityConfigs.publisher,
@@ -166,13 +166,13 @@ describe('UserMembershipHandler', function() {
})
})
- describe('addUser', function() {
- beforeEach(function() {
+ describe('addUser', function () {
+ beforeEach(function () {
return (this.email = this.newUser.email)
})
- describe('institution', function() {
- it('get user', function(done) {
+ describe('institution', function () {
+ it('get user', function (done) {
return this.UserMembershipHandler.addUser(
this.institution,
EntityConfigs.institution,
@@ -184,7 +184,7 @@ describe('UserMembershipHandler', function() {
)
})
- it('handle user not found', function(done) {
+ it('handle user not found', function (done) {
this.UserGetter.getUserByAnyEmail.yields(null, null)
return this.UserMembershipHandler.addUser(
this.institution,
@@ -198,7 +198,7 @@ describe('UserMembershipHandler', function() {
)
})
- it('handle user already added', function(done) {
+ it('handle user already added', function (done) {
this.institution.managerIds.push(this.newUser._id)
return this.UserMembershipHandler.addUser(
this.institution,
@@ -212,7 +212,7 @@ describe('UserMembershipHandler', function() {
)
})
- it('add user to institution', function(done) {
+ it('add user to institution', function (done) {
return this.UserMembershipHandler.addUser(
this.institution,
EntityConfigs.institution,
@@ -226,7 +226,7 @@ describe('UserMembershipHandler', function() {
)
})
- it('return user view', function(done) {
+ it('return user view', function (done) {
return this.UserMembershipHandler.addUser(
this.institution,
EntityConfigs.institution,
@@ -240,9 +240,9 @@ describe('UserMembershipHandler', function() {
})
})
- describe('removeUser', function() {
- describe('institution', function() {
- it('remove user from institution', function(done) {
+ describe('removeUser', function () {
+ describe('institution', function () {
+ it('remove user from institution', function (done) {
return this.UserMembershipHandler.removeUser(
this.institution,
EntityConfigs.institution,
@@ -257,7 +257,7 @@ describe('UserMembershipHandler', function() {
)
})
- it('handle admin', function(done) {
+ it('handle admin', function (done) {
this.subscription.admin_id = this.newUser._id
return this.UserMembershipHandler.removeUser(
this.subscription,
diff --git a/services/web/test/unit/src/UserMembership/UserMembershipViewModelTests.js b/services/web/test/unit/src/UserMembership/UserMembershipViewModelTests.js
index f1a6000be6..fece8b9c43 100644
--- a/services/web/test/unit/src/UserMembership/UserMembershipViewModelTests.js
+++ b/services/web/test/unit/src/UserMembership/UserMembershipViewModelTests.js
@@ -23,8 +23,8 @@ const {
normalizeQuery
} = require('../../../../app/src/Features/Helpers/Mongo')
-describe('UserMembershipViewModel', function() {
- beforeEach(function() {
+describe('UserMembershipViewModel', function () {
+ beforeEach(function () {
this.UserGetter = { getUser: sinon.stub() }
this.UserMembershipViewModel = SandboxedModule.require(modulePath, {
requires: {
@@ -42,8 +42,8 @@ describe('UserMembershipViewModel', function() {
}
})
- describe('build', function() {
- it('build email', function() {
+ describe('build', function () {
+ it('build email', function () {
const viewModel = this.UserMembershipViewModel.build(this.email)
return expect(viewModel).to.deep.equal({
email: this.email,
@@ -55,7 +55,7 @@ describe('UserMembershipViewModel', function() {
})
})
- it('build user', function() {
+ it('build user', function () {
const viewModel = this.UserMembershipViewModel.build(this.user)
expect(viewModel._id).to.equal(this.user._id)
expect(viewModel.email).to.equal(this.user.email)
@@ -64,12 +64,12 @@ describe('UserMembershipViewModel', function() {
})
})
- describe('build async', function() {
- beforeEach(function() {
+ describe('build async', function () {
+ beforeEach(function () {
return (this.UserMembershipViewModel.build = sinon.stub())
})
- it('build email', function(done) {
+ it('build email', function (done) {
return this.UserMembershipViewModel.buildAsync(
this.email,
(error, viewModel) => {
@@ -79,7 +79,7 @@ describe('UserMembershipViewModel', function() {
)
})
- it('build user', function(done) {
+ it('build user', function (done) {
return this.UserMembershipViewModel.buildAsync(
this.user,
(error, viewModel) => {
@@ -89,7 +89,7 @@ describe('UserMembershipViewModel', function() {
)
})
- it('build user id', function(done) {
+ it('build user id', function (done) {
this.UserGetter.getUser.yields(null, this.user)
return this.UserMembershipViewModel.buildAsync(
ObjectId(),
@@ -106,7 +106,7 @@ describe('UserMembershipViewModel', function() {
)
})
- it('build user id with error', function(done) {
+ it('build user id with error', function (done) {
this.UserGetter.getUser.yields(new Error('nope'))
const userId = ObjectId()
return this.UserMembershipViewModel.buildAsync(
diff --git a/services/web/test/unit/src/UserMembership/UserMembershipsHandlerTests.js b/services/web/test/unit/src/UserMembership/UserMembershipsHandlerTests.js
index 6da00d79df..946d260701 100644
--- a/services/web/test/unit/src/UserMembership/UserMembershipsHandlerTests.js
+++ b/services/web/test/unit/src/UserMembership/UserMembershipsHandlerTests.js
@@ -17,8 +17,8 @@ const modulePath =
'../../../../app/src/Features/UserMembership/UserMembershipsHandler'
const SandboxedModule = require('sandboxed-module')
-describe('UserMembershipsHandler', function() {
- beforeEach(function() {
+describe('UserMembershipsHandler', function () {
+ beforeEach(function () {
this.user = { _id: ObjectId() }
this.Institution = { updateMany: sinon.stub().yields(null) }
@@ -39,8 +39,8 @@ describe('UserMembershipsHandler', function() {
}))
})
- describe('remove user', function() {
- it('remove user from all entities', function(done) {
+ describe('remove user', function () {
+ it('remove user from all entities', function (done) {
return this.UserMembershipsHandler.removeUserFromAllEntities(
this.user._id,
error => {
diff --git a/services/web/test/unit/src/infrastructure/CsrfTests.js b/services/web/test/unit/src/infrastructure/CsrfTests.js
index a6aa2c0fc1..d51977b29b 100644
--- a/services/web/test/unit/src/infrastructure/CsrfTests.js
+++ b/services/web/test/unit/src/infrastructure/CsrfTests.js
@@ -15,8 +15,8 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/infrastructure/Csrf.js'
const SandboxedModule = require('sandboxed-module')
-describe('Csrf', function() {
- beforeEach(function() {
+describe('Csrf', function () {
+ beforeEach(function () {
this.csurf_csrf = sinon
.stub()
.callsArgWith(2, (this.err = { code: 'EBADCSRFTOKEN' }))
@@ -35,38 +35,38 @@ describe('Csrf', function() {
return (this.res = {})
})
- describe('the middleware', function() {
- describe('when there are no excluded routes', function() {
- it('passes the csrf error on', function() {
+ describe('the middleware', function () {
+ describe('when there are no excluded routes', function () {
+ it('passes the csrf error on', function () {
this.csrf.middleware(this.req, this.res, this.next)
return expect(this.next.calledWith(this.err)).to.equal(true)
})
})
- describe('when the route is excluded', function() {
- it('does not pass the csrf error on', function() {
+ describe('when the route is excluded', function () {
+ it('does not pass the csrf error on', function () {
this.csrf.disableDefaultCsrfProtection(this.path, 'POST')
this.csrf.middleware(this.req, this.res, this.next)
return expect(this.next.calledWith(this.err)).to.equal(false)
})
})
- describe('when there is a partial route match', function() {
- it('passes the csrf error on when the match is too short', function() {
+ describe('when there is a partial route match', function () {
+ it('passes the csrf error on when the match is too short', function () {
this.csrf.disableDefaultCsrfProtection('/foo', 'POST')
this.csrf.middleware(this.req, this.res, this.next)
return expect(this.next.calledWith(this.err)).to.equal(true)
})
- it('passes the csrf error on when the match is too long', function() {
+ it('passes the csrf error on when the match is too long', function () {
this.csrf.disableDefaultCsrfProtection('/foo/bar/baz', 'POST')
this.csrf.middleware(this.req, this.res, this.next)
return expect(this.next.calledWith(this.err)).to.equal(true)
})
})
- describe('when there are multiple exclusions', function() {
- it('does not pass the csrf error on when the match is present', function() {
+ describe('when there are multiple exclusions', function () {
+ it('does not pass the csrf error on when the match is present', function () {
this.csrf.disableDefaultCsrfProtection(this.path, 'POST')
this.csrf.disableDefaultCsrfProtection('/test', 'POST')
this.csrf.disableDefaultCsrfProtection('/a/b/c', 'POST')
@@ -74,7 +74,7 @@ describe('Csrf', function() {
return expect(this.next.calledWith(this.err)).to.equal(false)
})
- it('passes the csrf error on when the match is not present', function() {
+ it('passes the csrf error on when the match is not present', function () {
this.csrf.disableDefaultCsrfProtection('/url', 'POST')
this.csrf.disableDefaultCsrfProtection('/test', 'POST')
this.csrf.disableDefaultCsrfProtection('/a/b/c', 'POST')
@@ -83,8 +83,8 @@ describe('Csrf', function() {
})
})
- describe('when the method does not match', function() {
- it('passes the csrf error on', function() {
+ describe('when the method does not match', function () {
+ it('passes the csrf error on', function () {
this.csrf.disableDefaultCsrfProtection(this.path, 'POST')
this.req.method = 'GET'
this.csrf.middleware(this.req, this.res, this.next)
@@ -92,8 +92,8 @@ describe('Csrf', function() {
})
})
- describe('when the route is excluded, but the error is not a bad-csrf-token error', function() {
- it('passes the error on', function() {
+ describe('when the route is excluded, but the error is not a bad-csrf-token error', function () {
+ it('passes the error on', function () {
let err
this.Csrf = SandboxedModule.require(modulePath, {
globals: {
@@ -118,17 +118,17 @@ describe('Csrf', function() {
})
})
- describe('validateRequest', function() {
- describe('when the request is invalid', function() {
- it('calls the callback with error', function() {
+ describe('validateRequest', function () {
+ describe('when the request is invalid', function () {
+ it('calls the callback with error', function () {
this.cb = sinon.stub()
this.Csrf.validateRequest(this.req, this.cb)
return expect(this.cb.calledWith(this.err)).to.equal(true)
})
})
- describe('when the request is valid', function() {
- it('calls the callback without an error', function() {
+ describe('when the request is valid', function () {
+ it('calls the callback without an error', function () {
this.Csrf = SandboxedModule.require(modulePath, {
globals: {
console: console
@@ -146,17 +146,17 @@ describe('Csrf', function() {
})
})
- describe('validateToken', function() {
- describe('when the request is invalid', function() {
- it('calls the callback with `false`', function() {
+ describe('validateToken', function () {
+ describe('when the request is invalid', function () {
+ it('calls the callback with `false`', function () {
this.cb = sinon.stub()
this.Csrf.validateToken('token', {}, this.cb)
expect(this.cb.calledWith(this.err)).to.equal(true)
})
})
- describe('when the request is valid', function() {
- it('calls the callback with `true`', function() {
+ describe('when the request is valid', function () {
+ it('calls the callback with `true`', function () {
this.Csrf = SandboxedModule.require(modulePath, {
globals: {
console: console
@@ -173,8 +173,8 @@ describe('Csrf', function() {
})
})
- describe('when there is no token', function() {
- it('calls the callback with an error', function() {
+ describe('when there is no token', function () {
+ it('calls the callback with an error', function () {
this.Csrf = SandboxedModule.require(modulePath, {
globals: {
console: console
diff --git a/services/web/test/unit/src/infrastructure/FeaturesTests.js b/services/web/test/unit/src/infrastructure/FeaturesTests.js
index 3295d0ec7e..f770a45d84 100644
--- a/services/web/test/unit/src/infrastructure/FeaturesTests.js
+++ b/services/web/test/unit/src/infrastructure/FeaturesTests.js
@@ -2,53 +2,53 @@ const { expect } = require('chai')
const modulePath = '../../../../app/src/infrastructure/Features.js'
const SandboxedModule = require('sandboxed-module')
-describe('Features', function() {
- beforeEach(function() {
+describe('Features', function () {
+ beforeEach(function () {
this.Features = SandboxedModule.require(modulePath, {
requires: {
'settings-sharelatex': (this.settings = {})
}
})
})
- describe('externalAuthenticationSystemUsed', function() {
- describe('without any settings', function() {
- it('should return false', function() {
+ describe('externalAuthenticationSystemUsed', function () {
+ describe('without any settings', function () {
+ it('should return false', function () {
expect(this.Features.externalAuthenticationSystemUsed()).to.be.false
})
})
- describe('with ldap setting', function() {
- beforeEach(function() {
+ describe('with ldap setting', function () {
+ beforeEach(function () {
this.settings.ldap = true
})
- it('should return true', function() {
+ it('should return true', function () {
expect(this.Features.externalAuthenticationSystemUsed()).to.be.true
})
})
- describe('with saml setting', function() {
- beforeEach(function() {
+ describe('with saml setting', function () {
+ beforeEach(function () {
this.settings.saml = true
})
- it('should return true', function() {
+ it('should return true', function () {
expect(this.Features.externalAuthenticationSystemUsed()).to.be.true
})
})
- describe('with oauth setting', function() {
- beforeEach(function() {
+ describe('with oauth setting', function () {
+ beforeEach(function () {
this.settings.overleaf = { oauth: true }
})
- it('should return true', function() {
+ it('should return true', function () {
expect(this.Features.externalAuthenticationSystemUsed()).to.be.true
})
})
})
- describe('hasFeature', function() {
- describe('without any settings', function() {
- it('should return true', function() {
+ describe('hasFeature', function () {
+ describe('without any settings', function () {
+ it('should return true', function () {
expect(this.Features.hasFeature('registration')).to.be.true
expect(this.Features.hasFeature('templates-server-pro')).to.be.true
})
- it('should return false', function() {
+ it('should return false', function () {
expect(this.Features.hasFeature('affiliations')).to.be.false
expect(this.Features.hasFeature('analytics')).to.be.false
expect(this.Features.hasFeature('custom-togglers')).to.be.false
@@ -62,18 +62,18 @@ describe('Features', function() {
expect(this.Features.hasFeature('saml')).to.be.false
})
})
- describe('with settings', function() {
- describe('empty overleaf object', function() {
- beforeEach(function() {
+ describe('with settings', function () {
+ describe('empty overleaf object', function () {
+ beforeEach(function () {
this.settings.overleaf = {}
this.settings.apis = {}
})
- it('should return true', function() {
+ it('should return true', function () {
expect(this.Features.hasFeature('custom-togglers')).to.be.true
expect(this.Features.hasFeature('overleaf-integration')).to.be.true
expect(this.Features.hasFeature('registration')).to.be.true
})
- it('should return false', function() {
+ it('should return false', function () {
expect(this.Features.hasFeature('affiliations')).to.be.false
expect(this.Features.hasFeature('analytics')).to.be.false
expect(this.Features.hasFeature('git-bridge')).to.be.false
@@ -85,8 +85,8 @@ describe('Features', function() {
expect(this.Features.hasFeature('saml')).to.be.false
expect(this.Features.hasFeature('templates-server-pro')).to.be.false
})
- describe('with APIs', function() {
- beforeEach(function() {
+ describe('with APIs', function () {
+ beforeEach(function () {
this.settings.apis = {
linkedUrlProxy: {
url: 'https://www.overleaf.com'
@@ -99,7 +99,7 @@ describe('Features', function() {
}
}
})
- it('should return true', function() {
+ it('should return true', function () {
expect(this.Features.hasFeature('affiliations')).to.be.true
expect(this.Features.hasFeature('analytics')).to.be.true
expect(this.Features.hasFeature('custom-togglers')).to.be.true
@@ -108,7 +108,7 @@ describe('Features', function() {
expect(this.Features.hasFeature('references')).to.be.true
expect(this.Features.hasFeature('registration')).to.be.true
})
- it('should return false', function() {
+ it('should return false', function () {
expect(this.Features.hasFeature('git-bridge')).to.be.false
expect(this.Features.hasFeature('github-sync')).to.be.false
expect(this.Features.hasFeature('homepage')).to.be.false
@@ -116,15 +116,15 @@ describe('Features', function() {
expect(this.Features.hasFeature('saml')).to.be.false
expect(this.Features.hasFeature('templates-server-pro')).to.be.false
})
- describe('with all other settings flags', function() {
- beforeEach(function() {
+ describe('with all other settings flags', function () {
+ beforeEach(function () {
this.settings.enableHomepage = true
this.settings.enableGitBridge = true
this.settings.enableGithubSync = true
this.settings.enableSaml = true
this.settings.oauth = true
})
- it('should return true or return value', function() {
+ it('should return true or return value', function () {
expect(this.Features.hasFeature('affiliations')).to.be.true
expect(this.Features.hasFeature('analytics')).to.be.true
expect(this.Features.hasFeature('custom-togglers')).to.be.true
@@ -139,7 +139,7 @@ describe('Features', function() {
expect(this.Features.hasFeature('registration')).to.be.true
expect(this.Features.hasFeature('saml')).to.be.true
})
- it('should return false', function() {
+ it('should return false', function () {
expect(this.Features.hasFeature('templates-server-pro')).to.be
.false
})
diff --git a/services/web/test/unit/src/infrastructure/GeoIpLookupTests.js b/services/web/test/unit/src/infrastructure/GeoIpLookupTests.js
index d89563f8b5..7da836977b 100644
--- a/services/web/test/unit/src/infrastructure/GeoIpLookupTests.js
+++ b/services/web/test/unit/src/infrastructure/GeoIpLookupTests.js
@@ -21,8 +21,8 @@ const modulePath = path.join(
)
const { expect } = require('chai')
-describe('GeoIpLookup', function() {
- beforeEach(function() {
+describe('GeoIpLookup', function () {
+ beforeEach(function () {
this.settings = {
apis: {
geoIpLookup: {
@@ -54,12 +54,12 @@ describe('GeoIpLookup', function() {
})
})
- describe('getDetails', function() {
- beforeEach(function() {
+ describe('getDetails', function () {
+ beforeEach(function () {
return this.request.get.callsArgWith(1, null, null, this.stubbedResponse)
})
- it('should request the details using the ip', function(done) {
+ it('should request the details using the ip', function (done) {
return this.GeoIpLookup.getDetails(this.ipAddress, err => {
this.request.get
.calledWith({
@@ -72,7 +72,7 @@ describe('GeoIpLookup', function() {
})
})
- it('should return the ip details', function(done) {
+ it('should return the ip details', function (done) {
return this.GeoIpLookup.getDetails(
this.ipAddress,
(err, returnedDetails) => {
@@ -82,7 +82,7 @@ describe('GeoIpLookup', function() {
)
})
- it('should take the first ip in the string', function(done) {
+ it('should take the first ip in the string', function (done) {
return this.GeoIpLookup.getDetails(
` ${this.ipAddress} 456.312.452.102 432.433.888.234`,
err => {
@@ -99,8 +99,8 @@ describe('GeoIpLookup', function() {
})
})
- describe('getCurrencyCode', function() {
- it('should return GBP for GB country', function(done) {
+ describe('getCurrencyCode', function () {
+ it('should return GBP for GB country', function (done) {
this.GeoIpLookup.getDetails = sinon
.stub()
.callsArgWith(1, null, this.stubbedResponse)
@@ -113,7 +113,7 @@ describe('GeoIpLookup', function() {
)
})
- it('should return GBP for gb country', function(done) {
+ it('should return GBP for gb country', function (done) {
this.stubbedResponse.country_code = 'gb'
this.GeoIpLookup.getDetails = sinon
.stub()
@@ -127,7 +127,7 @@ describe('GeoIpLookup', function() {
)
})
- it('should return USD for US', function(done) {
+ it('should return USD for US', function (done) {
this.stubbedResponse.country_code = 'US'
this.GeoIpLookup.getDetails = sinon
.stub()
@@ -141,7 +141,7 @@ describe('GeoIpLookup', function() {
)
})
- it('should return EUR for DE', function(done) {
+ it('should return EUR for DE', function (done) {
this.stubbedResponse.country_code = 'DE'
this.GeoIpLookup.getDetails = sinon
.stub()
@@ -155,7 +155,7 @@ describe('GeoIpLookup', function() {
)
})
- it('should default to USD if there is an error', function(done) {
+ it('should default to USD if there is an error', function (done) {
this.GeoIpLookup.getDetails = sinon.stub().callsArgWith(1, 'problem')
return this.GeoIpLookup.getCurrencyCode(
this.ipAddress,
@@ -166,7 +166,7 @@ describe('GeoIpLookup', function() {
)
})
- it('should default to USD if there are no details', function(done) {
+ it('should default to USD if there are no details', function (done) {
this.GeoIpLookup.getDetails = sinon.stub().callsArgWith(1)
return this.GeoIpLookup.getCurrencyCode(
this.ipAddress,
@@ -177,7 +177,7 @@ describe('GeoIpLookup', function() {
)
})
- it('should default to USD if there is no match for their country', function(done) {
+ it('should default to USD if there is no match for their country', function (done) {
this.stubbedResponse.country_code = 'Non existant'
this.GeoIpLookup.getDetails = sinon
.stub()
diff --git a/services/web/test/unit/src/infrastructure/LockManager/ReleasingTheLock.js b/services/web/test/unit/src/infrastructure/LockManager/ReleasingTheLock.js
index 4e995282b4..34355e8dfa 100644
--- a/services/web/test/unit/src/infrastructure/LockManager/ReleasingTheLock.js
+++ b/services/web/test/unit/src/infrastructure/LockManager/ReleasingTheLock.js
@@ -20,7 +20,7 @@ const lockKey = `lock:web:{${5678}}`
const lockValue = '123456'
const SandboxedModule = require('sandboxed-module')
-describe('LockManager - releasing the lock', function() {
+describe('LockManager - releasing the lock', function () {
const deleteStub = sinon.stub().callsArgWith(4)
const mocks = {
'settings-sharelatex': {
@@ -47,7 +47,7 @@ describe('LockManager - releasing the lock', function() {
const LockManager = SandboxedModule.require(modulePath, { requires: mocks })
LockManager.unlockScript = 'this is the unlock script'
- it('should put a all data into memory', function(done) {
+ it('should put a all data into memory', function (done) {
return LockManager._releaseLock(lockKey, lockValue, () => {
deleteStub
.calledWith(LockManager.unlockScript, 1, lockKey, lockValue)
diff --git a/services/web/test/unit/src/infrastructure/LockManager/getLockTests.js b/services/web/test/unit/src/infrastructure/LockManager/getLockTests.js
index 23252c9070..e971461d48 100644
--- a/services/web/test/unit/src/infrastructure/LockManager/getLockTests.js
+++ b/services/web/test/unit/src/infrastructure/LockManager/getLockTests.js
@@ -21,8 +21,8 @@ const modulePath = path.join(
)
const SandboxedModule = require('sandboxed-module')
-describe('LockManager - getting the lock', function() {
- beforeEach(function() {
+describe('LockManager - getting the lock', function () {
+ beforeEach(function () {
this.LockManager = SandboxedModule.require(modulePath, {
requires: {
'./RedisWrapper': {
@@ -52,8 +52,8 @@ describe('LockManager - getting the lock', function() {
return (this.namespace = 'lockName')
})
- describe('when the lock is not set', function() {
- beforeEach(function(done) {
+ describe('when the lock is not set', function () {
+ beforeEach(function (done) {
this.LockManager._tryLock = sinon.stub().yields(null, true)
return this.LockManager._getLock(this.key, this.namespace, (...args) => {
this.callback(...Array.from(args || []))
@@ -61,29 +61,29 @@ describe('LockManager - getting the lock', function() {
})
})
- it('should try to get the lock', function() {
+ it('should try to get the lock', function () {
return this.LockManager._tryLock
.calledWith(this.key, this.namespace)
.should.equal(true)
})
- it('should only need to try once', function() {
+ it('should only need to try once', function () {
return this.LockManager._tryLock.callCount.should.equal(1)
})
- it('should return the callback', function() {
+ it('should return the callback', function () {
return this.callback.calledWith(null).should.equal(true)
})
})
- describe('when the lock is initially set', function() {
- beforeEach(function(done) {
+ describe('when the lock is initially set', function () {
+ beforeEach(function (done) {
const startTime = Date.now()
let tries = 0
this.LockManager.LOCK_TEST_INTERVAL = 5
- this.LockManager._tryLock = function(key, namespace, callback) {
+ this.LockManager._tryLock = function (key, namespace, callback) {
if (callback == null) {
- callback = function(error, isFree) {}
+ callback = function (error, isFree) {}
}
if (Date.now() - startTime < 20 || tries < 2) {
tries = tries + 1
@@ -100,17 +100,17 @@ describe('LockManager - getting the lock', function() {
})
})
- it('should call tryLock multiple times until free', function() {
+ it('should call tryLock multiple times until free', function () {
return (this.LockManager._tryLock.callCount > 1).should.equal(true)
})
- it('should return the callback', function() {
+ it('should return the callback', function () {
return this.callback.calledWith(null).should.equal(true)
})
})
- describe('when the lock times out', function() {
- beforeEach(function(done) {
+ describe('when the lock times out', function () {
+ beforeEach(function (done) {
const time = Date.now()
this.LockManager.LOCK_TEST_INTERVAL = 1
this.LockManager.MAX_LOCK_WAIT_TIME = 5
@@ -121,21 +121,21 @@ describe('LockManager - getting the lock', function() {
})
})
- it('should return the callback with an error', function() {
+ it('should return the callback with an error', function () {
this.callback.should.have.been.calledWith(
sinon.match.instanceOf(Error).and(sinon.match.has('message', 'Timeout'))
)
})
})
- describe('when there are multiple requests for the same lock', function() {
- beforeEach(function(done) {
+ describe('when there are multiple requests for the same lock', function () {
+ beforeEach(function (done) {
let locked = false
this.results = []
this.LockManager.LOCK_TEST_INTERVAL = 1
- this.LockManager._tryLock = function(key, namespace, callback) {
+ this.LockManager._tryLock = function (key, namespace, callback) {
if (callback == null) {
- callback = function(error, gotLock, lockValue) {}
+ callback = function (error, gotLock, lockValue) {}
}
if (locked) {
return callback(null, false)
@@ -175,7 +175,7 @@ describe('LockManager - getting the lock', function() {
)
})
- it('should process the requests in order', function() {
+ it('should process the requests in order', function () {
return this.results.should.deep.equal([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
})
})
diff --git a/services/web/test/unit/src/infrastructure/LockManager/tryLockTests.js b/services/web/test/unit/src/infrastructure/LockManager/tryLockTests.js
index ef30a29fd6..2d12411409 100644
--- a/services/web/test/unit/src/infrastructure/LockManager/tryLockTests.js
+++ b/services/web/test/unit/src/infrastructure/LockManager/tryLockTests.js
@@ -18,8 +18,8 @@ const modulePath = path.join(
)
const SandboxedModule = require('sandboxed-module')
-describe('LockManager - trying the lock', function() {
- beforeEach(function() {
+describe('LockManager - trying the lock', function () {
+ beforeEach(function () {
this.LockManager = SandboxedModule.require(modulePath, {
requires: {
'./RedisWrapper': {
@@ -50,31 +50,31 @@ describe('LockManager - trying the lock', function() {
return (this.namespace = 'lockName')
})
- describe('when the lock is not set', function() {
- beforeEach(function() {
+ describe('when the lock is not set', function () {
+ beforeEach(function () {
this.set.callsArgWith(5, null, 'OK')
this.LockManager.randomLock = sinon.stub().returns('random-lock-value')
return this.LockManager._tryLock(this.key, this.namespace, this.callback)
})
- it('should set the lock key with an expiry if it is not set', function() {
+ it('should set the lock key with an expiry if it is not set', function () {
return this.set
.calledWith(this.key, 'random-lock-value', 'EX', 30, 'NX')
.should.equal(true)
})
- it('should return the callback with true', function() {
+ it('should return the callback with true', function () {
return this.callback.calledWith(null, true).should.equal(true)
})
})
- describe('when the lock is already set', function() {
- beforeEach(function() {
+ describe('when the lock is already set', function () {
+ beforeEach(function () {
this.set.callsArgWith(5, null, null)
return this.LockManager._tryLock(this.key, this.namespace, this.callback)
})
- it('should return the callback with false', function() {
+ it('should return the callback with false', function () {
return this.callback.calledWith(null, false).should.equal(true)
})
})
diff --git a/services/web/test/unit/src/infrastructure/ProxyManagerTests.js b/services/web/test/unit/src/infrastructure/ProxyManagerTests.js
index 5a8fd06f36..98e626d45c 100644
--- a/services/web/test/unit/src/infrastructure/ProxyManagerTests.js
+++ b/services/web/test/unit/src/infrastructure/ProxyManagerTests.js
@@ -18,8 +18,8 @@ const SandboxedModule = require('sandboxed-module')
const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
-describe('ProxyManager', function() {
- beforeEach(function() {
+describe('ProxyManager', function () {
+ beforeEach(function () {
this.settings = { proxyUrls: {} }
this.request = sinon.stub().returns({
on() {},
@@ -37,8 +37,8 @@ describe('ProxyManager', function() {
return (this.next = sinon.stub())
})
- describe('apply', function() {
- it('applies all paths', function() {
+ describe('apply', function () {
+ it('applies all paths', function () {
this.router = { get: sinon.stub() }
this.settings.proxyUrls = {
'/foo/bar': '',
@@ -50,7 +50,7 @@ describe('ProxyManager', function() {
return assertCalledWith(this.router.get, '/foo/:id')
})
- it('applies methods other than get', function() {
+ it('applies methods other than get', function () {
this.router = {
post: sinon.stub(),
put: sinon.stub()
@@ -67,8 +67,8 @@ describe('ProxyManager', function() {
})
})
- describe('createProxy', function() {
- beforeEach(function() {
+ describe('createProxy', function () {
+ beforeEach(function () {
this.req.url = this.proxyPath
this.req.route.path = this.proxyPath
this.req.query = {}
@@ -77,12 +77,12 @@ describe('ProxyManager', function() {
return (this.settings.proxyUrls = {})
})
- afterEach(function() {
+ afterEach(function () {
this.next.reset()
return this.request.reset()
})
- it('does not calls next when match', function() {
+ it('does not calls next when match', function () {
const target = '/'
this.settings.proxyUrls[this.proxyPath] = target
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
@@ -90,14 +90,14 @@ describe('ProxyManager', function() {
return sinon.assert.called(this.request)
})
- it('proxy full URL', function() {
+ it('proxy full URL', function () {
const targetUrl = 'https://user:pass@foo.bar:123/pa/th.ext?query#hash'
this.settings.proxyUrls[this.proxyPath] = targetUrl
this.proxyManager.createProxy(targetUrl)(this.req)
return assertCalledWith(this.request, { url: targetUrl })
})
- it('overwrite query', function() {
+ it('overwrite query', function () {
const targetUrl = 'foo.bar/baz?query'
this.req.query = { requestQuery: 'important' }
this.settings.proxyUrls[this.proxyPath] = targetUrl
@@ -106,21 +106,21 @@ describe('ProxyManager', function() {
return assertCalledWith(this.request, { url: newTargetUrl })
})
- it('handles target objects', function() {
+ it('handles target objects', function () {
const target = { baseUrl: 'api.v1', path: '/pa/th' }
this.settings.proxyUrls[this.proxyPath] = target
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
return assertCalledWith(this.request, { url: 'api.v1/pa/th' })
})
- it('handles missing baseUrl', function() {
+ it('handles missing baseUrl', function () {
const target = { path: '/pa/th' }
this.settings.proxyUrls[this.proxyPath] = target
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
return assertCalledWith(this.request, { url: 'undefined/pa/th' })
})
- it('handles dynamic path', function() {
+ it('handles dynamic path', function () {
const target = {
baseUrl: 'api.v1',
path(params) {
@@ -135,7 +135,7 @@ describe('ProxyManager', function() {
return assertCalledWith(this.request, { url: 'api.v1/resource/123' })
})
- it('set arbitrary options on request', function() {
+ it('set arbitrary options on request', function () {
const target = {
baseUrl: 'api.v1',
path: '/foo',
@@ -150,7 +150,7 @@ describe('ProxyManager', function() {
})
})
- it('passes cookies', function() {
+ it('passes cookies', function () {
const target = { baseUrl: 'api.v1', path: '/foo' }
this.req.url = '/foo'
this.req.route.path = '/foo'
@@ -164,7 +164,7 @@ describe('ProxyManager', function() {
})
})
- it('passes body for post', function() {
+ it('passes body for post', function () {
const target = {
baseUrl: 'api.v1',
path: '/foo',
@@ -183,7 +183,7 @@ describe('ProxyManager', function() {
})
})
- it('passes body for put', function() {
+ it('passes body for put', function () {
const target = {
baseUrl: 'api.v1',
path: '/foo',
diff --git a/services/web/test/unit/src/infrastructure/RateLimterTests.js b/services/web/test/unit/src/infrastructure/RateLimterTests.js
index 0ce31fd3b1..f965935c8a 100644
--- a/services/web/test/unit/src/infrastructure/RateLimterTests.js
+++ b/services/web/test/unit/src/infrastructure/RateLimterTests.js
@@ -16,8 +16,8 @@ const sinon = require('sinon')
const modulePath = '../../../../app/src/infrastructure/RateLimiter.js'
const SandboxedModule = require('sandboxed-module')
-describe('RateLimiter', function() {
- beforeEach(function() {
+describe('RateLimiter', function () {
+ beforeEach(function () {
this.settings = {
redis: {
web: {
@@ -56,8 +56,8 @@ describe('RateLimiter', function() {
return (this.key = `RateLimiter:${this.endpointName}:{${this.subject}}`)
})
- describe('when action is permitted', function() {
- beforeEach(function() {
+ describe('when action is permitted', function () {
+ beforeEach(function () {
this.requires['rolling-rate-limiter'] = opts => {
return sinon.stub().callsArgWith(1, null, 0, 22)
}
@@ -66,21 +66,21 @@ describe('RateLimiter', function() {
}))
})
- it('should not produce and error', function(done) {
+ it('should not produce and error', function (done) {
return this.limiter.addCount({}, (err, should) => {
expect(err).to.equal(null)
return done()
})
})
- it('should callback with true', function(done) {
+ it('should callback with true', function (done) {
return this.limiter.addCount({}, (err, should) => {
expect(should).to.equal(true)
return done()
})
})
- it('should not increment the metric', function(done) {
+ it('should not increment the metric', function (done) {
return this.limiter.addCount(
{ endpointName: this.endpointName },
(err, should) => {
@@ -91,8 +91,8 @@ describe('RateLimiter', function() {
})
})
- describe('when action is not permitted', function() {
- beforeEach(function() {
+ describe('when action is not permitted', function () {
+ beforeEach(function () {
this.requires['rolling-rate-limiter'] = opts => {
return sinon.stub().callsArgWith(1, null, 4000, 0)
}
@@ -104,21 +104,21 @@ describe('RateLimiter', function() {
}))
})
- it('should not produce and error', function(done) {
+ it('should not produce and error', function (done) {
return this.limiter.addCount({}, (err, should) => {
expect(err).to.equal(null)
return done()
})
})
- it('should callback with false', function(done) {
+ it('should callback with false', function (done) {
return this.limiter.addCount({}, (err, should) => {
expect(should).to.equal(false)
return done()
})
})
- it('should increment the metric', function(done) {
+ it('should increment the metric', function (done) {
return this.limiter.addCount(
{ endpointName: this.endpointName },
(err, should) => {
@@ -131,8 +131,8 @@ describe('RateLimiter', function() {
})
})
- describe('when limiter produces an error', function() {
- beforeEach(function() {
+ describe('when limiter produces an error', function () {
+ beforeEach(function () {
this.requires['rolling-rate-limiter'] = opts => {
return sinon.stub().callsArgWith(1, new Error('woops'))
}
@@ -144,7 +144,7 @@ describe('RateLimiter', function() {
}))
})
- it('should produce and error', function(done) {
+ it('should produce and error', function (done) {
return this.limiter.addCount({}, (err, should) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
diff --git a/services/web/test/unit/src/infrastructure/RequestContentTypeDetectionTests.js b/services/web/test/unit/src/infrastructure/RequestContentTypeDetectionTests.js
index 913898501b..b214a71f56 100644
--- a/services/web/test/unit/src/infrastructure/RequestContentTypeDetectionTests.js
+++ b/services/web/test/unit/src/infrastructure/RequestContentTypeDetectionTests.js
@@ -5,18 +5,18 @@ const MODULE_PATH =
const MockRequest = require('../helpers/MockRequest')
const SandboxedModule = require('sandboxed-module')
-describe('RequestContentTypeDetection', function() {
- before(function() {
+describe('RequestContentTypeDetection', function () {
+ before(function () {
this.RequestContentTypeDetection = SandboxedModule.require(MODULE_PATH)
this.req = new MockRequest()
- this.req.accepts = function(...args) {
+ this.req.accepts = function (...args) {
return accepts(this).type(...args)
}
})
- describe('isJson=true', function() {
+ describe('isJson=true', function () {
function expectJson(type) {
- it(type, function() {
+ it(type, function () {
this.req.headers.accept = type
expect(this.RequestContentTypeDetection.acceptsJson(this.req)).to.equal(
true
@@ -29,9 +29,9 @@ describe('RequestContentTypeDetection', function() {
expectJson('application/json, text/html, */*')
})
- describe('isJson=false', function() {
+ describe('isJson=false', function () {
function expectNonJson(type) {
- it(type, function() {
+ it(type, function () {
this.req.headers.accept = type
expect(this.RequestContentTypeDetection.acceptsJson(this.req)).to.equal(
false
diff --git a/services/web/test/unit/src/infrastructure/TranslationsTests.js b/services/web/test/unit/src/infrastructure/TranslationsTests.js
index a77f31ab97..22d8ef8d71 100644
--- a/services/web/test/unit/src/infrastructure/TranslationsTests.js
+++ b/services/web/test/unit/src/infrastructure/TranslationsTests.js
@@ -3,7 +3,7 @@ const SandboxedModule = require('sandboxed-module')
const MODULE_PATH = '../../../../app/src/infrastructure/Translations.js'
-describe('Translations', function() {
+describe('Translations', function () {
let req, res, translations
function runMiddlewares(cb) {
translations.i18nMiddleware(req, res, () => {
@@ -11,7 +11,7 @@ describe('Translations', function() {
})
}
- beforeEach(function() {
+ beforeEach(function () {
translations = SandboxedModule.require(MODULE_PATH, {
requires: {
'settings-sharelatex': {
@@ -40,26 +40,26 @@ describe('Translations', function() {
}
})
- describe('translate', function() {
- beforeEach(function(done) {
+ describe('translate', function () {
+ beforeEach(function (done) {
runMiddlewares(done)
})
- it('works', function() {
+ it('works', function () {
expect(req.i18n.t('give_feedback')).to.equal('Give feedback')
})
- it('has translate alias', function() {
+ it('has translate alias', function () {
expect(req.i18n.translate('give_feedback')).to.equal('Give feedback')
})
})
- describe('interpolation', function() {
- beforeEach(function(done) {
+ describe('interpolation', function () {
+ beforeEach(function (done) {
runMiddlewares(done)
})
- it('works', function() {
+ it('works', function () {
expect(
req.i18n.t('please_confirm_email', {
emailAddress: 'foo@example.com'
@@ -69,7 +69,7 @@ describe('Translations', function() {
)
})
- it('handles dashes after interpolation', function() {
+ it('handles dashes after interpolation', function () {
// This translation string has a problematic interpolation followed by a
// dash: `__len__-day`
expect(
@@ -82,7 +82,7 @@ describe('Translations', function() {
)
})
- it('disables escaping', function() {
+ it('disables escaping', function () {
expect(
req.i18n.t('admin_user_created_message', {
link: 'http://google.com'
@@ -93,8 +93,8 @@ describe('Translations', function() {
})
})
- describe('setLangBasedOnDomainMiddleware', function() {
- it('should set the lang to french if the domain is fr', function(done) {
+ describe('setLangBasedOnDomainMiddleware', function () {
+ it('should set the lang to french if the domain is fr', function (done) {
req.headers.host = 'fr.sharelatex.com'
runMiddlewares(() => {
expect(req.lng).to.equal('fr')
@@ -102,8 +102,8 @@ describe('Translations', function() {
})
})
- describe('suggestedLanguageSubdomainConfig', function() {
- it('should set suggestedLanguageSubdomainConfig if the detected lang is different to subdomain lang', function(done) {
+ describe('suggestedLanguageSubdomainConfig', function () {
+ it('should set suggestedLanguageSubdomainConfig if the detected lang is different to subdomain lang', function (done) {
req.headers['accept-language'] = 'da, en-gb;q=0.8, en;q=0.7'
req.headers.host = 'fr.sharelatex.com'
runMiddlewares(() => {
@@ -115,7 +115,7 @@ describe('Translations', function() {
})
})
- it('should not set suggestedLanguageSubdomainConfig if the detected lang is the same as subdomain lang', function(done) {
+ it('should not set suggestedLanguageSubdomainConfig if the detected lang is the same as subdomain lang', function (done) {
req.headers['accept-language'] = 'da, en-gb;q=0.8, en;q=0.7'
req.headers.host = 'da.sharelatex.com'
runMiddlewares(() => {
diff --git a/services/web/test/unit/src/util/promisesTests.js b/services/web/test/unit/src/util/promisesTests.js
index 7029007892..d38cb20308 100644
--- a/services/web/test/unit/src/util/promisesTests.js
+++ b/services/web/test/unit/src/util/promisesTests.js
@@ -4,9 +4,9 @@ const {
callbackifyMultiResult
} = require('../../../../app/src/util/promises')
-describe('promisifyAll', function() {
- describe('basic functionality', function() {
- before(function() {
+describe('promisifyAll', function () {
+ describe('basic functionality', function () {
+ before(function () {
this.module = {
SOME_CONSTANT: 1,
asyncAdd(a, b, callback) {
@@ -19,27 +19,27 @@ describe('promisifyAll', function() {
this.promisified = promisifyAll(this.module)
})
- it('promisifies functions in the module', async function() {
+ it('promisifies functions in the module', async function () {
const sum = await this.promisified.asyncAdd(29, 33)
expect(sum).to.equal(62)
})
- it('binds this to the original module', async function() {
+ it('binds this to the original module', async function () {
const sum = await this.promisified.asyncDouble(38)
expect(sum).to.equal(76)
})
- it('does not copy over non-functions', async function() {
+ it('does not copy over non-functions', async function () {
expect(this.promisified).not.to.have.property('SOME_CONSTANT')
})
- it('does not modify the prototype of the module', async function() {
+ it('does not modify the prototype of the module', async function () {
expect(this.promisified.toString()).to.equal('[object Object]')
})
})
- describe('without option', function() {
- before(function() {
+ describe('without option', function () {
+ before(function () {
this.module = {
asyncAdd(a, b, callback) {
callback(null, a + b)
@@ -51,18 +51,18 @@ describe('promisifyAll', function() {
this.promisified = promisifyAll(this.module, { without: 'syncAdd' })
})
- it('does not promisify excluded functions', function() {
+ it('does not promisify excluded functions', function () {
expect(this.promisified.syncAdd).not.to.exist
})
- it('promisifies other functions', async function() {
+ it('promisifies other functions', async function () {
const sum = await this.promisified.asyncAdd(12, 89)
expect(sum).to.equal(101)
})
})
- describe('multiResult option', function() {
- before(function() {
+ describe('multiResult option', function () {
+ before(function () {
this.module = {
asyncAdd(a, b, callback) {
callback(null, a + b)
@@ -76,20 +76,20 @@ describe('promisifyAll', function() {
})
})
- it('promisifies multi-result functions', async function() {
+ it('promisifies multi-result functions', async function () {
const result = await this.promisified.asyncArithmetic(3, 6)
expect(result).to.deep.equal({ sum: 9, product: 18 })
})
- it('promisifies other functions normally', async function() {
+ it('promisifies other functions normally', async function () {
const sum = await this.promisified.asyncAdd(6, 1)
expect(sum).to.equal(7)
})
})
})
-describe('callbackifyMultiResult', function() {
- it('callbackifies a multi-result function', function(done) {
+describe('callbackifyMultiResult', function () {
+ it('callbackifies a multi-result function', function (done) {
async function asyncArithmetic(a, b) {
return { sum: a + b, product: a * b }
}
@@ -107,7 +107,7 @@ describe('callbackifyMultiResult', function() {
})
})
- it('propagates errors', function(done) {
+ it('propagates errors', function (done) {
async function asyncBomb() {
throw new Error('BOOM!')
}