text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
import { FC } from "react";
type Props = {
lines?: number;
};
const ClampedParagraph: FC<Props> = ({ children, lines = 1 }) => {
return (
<>
<p>{children}</p>
<style jsx>{`
p {
margin: 0.1em;
text-overflow: ellipsis;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: ${lines};
-webkit-box-orient: vertical;
max-lines: ${lines};
line-clamp: ${lines};
}
`}</style>
</>
);
};
export default ClampedParagraph;
| openmultiplayer/web/frontend/src/components/generic/ClampedParagraph.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/generic/ClampedParagraph.tsx",
"repo_id": "openmultiplayer",
"token_count": 277
} | 483 |
import Admonition from "../../../Admonition";
export default function WarningVersion({
version,
name = "function",
}: {
version: string;
name: string;
}) {
return (
<Admonition type="warning">
<p>
Esta {name} fue implementada en {version} y no funcionará en
versiones anteriores.
</p>
</Admonition>
);
}
| openmultiplayer/web/frontend/src/components/templates/translations/es/version-warning.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/templates/translations/es/version-warning.tsx",
"repo_id": "openmultiplayer",
"token_count": 141
} | 484 |
import { useToast, UseToastOptions } from "@chakra-ui/toast";
import nProgress from "nprogress";
import { useErrorHandler } from "src/utils/useErrorHandler";
import { useSWRConfig } from "swr";
import { api } from "./fetcher";
export type UseMutationOptions = {
mutate?: string;
progress?: boolean;
toast?: UseToastOptions;
};
export type UseMutationAPI<T, R> = (
method: string,
path: string,
opts?: UseMutationOptions
) => (data?: T) => Promise<R | undefined>;
export const useMutationAPI = <T, R = T>(
mutatePrefix?: boolean
): UseMutationAPI<T, R> => {
const toast = useToast();
const handler = useErrorHandler();
const { mutate: mutateExact } = useSWRConfig();
const mutateWithPrefix = useMutateWithPrefix();
const mutate = mutatePrefix ? mutateWithPrefix : mutateExact;
const request =
(method: string, path: string, opts?: UseMutationOptions) =>
async (data?: T) => {
const progress = opts?.progress ?? true;
progress && nProgress.start();
return api<R>(path, {
method: method,
body: data ? JSON.stringify(data) : undefined,
})
.then((response: R) => {
mutate(opts?.mutate ?? path);
progress && nProgress.done();
opts?.toast && toast(opts.toast);
return response;
})
.catch((e) => {
handler(e);
progress && nProgress.done();
return undefined;
});
};
return request;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type MutateWithPrefixFn = (prefix: string, ...args: any) => Promise<unknown>;
export const useMutateWithPrefix = (): MutateWithPrefixFn => {
const { cache, mutate } = useSWRConfig();
return (prefix, ...args) => {
if (!(cache instanceof Map)) {
throw new Error(
"matchMutate requires the cache provider to be a Map instance"
);
}
const keys = [];
for (const key of cache.keys()) {
if (key.startsWith(prefix)) {
keys.push(key);
}
}
return Promise.all(keys.map((key) => mutate(key, ...args)));
};
};
| openmultiplayer/web/frontend/src/fetcher/hooks.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/fetcher/hooks.ts",
"repo_id": "openmultiplayer",
"token_count": 828
} | 485 |
.card {
min-height: 320px;
}
.announcement {
background: linear-gradient(
98.18deg,
#f7f7f7 -5.01%,
rgba(247, 247, 247, 0) 100.73%
);
box-shadow: 0px 0px 40px 8px rgba(134, 119, 206, 0.05);
border: 1px solid rgba(134, 119, 206, 0.445);
border-radius: 8px;
padding: 0.8em 2em;
}
| openmultiplayer/web/frontend/src/styles/Card.module.css/0 | {
"file_path": "openmultiplayer/web/frontend/src/styles/Card.module.css",
"repo_id": "openmultiplayer",
"token_count": 145
} | 486 |
import { getLuminance } from "polished";
export const generateColour = (str: string, highlight = false): string => {
const hue: number = Math.abs(
str.split("").reduce((p, c) => c.charCodeAt(0) + ((p << 9) - p), 0) % 360
);
return `hsl(${hue}, 85%, ${highlight ? "90%" : "75%"})`;
};
export const alternativeColour = (c: string): string => {
const l = getLuminance(c);
if (l >= 0.7) {
return "var(--chakra-colors-gray-700)";
} else {
return "var(--chakra-colors-gray-50)";
}
};
| openmultiplayer/web/frontend/src/utils/colour-hash.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/utils/colour-hash.ts",
"repo_id": "openmultiplayer",
"token_count": 204
} | 487 |
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT NOT NULL,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Server" (
"id" TEXT NOT NULL,
"ip" TEXT NOT NULL,
"hn" TEXT NOT NULL,
"pc" INTEGER NOT NULL,
"pm" INTEGER NOT NULL,
"gm" TEXT NOT NULL,
"la" TEXT NOT NULL,
"pa" BOOLEAN NOT NULL,
"vn" TEXT NOT NULL,
"domain" TEXT,
"description" TEXT,
"banner" TEXT,
"userId" TEXT,
"active" BOOLEAN NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Rule" (
"id" SERIAL,
"name" TEXT NOT NULL,
"value" TEXT NOT NULL,
"serverId" TEXT,
PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Server.ip_unique" ON "Server"("ip");
-- CreateIndex
CREATE UNIQUE INDEX "Rule_serverId_rule_name_index" ON "Rule"("name", "serverId");
-- AddForeignKey
ALTER TABLE "Server" ADD FOREIGN KEY("userId")REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Rule" ADD FOREIGN KEY("serverId")REFERENCES "Server"("id") ON DELETE SET NULL ON UPDATE CASCADE;
| openmultiplayer/web/prisma/migrations/20201221190441_/migration.sql/0 | {
"file_path": "openmultiplayer/web/prisma/migrations/20201221190441_/migration.sql",
"repo_id": "openmultiplayer",
"token_count": 476
} | 488 |
BUILD_DIR_NAME ?= web
MODULE_NAME := $(notdir $(shell pwd))
MODULE_DIR := modules/$(MODULE_NAME)
PROJECT_NAME = web
export SHARELATEX_CONFIG = /app/$(MODULE_DIR)/test/acceptance/config/settings.test.js
export BASE_CONFIG ?= /app/test/acceptance/config/settings.test.saas.js
CFG_SAAS=/app/test/acceptance/config/settings.test.saas.js
CFG_SERVER_CE=/app/test/acceptance/config/settings.test.server-ce.js
CFG_SERVER_PRO=/app/test/acceptance/config/settings.test.server-pro.js
DOCKER_COMPOSE_FLAGS ?= -f docker-compose.yml --log-level ERROR
DOCKER_COMPOSE := cd ../../ && \
MODULE_DIR=$(MODULE_DIR) \
BUILD_NUMBER=$(BUILD_NUMBER) \
BRANCH_NAME=$(BRANCH_NAME) \
PROJECT_NAME=$(PROJECT_NAME) \
MOCHA_GREP=${MOCHA_GREP} \
docker-compose ${DOCKER_COMPOSE_FLAGS}
DOCKER_COMPOSE_TEST_ACCEPTANCE := \
export COMPOSE_PROJECT_NAME=acceptance_test_$(BUILD_DIR_NAME)_$(MODULE_NAME) \
&& $(DOCKER_COMPOSE)
DOCKER_COMPOSE_TEST_UNIT := \
export COMPOSE_PROJECT_NAME=unit_test_$(BUILD_DIR_NAME)_$(MODULE_NAME) \
&& $(DOCKER_COMPOSE)
ifeq (,$(wildcard test/unit))
test_unit:
else
test_unit:
${DOCKER_COMPOSE_TEST_UNIT} run --rm test_unit npm -q run test:unit:run_dir -- ${MOCHA_ARGS} $(MODULE_DIR)/test/unit/src
${DOCKER_COMPOSE_TEST_UNIT} down
endif
ALL_TEST_ACCEPTANCE_VARIANTS := \
test_acceptance \
test_acceptance_saas \
test_acceptance_server_ce \
test_acceptance_server_pro \
ifeq (,$(wildcard test/acceptance))
$(ALL_TEST_ACCEPTANCE_VARIANTS) test_acceptance_merged_inner:
@echo
@echo Module $(MODULE_NAME) does not have acceptance tests.
@echo
clean_test_acceptance:
else
test_acceptance_saas: export BASE_CONFIG = $(CFG_SAAS)
test_acceptance_server_ce: export BASE_CONFIG = $(CFG_SERVER_CE)
test_acceptance_server_pro: export BASE_CONFIG = $(CFG_SERVER_PRO)
$(ALL_TEST_ACCEPTANCE_VARIANTS):
$(MAKE) --no-print-directory clean_test_acceptance
${DOCKER_COMPOSE_TEST_ACCEPTANCE} run --rm test_acceptance npm -q run test:acceptance:run_dir -- ${MOCHA_ARGS} $(MODULE_DIR)/test/acceptance/src
$(MAKE) --no-print-directory clean_test_acceptance
test_acceptance_merged_inner:
cd ../../ && \
npm -q run test:acceptance:run_dir -- ${MOCHA_ARGS} $(MODULE_DIR)/test/acceptance/src
clean_test_acceptance:
${DOCKER_COMPOSE_TEST_ACCEPTANCE} down -v -t 0
endif
| overleaf/web/Makefile.module/0 | {
"file_path": "overleaf/web/Makefile.module",
"repo_id": "overleaf",
"token_count": 948
} | 489 |
module.exports = {
READ_ONLY: 'readOnly', // LEGACY
READ_AND_WRITE: 'readAndWrite', // LEGACY
PRIVATE: 'private',
TOKEN_BASED: 'tokenBased',
}
| overleaf/web/app/src/Features/Authorization/PublicAccessLevels.js/0 | {
"file_path": "overleaf/web/app/src/Features/Authorization/PublicAccessLevels.js",
"repo_id": "overleaf",
"token_count": 61
} | 490 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let rclient_secondary
const OError = require('@overleaf/o-error')
const Settings = require('@overleaf/settings')
const request = require('request').defaults({ timeout: 30 * 1000 })
const RedisWrapper = require('../../infrastructure/RedisWrapper')
const rclient = RedisWrapper.client('clsi_cookie')
if (Settings.redis.clsi_cookie_secondary != null) {
rclient_secondary = RedisWrapper.client('clsi_cookie_secondary')
}
const Cookie = require('cookie')
const logger = require('logger-sharelatex')
const clsiCookiesEnabled =
(Settings.clsiCookie != null ? Settings.clsiCookie.key : undefined) != null &&
Settings.clsiCookie.key.length !== 0
module.exports = function (backendGroup) {
return {
buildKey(project_id) {
if (backendGroup != null) {
return `clsiserver:${backendGroup}:${project_id}`
} else {
return `clsiserver:${project_id}`
}
},
_getServerId(project_id, callback) {
if (callback == null) {
callback = function (err, serverId) {}
}
return rclient.get(this.buildKey(project_id), (err, serverId) => {
if (err != null) {
return callback(err)
}
if (serverId == null || serverId === '') {
return this._populateServerIdViaRequest(project_id, callback)
} else {
return callback(null, serverId)
}
})
},
_populateServerIdViaRequest(project_id, callback) {
if (callback == null) {
callback = function (err, serverId) {}
}
const url = `${Settings.apis.clsi.url}/project/${project_id}/status`
return request.post(url, (err, res, body) => {
if (err != null) {
OError.tag(err, 'error getting initial server id for project', {
project_id,
})
return callback(err)
}
return this.setServerId(project_id, res, function (err, serverId) {
if (err != null) {
logger.warn(
{ err, project_id },
'error setting server id via populate request'
)
}
return callback(err, serverId)
})
})
},
_parseServerIdFromResponse(response) {
const cookies = Cookie.parse(
(response.headers['set-cookie'] != null
? response.headers['set-cookie'][0]
: undefined) || ''
)
return cookies != null ? cookies[Settings.clsiCookie.key] : undefined
},
setServerId(project_id, response, callback) {
if (callback == null) {
callback = function (err, serverId) {}
}
if (!clsiCookiesEnabled) {
return callback()
}
const serverId = this._parseServerIdFromResponse(response)
if (serverId == null) {
// We don't get a cookie back if it hasn't changed
return rclient.expire(
this.buildKey(project_id),
Settings.clsiCookie.ttl,
err => callback(err, undefined)
)
}
if (rclient_secondary != null) {
this._setServerIdInRedis(rclient_secondary, project_id, serverId)
}
return this._setServerIdInRedis(rclient, project_id, serverId, err =>
callback(err, serverId)
)
},
_setServerIdInRedis(rclient, project_id, serverId, callback) {
if (callback == null) {
callback = function (err) {}
}
rclient.setex(
this.buildKey(project_id),
Settings.clsiCookie.ttl,
serverId,
callback
)
},
clearServerId(project_id, callback) {
if (callback == null) {
callback = function (err) {}
}
if (!clsiCookiesEnabled) {
return callback()
}
return rclient.del(this.buildKey(project_id), callback)
},
getCookieJar(project_id, callback) {
if (callback == null) {
callback = function (err, jar, clsiServerId) {}
}
if (!clsiCookiesEnabled) {
return callback(null, request.jar(), undefined)
}
return this._getServerId(project_id, (err, serverId) => {
if (err != null) {
OError.tag(err, 'error getting server id', {
project_id,
})
return callback(err)
}
const serverCookie = request.cookie(
`${Settings.clsiCookie.key}=${serverId}`
)
const jar = request.jar()
jar.setCookie(serverCookie, Settings.apis.clsi.url)
return callback(null, jar, serverId)
})
},
}
}
| overleaf/web/app/src/Features/Compile/ClsiCookieManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/Compile/ClsiCookieManager.js",
"repo_id": "overleaf",
"token_count": 2085
} | 491 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let ProjectZipStreamManager
const archiver = require('archiver')
const async = require('async')
const logger = require('logger-sharelatex')
const ProjectEntityHandler = require('../Project/ProjectEntityHandler')
const ProjectGetter = require('../Project/ProjectGetter')
const FileStoreHandler = require('../FileStore/FileStoreHandler')
module.exports = ProjectZipStreamManager = {
createZipStreamForMultipleProjects(project_ids, callback) {
// We'll build up a zip file that contains multiple zip files
if (callback == null) {
callback = function (error, stream) {}
}
const archive = archiver('zip')
archive.on('error', err =>
logger.err(
{ err, project_ids },
'something went wrong building archive of project'
)
)
callback(null, archive)
const jobs = []
for (const 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()
})
}
)
}
)
))(project_id)
}
return async.series(jobs, function () {
logger.log(
{ project_ids },
'finished creating zip stream of multiple projects'
)
return archive.finalize()
})
},
createZipStreamForProject(project_id, callback) {
if (callback == null) {
callback = function (error, stream) {}
}
const archive = archiver('zip')
// return stream immediately before we start adding things to it
archive.on('error', err =>
logger.err(
{ err, project_id },
'something went wrong building archive of project'
)
)
callback(null, archive)
return this.addAllDocsToArchive(project_id, archive, error => {
if (error != null) {
logger.error(
{ err: error, project_id },
'error adding docs to zip stream'
)
}
return this.addAllFilesToArchive(project_id, archive, error => {
if (error != null) {
logger.error(
{ err: error, project_id },
'error adding files to zip stream'
)
}
return archive.finalize()
})
})
},
addAllDocsToArchive(project_id, archive, callback) {
if (callback == null) {
callback = function (error) {}
}
return ProjectEntityHandler.getAllDocs(project_id, function (error, docs) {
if (error != null) {
return callback(error)
}
const jobs = []
for (const path in docs) {
const doc = docs[path]
;(function (path, doc) {
if (path[0] === '/') {
path = path.slice(1)
}
return jobs.push(function (callback) {
logger.log({ project_id }, 'Adding doc')
archive.append(doc.lines.join('\n'), { name: path })
return callback()
})
})(path, doc)
}
return async.series(jobs, callback)
})
},
addAllFilesToArchive(project_id, archive, callback) {
if (callback == null) {
callback = function (error) {}
}
return ProjectEntityHandler.getAllFiles(
project_id,
function (error, files) {
if (error != null) {
return callback(error)
}
const jobs = []
for (const 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(error)
}
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)
}
)
},
}
| overleaf/web/app/src/Features/Downloads/ProjectZipStreamManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/Downloads/ProjectZipStreamManager.js",
"repo_id": "overleaf",
"token_count": 2635
} | 492 |
const logger = require('logger-sharelatex')
const Settings = require('@overleaf/settings')
function renderJSONError(res, message, info = {}) {
if (info.message) {
logger.warn(
info,
`http error info shouldn't contain a 'message' field, will be overridden`
)
}
if (message != null) {
res.json({ ...info, message })
} else {
res.json(info)
}
}
function handleGeneric500Error(req, res, statusCode, message) {
res.status(statusCode)
switch (req.accepts(['html', 'json'])) {
case 'html':
return res.render('general/500', { title: 'Server Error' })
case 'json':
return renderJSONError(res, message)
default:
return res.send('internal server error')
}
}
function handleGeneric400Error(req, res, statusCode, message, info = {}) {
res.status(statusCode)
switch (req.accepts(['html', 'json'])) {
case 'html':
return res.render('general/400', {
title: 'Client Error',
message: message,
})
case 'json':
return renderJSONError(res, message, info)
default:
return res.send('client error')
}
}
let HttpErrorHandler
module.exports = HttpErrorHandler = {
handleErrorByStatusCode(req, res, error, statusCode) {
const is400Error = statusCode >= 400 && statusCode < 500
const is500Error = statusCode >= 500 && statusCode < 600
if (is400Error) {
logger.warn(error)
} else if (is500Error) {
logger.error(error)
}
if (statusCode === 403) {
HttpErrorHandler.forbidden(req, res)
} else if (statusCode === 404) {
HttpErrorHandler.notFound(req, res)
} else if (statusCode === 409) {
HttpErrorHandler.conflict(req, res, '')
} else if (statusCode === 422) {
HttpErrorHandler.unprocessableEntity(req, res)
} else if (is400Error) {
handleGeneric400Error(req, res, statusCode)
} else if (is500Error) {
handleGeneric500Error(req, res, statusCode)
} else {
logger.error(
{ err: error, statusCode },
`unable to handle error with status code ${statusCode}`
)
res.sendStatus(500)
}
},
badRequest(req, res, message, info = {}) {
handleGeneric400Error(req, res, 400, message, info)
},
conflict(req, res, message, info = {}) {
res.status(409)
switch (req.accepts(['html', 'json'])) {
case 'html':
return res.render('general/400', {
title: 'Client Error',
message: message,
})
case 'json':
return renderJSONError(res, message, info)
default:
return res.send('conflict')
}
},
forbidden(req, res, message = 'restricted', info = {}) {
res.status(403)
switch (req.accepts(['html', 'json'])) {
case 'html':
return res.render('user/restricted', { title: 'restricted' })
case 'json':
return renderJSONError(res, message, info)
default:
return res.send('restricted')
}
},
notFound(req, res, message = 'not found', info = {}) {
res.status(404)
switch (req.accepts(['html', 'json'])) {
case 'html':
return res.render('general/404', { title: 'page_not_found' })
case 'json':
return renderJSONError(res, message, info)
default:
return res.send('not found')
}
},
unprocessableEntity(req, res, message = 'unprocessable entity', info = {}) {
res.status(422)
switch (req.accepts(['html', 'json'])) {
case 'html':
return res.render('general/400', {
title: 'Client Error',
message: message,
})
case 'json':
return renderJSONError(res, message, info)
default:
return res.send('unprocessable entity')
}
},
legacyInternal(req, res, message, error) {
logger.error(error)
handleGeneric500Error(req, res, 500, message)
},
maintenance(req, res) {
// load balancer health checks require a success response for /
if (req.url === '/') {
res.status(200)
} else {
res.status(503)
}
let message = `${Settings.appName} is currently down for maintenance.`
if (Settings.statusPageUrl) {
message += ` Please check https://${Settings.statusPageUrl} for updates.`
}
switch (req.accepts(['html', 'json'])) {
case 'html':
return res.render('general/closed', { title: 'maintenance' })
case 'json':
return renderJSONError(res, message, {})
default:
return res.send(message)
}
},
}
| overleaf/web/app/src/Features/Errors/HttpErrorHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Errors/HttpErrorHandler.js",
"repo_id": "overleaf",
"token_count": 1799
} | 493 |
let HistoryController
const OError = require('@overleaf/o-error')
const async = require('async')
const logger = require('logger-sharelatex')
const request = require('request')
const settings = require('@overleaf/settings')
const SessionManager = require('../Authentication/SessionManager')
const UserGetter = require('../User/UserGetter')
const Errors = require('../Errors/Errors')
const HistoryManager = require('./HistoryManager')
const ProjectDetailsHandler = require('../Project/ProjectDetailsHandler')
const ProjectEntityUpdateHandler = require('../Project/ProjectEntityUpdateHandler')
const RestoreManager = require('./RestoreManager')
const { pipeline } = require('stream')
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) {
if (err) {
return next(err)
}
const history = project.overleaf && project.overleaf.history
if (history && history.id && history.display) {
req.useProjectHistory = true
} else {
req.useProjectHistory = false
}
next()
})
},
ensureProjectHistoryEnabled(req, res, next) {
if (req.useProjectHistory) {
next()
} else {
res.sendStatus(404)
}
},
proxyToHistoryApi(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
const url =
HistoryController.buildHistoryServiceUrl(req.useProjectHistory) + req.url
const getReq = request({
url,
method: req.method,
headers: {
'X-User-Id': userId,
},
})
getReq.pipe(res)
getReq.on('error', function (err) {
logger.warn({ url, err }, 'history API error')
next(err)
})
},
proxyToHistoryApiAndInjectUserDetails(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
const url =
HistoryController.buildHistoryServiceUrl(req.useProjectHistory) + req.url
HistoryController._makeRequest(
{
url,
method: req.method,
json: true,
headers: {
'X-User-Id': userId,
},
},
function (err, body) {
if (err) {
return next(err)
}
HistoryManager.injectUserDetails(body, function (err, data) {
if (err) {
return next(err)
}
res.json(data)
})
}
)
},
buildHistoryServiceUrl(useProjectHistory) {
// choose a history service, either document-level (trackchanges)
// or project-level (project_history)
if (useProjectHistory) {
return settings.apis.project_history.url
} else {
return settings.apis.trackchanges.url
}
},
resyncProjectHistory(req, res, next) {
const projectId = req.params.Project_id
ProjectEntityUpdateHandler.resyncProjectHistory(projectId, function (err) {
if (err instanceof Errors.ProjectHistoryDisabledError) {
return res.sendStatus(404)
}
if (err) {
return next(err)
}
res.sendStatus(204)
})
},
restoreFileFromV2(req, res, next) {
const { project_id: projectId } = req.params
const { version, pathname } = req.body
const userId = SessionManager.getLoggedInUserId(req.session)
RestoreManager.restoreFileFromV2(
userId,
projectId,
version,
pathname,
function (err, entity) {
if (err) {
return next(err)
}
res.json({
type: entity.type,
id: entity._id,
})
}
)
},
restoreDocFromDeletedDoc(req, res, next) {
const { project_id: projectId, doc_id: docId } = req.params
const { name } = req.body
const userId = SessionManager.getLoggedInUserId(req.session)
if (name == null) {
return res.sendStatus(400) // Malformed request
}
RestoreManager.restoreDocFromDeletedDoc(
userId,
projectId,
docId,
name,
(err, doc) => {
if (err) return next(err)
res.json({
doc_id: doc._id,
})
}
)
},
getLabels(req, res, next) {
const projectId = req.params.Project_id
HistoryController._makeRequest(
{
method: 'GET',
url: `${settings.apis.project_history.url}/project/${projectId}/labels`,
json: true,
},
function (err, labels) {
if (err) {
return next(err)
}
HistoryController._enrichLabels(labels, (err, labels) => {
if (err) {
return next(err)
}
res.json(labels)
})
}
)
},
createLabel(req, res, next) {
const projectId = req.params.Project_id
const { comment, version } = req.body
const userId = SessionManager.getLoggedInUserId(req.session)
HistoryController._makeRequest(
{
method: 'POST',
url: `${settings.apis.project_history.url}/project/${projectId}/user/${userId}/labels`,
json: { comment, version },
},
function (err, label) {
if (err) {
return next(err)
}
HistoryController._enrichLabel(label, (err, label) => {
if (err) {
return next(err)
}
res.json(label)
})
}
)
},
_enrichLabel(label, callback) {
if (!label.user_id) {
return callback(null, label)
}
UserGetter.getUser(
label.user_id,
{ first_name: 1, last_name: 1, email: 1 },
(err, user) => {
if (err) {
return callback(err)
}
const newLabel = Object.assign({}, label)
newLabel.user_display_name = HistoryController._displayNameForUser(user)
callback(null, newLabel)
}
)
},
_enrichLabels(labels, callback) {
if (!labels || !labels.length) {
return callback(null, [])
}
const uniqueUsers = new Set(labels.map(label => label.user_id))
// For backwards compatibility expect missing user_id fields
uniqueUsers.delete(undefined)
if (!uniqueUsers.size) {
return callback(null, labels)
}
UserGetter.getUsers(
Array.from(uniqueUsers),
{ first_name: 1, last_name: 1, email: 1 },
function (err, rawUsers) {
if (err) {
return callback(err)
}
const users = new Map(rawUsers.map(user => [String(user._id), user]))
labels.forEach(label => {
const user = users.get(label.user_id)
if (!user) return
label.user_display_name = HistoryController._displayNameForUser(user)
})
callback(null, labels)
}
)
},
_displayNameForUser(user) {
if (user == null) {
return 'Anonymous'
}
if (user.name) {
return user.name
}
let name = [user.first_name, user.last_name]
.filter(n => n != null)
.join(' ')
.trim()
if (name === '') {
name = user.email.split('@')[0]
}
if (!name) {
return '?'
}
return name
},
deleteLabel(req, res, next) {
const { Project_id: projectId, label_id: labelId } = req.params
const userId = SessionManager.getLoggedInUserId(req.session)
HistoryController._makeRequest(
{
method: 'DELETE',
url: `${settings.apis.project_history.url}/project/${projectId}/user/${userId}/labels/${labelId}`,
},
function (err) {
if (err) {
return next(err)
}
res.sendStatus(204)
}
)
},
_makeRequest(options, callback) {
return request(options, function (err, response, body) {
if (err) {
return callback(err)
}
if (response.statusCode >= 200 && response.statusCode < 300) {
callback(null, body)
} else {
err = new Error(
`history api responded with non-success code: ${response.statusCode}`
)
callback(err)
}
})
},
downloadZipOfVersion(req, res, next) {
const { project_id: projectId, version } = req.params
ProjectDetailsHandler.getDetails(projectId, function (err, project) {
if (err) {
return next(err)
}
const v1Id =
project.overleaf &&
project.overleaf.history &&
project.overleaf.history.id
if (v1Id == null) {
logger.error(
{ projectId, version },
'got request for zip version of non-v1 history project'
)
return res.sendStatus(402)
}
HistoryController._pipeHistoryZipToResponse(
v1Id,
version,
`${project.name} (Version ${version})`,
req,
res,
next
)
})
},
_pipeHistoryZipToResponse(v1ProjectId, version, name, req, res, next) {
if (req.aborted) {
// client has disconnected -- skip project history api call and download
return
}
// increase timeout to 6 minutes
res.setTimeout(6 * 60 * 1000)
const url = `${settings.apis.v1_history.url}/projects/${v1ProjectId}/version/${version}/zip`
const options = {
auth: {
user: settings.apis.v1_history.user,
pass: settings.apis.v1_history.pass,
},
json: true,
method: 'post',
url,
}
request(options, function (err, response, body) {
if (err) {
OError.tag(err, 'history API error', {
v1ProjectId,
version,
})
return next(err)
}
if (req.aborted) {
// client has disconnected -- skip delayed s3 download
return
}
let retryAttempt = 0
let retryDelay = 2000
// retry for about 6 minutes starting with short delay
async.retry(
40,
callback =>
setTimeout(function () {
if (req.aborted) {
// client has disconnected -- skip s3 download
return callback() // stop async.retry loop
}
// increase delay by 1 second up to 10
if (retryDelay < 10000) {
retryDelay += 1000
}
retryAttempt++
const getReq = request({
url: body.zipUrl,
sendImmediately: true,
})
const abortS3Request = () => getReq.abort()
req.on('aborted', abortS3Request)
res.on('timeout', abortS3Request)
function cleanupAbortTrigger() {
req.off('aborted', abortS3Request)
res.off('timeout', abortS3Request)
}
getReq.on('response', function (response) {
if (response.statusCode !== 200) {
cleanupAbortTrigger()
return callback(new Error('invalid response'))
}
// pipe also proxies the headers, but we want to customize these ones
delete response.headers['content-disposition']
delete response.headers['content-type']
res.status(response.statusCode)
res.setContentDisposition('attachment', {
filename: `${name}.zip`,
})
res.contentType('application/zip')
pipeline(response, res, err => {
if (err) {
logger.warn(
{ err, v1ProjectId, version, retryAttempt },
'history s3 proxying error'
)
}
})
callback()
})
getReq.on('error', function (err) {
logger.warn(
{ err, v1ProjectId, version, retryAttempt },
'history s3 download error'
)
cleanupAbortTrigger()
callback(err)
})
}, retryDelay),
function (err) {
if (err) {
OError.tag(err, 'history s3 download failed', {
v1ProjectId,
version,
retryAttempt,
})
next(err)
}
}
)
})
},
}
| overleaf/web/app/src/Features/History/HistoryController.js/0 | {
"file_path": "overleaf/web/app/src/Features/History/HistoryController.js",
"repo_id": "overleaf",
"token_count": 5545
} | 494 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let ProjectOutputFileAgent
const AuthorizationManager = require('../Authorization/AuthorizationManager')
const ProjectGetter = require('../Project/ProjectGetter')
const Settings = require('@overleaf/settings')
const CompileManager = require('../Compile/CompileManager')
const ClsiManager = require('../Compile/ClsiManager')
const ProjectFileAgent = require('./ProjectFileAgent')
const _ = require('underscore')
const {
CompileFailedError,
BadDataError,
AccessDeniedError,
BadEntityTypeError,
OutputFileFetchFailedError,
} = require('./LinkedFilesErrors')
const LinkedFilesHandler = require('./LinkedFilesHandler')
const logger = require('logger-sharelatex')
module.exports = ProjectOutputFileAgent = {
_prepare(project_id, linkedFileData, user_id, callback) {
if (callback == null) {
callback = function (err, linkedFileData) {}
}
return this._checkAuth(
project_id,
linkedFileData,
user_id,
(err, allowed) => {
if (err != null) {
return callback(err)
}
if (!allowed) {
return callback(new AccessDeniedError())
}
if (!this._validate(linkedFileData)) {
return callback(new BadDataError())
}
return callback(null, linkedFileData)
}
)
},
createLinkedFile(
project_id,
linkedFileData,
name,
parent_folder_id,
user_id,
callback
) {
if (!this._canCreate(linkedFileData)) {
return callback(new AccessDeniedError())
}
linkedFileData = this._sanitizeData(linkedFileData)
return this._prepare(
project_id,
linkedFileData,
user_id,
(err, linkedFileData) => {
if (err != null) {
return callback(err)
}
return this._getFileStream(
linkedFileData,
user_id,
(err, readStream) => {
if (err != null) {
return callback(err)
}
readStream.on('error', callback)
return readStream.on('response', 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 {
err = new OutputFileFetchFailedError(
`Output file fetch failed: ${linkedFileData.build_id}, ${linkedFileData.source_output_file_path}`
)
err.statusCode = response.statusCode
return callback(err)
}
})
}
)
}
)
},
refreshLinkedFile(
project_id,
linkedFileData,
name,
parent_folder_id,
user_id,
callback
) {
return this._prepare(
project_id,
linkedFileData,
user_id,
(err, linkedFileData) => {
if (err != null) {
return callback(err)
}
return this._compileAndGetFileStream(
linkedFileData,
user_id,
(err, readStream, new_build_id) => {
if (err != null) {
return callback(err)
}
readStream.on('error', callback)
return readStream.on('response', response => {
if (response.statusCode >= 200 && response.statusCode < 300) {
readStream.resume()
linkedFileData.build_id = new_build_id
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 {
err = new OutputFileFetchFailedError(
`Output file fetch failed: ${linkedFileData.build_id}, ${linkedFileData.source_output_file_path}`
)
err.statusCode = response.statusCode
return callback(err)
}
})
}
)
}
)
},
_sanitizeData(data) {
return {
provider: data.provider,
source_project_id: data.source_project_id,
source_output_file_path: data.source_output_file_path,
build_id: data.build_id,
}
},
_canCreate: ProjectFileAgent._canCreate,
_getSourceProject: LinkedFilesHandler.getSourceProject,
_validate(data) {
if (data.v1_source_doc_id != null) {
return (
data.v1_source_doc_id != null && data.source_output_file_path != null
)
} else {
return (
data.source_project_id != null &&
data.source_output_file_path != null &&
data.build_id != null
)
}
},
_checkAuth(project_id, data, current_user_id, callback) {
if (callback == null) {
callback = function (err, allowed) {}
}
callback = _.once(callback)
if (!this._validate(data)) {
return callback(new BadDataError())
}
return this._getSourceProject(data, function (err, project) {
if (err != null) {
return callback(err)
}
return AuthorizationManager.canUserReadProject(
current_user_id,
project._id,
null,
function (err, canRead) {
if (err != null) {
return callback(err)
}
return callback(null, canRead)
}
)
})
},
_getFileStream(linkedFileData, user_id, callback) {
if (callback == null) {
callback = function (err, fileStream) {}
}
callback = _.once(callback)
const { source_output_file_path, build_id } = linkedFileData
return this._getSourceProject(linkedFileData, function (err, project) {
if (err != null) {
return callback(err)
}
const source_project_id = project._id
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)
}
)
})
},
_compileAndGetFileStream(linkedFileData, user_id, callback) {
if (callback == null) {
callback = function (err, stream, build_id) {}
}
callback = _.once(callback)
const { source_output_file_path } = linkedFileData
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 CompileFailedError())
}
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)
}
)
}
)
})
},
}
| overleaf/web/app/src/Features/LinkedFiles/ProjectOutputFileAgent.js/0 | {
"file_path": "overleaf/web/app/src/Features/LinkedFiles/ProjectOutputFileAgent.js",
"repo_id": "overleaf",
"token_count": 4158
} | 495 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let ProjectCollabratecDetailsHandler
const { ObjectId } = require('mongodb')
const { Project } = require('../../models/Project')
module.exports = ProjectCollabratecDetailsHandler = {
initializeCollabratecProject(
project_id,
user_id,
collabratec_document_id,
collabratec_privategroup_id,
callback
) {
if (callback == null) {
callback = function (err) {}
}
return ProjectCollabratecDetailsHandler.setCollabratecUsers(
project_id,
[{ user_id, collabratec_document_id, collabratec_privategroup_id }],
callback
)
},
isLinkedCollabratecUserProject(project_id, user_id, callback) {
if (callback == null) {
callback = function (err, isLinked) {}
}
try {
project_id = ObjectId(project_id)
user_id = ObjectId(user_id)
} catch (error) {
const err = error
return callback(err)
}
const query = {
_id: project_id,
collabratecUsers: {
$elemMatch: {
user_id,
},
},
}
return Project.findOne(query, { _id: 1 }, function (err, project) {
if (err != null) {
callback(err)
}
return callback(null, project != null)
})
},
linkCollabratecUserProject(
project_id,
user_id,
collabratec_document_id,
callback
) {
if (callback == null) {
callback = function (err) {}
}
try {
project_id = ObjectId(project_id)
user_id = ObjectId(user_id)
} catch (error) {
const err = error
return callback(err)
}
const query = {
_id: project_id,
collabratecUsers: {
$not: {
$elemMatch: {
collabratec_document_id,
user_id,
},
},
},
}
const update = {
$push: {
collabratecUsers: {
collabratec_document_id,
user_id,
},
},
}
return Project.updateOne(query, update, callback)
},
setCollabratecUsers(project_id, collabratec_users, callback) {
let err
if (callback == null) {
callback = function (err) {}
}
try {
project_id = ObjectId(project_id)
} catch (error) {
err = error
return callback(err)
}
if (!Array.isArray(collabratec_users)) {
callback(new Error('collabratec_users must be array'))
}
for (const collabratec_user of Array.from(collabratec_users)) {
try {
collabratec_user.user_id = ObjectId(collabratec_user.user_id)
} catch (error1) {
err = error1
return callback(err)
}
}
const update = { $set: { collabratecUsers: collabratec_users } }
return Project.updateOne({ _id: project_id }, update, callback)
},
unlinkCollabratecUserProject(project_id, user_id, callback) {
if (callback == null) {
callback = function (err) {}
}
try {
project_id = ObjectId(project_id)
user_id = ObjectId(user_id)
} catch (error) {
const err = error
return callback(err)
}
const query = { _id: project_id }
const update = {
$pull: {
collabratecUsers: {
user_id,
},
},
}
return Project.updateOne(query, update, callback)
},
updateCollabratecUserIds(old_user_id, new_user_id, callback) {
if (callback == null) {
callback = function (err) {}
}
try {
old_user_id = ObjectId(old_user_id)
new_user_id = ObjectId(new_user_id)
} catch (error) {
const err = error
return callback(err)
}
const query = { 'collabratecUsers.user_id': old_user_id }
const update = { $set: { 'collabratecUsers.$.user_id': new_user_id } }
return Project.updateMany(query, update, callback)
},
}
| overleaf/web/app/src/Features/Project/ProjectCollabratecDetailsHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Project/ProjectCollabratecDetailsHandler.js",
"repo_id": "overleaf",
"token_count": 1822
} | 496 |
/* eslint-disable
camelcase,
node/handle-callback-err,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const { Project } = require('../../models/Project')
const logger = require('logger-sharelatex')
module.exports = {
markAsUpdated(projectId, lastUpdatedAt, lastUpdatedBy, callback) {
if (callback == null) {
callback = function () {}
}
if (lastUpdatedAt == null) {
lastUpdatedAt = new Date()
}
const conditions = {
_id: projectId,
lastUpdated: { $lt: lastUpdatedAt },
}
const update = {
lastUpdated: lastUpdatedAt || new Date().getTime(),
lastUpdatedBy,
}
return Project.updateOne(conditions, update, {}, callback)
},
markAsOpened(project_id, callback) {
const conditions = { _id: project_id }
const update = { lastOpened: Date.now() }
return Project.updateOne(conditions, update, {}, function (err) {
if (callback != null) {
return callback()
}
})
},
markAsInactive(project_id, callback) {
const conditions = { _id: project_id }
const update = { active: false }
return Project.updateOne(conditions, update, {}, function (err) {
if (callback != null) {
return callback()
}
})
},
markAsActive(project_id, callback) {
const conditions = { _id: project_id }
const update = { active: true }
return Project.updateOne(conditions, update, {}, function (err) {
if (callback != null) {
return callback()
}
})
},
}
| overleaf/web/app/src/Features/Project/ProjectUpdateHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Project/ProjectUpdateHandler.js",
"repo_id": "overleaf",
"token_count": 665
} | 497 |
const request = require('request')
const Settings = require('@overleaf/settings')
const OError = require('@overleaf/o-error')
const TIMEOUT = 10 * 1000
module.exports = {
getUserDictionary(userId, callback) {
const url = `${Settings.apis.spelling.url}/user/${userId}`
request.get({ url: url, timeout: TIMEOUT }, (error, response) => {
if (error) {
return callback(
OError.tag(error, 'error getting user dictionary', { error, userId })
)
}
if (response.statusCode < 200 || response.statusCode >= 300) {
return callback(
new OError(
'Non-success code from spelling API when getting user dictionary',
{ userId, statusCode: response.statusCode }
)
)
}
callback(null, JSON.parse(response.body))
})
},
deleteWordFromUserDictionary(userId, word, callback) {
const url = `${Settings.apis.spelling.url}/user/${userId}/unlearn`
request.post(
{
url: url,
json: {
word,
},
timeout: TIMEOUT,
},
(error, response) => {
if (error) {
return callback(
OError.tag(error, 'error deleting word from user dictionary', {
userId,
word,
})
)
}
if (response.statusCode < 200 || response.statusCode >= 300) {
return callback(
new OError(
'Non-success code from spelling API when removing word from user dictionary',
{ userId, word, statusCode: response.statusCode }
)
)
}
callback()
}
)
},
deleteUserDictionary(userId, callback) {
const url = `${Settings.apis.spelling.url}/user/${userId}`
request.delete({ url: url, timeout: TIMEOUT }, (error, response) => {
if (error) {
return callback(
OError.tag(error, 'error deleting user dictionary', { userId })
)
}
if (response.statusCode < 200 || response.statusCode >= 300) {
return callback(
new OError(
'Non-success code from spelling API when removing user dictionary',
{ userId, statusCode: response.statusCode }
)
)
}
callback()
})
},
}
| overleaf/web/app/src/Features/Spelling/SpellingHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Spelling/SpellingHandler.js",
"repo_id": "overleaf",
"token_count": 1032
} | 498 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
no-unused-vars,
node/no-deprecated-api,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const OError = require('@overleaf/o-error')
const querystring = require('querystring')
const crypto = require('crypto')
const request = require('request')
const Settings = require('@overleaf/settings')
const xml2js = require('xml2js')
const logger = require('logger-sharelatex')
const Async = require('async')
const Errors = require('../Errors/Errors')
const SubscriptionErrors = require('./Errors')
const { promisify } = require('util')
function updateAccountEmailAddress(accountId, newEmail, callback) {
const data = {
email: newEmail,
}
const requestBody = RecurlyWrapper._buildXml('account', data)
RecurlyWrapper.apiRequest(
{
url: `accounts/${accountId}`,
method: 'PUT',
body: requestBody,
},
(error, response, body) => {
if (error != null) {
return callback(error)
}
RecurlyWrapper._parseAccountXml(body, callback)
}
)
}
const RecurlyWrapper = {
apiUrl: Settings.apis.recurly.url || 'https://api.recurly.com/v2',
_paypal: {
checkAccountExists(cache, next) {
const { user } = cache
const { subscriptionDetails } = cache
logger.log(
{ user_id: user._id },
'checking if recurly account exists for user'
)
return RecurlyWrapper.apiRequest(
{
url: `accounts/${user._id}`,
method: 'GET',
expect404: true,
},
function (error, response, responseBody) {
if (error) {
OError.tag(
error,
'error response from recurly while checking account',
{
user_id: user._id,
}
)
return next(error)
}
if (response.statusCode === 404) {
// actually not an error in this case, just no existing account
logger.log(
{ user_id: user._id },
'user does not currently exist in recurly, proceed'
)
cache.userExists = false
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)
}
cache.userExists = true
cache.account = account
return next(null, cache)
}
)
}
)
},
createAccount(cache, next) {
const { user } = cache
const { subscriptionDetails } = cache
if (cache.userExists) {
return next(null, cache)
}
let address
try {
address = getAddressFromSubscriptionDetails(subscriptionDetails, false)
} catch (error) {
return next(error)
}
const data = {
account_code: user._id,
email: user.email,
first_name: user.first_name,
last_name: user.last_name,
address,
}
const requestBody = RecurlyWrapper._buildXml('account', data)
return RecurlyWrapper.apiRequest(
{
url: 'accounts',
method: 'POST',
body: requestBody,
},
(error, response, responseBody) => {
if (error) {
OError.tag(
error,
'error response from recurly while creating account',
{
user_id: user._id,
}
)
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)
}
cache.account = account
return next(null, cache)
}
)
}
)
},
createBillingInfo(cache, next) {
const { user } = cache
const { recurlyTokenIds } = cache
const { subscriptionDetails } = cache
logger.log({ user_id: user._id }, 'creating billing info in recurly')
const accountCode = __guard__(
cache != null ? cache.account : undefined,
x1 => x1.account_code
)
if (!accountCode) {
return next(new Error('no account code at createBillingInfo stage'))
}
const data = { token_id: recurlyTokenIds.billing }
const requestBody = RecurlyWrapper._buildXml('billing_info', data)
return RecurlyWrapper.apiRequest(
{
url: `accounts/${accountCode}/billing_info`,
method: 'POST',
body: requestBody,
},
(error, response, responseBody) => {
if (error) {
OError.tag(
error,
'error response from recurly while creating billing info',
{
user_id: user._id,
}
)
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)
}
cache.billingInfo = billingInfo
return next(null, cache)
}
)
}
)
},
setAddressAndCompanyBillingInfo(cache, next) {
const { user } = cache
const { subscriptionDetails } = cache
logger.log(
{ user_id: user._id },
'setting billing address and company info in recurly'
)
const accountCode = __guard__(
cache != null ? cache.account : undefined,
x1 => x1.account_code
)
if (!accountCode) {
return next(
new Error('no account code at setAddressAndCompanyBillingInfo stage')
)
}
let addressAndCompanyBillingInfo
try {
addressAndCompanyBillingInfo = getAddressFromSubscriptionDetails(
subscriptionDetails,
true
)
} catch (error) {
return next(error)
}
const requestBody = RecurlyWrapper._buildXml(
'billing_info',
addressAndCompanyBillingInfo
)
return RecurlyWrapper.apiRequest(
{
url: `accounts/${accountCode}/billing_info`,
method: 'PUT',
body: requestBody,
},
(error, response, responseBody) => {
if (error) {
OError.tag(
error,
'error response from recurly while setting address',
{
user_id: user._id,
}
)
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)
}
cache.billingInfo = billingInfo
return next(null, cache)
}
)
}
)
},
createSubscription(cache, next) {
const { user } = cache
const { subscriptionDetails } = cache
logger.log({ user_id: user._id }, 'creating subscription in recurly')
const data = {
plan_code: subscriptionDetails.plan_code,
currency: subscriptionDetails.currencyCode,
coupon_code: subscriptionDetails.coupon_code,
account: {
account_code: user._id,
},
}
const customFields = getCustomFieldsFromSubscriptionDetails(
subscriptionDetails
)
if (customFields) {
data.custom_fields = customFields
}
const requestBody = RecurlyWrapper._buildXml('subscription', data)
return RecurlyWrapper.apiRequest(
{
url: 'subscriptions',
method: 'POST',
body: requestBody,
},
(error, response, responseBody) => {
if (error) {
OError.tag(
error,
'error response from recurly while creating subscription',
{
user_id: user._id,
}
)
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)
}
cache.subscription = subscription
return next(null, cache)
}
)
}
)
},
},
_createPaypalSubscription(
user,
subscriptionDetails,
recurlyTokenIds,
callback
) {
logger.log(
{ user_id: user._id },
'starting process of creating paypal subscription'
)
// We use `async.waterfall` to run each of these actions in sequence
// passing a `cache` object along the way. The cache is initialized
// with required data, and `async.apply` to pass the cache to the first function
const cache = { user, recurlyTokenIds, subscriptionDetails }
return Async.waterfall(
[
Async.apply(RecurlyWrapper._paypal.checkAccountExists, cache),
RecurlyWrapper._paypal.createAccount,
RecurlyWrapper._paypal.createBillingInfo,
RecurlyWrapper._paypal.setAddressAndCompanyBillingInfo,
RecurlyWrapper._paypal.createSubscription,
],
function (err, result) {
if (err) {
OError.tag(err, 'error in paypal subscription creation process', {
user_id: user._id,
})
return callback(err)
}
if (!result.subscription) {
err = new Error('no subscription object in result')
OError.tag(err, 'error in paypal subscription creation process', {
user_id: user._id,
})
return callback(err)
}
logger.log(
{ user_id: user._id },
'done creating paypal subscription for user'
)
return callback(null, result.subscription)
}
)
},
_createCreditCardSubscription(
user,
subscriptionDetails,
recurlyTokenIds,
callback
) {
const data = {
plan_code: subscriptionDetails.plan_code,
currency: subscriptionDetails.currencyCode,
coupon_code: subscriptionDetails.coupon_code,
account: {
account_code: user._id,
email: user.email,
first_name: subscriptionDetails.first_name || user.first_name,
last_name: subscriptionDetails.last_name || user.last_name,
billing_info: {
token_id: recurlyTokenIds.billing,
},
},
}
if (recurlyTokenIds.threeDSecureActionResult) {
data.account.billing_info.three_d_secure_action_result_token_id =
recurlyTokenIds.threeDSecureActionResult
}
const customFields = getCustomFieldsFromSubscriptionDetails(
subscriptionDetails
)
if (customFields) {
data.custom_fields = customFields
}
const requestBody = RecurlyWrapper._buildXml('subscription', data)
return RecurlyWrapper.apiRequest(
{
url: 'subscriptions',
method: 'POST',
body: requestBody,
expect422: true,
},
(error, response, responseBody) => {
if (error != null) {
return callback(error)
}
if (response.statusCode === 422) {
RecurlyWrapper._handle422Response(responseBody, callback)
} else {
RecurlyWrapper._parseSubscriptionXml(responseBody, callback)
}
}
)
},
createSubscription(user, subscriptionDetails, recurlyTokenIds, callback) {
const { isPaypal } = subscriptionDetails
logger.log(
{ user_id: user._id, isPaypal },
'setting up subscription in recurly'
)
const fn = isPaypal
? RecurlyWrapper._createPaypalSubscription
: RecurlyWrapper._createCreditCardSubscription
return fn(user, subscriptionDetails, recurlyTokenIds, callback)
},
apiRequest(options, callback) {
options.url = RecurlyWrapper.apiUrl + '/' + options.url
options.headers = {
Authorization: `Basic ${new Buffer(Settings.apis.recurly.apiKey).toString(
'base64'
)}`,
Accept: 'application/xml',
'Content-Type': 'application/xml; charset=utf-8',
'X-Api-Version': Settings.apis.recurly.apiVersion,
}
const { expect404, expect422 } = options
delete options.expect404
delete options.expect422
return request(options, function (error, response, body) {
if (
error == null &&
response.statusCode !== 200 &&
response.statusCode !== 201 &&
response.statusCode !== 204 &&
(response.statusCode !== 404 || !expect404) &&
(response.statusCode !== 422 || !expect422)
) {
logger.warn(
{
err: error,
body,
options,
statusCode: response != null ? response.statusCode : undefined,
},
'error returned from recurly'
)
// TODO: this should be an Error object not a string
error = `Recurly API returned with status code: ${response.statusCode}`
}
return callback(error, response, body)
})
},
getSubscriptions(accountId, callback) {
return RecurlyWrapper.apiRequest(
{
url: `accounts/${accountId}/subscriptions`,
},
(error, response, body) => {
if (error != null) {
return callback(error)
}
return RecurlyWrapper._parseXml(body, callback)
}
)
},
getSubscription(subscriptionId, options, callback) {
let url
if (callback == null) {
callback = options
}
if (!options) {
options = {}
}
if (options.recurlyJsResult) {
url = `recurly_js/result/${subscriptionId}`
} else {
url = `subscriptions/${subscriptionId}`
}
return RecurlyWrapper.apiRequest(
{
url,
},
(error, response, body) => {
if (error != null) {
return callback(error)
}
return RecurlyWrapper._parseSubscriptionXml(
body,
(error, recurlySubscription) => {
if (error != null) {
return callback(error)
}
if (options.includeAccount) {
let accountId
if (
recurlySubscription.account != null &&
recurlySubscription.account.url != null
) {
accountId = recurlySubscription.account.url.match(
/accounts\/(.*)/
)[1]
} else {
return callback(
new Error("I don't understand the response from Recurly")
)
}
return RecurlyWrapper.getAccount(
accountId,
function (error, account) {
if (error != null) {
return callback(error)
}
recurlySubscription.account = account
return callback(null, recurlySubscription)
}
)
} else {
return callback(null, recurlySubscription)
}
}
)
}
)
},
getPaginatedEndpoint(resource, queryParams, callback) {
queryParams.per_page = queryParams.per_page || 200
let allItems = []
var getPage = (cursor = null) => {
const opts = {
url: resource,
qs: queryParams,
}
if (cursor != null) {
opts.qs.cursor = cursor
}
return RecurlyWrapper.apiRequest(opts, (error, response, body) => {
if (error != null) {
return callback(error)
}
return RecurlyWrapper._parseXml(body, function (err, data) {
if (err != null) {
logger.warn({ err }, 'could not get accoutns')
callback(err)
}
const items = data[resource]
allItems = allItems.concat(items)
logger.log(
`got another ${items.length}, total now ${allItems.length}`
)
cursor = __guard__(
response.headers.link != null
? response.headers.link.match(/cursor=([0-9.]+%3A[0-9.]+)&/)
: undefined,
x1 => x1[1]
)
if (cursor != null) {
cursor = decodeURIComponent(cursor)
return getPage(cursor)
} else {
return callback(err, allItems)
}
})
})
}
return getPage()
},
getAccount(accountId, callback) {
return RecurlyWrapper.apiRequest(
{
url: `accounts/${accountId}`,
},
(error, response, body) => {
if (error != null) {
return callback(error)
}
return RecurlyWrapper._parseAccountXml(body, callback)
}
)
},
updateAccountEmailAddress,
getAccountActiveCoupons(accountId, callback) {
return RecurlyWrapper.apiRequest(
{
url: `accounts/${accountId}/redemptions`,
},
(error, response, body) => {
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) {
if (error != null) {
return callback(error)
}
return callback(null, coupons)
}
)
}
)
}
)
},
getCoupon(couponCode, callback) {
const opts = { url: `coupons/${couponCode}` }
return RecurlyWrapper.apiRequest(opts, (error, response, body) =>
RecurlyWrapper._parseCouponXml(body, callback)
)
},
getBillingInfo(accountId, callback) {
return RecurlyWrapper.apiRequest(
{
url: `accounts/${accountId}/billing_info`,
},
(error, response, body) => {
if (error != null) {
return callback(error)
}
return RecurlyWrapper._parseXml(body, callback)
}
)
},
getAccountPastDueInvoices(accountId, callback) {
RecurlyWrapper.apiRequest(
{
url: `accounts/${accountId}/invoices?state=past_due`,
},
(error, response, body) => {
if (error) {
return callback(error)
}
RecurlyWrapper._parseInvoicesXml(body, callback)
}
)
},
attemptInvoiceCollection(invoiceId, callback) {
RecurlyWrapper.apiRequest(
{
url: `invoices/${invoiceId}/collect`,
method: 'put',
},
callback
)
},
updateSubscription(subscriptionId, options, callback) {
logger.log(
{ subscriptionId, options },
'telling recurly to update subscription'
)
const data = {
plan_code: options.plan_code,
timeframe: options.timeframe,
}
const requestBody = RecurlyWrapper._buildXml('subscription', data)
return RecurlyWrapper.apiRequest(
{
url: `subscriptions/${subscriptionId}`,
method: 'put',
body: requestBody,
},
(error, response, responseBody) => {
if (error != null) {
return callback(error)
}
return RecurlyWrapper._parseSubscriptionXml(responseBody, callback)
}
)
},
createFixedAmmountCoupon(
coupon_code,
name,
currencyCode,
discount_in_cents,
plan_code,
callback
) {
const data = {
coupon_code,
name,
discount_type: 'dollars',
discount_in_cents: {},
plan_codes: {
plan_code,
},
applies_to_all_plans: false,
}
data.discount_in_cents[currencyCode] = discount_in_cents
const requestBody = RecurlyWrapper._buildXml('coupon', data)
logger.log({ coupon_code, requestBody }, 'creating coupon')
return RecurlyWrapper.apiRequest(
{
url: 'coupons',
method: 'post',
body: requestBody,
},
(error, response, responseBody) => {
if (error != null) {
logger.warn({ err: error, coupon_code }, 'error creating coupon')
}
return callback(error)
}
)
},
lookupCoupon(coupon_code, callback) {
return RecurlyWrapper.apiRequest(
{
url: `coupons/${coupon_code}`,
},
(error, response, body) => {
if (error != null) {
return callback(error)
}
return RecurlyWrapper._parseXml(body, callback)
}
)
},
redeemCoupon(account_code, coupon_code, callback) {
const data = {
account_code,
currency: 'USD',
}
const requestBody = RecurlyWrapper._buildXml('redemption', data)
logger.log(
{ account_code, coupon_code, requestBody },
'redeeming coupon for user'
)
return RecurlyWrapper.apiRequest(
{
url: `coupons/${coupon_code}/redeem`,
method: 'post',
body: requestBody,
},
(error, response, responseBody) => {
if (error != null) {
logger.warn(
{ err: error, account_code, coupon_code },
'error redeeming coupon'
)
}
return callback(error)
}
)
},
extendTrial(subscriptionId, daysUntilExpire, callback) {
if (daysUntilExpire == null) {
daysUntilExpire = 7
}
const next_renewal_date = new Date()
next_renewal_date.setDate(next_renewal_date.getDate() + daysUntilExpire)
logger.log(
{ subscriptionId, daysUntilExpire },
'Exending Free trial for user'
)
return RecurlyWrapper.apiRequest(
{
url: `/subscriptions/${subscriptionId}/postpone?next_renewal_date=${next_renewal_date}&bulk=false`,
method: 'put',
},
(error, response, responseBody) => {
if (error != null) {
logger.warn(
{ err: error, subscriptionId, daysUntilExpire },
'error exending trial'
)
}
return callback(error)
}
)
},
listAccountActiveSubscriptions(account_id, callback) {
if (callback == null) {
callback = function (error, subscriptions) {}
}
return RecurlyWrapper.apiRequest(
{
url: `accounts/${account_id}/subscriptions`,
qs: {
state: 'active',
},
expect404: true,
},
function (error, response, body) {
if (error != null) {
return callback(error)
}
if (response.statusCode === 404) {
return callback(null, [])
} else {
return RecurlyWrapper._parseSubscriptionsXml(body, callback)
}
}
)
},
_handle422Response(body, callback) {
RecurlyWrapper._parseErrorsXml(body, (error, data) => {
if (error) {
return callback(error)
}
let errorData = {}
if (data.transaction_error) {
errorData = {
message: data.transaction_error.merchant_message,
info: {
category: data.transaction_error.error_category,
gatewayCode: data.transaction_error.gateway_error_code,
public: {
code: data.transaction_error.error_code,
message: data.transaction_error.customer_message,
},
},
}
if (data.transaction_error.three_d_secure_action_token_id) {
errorData.info.public.threeDSecureActionTokenId =
data.transaction_error.three_d_secure_action_token_id
}
} else if (data.error && data.error._) {
// fallback for errors that don't have a `transaction_error` field, but
// instead a `error` field with a message (e.g. VATMOSS errors)
errorData = {
info: {
public: {
message: data.error._,
},
},
}
}
callback(new SubscriptionErrors.RecurlyTransactionError(errorData))
})
},
_parseSubscriptionsXml(xml, callback) {
return RecurlyWrapper._parseXmlAndGetAttribute(
xml,
'subscriptions',
callback
)
},
_parseSubscriptionXml(xml, callback) {
return RecurlyWrapper._parseXmlAndGetAttribute(
xml,
'subscription',
callback
)
},
_parseAccountXml(xml, callback) {
return RecurlyWrapper._parseXmlAndGetAttribute(xml, 'account', callback)
},
_parseBillingInfoXml(xml, callback) {
return RecurlyWrapper._parseXmlAndGetAttribute(
xml,
'billing_info',
callback
)
},
_parseRedemptionsXml(xml, callback) {
return RecurlyWrapper._parseXmlAndGetAttribute(xml, 'redemptions', callback)
},
_parseCouponXml(xml, callback) {
return RecurlyWrapper._parseXmlAndGetAttribute(xml, 'coupon', callback)
},
_parseErrorsXml(xml, callback) {
return RecurlyWrapper._parseXmlAndGetAttribute(xml, 'errors', callback)
},
_parseInvoicesXml(xml, callback) {
return RecurlyWrapper._parseXmlAndGetAttribute(xml, 'invoices', callback)
},
_parseXmlAndGetAttribute(xml, attribute, callback) {
return RecurlyWrapper._parseXml(xml, function (error, data) {
if (error != null) {
return callback(error)
}
if (data != null && data[attribute] != null) {
return callback(null, data[attribute])
} else {
return callback(
new Error("I don't understand the response from Recurly")
)
}
})
},
_parseXml(xml, callback) {
var convertDataTypes = function (data) {
let key, value
if (data != null && data.$ != null) {
if (data.$.nil === 'nil') {
data = null
} else if (data.$.href != null) {
data.url = data.$.href
delete data.$
} else if (data.$.type === 'integer') {
data = parseInt(data._, 10)
} else if (data.$.type === 'datetime') {
data = new Date(data._)
} else if (data.$.type === 'array') {
delete data.$
let array = []
for (key in data) {
value = data[key]
if (value instanceof Array) {
array = array.concat(convertDataTypes(value))
} else {
array.push(convertDataTypes(value))
}
}
data = array
}
}
if (data instanceof Array) {
data = Array.from(data).map(entry => convertDataTypes(entry))
} else if (typeof data === 'object') {
for (key in data) {
value = data[key]
data[key] = convertDataTypes(value)
}
}
return data
}
const parser = new xml2js.Parser({
explicitRoot: true,
explicitArray: false,
emptyTag: '',
})
return parser.parseString(xml, function (error, data) {
if (error != null) {
return callback(error)
}
const result = convertDataTypes(data)
return callback(null, result)
})
},
_buildXml(rootName, data) {
const options = {
headless: true,
renderOpts: {
pretty: true,
indent: '\t',
},
rootName,
}
const builder = new xml2js.Builder(options)
return builder.buildObject(data)
},
}
RecurlyWrapper.promises = {
updateAccountEmailAddress: promisify(updateAccountEmailAddress),
}
module.exports = RecurlyWrapper
function getCustomFieldsFromSubscriptionDetails(subscriptionDetails) {
if (!subscriptionDetails.ITMCampaign) {
return null
}
const customFields = [
{
name: 'itm_campaign',
value: subscriptionDetails.ITMCampaign,
},
]
if (subscriptionDetails.ITMContent) {
customFields.push({
name: 'itm_content',
value: subscriptionDetails.ITMContent,
})
}
return { custom_field: customFields }
}
function getAddressFromSubscriptionDetails(
subscriptionDetails,
includeCompanyInfo
) {
const { address } = subscriptionDetails
if (!address || !address.country) {
throw new Errors.InvalidError({
message: 'Invalid country',
info: {
public: {
message: 'Invalid country',
},
},
})
}
const addressObject = {
address1: address.address1,
address2: address.address2 || '',
city: address.city || '',
state: address.state || '',
zip: address.zip || '',
country: address.country,
}
if (
includeCompanyInfo &&
subscriptionDetails.billing_info &&
subscriptionDetails.billing_info.company &&
subscriptionDetails.billing_info.company !== ''
) {
addressObject.company = subscriptionDetails.billing_info.company
if (
subscriptionDetails.billing_info.vat_number &&
subscriptionDetails.billing_info.vat_number !== ''
) {
addressObject.vat_number = subscriptionDetails.billing_info.vat_number
}
}
return addressObject
}
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
? transform(value)
: undefined
}
| overleaf/web/app/src/Features/Subscription/RecurlyWrapper.js/0 | {
"file_path": "overleaf/web/app/src/Features/Subscription/RecurlyWrapper.js",
"repo_id": "overleaf",
"token_count": 14263
} | 499 |
const Settings = require('@overleaf/settings')
const SessionManager = require('../Authentication/SessionManager')
const SystemMessageManager = require('./SystemMessageManager')
const ProjectController = {
getMessages(req, res, next) {
if (!SessionManager.isUserLoggedIn(req.session)) {
// gracefully handle requests from anonymous users
return res.json([])
}
SystemMessageManager.getMessages((err, messages) => {
if (err) {
next(err)
} else {
if (!Settings.siteIsOpen) {
// Override all messages with notice for admins when site is closed.
messages = [
{
content:
'SITE IS CLOSED TO PUBLIC. OPEN ONLY FOR SITE ADMINS. DO NOT EDIT PROJECTS.',
_id: 'protected', // prevents hiding message in frontend
},
]
}
res.json(messages || [])
}
})
},
}
module.exports = ProjectController
| overleaf/web/app/src/Features/SystemMessages/SystemMessageController.js/0 | {
"file_path": "overleaf/web/app/src/Features/SystemMessages/SystemMessageController.js",
"repo_id": "overleaf",
"token_count": 390
} | 500 |
/* eslint-disable
node/handle-callback-err,
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const crypto = require('crypto')
const V1Api = require('../V1/V1Api')
const Features = require('../../infrastructure/Features')
const Async = require('async')
const { promisify } = require('util')
// (From Overleaf `random_token.rb`)
// Letters (not numbers! see generate_token) used in tokens. They're all
// consonants, to avoid embarassing words (I can't think of any that use only
// a y), and lower case "l" is omitted, because in many fonts it is
// indistinguishable from an upper case "I" (and sometimes even the number 1).
const TOKEN_LOWERCASE_ALPHA = 'bcdfghjkmnpqrstvwxyz'
const TOKEN_NUMERICS = '123456789'
const TOKEN_ALPHANUMERICS =
TOKEN_LOWERCASE_ALPHA + TOKEN_LOWERCASE_ALPHA.toUpperCase() + TOKEN_NUMERICS
// This module mirrors the token generation in Overleaf (`random_token.rb`),
// for the purposes of implementing token-based project access, like the
// 'unlisted-projects' feature in Overleaf
const TokenGenerator = {
_randomString(length, alphabet) {
const result = crypto
.randomBytes(length)
.toJSON()
.data.map(b => alphabet[b % alphabet.length])
.join('')
return result
},
// Generate a 12-char token with only characters from TOKEN_LOWERCASE_ALPHA,
// suitable for use as a read-only token for a project
readOnlyToken() {
return TokenGenerator._randomString(12, TOKEN_LOWERCASE_ALPHA)
},
// Generate a longer token, with a numeric prefix,
// suitable for use as a read-and-write token for a project
readAndWriteToken() {
const numerics = TokenGenerator._randomString(10, TOKEN_NUMERICS)
const token = TokenGenerator._randomString(12, TOKEN_LOWERCASE_ALPHA)
const fullToken = `${numerics}${token}`
return { token: fullToken, numericPrefix: numerics }
},
generateReferralId() {
return TokenGenerator._randomString(16, TOKEN_ALPHANUMERICS)
},
generateUniqueReadOnlyToken(callback) {
if (callback == null) {
callback = function (err, token) {}
}
return Async.retry(
10,
function (cb) {
const token = TokenGenerator.readOnlyToken()
if (!Features.hasFeature('overleaf-integration')) {
return cb(null, token)
}
return V1Api.request(
{
url: `/api/v1/sharelatex/docs/read_token/${token}/exists`,
json: true,
},
function (err, response, body) {
if (err != null) {
return cb(err)
}
if (response.statusCode !== 200) {
return cb(
new Error(
`non-200 response from v1 read-token-exists api: ${response.statusCode}`
)
)
}
if (body.exists === true) {
return cb(new Error(`token already exists in v1: ${token}`))
} else {
return cb(null, token)
}
}
)
},
callback
)
},
}
TokenGenerator.promises = {
generateUniqueReadOnlyToken: promisify(
TokenGenerator.generateUniqueReadOnlyToken
),
}
module.exports = TokenGenerator
| overleaf/web/app/src/Features/TokenGenerator/TokenGenerator.js/0 | {
"file_path": "overleaf/web/app/src/Features/TokenGenerator/TokenGenerator.js",
"repo_id": "overleaf",
"token_count": 1411
} | 501 |
const { callbackify } = require('util')
const { db } = require('../../infrastructure/mongodb')
const metrics = require('@overleaf/metrics')
const logger = require('logger-sharelatex')
const moment = require('moment')
const settings = require('@overleaf/settings')
const { promisifyAll } = require('../../util/promises')
const {
promises: InstitutionsAPIPromises,
} = require('../Institutions/InstitutionsAPI')
const InstitutionsHelper = require('../Institutions/InstitutionsHelper')
const Errors = require('../Errors/Errors')
const Features = require('../../infrastructure/Features')
const { User } = require('../../models/User')
const { normalizeQuery, normalizeMultiQuery } = require('../Helpers/Mongo')
function _lastDayToReconfirm(emailData, institutionData) {
const globalReconfirmPeriod = settings.reconfirmNotificationDays
if (!globalReconfirmPeriod) return undefined
// only show notification for institutions with reconfirmation enabled
if (!institutionData || !institutionData.maxConfirmationMonths)
return undefined
if (!emailData.confirmedAt) return undefined
if (institutionData.ssoEnabled && !emailData.samlProviderId) {
// For SSO, only show notification for linked email
return false
}
// reconfirmedAt will not always be set, use confirmedAt as fallback
const lastConfirmed = emailData.reconfirmedAt || emailData.confirmedAt
return moment(lastConfirmed)
.add(institutionData.maxConfirmationMonths, 'months')
.toDate()
}
function _pastReconfirmDate(lastDayToReconfirm) {
if (!lastDayToReconfirm) return false
return moment(lastDayToReconfirm).isBefore()
}
function _emailInReconfirmNotificationPeriod(lastDayToReconfirm) {
const globalReconfirmPeriod = settings.reconfirmNotificationDays
if (!globalReconfirmPeriod || !lastDayToReconfirm) return false
const notificationStarts = moment(lastDayToReconfirm).subtract(
globalReconfirmPeriod,
'days'
)
return moment().isAfter(notificationStarts)
}
async function getUserFullEmails(userId) {
const user = await UserGetter.promises.getUser(userId, {
email: 1,
emails: 1,
samlIdentifiers: 1,
})
if (!user) {
throw new Error('User not Found')
}
if (!Features.hasFeature('affiliations')) {
return decorateFullEmails(user.email, user.emails, [], [])
}
const affiliationsData = await InstitutionsAPIPromises.getUserAffiliations(
userId
)
return decorateFullEmails(
user.email,
user.emails || [],
affiliationsData,
user.samlIdentifiers || []
)
}
async function getSsoUsersAtInstitution(institutionId, projection) {
if (!projection) {
throw new Error('missing projection')
}
return await User.find(
{
'samlIdentifiers.providerId': institutionId.toString(),
},
projection
).exec()
}
const UserGetter = {
getSsoUsersAtInstitution: callbackify(getSsoUsersAtInstitution),
getUser(query, projection, callback) {
if (arguments.length === 2) {
callback = projection
projection = {}
}
try {
query = normalizeQuery(query)
db.users.findOne(query, { projection }, callback)
} catch (err) {
callback(err)
}
},
getUserEmail(userId, callback) {
this.getUser(userId, { email: 1 }, (error, user) =>
callback(error, user && user.email)
)
},
getUserFullEmails: callbackify(getUserFullEmails),
getUserByMainEmail(email, projection, callback) {
email = email.trim()
if (arguments.length === 2) {
callback = projection
projection = {}
}
db.users.findOne({ email }, { projection }, callback)
},
getUserByAnyEmail(email, projection, callback) {
email = email.trim()
if (arguments.length === 2) {
callback = projection
projection = {}
}
// $exists: true MUST be set to use the partial index
const query = { emails: { $exists: true }, 'emails.email': email }
db.users.findOne(query, { projection }, (error, user) => {
if (error || user) {
return callback(error, user)
}
// While multiple emails are being rolled out, check for the main email as
// well
this.getUserByMainEmail(email, projection, callback)
})
},
getUsersByAnyConfirmedEmail(emails, projection, callback) {
if (arguments.length === 2) {
callback = projection
projection = {}
}
const query = {
'emails.email': { $in: emails }, // use the index on emails.email
emails: {
$exists: true,
$elemMatch: {
email: { $in: emails },
confirmedAt: { $exists: true },
},
},
}
db.users.find(query, { projection }).toArray(callback)
},
getUsersByV1Ids(v1Ids, projection, callback) {
if (arguments.length === 2) {
callback = projection
projection = {}
}
const query = { 'overleaf.id': { $in: v1Ids } }
db.users.find(query, { projection }).toArray(callback)
},
getUsersByHostname(hostname, projection, callback) {
const reversedHostname = hostname.trim().split('').reverse().join('')
const query = {
emails: { $exists: true },
'emails.reversedHostname': reversedHostname,
}
db.users.find(query, { projection }).toArray(callback)
},
getUsers(query, projection, callback) {
try {
query = normalizeMultiQuery(query)
db.users.find(query, { projection }).toArray(callback)
} catch (err) {
callback(err)
}
},
// check for duplicate email address. This is also enforced at the DB level
ensureUniqueEmailAddress(newEmail, callback) {
this.getUserByAnyEmail(newEmail, function (error, user) {
if (user) {
return callback(new Errors.EmailExistsError())
}
callback(error)
})
},
}
var decorateFullEmails = (
defaultEmail,
emailsData,
affiliationsData,
samlIdentifiers
) => {
emailsData.forEach(function (emailData) {
emailData.default = emailData.email === defaultEmail
const affiliation = affiliationsData.find(
aff => aff.email === emailData.email
)
if (affiliation) {
const {
institution,
inferred,
role,
department,
licence,
portal,
} = affiliation
const lastDayToReconfirm = _lastDayToReconfirm(emailData, institution)
const pastReconfirmDate = _pastReconfirmDate(lastDayToReconfirm)
const inReconfirmNotificationPeriod = _emailInReconfirmNotificationPeriod(
lastDayToReconfirm
)
emailData.affiliation = {
institution,
inferred,
inReconfirmNotificationPeriod,
lastDayToReconfirm,
pastReconfirmDate,
role,
department,
licence,
portal,
}
}
if (emailData.samlProviderId) {
emailData.samlIdentifier = samlIdentifiers.find(
samlIdentifier => samlIdentifier.providerId === emailData.samlProviderId
)
}
emailData.emailHasInstitutionLicence = InstitutionsHelper.emailHasLicence(
emailData
)
})
return emailsData
}
;[
'getUser',
'getUserEmail',
'getUserByMainEmail',
'getUserByAnyEmail',
'getUsers',
'ensureUniqueEmailAddress',
].map(method =>
metrics.timeAsyncMethod(UserGetter, method, 'mongo.UserGetter', logger)
)
UserGetter.promises = promisifyAll(UserGetter, {
without: ['getSsoUsersAtInstitution', 'getUserFullEmails'],
})
UserGetter.promises.getUserFullEmails = getUserFullEmails
UserGetter.promises.getSsoUsersAtInstitution = getSsoUsersAtInstitution
module.exports = UserGetter
| overleaf/web/app/src/Features/User/UserGetter.js/0 | {
"file_path": "overleaf/web/app/src/Features/User/UserGetter.js",
"repo_id": "overleaf",
"token_count": 2785
} | 502 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const UserMembershipMiddleware = require('./UserMembershipMiddleware')
const UserMembershipController = require('./UserMembershipController')
const SubscriptionGroupController = require('../Subscription/SubscriptionGroupController')
const TeamInvitesController = require('../Subscription/TeamInvitesController')
const RateLimiterMiddleware = require('../Security/RateLimiterMiddleware')
module.exports = {
apply(webRouter) {
// group members routes
webRouter.get(
'/manage/groups/:id/members',
UserMembershipMiddleware.requireGroupManagementAccess,
UserMembershipController.index
)
webRouter.post(
'/manage/groups/:id/invites',
UserMembershipMiddleware.requireGroupManagementAccess,
RateLimiterMiddleware.rateLimit({
endpointName: 'create-team-invite',
maxRequests: 200,
timeInterval: 60,
}),
TeamInvitesController.createInvite
)
webRouter.delete(
'/manage/groups/:id/user/:user_id',
UserMembershipMiddleware.requireGroupManagementAccess,
SubscriptionGroupController.removeUserFromGroup
)
webRouter.delete(
'/manage/groups/:id/invites/:email',
UserMembershipMiddleware.requireGroupManagementAccess,
TeamInvitesController.revokeInvite
)
webRouter.get(
'/manage/groups/:id/members/export',
UserMembershipMiddleware.requireGroupManagementAccess,
RateLimiterMiddleware.rateLimit({
endpointName: 'export-team-csv',
maxRequests: 30,
timeInterval: 60,
}),
UserMembershipController.exportCsv
)
// group managers routes
webRouter.get(
'/manage/groups/:id/managers',
UserMembershipMiddleware.requireGroupManagersManagementAccess,
UserMembershipController.index
)
webRouter.post(
'/manage/groups/:id/managers',
UserMembershipMiddleware.requireGroupManagersManagementAccess,
UserMembershipController.add
)
webRouter.delete(
'/manage/groups/:id/managers/:userId',
UserMembershipMiddleware.requireGroupManagersManagementAccess,
UserMembershipController.remove
)
// institution members routes
webRouter.get(
'/manage/institutions/:id/managers',
UserMembershipMiddleware.requireInstitutionManagementAccess,
UserMembershipController.index
)
webRouter.post(
'/manage/institutions/:id/managers',
UserMembershipMiddleware.requireInstitutionManagementAccess,
UserMembershipController.add
)
webRouter.delete(
'/manage/institutions/:id/managers/:userId',
UserMembershipMiddleware.requireInstitutionManagementAccess,
UserMembershipController.remove
)
// publisher members routes
webRouter.get(
'/manage/publishers/:id/managers',
UserMembershipMiddleware.requirePublisherManagementAccess,
UserMembershipController.index
)
webRouter.post(
'/manage/publishers/:id/managers',
UserMembershipMiddleware.requirePublisherManagementAccess,
UserMembershipController.add
)
webRouter.delete(
'/manage/publishers/:id/managers/:userId',
UserMembershipMiddleware.requirePublisherManagementAccess,
UserMembershipController.remove
)
// publisher creation routes
webRouter.get(
'/entities/publisher/create/:id',
UserMembershipMiddleware.requirePublisherCreationAccess,
UserMembershipController.new
)
webRouter.post(
'/entities/publisher/create/:id',
UserMembershipMiddleware.requirePublisherCreationAccess,
UserMembershipController.create
)
// institution creation routes
webRouter.get(
'/entities/institution/create/:id',
UserMembershipMiddleware.requireInstitutionCreationAccess,
UserMembershipController.new
)
webRouter.post(
'/entities/institution/create/:id',
UserMembershipMiddleware.requireInstitutionCreationAccess,
UserMembershipController.create
)
},
}
| overleaf/web/app/src/Features/UserMembership/UserMembershipRouter.js/0 | {
"file_path": "overleaf/web/app/src/Features/UserMembership/UserMembershipRouter.js",
"repo_id": "overleaf",
"token_count": 1553
} | 503 |
const Metrics = require('@overleaf/metrics')
exports.analyticsQueue = new Metrics.prom.Counter({
name: 'analytics_queue',
help: 'Number of events sent to the analytics queue',
labelNames: ['status', 'event_type'],
})
| overleaf/web/app/src/infrastructure/Metrics.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/Metrics.js",
"repo_id": "overleaf",
"token_count": 71
} | 504 |
const { Joi: CelebrateJoi, celebrate, errors } = require('celebrate')
const { ObjectId } = require('mongodb')
const objectIdValidator = {
name: 'objectId',
language: {
invalid: 'needs to be a valid ObjectId',
},
pre(value, state, options) {
if (!ObjectId.isValid(value)) {
return this.createError('objectId.invalid', { value }, state, options)
}
if (options.convert) {
return new ObjectId(value)
}
return value
},
}
const Joi = CelebrateJoi.extend(objectIdValidator)
const errorMiddleware = errors()
module.exports = { Joi, validate, errorMiddleware }
/**
* Validation middleware
*/
function validate(schema) {
return celebrate(schema, { allowUnknown: true })
}
| overleaf/web/app/src/infrastructure/Validation.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/Validation.js",
"repo_id": "overleaf",
"token_count": 250
} | 505 |
const mongoose = require('../infrastructure/Mongoose')
const { Schema } = mongoose
const ProjectHistoryFailureSchema = new Schema(
{
project_id: Schema.Types.ObjectId,
ts: Date,
queueSize: Number,
error: String,
stack: String,
attempts: Number,
history: Schema.Types.Mixed,
resyncStartedAt: Date,
resyncAttempts: Number,
requestCount: Number,
},
{ collection: 'projectHistoryFailures' }
)
exports.ProjectHistoryFailure = mongoose.model(
'ProjectHistoryFailure',
ProjectHistoryFailureSchema
)
| overleaf/web/app/src/models/ProjectHistoryFailure.js/0 | {
"file_path": "overleaf/web/app/src/models/ProjectHistoryFailure.js",
"repo_id": "overleaf",
"token_count": 193
} | 506 |
@book{adams1995hitchhiker,
title={The Hitchhiker's Guide to the Galaxy},
author={Adams, D.},
isbn={9781417642595},
url={http://books.google.com/books?id=W-xMPgAACAAJ},
year={1995},
publisher={San Val}
}
| overleaf/web/app/templates/project_files/references.bib/0 | {
"file_path": "overleaf/web/app/templates/project_files/references.bib",
"repo_id": "overleaf",
"token_count": 88
} | 507 |
extends ../layout/layout-no-js
block vars
- metadata = { title: 'Something went wrong', viewport: true }
block body
body.full-height
main.content.content-alt.full-height#main-content
.container.full-height
.error-container.full-height
.error-details
p.error-status Something went wrong, sorry.
p.error-description Our staff are probably looking into this, but if it continues, please check our status page at
|
|
a(href="http://" + settings.statusPageUrl) #{settings.statusPageUrl}
|
| or contact us at
|
a(href="mailto:" + settings.adminEmail) #{settings.adminEmail}
| .
a.error-btn(href="/") Home
| overleaf/web/app/views/general/500.pug/0 | {
"file_path": "overleaf/web/app/views/general/500.pug",
"repo_id": "overleaf",
"token_count": 280
} | 508 |
aside.editor-sidebar.full-size(
ng-show="ui.view != 'history'"
vertical-resizable-panes="outline-resizer"
vertical-resizable-panes-toggled-externally-on="outline-toggled"
vertical-resizable-panes-min-size="32"
vertical-resizable-panes-max-size="75%"
vertical-resizable-panes-resize-on="left-pane-resize-all"
)
.file-tree(
ng-controller="ReactFileTreeController"
vertical-resizable-top
)
file-tree-root(
project-id="projectId"
root-folder="rootFolder"
root-doc-id="rootDocId"
has-write-permissions="hasWritePermissions"
on-select="onSelect"
on-init="onInit"
is-connected="isConnected"
user-has-feature="userHasFeature"
ref-providers="refProviders"
reindex-references="reindexReferences"
set-ref-provider-enabled="setRefProviderEnabled"
set-started-free-trial="setStartedFreeTrial"
)
.outline-container(
vertical-resizable-bottom
ng-controller="OutlineController"
)
outline-pane(
is-tex-file="isTexFile"
outline="outline"
project-id="project_id"
jump-to-line="jumpToLine"
on-toggle="onToggle"
event-tracking="eventTracking"
highlighted-line="highlightedLine"
)
| overleaf/web/app/views/project/editor/file-tree-react.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/file-tree-react.pug",
"repo_id": "overleaf",
"token_count": 476
} | 509 |
#editor(
ace-editor="editor",
ng-if="!editor.showRichText",
ng-show="!!editor.sharejs_doc && !editor.opening && multiSelectedCount === 0 && !editor.error_state",
theme="settings.editorTheme",
keybindings="settings.mode",
font-size="settings.fontSize",
auto-complete="settings.autoComplete",
auto-pair-delimiters="settings.autoPairDelimiters",
spell-check="!anonymous",
spell-check-language="project.spellCheckLanguage"
highlights="onlineUserCursorHighlights[editor.open_doc_id]"
show-print-margin="false",
sharejs-doc="editor.sharejs_doc",
last-updated="editor.last_updated",
cursor-position="editor.cursorPosition",
goto-line="editor.gotoLine",
resize-on="layout:main:resize,layout:pdf:resize,layout:review:resize,review-panel:toggle,layout:flat-screen:toggle",
annotations="pdf.logEntryAnnotations[editor.open_doc_id]",
read-only="!permissions.write",
file-name="editor.open_doc_name",
on-ctrl-enter="recompileViaKey",
on-save="recompileViaKey",
on-ctrl-j="toggleReviewPanel",
on-ctrl-shift-c="addNewCommentFromKbdShortcut",
on-ctrl-shift-a="toggleTrackChangesFromKbdShortcut",
syntax-validation="settings.syntaxValidation",
review-panel="reviewPanel",
events-bridge="reviewPanelEventsBridge"
track-changes= "editor.trackChanges",
doc-id="editor.open_doc_id"
renderer-data="reviewPanel.rendererData"
font-family="settings.fontFamily"
line-height="settings.lineHeight"
)
| overleaf/web/app/views/project/editor/source-editor.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/source-editor.pug",
"repo_id": "overleaf",
"token_count": 490
} | 510 |
//- Buy Buttons
mixin btn_buy_collaborator(location)
a.btn.btn-primary(
ng-href="/user/subscription/new?planCode={{ getCollaboratorPlanCode() }}¤cy={{currencyCode}}&itm_campaign=plans&itm_content=" + location,
ng-click="signUpNowClicked('collaborator','" + location + "')"
)
span(ng-show="ui.view != 'annual'") #{translate("start_free_trial")}
span(ng-show="ui.view == 'annual'") #{translate("buy_now")}
mixin btn_buy_personal(location)
a.btn.btn-primary(
ng-href="/user/subscription/new?planCode={{ getPersonalPlanCode() }}¤cy={{currencyCode}}&itm_campaign=plans&itm_content=" + location,
ng-click="signUpNowClicked('personal','" + location + "')"
)
span(ng-show="ui.view != 'annual'") #{translate("start_free_trial")}
span(ng-show="ui.view == 'annual'") #{translate("buy_now")}
mixin btn_buy_free(location)
a.btn.btn-primary(
href="/register"
style=(getLoggedInUserId() === null ? "" : "visibility: hidden")
ng-click="signUpNowClicked('free','" + location + "')"
)
span.text-capitalize #{translate('get_started_now')}
mixin btn_buy_professional(location)
a.btn.btn-primary(
ng-href="/user/subscription/new?planCode=professional{{ ui.view == 'annual' && '-annual' || planQueryString}}¤cy={{currencyCode}}&itm_campaign=plans&itm_content=" + location,
ng-click="signUpNowClicked('professional','" + location + "')"
)
span(ng-show="ui.view != 'annual'") #{translate("start_free_trial")}
span(ng-show="ui.view == 'annual'") #{translate("buy_now")}
mixin btn_buy_student(location, plan)
if plan == 'annual'
a.btn.btn-primary(
ng-href="/user/subscription/new?planCode=student-annual¤cy={{currencyCode}}&itm_campaign=plans&itm_content=" + location,
ng-click="signUpNowClicked('student-annual','" + location + "')"
) #{translate("buy_now")}
else
//- planQueryString will contain _free_trial_7_days
a.btn.btn-primary(
ng-href="/user/subscription/new?planCode=student{{planQueryString}}¤cy={{currencyCode}}&itm_campaign=plans&itm_content=" + location,
ng-click="signUpNowClicked('student-monthly','" + location + "')"
) #{translate("start_free_trial")}
//- Cards
mixin card_student_annual(location)
.best-value
strong #{translate('best_value')}
.card-header
h2 #{translate("student")} (#{translate("annual")})
h5.tagline #{translate('tagline_student_annual')}
.circle
span
+price_student_annual
+features_student(location, 'annual')
mixin card_student_monthly(location)
.card-header
h2 #{translate("student")}
h5.tagline #{translate('tagline_student_monthly')}
.circle
span
+price_student_monthly
+features_student(location, 'monthly')
//- Features Lists, used within cards
mixin features_collaborator(location)
ul.list-unstyled
li
strong #{translate("collabs_per_proj", {collabcount:10})}
+features_premium
li
br
+btn_buy_collaborator(location)
mixin features_free(location)
ul.list-unstyled
li #{translate("one_collaborator")}
li(class="hidden-xs hidden-sm")
li(class="hidden-xs hidden-sm")
li(class="hidden-xs hidden-sm")
li(class="hidden-xs hidden-sm")
li(class="hidden-xs hidden-sm")
li(class="hidden-xs hidden-sm")
li
br
+btn_buy_free(location)
mixin features_personal(location)
ul.list-unstyled
li #{translate("one_collaborator")}
li
li
strong #{translate('premium_features')}
li #{translate('sync_dropbox_github')}
li #{translate('full_doc_history')}
li + #{translate('more').toLowerCase()}
li(class="hidden-xs hidden-sm")
li
br
+btn_buy_personal(location)
mixin features_premium
li
li
strong #{translate('all_premium_features')}
li #{translate('sync_dropbox_github')}
li #{translate('full_doc_history')}
li #{translate('track_changes')}
li + #{translate('more').toLowerCase()}
mixin features_professional(location)
ul.list-unstyled
li
strong #{translate("unlimited_collabs")}
+features_premium
li
br
+btn_buy_professional(location)
mixin features_student(location, plan)
ul.list-unstyled
li
strong #{translate("collabs_per_proj", {collabcount:6})}
+features_premium
li
br
+btn_buy_student(location, plan)
//- Prices
mixin price_personal
span(ng-if="ui.view == 'monthly'")
| {{plans[currencyCode]['personal']['monthly']}}
span.small /mo
span(ng-if="ui.view == 'annual'")
| {{plans[currencyCode]['personal']['annual']}}
span.small /yr
mixin price_collaborator
span(ng-if="ui.view == 'monthly'")
| {{plans[currencyCode]['collaborator']['monthly']}}
span.small /mo
span(ng-if="ui.view == 'annual'")
| {{plans[currencyCode]['collaborator']['annual']}}
span.small /yr
mixin price_professional
span(ng-if="ui.view == 'monthly'")
| {{plans[currencyCode]['professional']['monthly']}}
span.small /mo
span(ng-if="ui.view == 'annual'")
| {{plans[currencyCode]['professional']['annual']}}
span.small /yr
mixin price_student_annual
| {{plans[currencyCode]['student']['annual']}}
span.small /yr
mixin price_student_monthly
| {{plans[currencyCode]['student']['monthly']}}
span.small /mo
//- UI Control
mixin currency_dropdown
.dropdown.currency-dropdown(dropdown)
a.btn.btn-default.dropdown-toggle(
href="#",
data-toggle="dropdown",
dropdown-toggle
)
| {{currencyCode}} ({{plans[currencyCode]['symbol']}})
span.caret
ul.dropdown-menu.dropdown-menu-right.text-right(role="menu")
li(ng-repeat="(currency, value) in plans")
a(
href="#",
ng-click="changeCurreny($event, currency)"
) {{currency}} ({{value['symbol']}})
mixin plan_switch(location)
ul.nav.nav-pills
li(ng-class="{'active': ui.view == 'monthly'}")
a.btn.btn-default-outline(
href="#"
ng-click="switchToMonthly($event,'" + location + "')"
) #{translate("monthly")}
li(ng-class="{'active': ui.view == 'annual'}")
a.btn.btn-default-outline(
href="#"
ng-click="switchToAnnual($event,'" + location + "')"
) #{translate("annual")}
li(ng-class="{'active': ui.view == 'student'}")
a.btn.btn-default-outline(
href="#"
ng-click="switchToStudent($event,'" + location + "')"
) #{translate("special_price_student")}
mixin allCardsAndControls(controlsRowSpaced, listLocation)
- var location = listLocation ? 'card_' + listLocation : 'card'
.row.top-switch(class=controlsRowSpaced ? "row-spaced" : "")
.col-md-6.col-md-offset-3
+plan_switch('card')
.col-md-2.text-right
+currency_dropdown
.row
.col-md-10.col-md-offset-1
.row
.card-group.text-centered(ng-if="ui.view == 'monthly' || ui.view == 'annual'")
.col-md-4
.card.card-first
.card-header
h2 #{translate("personal")}
h5.tagline #{translate("tagline_personal")}
.circle
+price_personal
+features_personal(location)
.col-md-4
.card.card-highlighted
.best-value
strong #{translate('best_value')}
.card-header
h2 #{translate("collaborator")}
h5.tagline #{translate("tagline_collaborator")}
.circle
+price_collaborator
+features_collaborator(location)
.col-md-4
.card.card-last
.card-header
h2 #{translate("professional")}
h5.tagline #{translate("tagline_professional")}
.circle
+price_professional
+features_professional(location)
.card-group.text-centered(ng-if="ui.view == 'student'")
.col-md-4
.card.card-first
.card-header
h2 #{translate("free")}
h5.tagline #{translate("tagline_free")}
.circle #{translate("free")}
+features_free(location)
.col-md-4
.card.card-highlighted
+card_student_annual(location)
.col-md-4
.card.card-last
+card_student_monthly(location)
| overleaf/web/app/views/subscriptions/_plans_page_mixins.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/_plans_page_mixins.pug",
"repo_id": "overleaf",
"token_count": 3327
} | 511 |
mixin teamName(subscription)
if (subscription.teamName && subscription.teamName != '')
strong(ng-non-bindable)= subscription.teamName
else if (subscription.admin_id._id == user._id)
| a group account
else
| the group account owned by
|
strong= subscription.admin_id.email
| overleaf/web/app/views/subscriptions/dashboard/_team_name_mixin.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/dashboard/_team_name_mixin.pug",
"repo_id": "overleaf",
"token_count": 95
} | 512 |
extends ../layout
block content
main.content.content-alt#main-content
.container
.row
.registration_message
if sharedProjectData.user_first_name !== undefined
h1(ng-non-bindable) #{translate("user_wants_you_to_see_project", {username:sharedProjectData.user_first_name, projectname:""})}
em(ng-non-bindable) #{sharedProjectData.project_name}
div
| #{translate("join_sl_to_view_project")}.
div
| #{translate("if_you_are_registered")},
a(href="/login") #{translate("login_here")}
else if newTemplateData.templateName !== undefined
h1(ng-non-bindable) #{translate("register_to_edit_template", {templateName:newTemplateData.templateName})}
div #{translate("already_have_sl_account")}
a(href="/login") #{translate("login_here")}
.row
.col-md-8.col-md-offset-2.col-lg-6.col-lg-offset-3
.card
.page-header
h1 #{translate("register")}
p
| Please contact
|
strong(ng-non-bindable) #{settings.adminEmail}
|
| to create an account.
| overleaf/web/app/views/user/register.pug/0 | {
"file_path": "overleaf/web/app/views/user/register.pug",
"repo_id": "overleaf",
"token_count": 492
} | 513 |
#! /usr/bin/env node
const acorn = require('acorn')
const acornWalk = require('acorn-walk')
const fs = require('fs')
const _ = require('lodash')
const glob = require('glob')
print = console.log
const Methods = new Set([
'get',
'head',
'post',
'put',
'delete',
'connect',
'options',
'trace',
'patch'
])
const isMethod = str => {
return Methods.has(str)
}
// Check if the expression is a call on a router, return data about it, or null
const routerCall = callExpression => {
const callee = callExpression.callee
const property = callee.property
const args = callExpression.arguments
if (!callee.object || !callee.object.name) {
return false
}
const routerName = callee.object.name
if ( // Match known names for the Express routers: app, webRouter, whateverRouter, etc...
isMethod(property.name) &&
(routerName === 'app' || routerName.match('^.*[rR]outer$'))
) {
return {
routerName: routerName,
method: property.name,
args: args
}
} else {
return null
}
}
const formatMethodCall = expression => {
if (!expression.object || !expression.property) {
return '????'
}
return `${expression.object.name}.${expression.property.name}`
}
const parseAndPrintRoutesSync = path => {
const content = fs.readFileSync(path)
// Walk the AST (Abstract Syntax Tree)
acornWalk.simple(acorn.parse(content), {
// We only care about call expression ( like `a.b()` )
CallExpression(node) {
const call = routerCall(node)
if (call) {
const firstArg = _.first(call.args)
const lastArg = _.last(call.args)
try {
print(
` ${formatRouterName(call.routerName)}\t .${call.method} \t: ${
firstArg.value
} => ${formatMethodCall(lastArg)}`
)
} catch (e) {
print('>> Error')
print(e)
print(JSON.stringify(call))
process.exit(1)
}
}
}
})
}
const routerNameMapping = {
'privateApiRouter': 'privateApi',
'publicApiRouter': 'publicApi'
}
const formatRouterName = (name) => {
return routerNameMapping[name] || name
}
const main = () => {
// Take an optional filter to apply to file names
const filter = process.argv[2] || null
if (filter && (filter === '--help' || filter == 'help')) {
print('')
print(' Usage: bin/routes [filter]')
print(' Examples:')
print(' bin/routes')
print(' bin/routes GitBridge')
print('')
process.exit(0)
}
// Find all routers
glob('*[rR]outer.js', { matchBase: true }, (err, files) => {
for (file of files) {
if (file.match('^node_modules.*$') || file.match('.*/public/.*')) {
continue
}
// Restrict to the filter (if filter is present)
if (filter && !file.match(`.*${filter}.*`)) {
continue
}
print(`[${file}]`)
try {
parseAndPrintRoutesSync(file)
} catch (_e) {
print('>> Error parsing file')
continue
}
}
process.exit(0)
})
}
if (require.main === module) {
main()
}
| overleaf/web/bin/routes/0 | {
"file_path": "overleaf/web/bin/routes",
"repo_id": "overleaf",
"token_count": 1278
} | 514 |
/* eslint-disable
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../base'
App.directive('stopPropagation', $http => ({
restrict: 'A',
link(scope, element, attrs) {
return element.bind(attrs.stopPropagation, e => e.stopPropagation())
},
}))
export default App.directive('preventDefault', $http => ({
restrict: 'A',
link(scope, element, attrs) {
return element.bind(attrs.preventDefault, e => e.preventDefault())
},
}))
| overleaf/web/frontend/js/directives/stopPropagation.js/0 | {
"file_path": "overleaf/web/frontend/js/directives/stopPropagation.js",
"repo_id": "overleaf",
"token_count": 240
} | 515 |
import Icon from '../../../shared/components/icon'
import { useTranslation } from 'react-i18next'
function BackToProjectsButton() {
const { t } = useTranslation()
return (
<a className="toolbar-header-back-projects" href="/project">
<Icon
type="fw"
modifier="level-up"
accessibilityLabel={t('back_to_your_projects')}
/>
</a>
)
}
export default BackToProjectsButton
| overleaf/web/frontend/js/features/editor-navigation-toolbar/components/back-to-projects-button.js/0 | {
"file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/components/back-to-projects-button.js",
"repo_id": "overleaf",
"token_count": 159
} | 516 |
import PropTypes from 'prop-types'
import { useTranslation, Trans } from 'react-i18next'
import { FetchError } from '../../../../infrastructure/fetch-json'
import RedirectToLogin from './redirect-to-login'
import {
BlockedFilenameError,
DuplicateFilenameError,
InvalidFilenameError,
} from '../../errors'
import DangerMessage from './danger-message'
export default function ErrorMessage({ error }) {
const { t } = useTranslation()
const fileNameLimit = 150
// the error is a string
// TODO: translate? always? is this a key or a message?
if (typeof error === 'string') {
switch (error) {
case 'name-exists':
return <DangerMessage>{t('file_already_exists')}</DangerMessage>
case 'too-many-files':
return <DangerMessage>{t('project_has_too_many_files')}</DangerMessage>
case 'remote-service-error':
return <DangerMessage>{t('remote_service_error')}</DangerMessage>
case 'invalid_filename':
return (
<DangerMessage>
<Trans
i18nKey="invalid_filename"
values={{
nameLimit: fileNameLimit,
}}
/>
</DangerMessage>
)
case 'rate-limit-hit':
return (
<DangerMessage>
{t('too_many_files_uploaded_throttled_short_period')}
</DangerMessage>
)
case 'not-logged-in':
return (
<DangerMessage>
<RedirectToLogin />
</DangerMessage>
)
case 'linked-project-compile-error':
return (
<DangerMessage>
{t('generic_linked_file_compile_error')}
</DangerMessage>
)
default:
// TODO: convert error.response.data to an error key and try again?
// return error
return (
<DangerMessage>{t('generic_something_went_wrong')}</DangerMessage>
)
}
}
// the error is an object
// TODO: error.name?
switch (error.constructor) {
case FetchError: {
const message = error.data?.message
if (message) {
return <DangerMessage>{message.text || message}</DangerMessage>
}
// TODO: translations
switch (error.response?.status) {
case 400:
return <DangerMessage>{t('invalid_request')}</DangerMessage>
case 403:
return <DangerMessage>{t('session_error')}</DangerMessage>
case 429:
return <DangerMessage>{t('too_many_attempts')}</DangerMessage>
default:
return (
<DangerMessage>{t('something_went_wrong_server')}</DangerMessage>
)
}
}
// these are handled by the filename input component
case DuplicateFilenameError:
case InvalidFilenameError:
case BlockedFilenameError:
return null
// a generic error message
default:
// return error.message
return <DangerMessage>{t('generic_something_went_wrong')}</DangerMessage>
}
}
ErrorMessage.propTypes = {
error: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
}
| overleaf/web/frontend/js/features/file-tree/components/file-tree-create/error-message.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-create/error-message.js",
"repo_id": "overleaf",
"token_count": 1330
} | 517 |
import { useTranslation } from 'react-i18next'
import { MenuItem } from 'react-bootstrap'
import { useFileTreeActionable } from '../../contexts/file-tree-actionable'
function FileTreeItemMenuItems() {
const { t } = useTranslation()
const {
canRename,
canDelete,
canCreate,
startRenaming,
startDeleting,
startCreatingFolder,
startCreatingDocOrFile,
startUploadingDocOrFile,
} = useFileTreeActionable()
return (
<>
{canRename ? (
<MenuItem onClick={startRenaming}>{t('rename')}</MenuItem>
) : null}
{canDelete ? (
<MenuItem onClick={startDeleting}>{t('delete')}</MenuItem>
) : null}
{canCreate ? (
<>
<MenuItem divider />
<MenuItem onClick={startCreatingDocOrFile}>{t('new_file')}</MenuItem>
<MenuItem onClick={startCreatingFolder}>{t('new_folder')}</MenuItem>
<MenuItem onClick={startUploadingDocOrFile}>{t('upload')}</MenuItem>
</>
) : null}
</>
)
}
export default FileTreeItemMenuItems
| overleaf/web/frontend/js/features/file-tree/components/file-tree-item/file-tree-item-menu-items.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-item/file-tree-item-menu-items.js",
"repo_id": "overleaf",
"token_count": 445
} | 518 |
import App from '../../../base'
import { react2angular } from 'react2angular'
import { cloneDeep } from 'lodash'
import FileTreeRoot from '../components/file-tree-root'
import { rootContext } from '../../../shared/context/root-context'
App.controller('ReactFileTreeController', function (
$scope,
$timeout,
ide
// eventTracking
) {
$scope.projectId = ide.project_id
$scope.rootFolder = null
$scope.rootDocId = null
$scope.hasWritePermissions = false
$scope.isConnected = true
$scope.$on('project:joined', () => {
$scope.rootFolder = $scope.project.rootFolder
$scope.rootDocId = $scope.project.rootDoc_id
$scope.$emit('file-tree:initialized')
})
$scope.$watch('permissions.write', hasWritePermissions => {
$scope.hasWritePermissions = hasWritePermissions
})
$scope.$watch('editor.open_doc_id', openDocId => {
window.dispatchEvent(
new CustomEvent('editor.openDoc', { detail: openDocId })
)
})
// Set isConnected to true if:
// - connection state is 'ready', OR
// - connection state is 'waitingCountdown' and reconnection_countdown is null
// The added complexity is needed because in Firefox on page reload the
// connection state goes into 'waitingCountdown' before being hidden and we
// don't want to show a disconnect UI.
function updateIsConnected() {
const isReady = $scope.connection.state === 'ready'
const willStartCountdown =
$scope.connection.state === 'waitingCountdown' &&
$scope.connection.reconnection_countdown === null
$scope.isConnected = isReady || willStartCountdown
}
$scope.$watch('connection.state', updateIsConnected)
$scope.$watch('connection.reconnection_countdown', updateIsConnected)
$scope.onInit = () => {
// HACK: resize the vertical pane on init after a 0ms timeout. We do not
// understand why this is necessary but without this the resized handle is
// stuck at the bottom. The vertical resize will soon be migrated to React
// so we accept to live with this hack for now.
$timeout(() => {
$scope.$emit('left-pane-resize-all')
})
}
$scope.onSelect = selectedEntities => {
if (selectedEntities.length === 1) {
const selectedEntity = selectedEntities[0]
const type =
selectedEntity.type === 'fileRef' ? 'file' : selectedEntity.type
$scope.$emit('entity:selected', {
...selectedEntity.entity,
id: selectedEntity.entity._id,
type,
})
// in the react implementation there is no such concept as "1
// multi-selected entity" so here we pass a count of 0
$scope.$emit('entities:multiSelected', { count: 0 })
} else if (selectedEntities.length > 1) {
$scope.$emit('entities:multiSelected', {
count: selectedEntities.length,
})
} else {
$scope.$emit('entity:no-selection')
}
}
$scope.userHasFeature = feature => ide.$scope.user.features[feature]
$scope.$watch('permissions.write', hasWritePermissions => {
$scope.hasWritePermissions = hasWritePermissions
})
$scope.refProviders = ide.$scope.user.refProviders || {}
ide.$scope.$watch(
'user.refProviders',
refProviders => {
$scope.refProviders = cloneDeep(refProviders)
},
true
)
$scope.setRefProviderEnabled = provider => {
ide.$scope.$applyAsync(() => {
ide.$scope.user.refProviders[provider] = true
})
}
$scope.setStartedFreeTrial = started => {
$scope.$applyAsync(() => {
$scope.startedFreeTrial = started
})
}
$scope.reindexReferences = () => {
ide.$scope.$emit('references:should-reindex', {})
}
})
App.component(
'fileTreeRoot',
react2angular(
rootContext.use(FileTreeRoot),
Object.keys(FileTreeRoot.propTypes)
)
)
| overleaf/web/frontend/js/features/file-tree/controllers/file-tree-controller.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/controllers/file-tree-controller.js",
"repo_id": "overleaf",
"token_count": 1312
} | 519 |
import { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import { useProjectContext } from '../../../shared/context/project-context'
const MAX_FILE_SIZE = 2 * 1024 * 1024
export default function FileViewText({ file, onLoad, onError }) {
const { _id: projectId } = useProjectContext({
_id: PropTypes.string.isRequired,
})
const [textPreview, setTextPreview] = useState('')
const [shouldShowDots, setShouldShowDots] = useState(false)
const [inFlight, setInFlight] = useState(false)
useEffect(() => {
if (inFlight) {
return
}
let path = `/project/${projectId}/file/${file.id}`
fetch(path, { method: 'HEAD' })
.then(response => {
if (!response.ok) throw new Error('HTTP Error Code: ' + response.status)
return response.headers.get('Content-Length')
})
.then(fileSize => {
let truncated = false
let maxSize = null
if (fileSize > MAX_FILE_SIZE) {
truncated = true
maxSize = MAX_FILE_SIZE
}
if (maxSize != null) {
path += `?range=0-${maxSize}`
}
return fetch(path).then(response => {
return response.text().then(text => {
if (truncated) {
text = text.replace(/\n.*$/, '')
}
setTextPreview(text)
onLoad()
setShouldShowDots(truncated)
})
})
})
.catch(err => {
console.error(err)
onError()
})
.finally(() => {
setInFlight(false)
})
}, [projectId, file.id, onError, onLoad, inFlight])
return (
<div>
{textPreview && (
<div className="text-preview">
<div className="scroll-container">
<p>{textPreview}</p>
{shouldShowDots && <p>...</p>}
</div>
</div>
)}
</div>
)
}
FileViewText.propTypes = {
file: PropTypes.shape({ id: PropTypes.string }).isRequired,
onLoad: PropTypes.func.isRequired,
onError: PropTypes.func.isRequired,
}
| overleaf/web/frontend/js/features/file-view/components/file-view-text.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-view/components/file-view-text.js",
"repo_id": "overleaf",
"token_count": 933
} | 520 |
import { useState, useRef } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { useTranslation } from 'react-i18next'
import { OverlayTrigger, Tooltip } from 'react-bootstrap'
import useExpandCollapse from '../../../shared/hooks/use-expand-collapse'
import useResizeObserver from '../../../shared/hooks/use-resize-observer'
import Icon from '../../../shared/components/icon'
function PreviewLogsPaneEntry({
headerTitle,
headerIcon,
rawContent,
logType,
formattedContent,
extraInfoURL,
level,
sourceLocation,
showSourceLocationLink = true,
showCloseButton = false,
entryAriaLabel = null,
customClass,
onSourceLocationClick,
onClose,
}) {
const logEntryClasses = classNames('log-entry', customClass)
function handleLogEntryLinkClick(e) {
e.preventDefault()
onSourceLocationClick(sourceLocation)
}
return (
<div className={logEntryClasses} aria-label={entryAriaLabel}>
<PreviewLogEntryHeader
level={level}
sourceLocation={sourceLocation}
headerTitle={headerTitle}
headerIcon={headerIcon}
logType={logType}
showSourceLocationLink={showSourceLocationLink}
onSourceLocationClick={handleLogEntryLinkClick}
showCloseButton={showCloseButton}
onClose={onClose}
/>
{rawContent || formattedContent ? (
<PreviewLogEntryContent
rawContent={rawContent}
formattedContent={formattedContent}
extraInfoURL={extraInfoURL}
/>
) : null}
</div>
)
}
function PreviewLogEntryHeader({
sourceLocation,
level,
headerTitle,
headerIcon,
logType,
showSourceLocationLink = true,
showCloseButton = false,
onSourceLocationClick,
onClose,
}) {
const { t } = useTranslation()
const logLocationSpanRef = useRef()
const [locationSpanOverflown, setLocationSpanOverflown] = useState(false)
useResizeObserver(
logLocationSpanRef,
locationSpanOverflown,
checkLocationSpanOverflow
)
const file = sourceLocation ? sourceLocation.file : null
const line = sourceLocation ? sourceLocation.line : null
const logEntryHeaderClasses = classNames('log-entry-header', {
'log-entry-header-error': level === 'error',
'log-entry-header-warning': level === 'warning',
'log-entry-header-typesetting': level === 'typesetting',
'log-entry-header-raw': level === 'raw',
'log-entry-header-success': level === 'success',
})
const logEntryLocationBtnClasses = classNames('log-entry-header-link', {
'log-entry-header-link-error': level === 'error',
'log-entry-header-link-warning': level === 'warning',
'log-entry-header-link-typesetting': level === 'typesetting',
'log-entry-header-link-raw': level === 'raw',
'log-entry-header-link-success': level === 'success',
})
const headerLogLocationTitle = t('navigate_log_source', {
location: file + (line ? `, ${line}` : ''),
})
function checkLocationSpanOverflow(observedElement) {
const spanEl = observedElement.target
const isOverflowing = spanEl.scrollWidth > spanEl.clientWidth
setLocationSpanOverflown(isOverflowing)
}
const locationLinkText =
showSourceLocationLink && file ? `${file}${line ? `, ${line}` : ''}` : null
// Because we want an ellipsis on the left-hand side (e.g. "...longfilename.tex"), the
// `log-entry-header-link-location` class has text laid out from right-to-left using the CSS
// rule `direction: rtl;`.
// This works most of the times, except when the first character of the filename is considered
// a punctuation mark, like `/` (e.g. `/foo/bar/baz.sty`). In this case, because of
// right-to-left writing rules, the punctuation mark is moved to the right-side of the string,
// resulting in `...bar/baz.sty/` instead of `...bar/baz.sty`.
// To avoid this edge-case, we wrap the `logLocationLinkText` in two directional formatting
// characters:
// * \u202A LEFT-TO-RIGHT EMBEDDING Treat the following text as embedded left-to-right.
// * \u202C POP DIRECTIONAL FORMATTING End the scope of the last LRE, RLE, RLO, or LRO.
// This essentially tells the browser that, althought the text is laid out from right-to-left,
// the wrapped portion of text should follow left-to-right writing rules.
const locationLink = locationLinkText ? (
<button
className={logEntryLocationBtnClasses}
type="button"
aria-label={headerLogLocationTitle}
onClick={onSourceLocationClick}
>
<Icon type="chain" />
<span ref={logLocationSpanRef} className="log-entry-header-link-location">
{`\u202A${locationLinkText}\u202C`}
</span>
</button>
) : null
const locationTooltip =
locationSpanOverflown && locationLinkText ? (
<Tooltip id={locationLinkText} className="log-location-tooltip">
{locationLinkText}
</Tooltip>
) : null
var headerTitleText = logType ? `${logType} ${headerTitle}` : headerTitle
return (
<header className={logEntryHeaderClasses}>
{headerIcon ? (
<div className="log-entry-header-icon-container">{headerIcon}</div>
) : null}
<h3 className="log-entry-header-title">{headerTitleText}</h3>
{locationTooltip ? (
<OverlayTrigger placement="left" overlay={locationTooltip}>
{locationLink}
</OverlayTrigger>
) : (
locationLink
)}
{showCloseButton ? (
<button
className="btn-inline-link log-entry-header-link"
type="button"
aria-label={t('dismiss_error_popup')}
onClick={onClose}
>
<span aria-hidden="true">×</span>
</button>
) : null}
</header>
)
}
function PreviewLogEntryContent({
rawContent,
formattedContent,
extraInfoURL,
}) {
const {
isExpanded,
needsExpandCollapse,
expandableProps,
toggleProps,
} = useExpandCollapse({
collapsedSize: 150,
})
const buttonContainerClasses = classNames(
'log-entry-content-button-container',
{
'log-entry-content-button-container-collapsed': !isExpanded,
}
)
const { t } = useTranslation()
return (
<div className="log-entry-content">
{rawContent ? (
<div className="log-entry-content-raw-container">
<div {...expandableProps}>
<pre className="log-entry-content-raw">{rawContent.trim()}</pre>
</div>
{needsExpandCollapse ? (
<div className={buttonContainerClasses}>
<button
type="button"
className="btn btn-xs btn-default log-entry-btn-expand-collapse"
{...toggleProps}
>
{isExpanded ? (
<>
<Icon type="angle-up" /> {t('collapse')}
</>
) : (
<>
<Icon type="angle-down" /> {t('expand')}
</>
)}
</button>
</div>
) : null}
</div>
) : null}
{formattedContent ? (
<div className="log-entry-formatted-content">{formattedContent}</div>
) : null}
{extraInfoURL ? (
<div className="log-entry-content-link">
<a href={extraInfoURL} target="_blank">
{t('log_hint_extra_info')}
</a>
</div>
) : null}
</div>
)
}
PreviewLogEntryHeader.propTypes = {
sourceLocation: PropTypes.shape({
file: PropTypes.string,
// `line should be either a number or null (i.e. not required), but currently sometimes we get
// an empty string (from BibTeX errors), which is why we're using `any` here. We should revert
// to PropTypes.number (not required) once we fix that.
line: PropTypes.any,
column: PropTypes.any,
}),
level: PropTypes.string.isRequired,
headerTitle: PropTypes.string,
headerIcon: PropTypes.element,
logType: PropTypes.string,
showSourceLocationLink: PropTypes.bool,
showCloseButton: PropTypes.bool,
onSourceLocationClick: PropTypes.func,
onClose: PropTypes.func,
}
PreviewLogEntryContent.propTypes = {
rawContent: PropTypes.string,
formattedContent: PropTypes.node,
extraInfoURL: PropTypes.string,
}
PreviewLogsPaneEntry.propTypes = {
sourceLocation: PreviewLogEntryHeader.propTypes.sourceLocation,
headerTitle: PropTypes.string,
headerIcon: PropTypes.element,
rawContent: PropTypes.string,
logType: PropTypes.string,
formattedContent: PropTypes.node,
extraInfoURL: PropTypes.string,
level: PropTypes.oneOf(['error', 'warning', 'typesetting', 'raw', 'success'])
.isRequired,
customClass: PropTypes.string,
showSourceLocationLink: PropTypes.bool,
showCloseButton: PropTypes.bool,
entryAriaLabel: PropTypes.string,
onSourceLocationClick: PropTypes.func,
onClose: PropTypes.func,
}
export default PreviewLogsPaneEntry
| overleaf/web/frontend/js/features/preview/components/preview-logs-pane-entry.js/0 | {
"file_path": "overleaf/web/frontend/js/features/preview/components/preview-logs-pane-entry.js",
"repo_id": "overleaf",
"token_count": 3456
} | 521 |
import { useMemo } from 'react'
import { Row } from 'react-bootstrap'
import AddCollaborators from './add-collaborators'
import AddCollaboratorsUpgrade from './add-collaborators-upgrade'
import { useProjectContext } from '../../../shared/context/project-context'
export default function SendInvites() {
const project = useProjectContext()
// whether the project has not reached the collaborator limit
const canAddCollaborators = useMemo(() => {
if (!project) {
return false
}
if (project.features.collaborators === -1) {
// infinite collaborators
return true
}
return (
project.members.length + project.invites.length <
project.features.collaborators
)
}, [project])
return (
<Row className="invite-controls">
{canAddCollaborators ? <AddCollaborators /> : <AddCollaboratorsUpgrade />}
</Row>
)
}
| overleaf/web/frontend/js/features/share-project-modal/components/send-invites.js/0 | {
"file_path": "overleaf/web/frontend/js/features/share-project-modal/components/send-invites.js",
"repo_id": "overleaf",
"token_count": 294
} | 522 |
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import PropTypes from 'prop-types'
import { FormControl } from 'react-bootstrap'
import useDebounce from '../../../shared/hooks/use-debounce'
export default function SymbolPaletteSearch({ setInput, inputRef }) {
const [localInput, setLocalInput] = useState('')
// debounce the search input until a typing delay
const debouncedLocalInput = useDebounce(localInput, 250)
useEffect(() => {
setInput(debouncedLocalInput)
}, [debouncedLocalInput, setInput])
const { t } = useTranslation()
const inputRefCallback = useCallback(
element => {
inputRef.current = element
},
[inputRef]
)
return (
<FormControl
className="symbol-palette-search"
type="search"
inputRef={inputRefCallback}
id="symbol-palette-input"
aria-label="Search"
value={localInput}
placeholder={t('search') + '…'}
onChange={event => {
setLocalInput(event.target.value)
}}
/>
)
}
SymbolPaletteSearch.propTypes = {
setInput: PropTypes.func.isRequired,
inputRef: PropTypes.object.isRequired,
}
| overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-search.js/0 | {
"file_path": "overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-search.js",
"repo_id": "overleaf",
"token_count": 417
} | 523 |
/* eslint-disable
max-len,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import './controllers/BinaryFileController'
let BinaryFilesManager
export default BinaryFilesManager = class BinaryFilesManager {
constructor(ide, $scope) {
this.ide = ide
this.$scope = $scope
this.$scope.$on('entity:selected', (event, entity) => {
if (this.$scope.ui.view !== 'track-changes' && entity.type === 'file') {
return this.openFile(entity)
}
})
}
openFile(file) {
this.ide.fileTreeManager.selectEntity(file)
this.$scope.ui.view = 'file'
this.$scope.openFile = null
this.$scope.$apply()
return window.setTimeout(
() => {
this.$scope.openFile = file
this.$scope.$apply()
this.$scope.$broadcast('file-view:file-opened')
},
0,
this
)
}
}
| overleaf/web/frontend/js/ide/binary-files/BinaryFilesManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/binary-files/BinaryFilesManager.js",
"repo_id": "overleaf",
"token_count": 420
} | 524 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS001: Remove Babel/TypeScript constructor workaround
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__
* DS205: Consider reworking code to avoid use of IIFEs
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import EventEmitter from '../../utils/EventEmitter'
import ShareJsDoc from './ShareJsDoc'
import RangesTracker from '../review-panel/RangesTracker'
let Document
export default Document = (function () {
Document = class Document extends EventEmitter {
static initClass() {
this.prototype.MAX_PENDING_OP_SIZE = 64
}
static getDocument(ide, doc_id) {
if (!this.openDocs) {
this.openDocs = {}
}
// Try to clean up existing docs before reopening them. If the doc has no
// buffered ops then it will be deleted by _cleanup() and a new instance
// of the document created below. This prevents us trying to follow the
// joinDoc:existing code path on an existing doc that doesn't have any
// local changes and getting an error if its version is too old.
if (this.openDocs[doc_id]) {
sl_console.log(
`[getDocument] Cleaning up existing document instance for ${doc_id}`
)
this.openDocs[doc_id]._cleanUp()
}
if (this.openDocs[doc_id] == null) {
sl_console.log(
`[getDocument] Creating new document instance for ${doc_id}`
)
this.openDocs[doc_id] = new Document(ide, doc_id)
} else {
sl_console.log(
`[getDocument] Returning existing document instance for ${doc_id}`
)
}
return this.openDocs[doc_id]
}
static hasUnsavedChanges() {
const object = this.openDocs || {}
for (const doc_id in object) {
const doc = object[doc_id]
if (doc.hasBufferedOps()) {
return true
}
}
return false
}
static flushAll() {
return (() => {
const result = []
for (const doc_id in this.openDocs) {
const doc = this.openDocs[doc_id]
result.push(doc.flush())
}
return result
})()
}
constructor(ide, doc_id) {
super()
this.ide = ide
this.doc_id = doc_id
this.connected = this.ide.socket.socket.connected
this.joined = false
this.wantToBeJoined = false
this._checkAceConsistency = () => this._checkConsistency(this.ace)
this._checkCMConsistency = () => this._checkConsistency(this.cm)
this._bindToEditorEvents()
this._bindToSocketEvents()
}
attachToAce(ace) {
this.ace = ace
if (this.doc != null) {
this.doc.attachToAce(this.ace)
}
const editorDoc = this.ace.getSession().getDocument()
editorDoc.on('change', this._checkAceConsistency)
return this.ide.$scope.$emit('document:opened', this.doc)
}
detachFromAce() {
if (this.doc != null) {
this.doc.detachFromAce()
}
const editorDoc =
this.ace != null ? this.ace.getSession().getDocument() : undefined
if (editorDoc != null) {
editorDoc.off('change', this._checkAceConsistency)
}
return this.ide.$scope.$emit('document:closed', this.doc)
}
attachToCM(cm) {
this.cm = cm
if (this.doc != null) {
this.doc.attachToCM(this.cm)
}
if (this.cm != null) {
this.cm.on('change', this._checkCMConsistency)
}
return this.ide.$scope.$emit('document:opened', this.doc)
}
detachFromCM() {
if (this.doc != null) {
this.doc.detachFromCM()
}
if (this.cm != null) {
this.cm.off('change', this._checkCMConsistency)
}
return this.ide.$scope.$emit('document:closed', this.doc)
}
submitOp(...args) {
return this.doc != null
? this.doc.submitOp(...Array.from(args || []))
: undefined
}
_checkConsistency(editor) {
// We've been seeing a lot of errors when I think there shouldn't be
// any, which may be related to this check happening before the change is
// applied. If we use a timeout, hopefully we can reduce this.
return setTimeout(() => {
const editorValue = editor != null ? editor.getValue() : undefined
const sharejsValue =
this.doc != null ? this.doc.getSnapshot() : undefined
if (editorValue !== sharejsValue) {
return this._onError(
new Error('Editor text does not match server text'),
{},
editorValue
)
}
}, 0)
}
getSnapshot() {
return this.doc != null ? this.doc.getSnapshot() : undefined
}
getType() {
return this.doc != null ? this.doc.getType() : undefined
}
getInflightOp() {
return this.doc != null ? this.doc.getInflightOp() : undefined
}
getPendingOp() {
return this.doc != null ? this.doc.getPendingOp() : undefined
}
getRecentAck() {
return this.doc != null ? this.doc.getRecentAck() : undefined
}
getOpSize(op) {
return this.doc != null ? this.doc.getOpSize(op) : undefined
}
hasBufferedOps() {
return this.doc != null ? this.doc.hasBufferedOps() : undefined
}
setTrackingChanges(track_changes) {
return (this.doc.track_changes = track_changes)
}
getTrackingChanges() {
return !!this.doc.track_changes
}
setTrackChangesIdSeeds(id_seeds) {
return (this.doc.track_changes_id_seeds = id_seeds)
}
_bindToSocketEvents() {
this._onUpdateAppliedHandler = update => this._onUpdateApplied(update)
this.ide.socket.on('otUpdateApplied', this._onUpdateAppliedHandler)
this._onErrorHandler = (error, message) => {
// 'otUpdateError' are emitted per doc socket.io room, hence we can be
// sure that message.doc_id exists.
if (message.doc_id !== this.doc_id) {
// This error is for another doc. Do not action it. We could open
// a modal that has the wrong context on it.
return
}
this._onError(error, message)
}
this.ide.socket.on('otUpdateError', this._onErrorHandler)
this._onDisconnectHandler = error => this._onDisconnect(error)
return this.ide.socket.on('disconnect', this._onDisconnectHandler)
}
_bindToEditorEvents() {
const onReconnectHandler = update => {
return this._onReconnect(update)
}
return (this._unsubscribeReconnectHandler = this.ide.$scope.$on(
'project:joined',
onReconnectHandler
))
}
_unBindFromEditorEvents() {
return this._unsubscribeReconnectHandler()
}
_unBindFromSocketEvents() {
this.ide.socket.removeListener(
'otUpdateApplied',
this._onUpdateAppliedHandler
)
this.ide.socket.removeListener('otUpdateError', this._onErrorHandler)
return this.ide.socket.removeListener(
'disconnect',
this._onDisconnectHandler
)
}
leaveAndCleanUp(cb) {
return this.leave(error => {
this._cleanUp()
if (cb) cb(error)
})
}
join(callback) {
if (callback == null) {
callback = function (error) {}
}
this.wantToBeJoined = true
this._cancelLeave()
if (this.connected) {
return this._joinDoc(callback)
} else {
if (!this._joinCallbacks) {
this._joinCallbacks = []
}
return this._joinCallbacks.push(callback)
}
}
leave(callback) {
if (callback == null) {
callback = function (error) {}
}
this.flush() // force an immediate flush when leaving document
this.wantToBeJoined = false
this._cancelJoin()
if (this.doc != null && this.doc.hasBufferedOps()) {
sl_console.log(
'[leave] Doc has buffered ops, pushing callback for later'
)
if (!this._leaveCallbacks) {
this._leaveCallbacks = []
}
return this._leaveCallbacks.push(callback)
} else if (!this.connected) {
sl_console.log('[leave] Not connected, returning now')
return callback()
} else {
sl_console.log('[leave] Leaving now')
return this._leaveDoc(callback)
}
}
flush() {
return this.doc != null ? this.doc.flushPendingOps() : undefined
}
chaosMonkey(line, char) {
if (line == null) {
line = 0
}
if (char == null) {
char = 'a'
}
const orig = char
let copy = null
let pos = 0
var timer = () => {
if (copy == null || !copy.length) {
copy = orig.slice() + ' ' + new Date() + '\n'
line += Math.random() > 0.1 ? 1 : -2
if (line < 0) {
line = 0
}
pos = 0
}
char = copy[0]
copy = copy.slice(1)
this.ace.session.insert({ row: line, column: pos }, char)
pos += 1
return (this._cm = setTimeout(
timer,
100 + (Math.random() < 0.1 ? 1000 : 0)
))
}
return (this._cm = timer())
}
clearChaosMonkey() {
return clearTimeout(this._cm) // pending ops bigger than this are always considered unsaved
}
pollSavedStatus() {
// returns false if doc has ops waiting to be acknowledged or
// sent that haven't changed since the last time we checked.
// Otherwise returns true.
let saved
const inflightOp = this.getInflightOp()
const pendingOp = this.getPendingOp()
const recentAck = this.getRecentAck()
const pendingOpSize = pendingOp != null && this.getOpSize(pendingOp)
if (inflightOp == null && pendingOp == null) {
// there's nothing going on, this is ok.
saved = true
sl_console.log('[pollSavedStatus] no inflight or pending ops')
} else if (inflightOp != null && inflightOp === this.oldInflightOp) {
// The same inflight op has been sitting unacked since we
// last checked, this is bad.
saved = false
sl_console.log('[pollSavedStatus] inflight op is same as before')
} else if (
pendingOp != null &&
recentAck &&
pendingOpSize < this.MAX_PENDING_OP_SIZE
) {
// There is an op waiting to go to server but it is small and
// within the flushDelay, this is ok for now.
saved = true
sl_console.log(
'[pollSavedStatus] pending op (small with recent ack) assume ok',
pendingOp,
pendingOpSize
)
} else {
// In any other situation, assume the document is unsaved.
saved = false
sl_console.log(
`[pollSavedStatus] assuming not saved (inflightOp?: ${
inflightOp != null
}, pendingOp?: ${pendingOp != null})`
)
}
this.oldInflightOp = inflightOp
return saved
}
_cancelLeave() {
if (this._leaveCallbacks != null) {
return delete this._leaveCallbacks
}
}
_cancelJoin() {
if (this._joinCallbacks != null) {
return delete this._joinCallbacks
}
}
_onUpdateApplied(update) {
this.ide.pushEvent('received-update', {
doc_id: this.doc_id,
remote_doc_id: update != null ? update.doc : undefined,
wantToBeJoined: this.wantToBeJoined,
update,
hasDoc: this.doc != null,
})
if (
window.disconnectOnAck != null &&
Math.random() < window.disconnectOnAck
) {
sl_console.log('Disconnecting on ack', update)
window._ide.socket.socket.disconnect()
// Pretend we never received the ack
return
}
if (window.dropAcks != null && Math.random() < window.dropAcks) {
if (update.op == null) {
// Only drop our own acks, not collaborator updates
sl_console.log('Simulating a lost ack', update)
return
}
}
if (
(update != null ? update.doc : undefined) === this.doc_id &&
this.doc != null
) {
this.ide.pushEvent('received-update:processing', {
update,
})
// FIXME: change this back to processUpdateFromServer when redis fixed
this.doc.processUpdateFromServerInOrder(update)
if (!this.wantToBeJoined) {
return this.leave()
}
}
}
_onDisconnect() {
sl_console.log('[onDisconnect] disconnecting')
this.connected = false
this.joined = false
return this.doc != null
? this.doc.updateConnectionState('disconnected')
: undefined
}
_onReconnect() {
sl_console.log('[onReconnect] reconnected (joined project)')
this.ide.pushEvent('reconnected:afterJoinProject')
this.connected = true
if (
this.wantToBeJoined ||
(this.doc != null ? this.doc.hasBufferedOps() : undefined)
) {
sl_console.log(
`[onReconnect] Rejoining (wantToBeJoined: ${
this.wantToBeJoined
} OR hasBufferedOps: ${
this.doc != null ? this.doc.hasBufferedOps() : undefined
})`
)
return this._joinDoc(error => {
if (error != null) {
return this._onError(error)
}
this.doc.updateConnectionState('ok')
this.doc.flushPendingOps()
return this._callJoinCallbacks()
})
}
}
_callJoinCallbacks() {
for (const callback of Array.from(this._joinCallbacks || [])) {
callback()
}
return delete this._joinCallbacks
}
_joinDoc(callback) {
if (callback == null) {
callback = function (error) {}
}
if (this.doc != null) {
this.ide.pushEvent('joinDoc:existing', {
doc_id: this.doc_id,
version: this.doc.getVersion(),
})
return this.ide.socket.emit(
'joinDoc',
this.doc_id,
this.doc.getVersion(),
{ encodeRanges: true },
(error, docLines, version, updates, ranges) => {
if (error != null) {
return callback(error)
}
this.joined = true
this.doc.catchUp(updates)
this._decodeRanges(ranges)
this._catchUpRanges(
ranges != null ? ranges.changes : undefined,
ranges != null ? ranges.comments : undefined
)
return callback()
}
)
} else {
this.ide.pushEvent('joinDoc:new', {
doc_id: this.doc_id,
})
return this.ide.socket.emit(
'joinDoc',
this.doc_id,
{ encodeRanges: true },
(error, docLines, version, updates, ranges) => {
if (error != null) {
return callback(error)
}
this.joined = true
this.ide.pushEvent('joinDoc:inited', {
doc_id: this.doc_id,
version,
})
this.doc = new ShareJsDoc(
this.doc_id,
docLines,
version,
this.ide.socket,
this.ide.globalEditorWatchdogManager
)
this._decodeRanges(ranges)
this.ranges = new RangesTracker(
ranges != null ? ranges.changes : undefined,
ranges != null ? ranges.comments : undefined
)
this._bindToShareJsDocEvents()
return callback()
}
)
}
}
_decodeRanges(ranges) {
const decodeFromWebsockets = text => decodeURIComponent(escape(text))
try {
for (const change of Array.from(ranges.changes || [])) {
if (change.op.i != null) {
change.op.i = decodeFromWebsockets(change.op.i)
}
if (change.op.d != null) {
change.op.d = decodeFromWebsockets(change.op.d)
}
}
return (() => {
const result = []
for (const comment of Array.from(ranges.comments || [])) {
if (comment.op.c != null) {
result.push((comment.op.c = decodeFromWebsockets(comment.op.c)))
} else {
result.push(undefined)
}
}
return result
})()
} catch (err) {
return console.log(err)
}
}
_leaveDoc(callback) {
if (callback == null) {
callback = function (error) {}
}
this.ide.pushEvent('leaveDoc', {
doc_id: this.doc_id,
})
sl_console.log('[_leaveDoc] Sending leaveDoc request')
return this.ide.socket.emit('leaveDoc', this.doc_id, error => {
if (error != null) {
return callback(error)
}
this.joined = false
for (callback of Array.from(this._leaveCallbacks || [])) {
sl_console.log('[_leaveDoc] Calling buffered callback', callback)
callback(error)
}
delete this._leaveCallbacks
return callback(error)
})
}
_cleanUp() {
// if we arrive here from _onError the pending and inflight ops will have been cleared
if (this.hasBufferedOps()) {
sl_console.log(
`[_cleanUp] Document (${this.doc_id}) has buffered ops, refusing to remove from openDocs`
)
return // return immediately, do not unbind from events
} else if (Document.openDocs[this.doc_id] === this) {
sl_console.log(
`[_cleanUp] Removing self (${this.doc_id}) from in openDocs`
)
delete Document.openDocs[this.doc_id]
} else {
// It's possible that this instance has error, and the doc has been reloaded.
// This creates a new instance in Document.openDoc with the same id. We shouldn't
// clear it because it's not this instance.
sl_console.log(
`[_cleanUp] New instance of (${this.doc_id}) created. Not removing`
)
}
this._unBindFromEditorEvents()
return this._unBindFromSocketEvents()
}
_bindToShareJsDocEvents() {
this.doc.on('error', (error, meta) => this._onError(error, meta))
this.doc.on('externalUpdate', update => {
this.ide.pushEvent('externalUpdate', { doc_id: this.doc_id })
return this.trigger('externalUpdate', update)
})
this.doc.on('remoteop', (...args) => {
this.ide.pushEvent('remoteop', { doc_id: this.doc_id })
return this.trigger('remoteop', ...Array.from(args))
})
this.doc.on('op:sent', op => {
this.ide.pushEvent('op:sent', {
doc_id: this.doc_id,
op,
})
return this.trigger('op:sent')
})
this.doc.on('op:acknowledged', op => {
this.ide.pushEvent('op:acknowledged', {
doc_id: this.doc_id,
op,
})
this.ide.$scope.$emit('ide:opAcknowledged', {
doc_id: this.doc_id,
op,
})
return this.trigger('op:acknowledged')
})
this.doc.on('op:timeout', op => {
this.ide.pushEvent('op:timeout', {
doc_id: this.doc_id,
op,
})
this.trigger('op:timeout')
return this._onError(new Error('op timed out'), { op })
})
this.doc.on('flush', (inflightOp, pendingOp, version) => {
return this.ide.pushEvent('flush', {
doc_id: this.doc_id,
inflightOp,
pendingOp,
v: version,
})
})
this.doc.on('change', (ops, oldSnapshot, msg) => {
this._applyOpsToRanges(ops, oldSnapshot, msg)
return this.ide.$scope.$emit('doc:changed', { doc_id: this.doc_id })
})
this.doc.on('flipped_pending_to_inflight', () => {
return this.trigger('flipped_pending_to_inflight')
})
return this.doc.on('saved', () => {
return this.ide.$scope.$emit('doc:saved', { doc_id: this.doc_id })
})
}
_onError(error, meta, editorContent) {
if (meta == null) {
meta = {}
}
meta.doc_id = this.doc_id
sl_console.log('ShareJS error', error, meta)
if (error.message === 'no project_id found on client') {
sl_console.log('ignoring error, will wait to join project')
return
}
if (typeof ga === 'function') {
// sanitise the error message before sending (the "delete component"
// error in public/js/libs/sharejs.js includes the some document
// content).
let message = error.message
if (/^Delete component/.test(message)) {
message = 'Delete component does not match deleted text'
}
ga(
'send',
'event',
'error',
'shareJsError',
`${message} - ${this.ide.socket.socket.transport.name}`
)
}
if (this.doc != null) {
this.doc.clearInflightAndPendingOps()
}
this.trigger('error', error, meta, editorContent)
// The clean up should run after the error is triggered because the error triggers a
// disconnect. If we run the clean up first, we remove our event handlers and miss
// the disconnect event, which means we try to leaveDoc when the connection comes back.
// This could intefere with the new connection of a new instance of this document.
return this._cleanUp()
}
_applyOpsToRanges(ops, oldSnapshot, msg) {
let old_id_seed
if (ops == null) {
ops = []
}
let track_changes_as = null
const remote_op = msg != null
if (__guard__(msg != null ? msg.meta : undefined, x => x.tc) != null) {
old_id_seed = this.ranges.getIdSeed()
this.ranges.setIdSeed(msg.meta.tc)
}
if (remote_op && (msg.meta != null ? msg.meta.tc : undefined)) {
track_changes_as = msg.meta.user_id
} else if (!remote_op && this.track_changes_as != null) {
;({ track_changes_as } = this)
}
this.ranges.track_changes = track_changes_as != null
for (const op of Array.from(ops)) {
this.ranges.applyOp(op, { user_id: track_changes_as })
}
if (old_id_seed != null) {
this.ranges.setIdSeed(old_id_seed)
}
if (remote_op) {
// With remote ops, Ace hasn't been updated when we receive this op,
// so defer updating track changes until it has
return setTimeout(() => this.emit('ranges:dirty'))
} else {
return this.emit('ranges:dirty')
}
}
_catchUpRanges(changes, comments) {
// We've just been given the current server's ranges, but need to apply any local ops we have.
// Reset to the server state then apply our local ops again.
if (changes == null) {
changes = []
}
if (comments == null) {
comments = []
}
this.emit('ranges:clear')
this.ranges.changes = changes
this.ranges.comments = comments
this.ranges.track_changes = this.doc.track_changes
for (var op of Array.from(this.doc.getInflightOp() || [])) {
this.ranges.setIdSeed(this.doc.track_changes_id_seeds.inflight)
this.ranges.applyOp(op, { user_id: this.track_changes_as })
}
for (op of Array.from(this.doc.getPendingOp() || [])) {
this.ranges.setIdSeed(this.doc.track_changes_id_seeds.pending)
this.ranges.applyOp(op, { user_id: this.track_changes_as })
}
return this.emit('ranges:redraw')
}
}
Document.initClass()
return Document
})()
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
? transform(value)
: undefined
}
| overleaf/web/frontend/js/ide/editor/Document.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/Document.js",
"repo_id": "overleaf",
"token_count": 10769
} | 525 |
/* eslint-disable
camelcase,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import 'ace/ace'
import ColorManager from '../../../../colors/ColorManager'
let HighlightsManager
const { Range } = ace.require('ace/range')
export default HighlightsManager = class HighlightsManager {
constructor($scope, editor, element) {
this.$scope = $scope
this.editor = editor
this.element = element
this.markerIds = []
this.labels = []
this.$scope.annotationLabel = {
show: false,
right: 'auto',
left: 'auto',
top: 'auto',
bottom: 'auto',
backgroundColor: 'black',
text: '',
}
this.$scope.updateLabels = {
updatesAbove: 0,
updatesBelow: 0,
}
this.$scope.$watch('highlights', value => {
return this.redrawAnnotations()
})
this.$scope.$watch('theme', value => {
return this.redrawAnnotations()
})
this.editor.on('mousemove', e => {
const position = this.editor.renderer.screenToTextCoordinates(
e.clientX,
e.clientY
)
e.position = position
return this.showAnnotationLabels(position)
})
const onChangeScrollTop = () => {
return this.updateShowMoreLabels()
}
this.editor.getSession().on('changeScrollTop', onChangeScrollTop)
this.$scope.$watch('text', () => {
if (this.$scope.navigateHighlights) {
return setTimeout(() => {
return this.scrollToFirstHighlight()
}, 0)
}
})
this.editor.on('changeSession', e => {
if (e.oldSession != null) {
e.oldSession.off('changeScrollTop', onChangeScrollTop)
}
e.session.on('changeScrollTop', onChangeScrollTop)
return this.redrawAnnotations()
})
this.$scope.gotoHighlightBelow = () => {
if (this.firstHiddenHighlightAfter == null) {
return
}
return this.editor.scrollToLine(
this.firstHiddenHighlightAfter.end.row,
true,
false
)
}
this.$scope.gotoHighlightAbove = () => {
if (this.lastHiddenHighlightBefore == null) {
return
}
return this.editor.scrollToLine(
this.lastHiddenHighlightBefore.start.row,
true,
false
)
}
}
redrawAnnotations() {
this._clearMarkers()
this._clearLabels()
for (const annotation of Array.from(this.$scope.highlights || [])) {
;(annotation => {
const colorScheme = ColorManager.getColorScheme(
annotation.hue,
this.element
)
if (annotation.cursor != null) {
this.labels.push({
text: annotation.label,
range: new Range(
annotation.cursor.row,
annotation.cursor.column,
annotation.cursor.row,
annotation.cursor.column + 1
),
colorScheme,
snapToStartOfRange: true,
})
return this._drawCursor(annotation, colorScheme)
} else if (annotation.highlight != null) {
this.labels.push({
text: annotation.label,
range: new Range(
annotation.highlight.start.row,
annotation.highlight.start.column,
annotation.highlight.end.row,
annotation.highlight.end.column
),
colorScheme,
})
return this._drawHighlight(annotation, colorScheme)
} else if (annotation.strikeThrough != null) {
this.labels.push({
text: annotation.label,
range: new Range(
annotation.strikeThrough.start.row,
annotation.strikeThrough.start.column,
annotation.strikeThrough.end.row,
annotation.strikeThrough.end.column
),
colorScheme,
})
return this._drawStrikeThrough(annotation, colorScheme)
}
})(annotation)
}
return this.updateShowMoreLabels()
}
showAnnotationLabels(position) {
let labelToShow = null
for (const label of Array.from(this.labels || [])) {
if (label.range.contains(position.row, position.column)) {
labelToShow = label
}
}
if (labelToShow == null) {
// this is the most common path, triggered on mousemove, so
// for performance only apply setting when it changes
if (
__guard__(
this.$scope != null ? this.$scope.annotationLabel : undefined,
x => x.show
) !== false
) {
return this.$scope.$apply(() => {
return (this.$scope.annotationLabel.show = false)
})
}
} else {
let bottom, coords, left, right, top
const $ace = $(this.editor.renderer.container).find('.ace_scroller')
// Move the label into the Ace content area so that offsets and positions are easy to calculate.
$ace.append(this.element.find('.annotation-label'))
if (labelToShow.snapToStartOfRange) {
coords = this.editor.renderer.textToScreenCoordinates(
labelToShow.range.start.row,
labelToShow.range.start.column
)
} else {
coords = this.editor.renderer.textToScreenCoordinates(
position.row,
position.column
)
}
const offset = $ace.offset()
const height = $ace.height()
coords.pageX = coords.pageX - offset.left
coords.pageY = coords.pageY - offset.top
if (coords.pageY > this.editor.renderer.lineHeight * 2) {
top = 'auto'
bottom = height - coords.pageY
} else {
top = coords.pageY + this.editor.renderer.lineHeight
bottom = 'auto'
}
// Apply this first that the label has the correct width when calculating below
this.$scope.$apply(() => {
this.$scope.annotationLabel.text = labelToShow.text
return (this.$scope.annotationLabel.show = true)
})
const $label = this.element.find('.annotation-label')
if (coords.pageX + $label.outerWidth() < $ace.width()) {
left = coords.pageX
right = 'auto'
} else {
right = 0
left = 'auto'
}
return this.$scope.$apply(() => {
return (this.$scope.annotationLabel = {
show: true,
left,
right,
bottom,
top,
backgroundColor: labelToShow.colorScheme.labelBackgroundColor,
text: labelToShow.text,
})
})
}
}
updateShowMoreLabels() {
if (!this.$scope.navigateHighlights) {
return
}
return setTimeout(() => {
const firstRow = this.editor.getFirstVisibleRow()
const lastRow = this.editor.getLastVisibleRow()
let highlightsBefore = 0
let highlightsAfter = 0
this.lastHiddenHighlightBefore = null
this.firstHiddenHighlightAfter = null
for (const annotation of Array.from(this.$scope.highlights || [])) {
const range = annotation.highlight || annotation.strikeThrough
if (range == null) {
continue
}
if (range.start.row < firstRow) {
highlightsBefore += 1
this.lastHiddenHighlightBefore = range
}
if (range.end.row > lastRow) {
highlightsAfter += 1
if (!this.firstHiddenHighlightAfter) {
this.firstHiddenHighlightAfter = range
}
}
}
return this.$scope.$apply(() => {
return (this.$scope.updateLabels = {
highlightsBefore,
highlightsAfter,
})
})
}, 100)
}
scrollToFirstHighlight() {
return (() => {
const result = []
for (const annotation of Array.from(this.$scope.highlights || [])) {
const range = annotation.highlight || annotation.strikeThrough
if (range == null) {
continue
}
this.editor.scrollToLine(range.start.row, true, false)
break
}
return result
})()
}
_clearMarkers() {
for (const marker_id of Array.from(this.markerIds)) {
this.editor.getSession().removeMarker(marker_id)
}
return (this.markerIds = [])
}
_clearLabels() {
return (this.labels = [])
}
_drawCursor(annotation, colorScheme) {
return this._addMarkerWithCustomStyle(
new Range(
annotation.cursor.row,
annotation.cursor.column,
annotation.cursor.row,
annotation.cursor.column + 1
),
'annotation remote-cursor',
false,
`border-color: ${colorScheme.cursor};`
)
}
_drawHighlight(annotation, colorScheme) {
return this._addMarkerWithCustomStyle(
new Range(
annotation.highlight.start.row,
annotation.highlight.start.column,
annotation.highlight.end.row,
annotation.highlight.end.column
),
'annotation highlight',
false,
`background-color: ${colorScheme.highlightBackgroundColor}`
)
}
_drawStrikeThrough(annotation, colorScheme) {
this._addMarkerWithCustomStyle(
new Range(
annotation.strikeThrough.start.row,
annotation.strikeThrough.start.column,
annotation.strikeThrough.end.row,
annotation.strikeThrough.end.column
),
'annotation strike-through-background',
false,
`background-color: ${colorScheme.strikeThroughBackgroundColor}`
)
return this._addMarkerWithCustomStyle(
new Range(
annotation.strikeThrough.start.row,
annotation.strikeThrough.start.column,
annotation.strikeThrough.end.row,
annotation.strikeThrough.end.column
),
'annotation strike-through-foreground',
true,
`color: ${colorScheme.strikeThroughForegroundColor};`
)
}
_addMarkerWithCustomStyle(range, klass, foreground, style) {
let markerLayer
if (!foreground) {
markerLayer = this.editor.renderer.$markerBack
} else {
markerLayer = this.editor.renderer.$markerFront
}
return this.markerIds.push(
this.editor.getSession().addMarker(
range,
klass,
function (html, range, left, top, config) {
if (range.isMultiLine()) {
return markerLayer.drawTextMarker(html, range, klass, config, style)
} else {
return markerLayer.drawSingleLineMarker(
html,
range,
`${klass} ace_start`,
config,
0,
style
)
}
},
foreground
)
)
}
}
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
? transform(value)
: undefined
}
| overleaf/web/frontend/js/ide/editor/directives/aceEditor/highlights/HighlightsManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/highlights/HighlightsManager.js",
"repo_id": "overleaf",
"token_count": 4866
} | 526 |
import '../../features/file-view/controllers/file-view-controller'
| overleaf/web/frontend/js/ide/file-view/index.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/file-view/index.js",
"repo_id": "overleaf",
"token_count": 20
} | 527 |
/* eslint-disable
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
export default App.controller(
'HistoryV2ListController',
function ($scope, $modal, ide) {
$scope.hoveringOverListSelectors = false
$scope.listConfig = { showOnlyLabelled: false }
$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
},
},
}))
}
)
| overleaf/web/frontend/js/ide/history/controllers/HistoryV2ListController.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/history/controllers/HistoryV2ListController.js",
"repo_id": "overleaf",
"token_count": 582
} | 528 |
import App from '../../../base'
import HumanReadableLogs from '../../human-readable-logs/HumanReadableLogs'
import BibLogParser from 'libs/bib-log-parser'
import PreviewPane from '../../../features/preview/components/preview-pane'
import { react2angular } from 'react2angular'
import { rootContext } from '../../../shared/context/root-context'
import 'ace/ace'
import getMeta from '../../../utils/meta'
import { trackPdfDownload } from './PdfJsMetrics'
const AUTO_COMPILE_MAX_WAIT = 5000
// We add a 1 second debounce to sending user changes to server if they aren't
// collaborating with anyone. This needs to be higher than that, and allow for
// client to server latency, otherwise we compile before the op reaches the server
// and then again on ack.
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
// pdf.view = uncompiled | pdf | errors
$scope.pdf.view = $scope.pdf.url ? 'pdf' : 'uncompiled'
$scope.pdf.clearingCache = false
$scope.shouldShowLogs = false
$scope.logsUISubvariant = window.logsUISubvariant
// 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
}
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
}
// 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
}
// 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()
}
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 (getMeta('ol-enablePdfCaching')) {
params.enable_pdf_caching = 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 noop() {}
function parseCompileResponse(response, compileTimeClientE2E) {
// 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.updateConsumedBandwidth = noop
$scope.pdf.firstRenderDone = noop
$scope.pdf.clsiMaintenance = false
$scope.pdf.clsiUnavailable = 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
$scope.pdf.compileFailed = false
// 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
)
if (window.location.search.includes('verify_chunks=true')) {
// Instruct the serviceWorker to verify composed ranges.
qs.verify_chunks = 'true'
}
if (getMeta('ol-enablePdfCaching')) {
// Tag traffic that uses the pdf caching logic.
qs.enable_pdf_caching = 'true'
}
// convert the qs hash into a query string and append it
$scope.pdf.url += createQueryString(qs)
if (getMeta('ol-trackPdfDownload')) {
const { firstRenderDone, updateConsumedBandwidth } = trackPdfDownload(
response,
compileTimeClientE2E
)
$scope.pdf.firstRenderDone = firstRenderDone
$scope.pdf.updateConsumedBandwidth = updateConsumedBandwidth
}
// 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'
)
eventTracking.sendMB('compile-timeout-paywall-prompt')
}
} 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.pdf.downloadUrl = null
$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
}
const IGNORE_FILES = ['output.fls', 'output.fdb_latexmk']
$scope.pdf.outputFiles = []
if (response.outputFiles == null) {
return
}
// 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,
})
}
}
// 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)
)
}
// In the existing compile UI, errors and validation problems are shown in the PDF pane, whereas in the new
// one they're shown in the logs pane. This `$watch`er makes sure we change the view in the new logs UI.
// This should be removed once we stop supporting the two different log UIs.
if (window.showNewLogsUI) {
$scope.$watch(
() =>
$scope.pdf.view === 'errors' ||
$scope.pdf.view === 'validation-problems',
newVal => {
if (newVal) {
$scope.shouldShowLogs = true
$scope.pdf.compileFailed = true
}
}
)
}
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 (const key of ['all', 'errors', 'warnings', 'typesetting']) {
if (newEntries[key]) {
if (newEntries.type != null) {
for (const 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 (const 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', 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 (const 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()
const t0 = performance.now()
sendCompileRequest(options)
.then(function (response) {
const { data } = response
const compileTimeClientE2E = performance.now() - t0
$scope.pdf.view = 'pdf'
$scope.pdf.compiling = false
parseCompileResponse(data, compileTimeClientE2E)
})
.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'
})
.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,
})
}
}
)
App.factory('synctex', function (ide, $http, $q) {
const synctex = {
syncToPdfInFlight: false,
syncToCodeInFlight: false,
syncToPdf(cursorPosition) {
const deferred = $q.defer()
const docId = ide.editorManager.getCurrentDocId()
if (docId == null) {
deferred.reject()
return deferred.promise
}
const doc = ide.fileTreeManager.findEntityById(docId)
if (doc == null) {
deferred.reject()
return deferred.promise
}
let path = ide.fileTreeManager.getEntityPath(doc)
if (path == null) {
deferred.reject()
return deferred.promise
}
// If the root file is folder/main.tex, then synctex sees the
// path as folder/./main.tex
const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
if (rootDocDirname != null && rootDocDirname !== '') {
path = path.replace(RegExp(`^${rootDocDirname}`), `${rootDocDirname}/.`)
}
const { row, column } = cursorPosition
this.syncToPdfInFlight = true
$http({
url: `/project/${ide.project_id}/sync/code`,
method: 'GET',
params: {
file: path,
line: row + 1,
column,
clsiserverid: ide.clsiServerId,
},
})
.then(response => {
this.syncToPdfInFlight = false
const { data } = response
return deferred.resolve(data.pdf || [])
})
.catch(response => {
this.syncToPdfInFlight = false
const error = response.data
return deferred.reject(error)
})
return deferred.promise
},
syncToCode(position, options) {
if (options == null) {
options = {}
}
const deferred = $q.defer()
if (position == null) {
deferred.reject()
return deferred.promise
}
// FIXME: this actually works better if it's halfway across the
// page (or the visible part of the page). Synctex doesn't
// always find the right place in the file when the point is at
// the edge of the page, it sometimes returns the start of the
// next paragraph instead.
const h = position.offset.left
// Compute the vertical position to pass to synctex, which
// works with coordinates increasing from the top of the page
// down. This matches the browser's DOM coordinate of the
// click point, but the pdf position is measured from the
// bottom of the page so we need to invert it.
let v
if (
options.fromPdfPosition &&
(position.pageSize != null ? position.pageSize.height : undefined) !=
null
) {
v = position.pageSize.height - position.offset.top || 0 // measure from pdf point (inverted)
} else {
v = position.offset.top || 0 // measure from html click position
}
// It's not clear exactly where we should sync to if it wasn't directly
// clicked on, but a little bit down from the very top seems best.
if (options.includeVisualOffset) {
v += 72 // use the same value as in pdfViewer highlighting visual offset
}
this.syncToCodeInFlight = true
$http({
url: `/project/${ide.project_id}/sync/pdf`,
method: 'GET',
params: {
page: position.page + 1,
h: h.toFixed(2),
v: v.toFixed(2),
clsiserverid: ide.clsiServerId,
},
})
.then(response => {
this.syncToCodeInFlight = false
const { data } = response
if (
data.code != null &&
data.code.length > 0 &&
data.code[0].file !== ''
) {
const doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
if (doc == null) {
deferred.reject()
}
return deferred.resolve({ doc, line: data.code[0].line })
} else if (data.code[0].file === '') {
ide.$scope.sync_tex_error = true
setTimeout(() => (ide.$scope.sync_tex_error = false), 4000)
}
})
.catch(response => {
this.syncToCodeInFlight = false
const error = response.data
return deferred.reject(error)
})
return deferred.promise
},
}
return synctex
})
App.controller('PdfSynctexController', function ($scope, synctex, ide) {
this.cursorPosition = null
$scope.$watch(
() => synctex.syncToPdfInFlight,
value => ($scope.syncToPdfInFlight = value)
)
$scope.$watch(
() => synctex.syncToCodeInFlight,
value => ($scope.syncToCodeInFlight = value)
)
ide.$scope.$on('cursor:editor:update', (event, cursorPosition) => {
this.cursorPosition = cursorPosition
})
$scope.syncToPdf = () => {
if (this.cursorPosition == null) {
return
}
synctex.syncToPdf(this.cursorPosition).then(highlights => {
$scope.pdf.highlights = highlights
})
}
ide.$scope.$on('cursor:editor:syncToPdf', $scope.syncToPdf)
$scope.syncToCode = function () {
synctex
.syncToCode($scope.pdf.position, {
includeVisualOffset: true,
fromPdfPosition: true,
})
.then(function (data) {
const { doc, line } = data
ide.editorManager.openDoc(doc, { gotoLine: line })
})
}
})
App.controller('ClearCacheModalController', function ($scope, $modalInstance) {
$scope.state = { error: false, inflight: false }
$scope.clear = function () {
$scope.state.inflight = true
$scope
.clearCache()
.then(function () {
$scope.state.inflight = false
$modalInstance.close()
})
.catch(function () {
$scope.state.error = true
$scope.state.inflight = false
})
}
$scope.cancel = () => $modalInstance.dismiss('cancel')
})
// Wrap React component as Angular component. Only needed for "top-level" component
App.component(
'previewPane',
react2angular(
rootContext.use(PreviewPane),
Object.keys(PreviewPane.propTypes)
)
)
| overleaf/web/frontend/js/ide/pdf/controllers/PdfController.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/pdf/controllers/PdfController.js",
"repo_id": "overleaf",
"token_count": 16428
} | 529 |
/* eslint-disable
camelcase,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
// This file is shared between document-updater and web, so that the server and client share
// an identical track changes implementation. Do not edit it directly in web or document-updater,
// instead edit it at https://github.com/sharelatex/ranges-tracker, where it has a suite of tests
let RangesTracker
export default RangesTracker = class RangesTracker {
// The purpose of this class is to track a set of inserts and deletes to a document, like
// track changes in Word. We store these as a set of ShareJs style ranges:
// {i: "foo", p: 42} # Insert 'foo' at offset 42
// {d: "bar", p: 37} # Delete 'bar' at offset 37
// We only track the inserts and deletes, not the whole document, but by being given all
// updates that are applied to a document, we can update these appropriately.
//
// Note that the set of inserts and deletes we store applies to the document as-is at the moment.
// So inserts correspond to text which is in the document, while deletes correspond to text which
// is no longer there, so their lengths do not affect the position of later offsets.
// E.g.
// this is the current text of the document
// |-----| |
// {i: "current ", p:12} -^ ^- {d: "old ", p: 31}
//
// Track changes rules (should be consistent with Word):
// * When text is inserted at a delete, the text goes to the left of the delete
// I.e. "foo|bar" -> "foobaz|bar", where | is the delete, and 'baz' is inserted
// * Deleting content flagged as 'inserted' does not create a new delete marker, it only
// removes the insert marker. E.g.
// * "abdefghijkl" -> "abfghijkl" when 'de' is deleted. No delete marker added
// |---| <- inserted |-| <- inserted
// * Deletes overlapping regular text and inserted text will insert a delete marker for the
// regular text:
// "abcdefghijkl" -> "abcdejkl" when 'fghi' is deleted
// |----| |--||
// ^- inserted 'bcdefg' \ ^- deleted 'hi'
// \--inserted 'bcde'
// * Deletes overlapping other deletes are merged. E.g.
// "abcghijkl" -> "ahijkl" when 'bcg is deleted'
// | <- delete 'def' | <- delete 'bcdefg'
// * Deletes by another user will consume deletes by the first user
// * Inserts by another user will not combine with inserts by the first user. If they are in the
// middle of a previous insert by the first user, the original insert will be split into two.
constructor(changes, comments) {
if (changes == null) {
changes = []
}
this.changes = changes
if (comments == null) {
comments = []
}
this.comments = comments
this.setIdSeed(RangesTracker.generateIdSeed())
this.resetDirtyState()
}
getIdSeed() {
return this.id_seed
}
setIdSeed(seed) {
this.id_seed = seed
return (this.id_increment = 0)
}
static generateIdSeed() {
// Generate a the first 18 characters of Mongo ObjectId, leaving 6 for the increment part
// Reference: https://github.com/dreampulse/ObjectId.js/blob/master/src/main/javascript/Objectid.js
const pid = Math.floor(Math.random() * 32767).toString(16)
const machine = Math.floor(Math.random() * 16777216).toString(16)
const timestamp = Math.floor(new Date().valueOf() / 1000).toString(16)
return (
'00000000'.substr(0, 8 - timestamp.length) +
timestamp +
'000000'.substr(0, 6 - machine.length) +
machine +
'0000'.substr(0, 4 - pid.length) +
pid
)
}
static generateId() {
return this.generateIdSeed() + '000001'
}
newId() {
this.id_increment++
const increment = this.id_increment.toString(16)
const id =
this.id_seed + '000000'.substr(0, 6 - increment.length) + increment
return id
}
getComment(comment_id) {
let comment = null
for (const c of Array.from(this.comments)) {
if (c.id === comment_id) {
comment = c
break
}
}
return comment
}
removeCommentId(comment_id) {
const comment = this.getComment(comment_id)
if (comment == null) {
return
}
this.comments = this.comments.filter(c => c.id !== comment_id)
return this._markAsDirty(comment, 'comment', 'removed')
}
moveCommentId(comment_id, position, text) {
return (() => {
const result = []
for (const comment of Array.from(this.comments)) {
if (comment.id === comment_id) {
comment.op.p = position
comment.op.c = text
result.push(this._markAsDirty(comment, 'comment', 'moved'))
} else {
result.push(undefined)
}
}
return result
})()
}
getChange(change_id) {
let change = null
for (const c of Array.from(this.changes)) {
if (c.id === change_id) {
change = c
break
}
}
return change
}
getChanges(change_ids) {
const changes_response = []
const ids_map = {}
for (const change_id of Array.from(change_ids)) {
ids_map[change_id] = true
}
for (const change of Array.from(this.changes)) {
if (ids_map[change.id]) {
delete ids_map[change.id]
changes_response.push(change)
}
}
return changes_response
}
removeChangeId(change_id) {
const change = this.getChange(change_id)
if (change == null) {
return
}
return this._removeChange(change)
}
removeChangeIds(change_to_remove_ids) {
if (
!(change_to_remove_ids != null
? change_to_remove_ids.length
: undefined) > 0
) {
return
}
const i = this.changes.length
const remove_change_id = {}
for (const change_id of Array.from(change_to_remove_ids)) {
remove_change_id[change_id] = true
}
const remaining_changes = []
for (const change of Array.from(this.changes)) {
if (remove_change_id[change.id]) {
delete remove_change_id[change.id]
this._markAsDirty(change, 'change', 'removed')
} else {
remaining_changes.push(change)
}
}
return (this.changes = remaining_changes)
}
validate(text) {
let content
for (const change of Array.from(this.changes)) {
if (change.op.i != null) {
content = text.slice(change.op.p, change.op.p + change.op.i.length)
if (content !== change.op.i) {
throw new Error(
`Change (${JSON.stringify(
change
)}) doesn't match text (${JSON.stringify(content)})`
)
}
}
}
for (const comment of Array.from(this.comments)) {
content = text.slice(comment.op.p, comment.op.p + comment.op.c.length)
if (content !== comment.op.c) {
throw new Error(
`Comment (${JSON.stringify(
comment
)}) doesn't match text (${JSON.stringify(content)})`
)
}
}
return true
}
applyOp(op, metadata) {
if (metadata == null) {
metadata = {}
}
if (metadata.ts == null) {
metadata.ts = new Date()
}
// Apply an op that has been applied to the document to our changes to keep them up to date
if (op.i != null) {
this.applyInsertToChanges(op, metadata)
return this.applyInsertToComments(op)
} else if (op.d != null) {
this.applyDeleteToChanges(op, metadata)
return this.applyDeleteToComments(op)
} else if (op.c != null) {
return this.addComment(op, metadata)
} else {
throw new Error('unknown op type')
}
}
applyOps(ops, metadata) {
if (metadata == null) {
metadata = {}
}
return Array.from(ops).map(op => this.applyOp(op, metadata))
}
addComment(op, metadata) {
const existing = this.getComment(op.t)
if (existing != null) {
this.moveCommentId(op.t, op.p, op.c)
return existing
} else {
let comment
this.comments.push(
(comment = {
id: op.t || this.newId(),
op: {
// Copy because we'll modify in place
c: op.c,
p: op.p,
t: op.t,
},
metadata,
})
)
this._markAsDirty(comment, 'comment', 'added')
return comment
}
}
applyInsertToComments(op) {
return (() => {
const result = []
for (const comment of Array.from(this.comments)) {
if (op.p <= comment.op.p) {
comment.op.p += op.i.length
result.push(this._markAsDirty(comment, 'comment', 'moved'))
} else if (op.p < comment.op.p + comment.op.c.length) {
const offset = op.p - comment.op.p
comment.op.c =
comment.op.c.slice(0, +(offset - 1) + 1 || undefined) +
op.i +
comment.op.c.slice(offset)
result.push(this._markAsDirty(comment, 'comment', 'moved'))
} else {
result.push(undefined)
}
}
return result
})()
}
applyDeleteToComments(op) {
const op_start = op.p
const op_length = op.d.length
const op_end = op.p + op_length
return (() => {
const result = []
for (const comment of Array.from(this.comments)) {
const comment_start = comment.op.p
const comment_end = comment.op.p + comment.op.c.length
const comment_length = comment_end - comment_start
if (op_end <= comment_start) {
// delete is fully before comment
comment.op.p -= op_length
result.push(this._markAsDirty(comment, 'comment', 'moved'))
} else if (op_start >= comment_end) {
// delete is fully after comment, nothing to do
} else {
// delete and comment overlap
var remaining_after, remaining_before
if (op_start <= comment_start) {
remaining_before = ''
} else {
remaining_before = comment.op.c.slice(0, op_start - comment_start)
}
if (op_end >= comment_end) {
remaining_after = ''
} else {
remaining_after = comment.op.c.slice(op_end - comment_start)
}
// Check deleted content matches delete op
const deleted_comment = comment.op.c.slice(
remaining_before.length,
comment_length - remaining_after.length
)
const offset = Math.max(0, comment_start - op_start)
const deleted_op_content = op.d
.slice(offset)
.slice(0, deleted_comment.length)
if (deleted_comment !== deleted_op_content) {
throw new Error('deleted content does not match comment content')
}
comment.op.p = Math.min(comment_start, op_start)
comment.op.c = remaining_before + remaining_after
result.push(this._markAsDirty(comment, 'comment', 'moved'))
}
}
return result
})()
}
applyInsertToChanges(op, metadata) {
let change
const op_start = op.p
const op_length = op.i.length
const op_end = op.p + op_length
const undoing = !!op.u
let already_merged = false
let previous_change = null
const moved_changes = []
const remove_changes = []
const new_changes = []
for (let i = 0; i < this.changes.length; i++) {
change = this.changes[i]
const change_start = change.op.p
if (change.op.d != null) {
// Shift any deletes after this along by the length of this insert
if (op_start < change_start) {
change.op.p += op_length
moved_changes.push(change)
} else if (op_start === change_start) {
// If we are undoing, then we want to cancel any existing delete ranges if we can.
// Check if the insert matches the start of the delete, and just remove it from the delete instead if so.
if (
undoing &&
change.op.d.length >= op.i.length &&
change.op.d.slice(0, op.i.length) === op.i
) {
change.op.d = change.op.d.slice(op.i.length)
change.op.p += op.i.length
if (change.op.d === '') {
remove_changes.push(change)
} else {
moved_changes.push(change)
}
already_merged = true
} else {
change.op.p += op_length
moved_changes.push(change)
}
}
} else if (change.op.i != null) {
var offset
const change_end = change_start + change.op.i.length
const is_change_overlapping =
op_start >= change_start && op_start <= change_end
// Only merge inserts if they are from the same user
const is_same_user = metadata.user_id === change.metadata.user_id
// If we are undoing, then our changes will be removed from any delete ops just after. In that case, if there is also
// an insert op just before, then we shouldn't append it to this insert, but instead only cancel the following delete.
// E.g.
// foo|<--- about to insert 'b' here
// inserted 'foo' --^ ^-- deleted 'bar'
// should become just 'foo' not 'foob' (with the delete marker becoming just 'ar'), .
const next_change = this.changes[i + 1]
const is_op_adjacent_to_next_delete =
next_change != null &&
next_change.op.d != null &&
op.p === change_end &&
next_change.op.p === op.p
const will_op_cancel_next_delete =
undoing &&
is_op_adjacent_to_next_delete &&
next_change.op.d.slice(0, op.i.length) === op.i
// If there is a delete at the start of the insert, and we're inserting
// at the start, we SHOULDN'T merge since the delete acts as a partition.
// The previous op will be the delete, but it's already been shifted by this insert
//
// I.e.
// Originally: |-- existing insert --|
// | <- existing delete at same offset
//
// Now: |-- existing insert --| <- not shifted yet
// |-- this insert --|| <- existing delete shifted along to end of this op
//
// After: |-- existing insert --|
// |-- this insert --|| <- existing delete
//
// Without the delete, the inserts would be merged.
const is_insert_blocked_by_delete =
previous_change != null &&
previous_change.op.d != null &&
previous_change.op.p === op_end
// If the insert is overlapping another insert, either at the beginning in the middle or touching the end,
// then we merge them into one.
if (
this.track_changes &&
is_change_overlapping &&
!is_insert_blocked_by_delete &&
!already_merged &&
!will_op_cancel_next_delete &&
is_same_user
) {
offset = op_start - change_start
change.op.i =
change.op.i.slice(0, offset) + op.i + change.op.i.slice(offset)
change.metadata.ts = metadata.ts
already_merged = true
moved_changes.push(change)
} else if (op_start <= change_start) {
// If we're fully before the other insert we can just shift the other insert by our length.
// If they are touching, and should have been merged, they will have been above.
// If not merged above, then it must be blocked by a delete, and will be after this insert, so we shift it along as well
change.op.p += op_length
moved_changes.push(change)
} else if (
(!is_same_user || !this.track_changes) &&
change_start < op_start &&
op_start < change_end
) {
// This user is inserting inside a change by another user, so we need to split the
// other user's change into one before and after this one.
offset = op_start - change_start
const before_content = change.op.i.slice(0, offset)
const after_content = change.op.i.slice(offset)
// The existing change can become the 'before' change
change.op.i = before_content
moved_changes.push(change)
// Create a new op afterwards
const after_change = {
op: {
i: after_content,
p: change_start + offset + op_length,
},
metadata: {},
}
for (const key in change.metadata) {
const value = change.metadata[key]
after_change.metadata[key] = value
}
new_changes.push(after_change)
}
}
previous_change = change
}
if (this.track_changes && !already_merged) {
this._addOp(op, metadata)
}
for ({ op, metadata } of Array.from(new_changes)) {
this._addOp(op, metadata)
}
for (change of Array.from(remove_changes)) {
this._removeChange(change)
}
return (() => {
const result = []
for (change of Array.from(moved_changes)) {
result.push(this._markAsDirty(change, 'change', 'moved'))
}
return result
})()
}
applyDeleteToChanges(op, metadata) {
const op_start = op.p
const op_length = op.d.length
const op_end = op.p + op_length
const remove_changes = []
let moved_changes = []
// We might end up modifying our delete op if it merges with existing deletes, or cancels out
// with an existing insert. Since we might do multiple modifications, we record them and do
// all the modifications after looping through the existing changes, so as not to mess up the
// offset indexes as we go.
const op_modifications = []
for (var change of Array.from(this.changes)) {
var change_start
if (change.op.i != null) {
change_start = change.op.p
const change_end = change_start + change.op.i.length
if (op_end <= change_start) {
// Shift ops after us back by our length
change.op.p -= op_length
moved_changes.push(change)
} else if (op_start >= change_end) {
// Delete is after insert, nothing to do
} else {
// When the new delete overlaps an insert, we should remove the part of the insert that
// is now deleted, and also remove the part of the new delete that overlapped. I.e.
// the two cancel out where they overlap.
var delete_remaining_after,
delete_remaining_before,
insert_remaining_after,
insert_remaining_before
if (op_start >= change_start) {
// |-- existing insert --|
// insert_remaining_before -> |.....||-- new delete --|
delete_remaining_before = ''
insert_remaining_before = change.op.i.slice(
0,
op_start - change_start
)
} else {
// delete_remaining_before -> |.....||-- existing insert --|
// |-- new delete --|
delete_remaining_before = op.d.slice(0, change_start - op_start)
insert_remaining_before = ''
}
if (op_end <= change_end) {
// |-- existing insert --|
// |-- new delete --||.....| <- insert_remaining_after
delete_remaining_after = ''
insert_remaining_after = change.op.i.slice(op_end - change_start)
} else {
// |-- existing insert --||.....| <- delete_remaining_after
// |-- new delete --|
delete_remaining_after = op.d.slice(change_end - op_start)
insert_remaining_after = ''
}
const insert_remaining =
insert_remaining_before + insert_remaining_after
if (insert_remaining.length > 0) {
change.op.i = insert_remaining
change.op.p = Math.min(change_start, op_start)
change.metadata.ts = metadata.ts
moved_changes.push(change)
} else {
remove_changes.push(change)
}
// We know what we want to preserve of our delete op before (delete_remaining_before) and what we want to preserve
// afterwards (delete_remaining_before). Now we need to turn that into a modification which deletes the
// chunk in the middle not covered by these.
const delete_removed_length =
op.d.length -
delete_remaining_before.length -
delete_remaining_after.length
const delete_removed_start = delete_remaining_before.length
const modification = {
d: op.d.slice(
delete_removed_start,
delete_removed_start + delete_removed_length
),
p: delete_removed_start,
}
if (modification.d.length > 0) {
op_modifications.push(modification)
}
}
} else if (change.op.d != null) {
change_start = change.op.p
if (
op_end < change_start ||
(!this.track_changes && op_end === change_start)
) {
// Shift ops after us back by our length.
// If we're tracking changes, it must be strictly before, since we'll merge
// below if they are touching. Otherwise, touching is fine.
change.op.p -= op_length
moved_changes.push(change)
} else if (op_start <= change_start && change_start <= op_end) {
if (this.track_changes) {
// If we overlap a delete, add it in our content, and delete the existing change.
// It's easier to do it this way, rather than modifying the existing delete in case
// we overlap many deletes and we'd need to track that. We have a workaround to
// update the delete in place if possible below.
const offset = change_start - op_start
op_modifications.push({ i: change.op.d, p: offset })
remove_changes.push(change)
} else {
change.op.p = op_start
moved_changes.push(change)
}
}
}
}
// Copy rather than modify because we still need to apply it to comments
op = {
p: op.p,
d: this._applyOpModifications(op.d, op_modifications),
}
for (change of Array.from(remove_changes)) {
// This is a bit of hack to avoid removing one delete and replacing it with another.
// If we don't do this, it causes the UI to flicker
if (
op.d.length > 0 &&
change.op.d != null &&
op.p <= change.op.p &&
change.op.p <= op.p + op.d.length
) {
change.op.p = op.p
change.op.d = op.d
change.metadata = metadata
moved_changes.push(change)
op.d = '' // stop it being added
} else {
this._removeChange(change)
}
}
if (this.track_changes && op.d.length > 0) {
this._addOp(op, metadata)
} else {
// It's possible that we deleted an insert between two other inserts. I.e.
// If we delete 'user_2 insert' in:
// |-- user_1 insert --||-- user_2 insert --||-- user_1 insert --|
// it becomes:
// |-- user_1 insert --||-- user_1 insert --|
// We need to merge these together again
const results = this._scanAndMergeAdjacentUpdates()
moved_changes = moved_changes.concat(results.moved_changes)
for (change of Array.from(results.remove_changes)) {
this._removeChange(change)
moved_changes = moved_changes.filter(c => c !== change)
}
}
return (() => {
const result = []
for (change of Array.from(moved_changes)) {
result.push(this._markAsDirty(change, 'change', 'moved'))
}
return result
})()
}
_addOp(op, metadata) {
const change = {
id: this.newId(),
op: this._clone(op), // Don't take a reference to the existing op since we'll modify this in place with future changes
metadata: this._clone(metadata),
}
this.changes.push(change)
// Keep ops in order of offset, with deletes before inserts
this.changes.sort(function (c1, c2) {
const result = c1.op.p - c2.op.p
if (result !== 0) {
return result
} else if (c1.op.i != null && c2.op.d != null) {
return 1
} else if (c1.op.d != null && c2.op.i != null) {
return -1
} else {
return 0
}
})
return this._markAsDirty(change, 'change', 'added')
}
_removeChange(change) {
this.changes = this.changes.filter(c => c.id !== change.id)
return this._markAsDirty(change, 'change', 'removed')
}
_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) {
const result = b.p - a.p
if (result !== 0) {
return result
} else if (a.i != null && b.d != null) {
return 1
} else if (a.d != null && b.i != null) {
return -1
} else {
return 0
}
})
for (const modification of Array.from(op_modifications)) {
if (modification.i != null) {
content =
content.slice(0, modification.p) +
modification.i +
content.slice(modification.p)
} else if (modification.d != null) {
if (
content.slice(
modification.p,
modification.p + modification.d.length
) !== modification.d
) {
throw new Error(
`deleted content does not match. content: ${JSON.stringify(
content
)}; modification: ${JSON.stringify(modification)}`
)
}
content =
content.slice(0, modification.p) +
content.slice(modification.p + modification.d.length)
}
}
return content
}
_scanAndMergeAdjacentUpdates() {
// This should only need calling when deleting an update between two
// other updates. There's no other way to get two adjacent updates from the
// same user, since they would be merged on insert.
let previous_change = null
const remove_changes = []
const moved_changes = []
for (const change of Array.from(this.changes)) {
if (
(previous_change != null ? previous_change.op.i : undefined) != null &&
change.op.i != null
) {
const previous_change_end =
previous_change.op.p + previous_change.op.i.length
const previous_change_user_id = previous_change.metadata.user_id
const change_start = change.op.p
const change_user_id = change.metadata.user_id
if (
previous_change_end === change_start &&
previous_change_user_id === change_user_id
) {
remove_changes.push(change)
previous_change.op.i += change.op.i
moved_changes.push(previous_change)
}
} else if (
(previous_change != null ? previous_change.op.d : undefined) != null &&
change.op.d != null &&
previous_change.op.p === change.op.p
) {
// Merge adjacent deletes
previous_change.op.d += change.op.d
remove_changes.push(change)
moved_changes.push(previous_change)
} else {
// Only update to the current change if we haven't removed it.
previous_change = change
}
}
return { moved_changes, remove_changes }
}
resetDirtyState() {
return (this._dirtyState = {
comment: {
moved: {},
removed: {},
added: {},
},
change: {
moved: {},
removed: {},
added: {},
},
})
}
getDirtyState() {
return this._dirtyState
}
_markAsDirty(object, type, action) {
return (this._dirtyState[type][action][object.id] = object)
}
_clone(object) {
const clone = {}
for (const k in object) {
const v = object[k]
clone[k] = v
}
return clone
}
}
| overleaf/web/frontend/js/ide/review-panel/RangesTracker.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/review-panel/RangesTracker.js",
"repo_id": "overleaf",
"token_count": 12507
} | 530 |
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
export default App.filter(
'numKeys',
() =>
function (object) {
if (object != null) {
return Object.keys(object).length
} else {
return 0
}
}
)
| overleaf/web/frontend/js/ide/review-panel/filters/numKeys.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/review-panel/filters/numKeys.js",
"repo_id": "overleaf",
"token_count": 193
} | 531 |
import 'jquery'
import 'angular'
import 'angular-sanitize'
import 'lodash'
import 'libs/angular-autocomplete/angular-autocomplete'
import 'libs/ui-bootstrap'
import 'libs/ng-context-menu-0.1.4'
import 'libs/jquery.storage'
import 'libs/angular-cookie'
import 'libs/passfield'
import 'libs/select/select'
// CSS
import 'angular/angular-csp.css'
// Polyfill fetch for IE11
import 'isomorphic-unfetch'
// Rewrite meta elements
import './utils/meta'
| overleaf/web/frontend/js/libraries.js/0 | {
"file_path": "overleaf/web/frontend/js/libraries.js",
"repo_id": "overleaf",
"token_count": 164
} | 532 |
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../base'
export default App.constant('Keys', {
ENTER: 13,
TAB: 9,
ESCAPE: 27,
SPACE: 32,
BACKSPACE: 8,
UP: 38,
DOWN: 40,
LEFT: 37,
RIGHT: 39,
PERIOD: 190,
COMMA: 188,
END: 35,
})
| overleaf/web/frontend/js/main/keys.js/0 | {
"file_path": "overleaf/web/frontend/js/main/keys.js",
"repo_id": "overleaf",
"token_count": 185
} | 533 |
/* eslint-disable
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../base'
import getMeta from '../../utils/meta'
export default App.controller('TeamInviteController', function ($scope, $http) {
$scope.inflight = false
const hasIndividualRecurlySubscription = getMeta(
'ol-hasIndividualRecurlySubscription'
)
if (hasIndividualRecurlySubscription) {
$scope.view = 'hasIndividualRecurlySubscription'
} else {
$scope.view = 'teamInvite'
}
$scope.keepPersonalSubscription = () => ($scope.view = 'teamInvite')
$scope.cancelPersonalSubscription = function () {
$scope.inflight = true
const request = $http.post('/user/subscription/cancel', {
_csrf: window.csrfToken,
})
request.then(function () {
$scope.inflight = false
return ($scope.view = 'teamInvite')
})
return request.catch(() => {
$scope.inflight = false
$scope.cancel_error = true
console.log('the request failed')
})
}
return ($scope.joinTeam = function () {
$scope.inflight = true
const inviteToken = getMeta('ol-inviteToken')
const request = $http.put(`/subscription/invites/${inviteToken}/`, {
_csrf: window.csrfToken,
})
request.then(function (response) {
const { status } = response
$scope.inflight = false
$scope.view = 'inviteAccepted'
if (status !== 200) {
// assume request worked
return ($scope.requestSent = false)
}
})
return request.catch(() => console.log('the request failed'))
})
})
| overleaf/web/frontend/js/main/subscription/team-invite-controller.js/0 | {
"file_path": "overleaf/web/frontend/js/main/subscription/team-invite-controller.js",
"repo_id": "overleaf",
"token_count": 669
} | 534 |
import { useCallback } from 'react'
import PropTypes from 'prop-types'
import { Modal } from 'react-bootstrap'
// a bootstrap Modal with its `aria-hidden` attribute removed. Visisble modals
// should not have their `aria-hidden` attribute set but that's a bug in our
// version of react-bootstrap.
function AccessibleModal({ show, ...otherProps }) {
// use a callback ref to track the modal. This will re-run the function
// when the element node or any of the dependencies are updated
const setModalRef = useCallback(
element => {
if (!element) return
const modalNode = element._modal && element._modal.modalNode
if (!modalNode) return
if (show) {
modalNode.removeAttribute('aria-hidden')
} else {
modalNode.setAttribute('aria-hidden', 'true')
}
},
// `show` is necessary as a dependency, but eslint thinks it is not
// eslint-disable-next-line react-hooks/exhaustive-deps
[show]
)
return <Modal show={show} {...otherProps} ref={setModalRef} />
}
AccessibleModal.propTypes = {
show: PropTypes.bool,
}
export default AccessibleModal
| overleaf/web/frontend/js/shared/components/accessible-modal.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/components/accessible-modal.js",
"repo_id": "overleaf",
"token_count": 386
} | 535 |
import { createContext, useContext } from 'react'
import PropTypes from 'prop-types'
import useScopeValue from './util/scope-value-hook'
export const UserContext = createContext()
UserContext.Provider.propTypes = {
value: PropTypes.shape({
user: PropTypes.shape({
id: PropTypes.string,
allowedFreeTrial: PropTypes.boolean,
first_name: PropTypes.string,
last_name: PropTypes.string,
}),
}),
}
export function UserProvider({ children }) {
const [user] = useScopeValue('user', true)
return <UserContext.Provider value={user}>{children}</UserContext.Provider>
}
UserProvider.propTypes = {
children: PropTypes.any,
}
export function useUserContext(propTypes) {
const data = useContext(UserContext)
PropTypes.checkPropTypes(propTypes, data, 'data', 'UserContext.Provider')
return data
}
| overleaf/web/frontend/js/shared/context/user-context.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/context/user-context.js",
"repo_id": "overleaf",
"token_count": 273
} | 536 |
/* --- Made by justgoscha and licensed under MIT license --- */
var app = angular.module('autocomplete', []);
app.directive('autocomplete', function() {
var index = -1;
return {
restrict: 'E',
scope: {
searchParam: '=ngModel',
suggestions: '=data',
onType: '=onType',
onSelect: '=onSelect'
},
controller: ['$scope', function($scope){
// the index of the suggestions that's currently selected
$scope.selectedIndex = -1;
// set new index
$scope.setIndex = function(i){
$scope.selectedIndex = parseInt(i);
};
this.setIndex = function(i){
$scope.setIndex(i);
$scope.$apply();
};
$scope.getIndex = function(i){
return $scope.selectedIndex;
};
// watches if the parameter filter should be changed
var watching = true;
// autocompleting drop down on/off
$scope.completing = false;
// starts autocompleting on typing in something
$scope.$watch('searchParam', function(newValue, oldValue){
if (oldValue === newValue) {
return;
}
if(watching && $scope.searchParam) {
$scope.completing = true;
$scope.searchFilter = $scope.searchParam;
$scope.selectedIndex = -1;
}
// function thats passed to on-type attribute gets executed
if($scope.onType)
$scope.onType($scope.searchParam);
});
// for hovering over suggestions
this.preSelect = function(suggestion){
watching = false;
// this line determines if it is shown
// in the input field before it's selected:
//$scope.searchParam = suggestion;
$scope.$apply();
watching = true;
};
$scope.preSelect = this.preSelect;
this.preSelectOff = function(){
watching = true;
};
$scope.preSelectOff = this.preSelectOff;
// selecting a suggestion with RIGHT ARROW or ENTER
$scope.select = function(suggestion){
if(suggestion){
$scope.searchParam = suggestion;
$scope.searchFilter = suggestion;
if($scope.onSelect)
$scope.onSelect(suggestion);
}
watching = false;
$scope.completing = false;
setTimeout(function(){watching = true;},1000);
$scope.setIndex(-1);
};
}],
link: function(scope, element, attrs){
var attr = '';
// Default atts
scope.attrs = {
"placeholder": "start typing...",
"class": "",
"id": "",
"inputclass": "",
"inputid": ""
};
for (var a in attrs) {
attr = a.replace('attr', '').toLowerCase();
// add attribute overriding defaults
// and preventing duplication
if (a.indexOf('attr') === 0) {
scope.attrs[attr] = attrs[a];
}
}
if (attrs.clickActivation) {
element[0].onclick = function(e){
if(!scope.searchParam){
scope.completing = true;
scope.$apply();
}
};
}
var key = {left: 37, up: 38, right: 39, down: 40 , enter: 13, esc: 27};
document.addEventListener("keydown", function(e){
var keycode = e.keyCode || e.which;
switch (keycode){
case key.esc:
// disable suggestions on escape
scope.select();
scope.setIndex(-1);
scope.$apply();
e.preventDefault();
}
}, true);
document.addEventListener("blur", function(e){
// disable suggestions on blur
// we do a timeout to prevent hiding it before a click event is registered
setTimeout(function() {
scope.select();
scope.setIndex(-1);
scope.$apply();
}, 200);
}, true);
element[0].addEventListener("keydown",function (e){
var keycode = e.keyCode || e.which;
var l = angular.element(this).find('li').length;
// implementation of the up and down movement in the list of suggestions
switch (keycode){
case key.up:
index = scope.getIndex()-1;
if(index<-1){
index = l-1;
} else if (index >= l ){
index = -1;
scope.setIndex(index);
scope.preSelectOff();
break;
}
scope.setIndex(index);
if(index!==-1)
scope.preSelect(angular.element(angular.element(this).find('li')[index]).text());
scope.$apply();
break;
case key.down:
index = scope.getIndex()+1;
if(index<-1){
index = l-1;
} else if (index >= l ){
index = -1;
scope.setIndex(index);
scope.preSelectOff();
scope.$apply();
break;
}
scope.setIndex(index);
if(index!==-1)
scope.preSelect(angular.element(angular.element(this).find('li')[index]).text());
break;
case key.left:
break;
case key.right:
case key.enter:
index = scope.getIndex();
// scope.preSelectOff();
if(index !== -1)
scope.select(angular.element(angular.element(this).find('li')[index]).text());
scope.setIndex(-1);
scope.$apply();
break;
case key.esc:
// disable suggestions on escape
scope.select();
scope.setIndex(-1);
scope.$apply();
e.preventDefault();
break;
default:
return;
}
if(scope.getIndex()!==-1 || keycode == key.enter)
e.preventDefault();
});
},
templateUrl: 'js/libs/angular-autocomplete/ac_template.html'
};
});
app.filter('highlight', ['$sce', function ($sce) {
return function (input, searchParam) {
if (typeof input === 'function') return '';
if (searchParam) {
var words = '(' +
searchParam.split(/\ /).join(' |') + '|' +
searchParam.split(/\ /).join('|') +
')',
exp = new RegExp(words, 'gi');
if (words.length) {
input = input.replace(exp, "<span class=\"highlight\">$1</span>");
}
}
return $sce.trustAsHtml(input);
};
}]);
app.directive('suggestion', function(){
return {
restrict: 'A',
require: '^autocomplete', // ^look for controller on parents element
link: function(scope, element, attrs, autoCtrl){
element.bind('mouseenter', function() {
autoCtrl.preSelect(attrs.val);
autoCtrl.setIndex(attrs.index);
});
element.bind('mouseleave', function() {
autoCtrl.preSelectOff();
});
}
};
});
| overleaf/web/frontend/js/vendor/libs/angular-autocomplete/angular-autocomplete.js/0 | {
"file_path": "overleaf/web/frontend/js/vendor/libs/angular-autocomplete/angular-autocomplete.js",
"repo_id": "overleaf",
"token_count": 3231
} | 537 |
From 9826c6eb1ecd501ac3eb1e9d9a98a3e6edde3fd0 Mon Sep 17 00:00:00 2001
From: Jakob Ackermann <jakob.ackermann@overleaf.com>
Date: Mon, 5 Jul 2021 16:23:18 +0100
Subject: [PATCH] [misc] fix handling of fetch errors (backport)
Testing:
- delete the pdf file while the initial request is inflight
- delete the pdf file after the initial request has finished
---
src/core/chunked_stream.js | 8 +++-----
src/display/fetch_stream.js | 2 +-
2 files changed, 4 insertions(+), 6 deletions(-)
diff --git a/src/core/chunked_stream.js b/src/core/chunked_stream.js
index 26a93f673..ab39037c1 100644
--- a/src/core/chunked_stream.js
+++ b/src/core/chunked_stream.js
@@ -307,7 +307,7 @@ class ChunkedStreamManager {
}
let chunks = [], loaded = 0;
- const promise = new Promise((resolve, reject) => {
+ return new Promise((resolve, reject) => {
const readChunk = (chunk) => {
try {
if (!chunk.done) {
@@ -328,14 +328,12 @@ class ChunkedStreamManager {
}
};
rangeReader.read().then(readChunk, reject);
- });
- promise.then((data) => {
+ }).then((data) => {
if (this.aborted) {
return; // Ignoring any data after abort.
}
this.onReceiveData({ chunk: data, begin, });
});
- // TODO check errors
}
/**
@@ -384,7 +382,7 @@ class ChunkedStreamManager {
for (const groupedChunk of groupedChunksToRequest) {
const begin = groupedChunk.beginChunk * this.chunkSize;
const end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
- this.sendRequest(begin, end);
+ this.sendRequest(begin, end).catch(capability.reject);
}
return capability.promise;
diff --git a/src/display/fetch_stream.js b/src/display/fetch_stream.js
index f70ed1d54..e736c9494 100644
--- a/src/display/fetch_stream.js
+++ b/src/display/fetch_stream.js
@@ -222,7 +222,7 @@ class PDFFetchStreamRangeReader {
}
this._readCapability.resolve();
this._reader = response.body.getReader();
- });
+ }).catch(this._readCapability.reject);
this.onProgress = null;
}
--
2.17.1
| overleaf/web/frontend/js/vendor/libs/pdfjs-dist/patches/0001-misc-fix-handling-of-fetch-errors-backport.patch/0 | {
"file_path": "overleaf/web/frontend/js/vendor/libs/pdfjs-dist/patches/0001-misc-fix-handling-of-fetch-errors-backport.patch",
"repo_id": "overleaf",
"token_count": 885
} | 538 |
import MockedSocket from 'socket.io-mock'
import { ContextRoot } from '../js/shared/context/root-context'
import { rootFolderBase } from './fixtures/file-tree-base'
import { rootFolderLimit } from './fixtures/file-tree-limit'
import FileTreeRoot from '../js/features/file-tree/components/file-tree-root'
import FileTreeError from '../js/features/file-tree/components/file-tree-error'
import useFetchMock from './hooks/use-fetch-mock'
const MOCK_DELAY = 2000
window._ide = {
socket: new MockedSocket(),
}
function defaultSetupMocks(fetchMock) {
fetchMock
.post(
/\/project\/\w+\/(file|doc|folder)\/\w+\/rename/,
(path, req) => {
const body = JSON.parse(req.body)
const entityId = path.match(/([^/]+)\/rename$/)[1]
window._ide.socket.socketClient.emit(
'reciveEntityRename',
entityId,
body.name
)
return 204
},
{
delay: MOCK_DELAY,
}
)
.post(
/\/project\/\w+\/folder/,
(_path, req) => {
const body = JSON.parse(req.body)
const newFolder = {
folders: [],
fileRefs: [],
docs: [],
_id: Math.random().toString(16).replace(/0\./, 'random-test-id-'),
name: body.name,
}
window._ide.socket.socketClient.emit(
'reciveNewFolder',
body.parent_folder_id,
newFolder
)
return newFolder
},
{
delay: MOCK_DELAY,
}
)
.delete(
/\/project\/\w+\/(file|doc|folder)\/\w+/,
path => {
const entityId = path.match(/[^/]+$/)[0]
window._ide.socket.socketClient.emit('removeEntity', entityId)
return 204
},
{
delay: MOCK_DELAY,
}
)
.post(/\/project\/\w+\/(file|doc|folder)\/\w+\/move/, (path, req) => {
const body = JSON.parse(req.body)
const entityId = path.match(/([^/]+)\/move/)[1]
window._ide.socket.socketClient.emit(
'reciveEntityMove',
entityId,
body.folder_id
)
return 204
})
}
export const FullTree = args => {
useFetchMock(defaultSetupMocks)
return <FileTreeRoot {...args} />
}
export const ReadOnly = args => <FileTreeRoot {...args} />
ReadOnly.args = { hasWritePermissions: false }
export const Disconnected = args => <FileTreeRoot {...args} />
Disconnected.args = { isConnected: false }
export const NetworkErrors = args => {
useFetchMock(fetchMock => {
fetchMock
.post(/\/project\/\w+\/folder/, 500, {
delay: MOCK_DELAY,
})
.post(/\/project\/\w+\/(file|doc|folder)\/\w+\/rename/, 500, {
delay: MOCK_DELAY,
})
.post(/\/project\/\w+\/(file|doc|folder)\/\w+\/move/, 500, {
delay: MOCK_DELAY,
})
.delete(/\/project\/\w+\/(file|doc|folder)\/\w+/, 500, {
delay: MOCK_DELAY,
})
})
return <FileTreeRoot {...args} />
}
export const FallbackError = args => <FileTreeError {...args} />
export const FilesLimit = args => {
useFetchMock(defaultSetupMocks)
return <FileTreeRoot {...args} />
}
FilesLimit.args = { rootFolder: rootFolderLimit }
export default {
title: 'File Tree',
component: FileTreeRoot,
args: {
rootFolder: rootFolderBase,
hasWritePermissions: true,
setStartedFreeTrial: () => {
console.log('started free trial')
},
refProviders: {},
reindexReferences: () => {
console.log('reindex references')
},
userHasFeature: () => true,
setRefProviderEnabled: provider => {
console.log(`ref provider ${provider} enabled`)
},
projectId: '123abc',
rootDocId: '5e74f1a7ce17ae0041dfd056',
isConnected: true,
},
argTypes: {
onInit: { action: 'onInit' },
onSelect: { action: 'onSelect' },
},
decorators: [
Story => (
<>
<style>{'html, body, .file-tree { height: 100%; width: 100%; }'}</style>
<div className="editor-sidebar full-size">
<div className="file-tree">
<ContextRoot ide={window._ide} settings={{}}>
<Story />
</ContextRoot>
</div>
</div>
</>
),
],
}
| overleaf/web/frontend/stories/file-tree.stories.js/0 | {
"file_path": "overleaf/web/frontend/stories/file-tree.stories.js",
"repo_id": "overleaf",
"token_count": 1915
} | 539 |
import OutlinePane from '../js/features/outline/components/outline-pane'
import { ContextRoot } from '../js/shared/context/root-context'
import { setupContext } from './fixtures/context'
setupContext()
export const Basic = args => <OutlinePane {...args} />
Basic.args = {
outline: [{ line: 1, title: 'Hello', level: 1 }],
}
export const Nested = args => <OutlinePane {...args} />
Nested.args = {
outline: [
{
line: 1,
title: 'Section',
level: 1,
children: [
{
line: 2,
title: 'Subsection',
level: 2,
children: [
{
line: 3,
title: 'Subsubsection',
level: 3,
},
],
},
],
},
],
}
export const NoSections = args => <OutlinePane {...args} />
NoSections.args = {}
export const NonTexFile = args => <OutlinePane {...args} />
NonTexFile.args = {
isTexFile: false,
}
export default {
title: 'Outline',
component: OutlinePane,
argTypes: {
jumpToLine: { action: 'jumpToLine' },
},
args: {
eventTracking: { sendMB: () => {} },
isTexFile: true,
outline: [],
jumpToLine: () => {},
onToggle: () => {},
},
decorators: [
Story => (
<ContextRoot ide={window._ide} settings={{}}>
<Story />
</ContextRoot>
),
],
}
| overleaf/web/frontend/stories/outline.stories.js/0 | {
"file_path": "overleaf/web/frontend/stories/outline.stories.js",
"repo_id": "overleaf",
"token_count": 617
} | 540 |
.circle(@size, @background_color) {
display: inline-block;
background-color: @background_color;
border-radius: 50%;
width: @size;
height: @size;
text-align: center;
padding-top: @size / 6.4;
img {
height: @size - @size / 3.2;
}
}
.hub-header {
h2 {
display: inline-block;
}
a {
color: @ol-dark-green;
}
i {
font-size: 30px;
}
.dropdown {
margin-right: 10px;
}
}
.admin-item {
position: relative;
margin-bottom: 60px;
.section-title {
text-transform: capitalize;
}
.alert-danger {
color: @ol-red;
}
}
.hidden-chart-section {
display: none;
}
.hub-circle {
.circle(160px, @accent-color-secondary);
padding-top: 50px;
color: white;
}
.hub-circle-number {
display: block;
font-size: 36px;
font-weight: 900;
line-height: 1;
}
.hub-big-number {
float: left;
font-size: 32px;
font-weight: 900;
line-height: 40px;
color: @accent-color-secondary;
}
.hub-big-number,
.hub-number-label {
display: block;
}
.hub-metric-link {
position: absolute;
top: 9px;
right: 0;
a {
color: @accent-color-secondary;
}
i {
margin-right: 5px;
}
}
.custom-donut-container {
svg {
max-width: 700px;
margin: auto;
}
.chart-center-text {
font-family: @font-family-sans-serif;
font-size: 40px;
font-weight: bold;
fill: @accent-color-secondary;
text-anchor: middle;
}
.nv-legend-text {
font-family: @font-family-sans-serif;
font-size: 14px;
}
}
.chart-no-center-text {
.chart-center-text {
display: none;
}
}
.superscript {
font-size: @font-size-large;
}
| overleaf/web/frontend/stylesheets/app/admin-hub.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/admin-hub.less",
"repo_id": "overleaf",
"token_count": 704
} | 541 |
#left-menu {
position: absolute;
width: @left-menu-width;
padding: (@line-height-computed / 2);
top: 0;
bottom: 0;
background-color: #f4f4f4;
z-index: 100;
overflow-y: auto;
overflow-x: hidden;
-webkit-transition: left ease-in-out @left-menu-animation-duration;
transition: left ease-in-out @left-menu-animation-duration;
font-size: 14px;
left: -280px;
&.shown {
left: 0;
}
h4 {
font-family: @font-family-sans-serif;
font-weight: 400;
font-size: 1rem;
margin: (@line-height-computed / 2) 0;
padding-bottom: (@line-height-computed / 4);
color: @gray-light;
border-bottom: 1px solid @gray-lighter;
}
> h4:first-child {
margin-top: 0;
}
ul.nav {
a {
cursor: pointer;
&:hover,
&:active,
&:focus {
background-color: @link-color;
color: white;
i {
color: white;
}
}
i {
color: @gray;
}
padding: (@line-height-computed / 4);
font-weight: 700;
}
.link-disabled {
color: @gray-light;
}
}
> ul.nav:last-child {
margin-bottom: @line-height-computed / 2;
}
ul.nav-downloads {
li {
display: inline-block;
text-align: center;
width: 100px;
a {
color: @gray-dark;
}
i {
margin: (@line-height-computed / 4) 0;
}
}
}
form.settings {
label {
font-weight: normal;
color: @gray-dark;
flex: 1 0 50%;
margin-bottom: 0;
margin-top: 9px;
padding-right: 5px;
white-space: nowrap;
}
select {
width: 50%;
margin: 9px 0;
}
.form-controls {
clear: both;
padding: 0 9px;
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: flex-end;
border-bottom: solid 1px rgba(0, 0, 0, 0.07);
&:first-child {
margin-top: -9px;
}
&:last-child {
border-bottom: 0;
}
&:hover {
background-color: @link-color;
// select.form-control {
// color: white;
// }
label,
i.fa {
color: white;
}
}
&:after {
content: '';
display: table;
clear: both;
}
}
}
}
#left-menu-mask {
.full-size;
opacity: 0.4;
background-color: #999;
z-index: 99;
}
| overleaf/web/frontend/stylesheets/app/editor/left-menu.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/editor/left-menu.less",
"repo_id": "overleaf",
"token_count": 1208
} | 542 |
@register-v-spacing: 20px;
.deprecated-sl-masthead {
display: inline-block;
margin-top: @header-height;
width: 100%;
text-align: center;
h1 {
font-size: 3.3rem;
line-height: 5rem;
margin-bottom: 0;
margin-top: @line-height-computed;
}
.img {
max-width: 420px;
background-image: url('/img/ol_plus_sl.png');
background-size: 100%;
background-repeat: no-repeat;
margin: 20px auto 0;
height: 197px;
}
}
.deprecated-sl-login-buttons {
margin: 35px 0;
}
.deprecated-sl-msg {
width: 80%;
margin: 35px auto 0;
}
.deprecated-sl-long-cta {
padding-top: 12.5px;
padding-bottom: 93px;
.card {
margin-top: 12.5px;
min-height: 397px;
}
h3 {
margin-top: 0;
}
}
.masthead {
background-image: -webkit-linear-gradient(
to left,
rgba(79, 156, 69, 1),
rgba(28, 91, 38, 1)
);
background-image: linear-gradient(
to left,
rgba(79, 156, 69, 1),
rgba(28, 91, 38, 1)
);
position: relative;
text-align: center;
overflow: hidden;
padding-top: @header-height;
h1,
p,
label {
color: white;
text-align: center;
}
h1 {
font-size: 4.75rem;
line-height: 6.25rem;
margin-bottom: 0;
margin-top: @line-height-computed;
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.42);
span {
font-family: @font-family-sans-serif;
font-weight: 100;
letter-spacing: 5px;
}
}
p:first-of-type {
font-size: @line-height-computed;
font-weight: 200;
margin-top: 0;
text-rendering: auto;
margin-bottom: @line-height-computed;
}
label {
display: block;
}
.register-banner {
background-image: -webkit-linear-gradient(
top,
rgba(0, 0, 0, 0.7),
rgba(0, 0, 0, 0.9)
);
background-image: linear-gradient(
to bottom,
rgba(0, 0, 0, 0.7),
rgba(0, 0, 0, 0.9)
);
padding: @register-v-spacing 0;
position: absolute;
bottom: 0;
width: 100%;
h2 {
color: white;
margin-top: 0;
font-family: @font-family-sans-serif;
font-weight: 500;
letter-spacing: 1px;
margin-bottom: @register-v-spacing;
}
.form-group {
margin-left: @line-height-computed / 2;
}
.input-lg {
border-radius: 9999px;
}
}
.hp-register-password-error {
margin-bottom: 9px;
}
.register-banner__password-error {
padding: 5px 9px;
border: none;
border-radius: @btn-border-radius-base;
}
.screenshot {
height: 600px;
margin: auto;
margin-bottom: -50px;
overflow-y: hidden;
box-shadow: 0 0 50px rgba(0, 0, 0, 0.67);
max-width: 960px;
.img {
max-width: 960px;
background-image: url('/img/homepage.png');
background-size: 100%;
background-repeat: no-repeat;
margin: auto;
height: 672px;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min--moz-device-pixel-ratio: 2),
only screen and (-o-min-device-pixel-ratio: 2/1),
only screen and (min-device-pixel-ratio: 2),
only screen and (min-resolution: 192dpi),
only screen and (min-resolution: 2dppx) {
.img {
background-image: url('/img/homepage@2x.png');
}
}
}
}
.hp-register-external-separator {
margin: 0 0 (@register-v-spacing / 2);
color: #fff;
}
.hp-register-external-separator-or {
vertical-align: middle;
&::before,
&::after {
content: '';
display: inline-block;
vertical-align: middle;
width: 5em;
height: 1px;
background-color: rgba(255, 255, 255, 0.3);
}
&::before {
margin-right: 1.25em;
}
&::after {
margin-left: 1.25em;
}
}
.hp-register-newsletter-checkbox {
font-size: 90%;
& > .checkbox-newsletter {
text-align: left;
@media only screen and (min-width: @screen-sm-min) {
text-align: center;
}
}
}
.hp-login-btn {
.login-btn;
min-width: 220px;
background-color: @ol-blue-gray-3;
&:hover,
&:focus,
&:active {
background-color: darken(@ol-blue-gray-3, 8%);
}
}
.hp-register-form-email-pwd {
position: relative;
}
.hp-register-form-email-pwd-btn-container.form-group {
display: block;
margin-top: (@register-v-spacing / 2);
@media only screen and (min-width: @screen-md-min) {
position: absolute;
display: inline-block;
height: 100%;
top: -(@register-v-spacing / 2);
& > .btn-hero {
height: 100%;
}
}
}
.universities-container {
border-bottom: 1px solid @gray-lighter;
}
.universities {
text-align: center;
.uni-logo {
display: inline-block;
padding: 0 @padding-md;
width: 20%;
}
}
.pattern-container {
background: url('/img/pattern-home.png') repeat #f1f1f1;
border-top: 1px solid @gray-lightest;
border-bottom: 1px solid @gray-lightest;
}
.pattern-grid {
background: url('/img/grid.png') repeat @content-alt-bg-color;
border-top: 1px solid @gray-lighter;
border-bottom: 1px solid @gray-lighter;
}
.real-time-example {
.cursor {
background-color: hsl(200, 70%, 70%);
display: inline-block;
width: 2px;
color: transparent;
line-height: 1.4;
position: relative;
&:after {
content: 'Joe';
top: 22px;
right: 0;
position: absolute;
display: block;
background-color: hsl(200, 70%, 70%);
padding: (@line-height-computed / 4) (@line-height-computed / 2);
font-size: 0.8rem;
z-index: 100;
font-family: @font-family-sans-serif;
color: white;
font-weight: 700;
}
}
}
.track-changes-example {
.removed,
.added {
color: #333;
margin: 0 -1px;
padding: 0 3px;
}
.added {
background-color: hsl(200, 70%, 80%);
}
.removed {
background-color: hsl(200, 70%, 95%);
position: relative;
&:after {
content: ' ';
position: absolute;
top: 50%;
left: 0;
right: 0;
border-top: 1px solid hsl(200, 70%, 40%);
}
}
}
.real-time-example-code {
border-radius: 3px;
border-left: 42px solid @gray-lighter;
background-color: white;
padding: 12px;
font-family: @font-family-monospace;
.highlight {
color: @blue;
}
box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3);
}
@media only screen and (max-width: @screen-sm-max) {
.doc-history-example {
margin-bottom: @margin-md;
}
.universities {
.uni-logo {
padding: @padding-md;
width: 50%;
}
}
}
| overleaf/web/frontend/stylesheets/app/homepage.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/homepage.less",
"repo_id": "overleaf",
"token_count": 2910
} | 543 |
.registration_message {
text-align: center;
padding-bottom: 20px;
}
| overleaf/web/frontend/stylesheets/app/register.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/register.less",
"repo_id": "overleaf",
"token_count": 26
} | 544 |
//
// Carousel
// --------------------------------------------------
// Wrapper for the slide container and indicators
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
overflow: hidden;
width: 100%;
> .item {
display: none;
position: relative;
.transition(0.6s ease-in-out left);
// Account for jankitude on images
> img,
> a > img {
&:extend(.img-responsive);
line-height: 1;
}
}
> .active,
> .next,
> .prev {
display: block;
}
> .active {
left: 0;
}
> .next,
> .prev {
position: absolute;
top: 0;
width: 100%;
}
> .next {
left: 100%;
}
> .prev {
left: -100%;
}
> .next.left,
> .prev.right {
left: 0;
}
> .active.left {
left: -100%;
}
> .active.right {
left: 100%;
}
}
// Left/right controls for nav
// ---------------------------
.carousel-control {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: @carousel-control-width;
.opacity(@carousel-control-opacity);
font-size: @carousel-control-font-size;
color: @carousel-control-color;
text-align: center;
text-shadow: @carousel-text-shadow;
// We can't have this transition here because WebKit cancels the carousel
// animation if you trip this while in the middle of another animation.
// 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)
);
}
&.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)
);
}
// Hover/focus state
&:hover,
&:focus {
outline: none;
color: @carousel-control-color;
text-decoration: none;
.opacity(0.9);
}
// Toggles
.icon-prev,
.icon-next,
.glyphicon-chevron-left,
.glyphicon-chevron-right {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
}
.icon-prev,
.glyphicon-chevron-left {
left: 50%;
}
.icon-next,
.glyphicon-chevron-right {
right: 50%;
}
.icon-prev,
.icon-next {
width: 20px;
height: 20px;
margin-top: -10px;
margin-left: -10px;
font-family: serif;
}
.icon-prev {
&:before {
content: '\2039'; // SINGLE LEFT-POINTING ANGLE QUOTATION MARK (U+2039)
}
}
.icon-next {
&:before {
content: '\203a'; // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK (U+203A)
}
}
}
// Optional indicator pips
//
// Add an unordered list with the following class and add a list item for each
// slide your carousel holds.
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 15;
width: 60%;
margin-left: -30%;
padding-left: 0;
list-style: none;
text-align: center;
li {
display: inline-block;
width: 10px;
height: 10px;
margin: 1px;
text-indent: -999px;
border: 1px solid @carousel-indicator-border-color;
border-radius: 10px;
cursor: pointer;
// IE8-9 hack for event handling
//
// Internet Explorer 8-9 does not support clicks on elements without a set
// `background-color`. We cannot use `filter` since that's not viewed as a
// background color by the browser. Thus, a hack is needed.
//
// For IE8, we set solid black as it doesn't support `rgba()`. For IE9, we
// set alpha transparency for the best results possible.
background-color: #000 \9; // IE8
background-color: rgba(0, 0, 0, 0); // IE9
}
.active {
margin: 0;
width: 12px;
height: 12px;
background-color: @carousel-indicator-active-bg;
}
}
// Optional captions
// -----------------------------
// Hidden by default for smaller viewports
.carousel-caption {
position: absolute;
left: 15%;
right: 15%;
bottom: 20px;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: @carousel-caption-color;
text-align: center;
text-shadow: @carousel-text-shadow;
& .btn {
text-shadow: none; // No shadow for button elements in carousel-caption
}
}
// Scale up controls for tablets and up
@media screen and (min-width: @screen-sm-min) {
// Scale up the controls a smidge
.carousel-control {
.glyphicon-chevron-left,
.glyphicon-chevron-right,
.icon-prev,
.icon-next {
width: 30px;
height: 30px;
margin-top: -15px;
margin-left: -15px;
font-size: 30px;
}
}
// Show and left align the captions
.carousel-caption {
left: 20%;
right: 20%;
padding-bottom: 30px;
}
// Move up the indicators
.carousel-indicators {
bottom: 20px;
}
}
| overleaf/web/frontend/stylesheets/components/carousel.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/carousel.less",
"repo_id": "overleaf",
"token_count": 1917
} | 545 |
.input-suggestions {
position: relative;
height: @input-height-base;
}
.input-suggestions-main {
position: absolute;
top: 0;
background-color: transparent;
}
.input-suggestions-shadow {
background-color: @input-bg;
padding-top: @input-suggestion-v-offset;
}
.input-suggestions-shadow-existing {
color: transparent;
}
.input-suggestions-shadow-suggested {
color: lighten(@input-color, 25%);
}
| overleaf/web/frontend/stylesheets/components/input-suggestions.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/input-suggestions.less",
"repo_id": "overleaf",
"token_count": 144
} | 546 |
//
// Panels
// --------------------------------------------------
// Base class
.panel {
margin-bottom: @line-height-computed;
background-color: @panel-bg;
border: 1px solid transparent;
border-radius: @panel-border-radius;
.box-shadow(0 1px 1px rgba(0, 0, 0, 0.05));
}
// Panel contents
.panel-body {
padding: @panel-body-padding;
&:extend(.clearfix all);
}
// Optional heading
.panel-heading {
padding: 10px 15px;
border-bottom: 1px solid transparent;
.border-top-radius((@panel-border-radius - 1));
> .dropdown .dropdown-toggle {
color: inherit;
}
}
// Within heading, strip any `h*` tag of its default margins for spacing.
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: ceil((@font-size-base * 1.125));
color: inherit;
> a {
color: inherit;
}
}
// Optional footer (stays gray in every modifier class)
.panel-footer {
padding: 10px 15px;
background-color: @panel-footer-bg;
border-top: 1px solid @panel-inner-border;
.border-bottom-radius((@panel-border-radius - 1));
}
// List groups in panels
//
// By default, space out list group content from panel headings to account for
// any kind of custom content between the two.
.panel {
> .list-group {
margin-bottom: 0;
.list-group-item {
border-width: 1px 0;
border-radius: 0;
}
// Add border top radius for first one
&:first-child {
.list-group-item:first-child {
border-top: 0;
.border-top-radius((@panel-border-radius - 1));
}
}
// Add border bottom radius for last one
&:last-child {
.list-group-item:last-child {
border-bottom: 0;
.border-bottom-radius((@panel-border-radius - 1));
}
}
}
}
// Collapse space between when there's no additional content.
.panel-heading + .list-group {
.list-group-item:first-child {
border-top-width: 0;
}
}
// Tables in panels
//
// Place a non-bordered `.table` within a panel (not within a `.panel-body`) and
// watch it go full width.
.panel {
> .table,
> .table-responsive > .table {
margin-bottom: 0;
}
// Add border top radius for first one
> .table:first-child,
> .table-responsive:first-child > .table:first-child {
.border-top-radius((@panel-border-radius - 1));
> thead:first-child,
> tbody:first-child {
> tr:first-child {
td:first-child,
th:first-child {
border-top-left-radius: (@panel-border-radius - 1);
}
td:last-child,
th:last-child {
border-top-right-radius: (@panel-border-radius - 1);
}
}
}
}
// Add border bottom radius for last one
> .table:last-child,
> .table-responsive:last-child > .table:last-child {
.border-bottom-radius((@panel-border-radius - 1));
> tbody:last-child,
> tfoot:last-child {
> tr:last-child {
td:first-child,
th:first-child {
border-bottom-left-radius: (@panel-border-radius - 1);
}
td:last-child,
th:last-child {
border-bottom-right-radius: (@panel-border-radius - 1);
}
}
}
}
> .panel-body + .table,
> .panel-body + .table-responsive {
border-top: 1px solid @table-border-color;
}
> .table > tbody:first-child > tr:first-child th,
> .table > tbody:first-child > tr:first-child td {
border-top: 0;
}
> .table-bordered,
> .table-responsive > .table-bordered {
border: 0;
> thead,
> tbody,
> tfoot {
> tr {
> th:first-child,
> td:first-child {
border-left: 0;
}
> th:last-child,
> td:last-child {
border-right: 0;
}
}
}
> thead,
> tbody {
> tr:first-child {
> td,
> th {
border-bottom: 0;
}
}
}
> tbody,
> tfoot {
> tr:last-child {
> td,
> th {
border-bottom: 0;
}
}
}
}
> .table-responsive {
border: 0;
margin-bottom: 0;
}
}
// Collapsable panels (aka, accordion)
//
// Wrap a series of panels in `.panel-group` to turn them into an accordion with
// the help of our collapse JavaScript plugin.
.panel-group {
margin-bottom: @line-height-computed;
// Tighten up margin so it's only between panels
.panel {
margin-bottom: 0;
border-radius: @panel-border-radius;
overflow: hidden; // crop contents when collapsed
+ .panel {
margin-top: 5px;
}
}
.panel-heading {
border-bottom: 0;
+ .panel-collapse .panel-body {
border-top: 1px solid @panel-inner-border;
}
}
.panel-footer {
border-top: 0;
+ .panel-collapse .panel-body {
border-bottom: 1px solid @panel-inner-border;
}
}
}
// Contextual variations
.panel-default {
.panel-variant(
@panel-default-border; @panel-default-text; @panel-default-heading-bg;
@panel-default-border
);
}
.panel-primary {
.panel-variant(
@panel-primary-border; @panel-primary-text; @panel-primary-heading-bg;
@panel-primary-border
);
}
.panel-success {
.panel-variant(
@panel-success-border; @panel-success-text; @panel-success-heading-bg;
@panel-success-border
);
}
.panel-info {
.panel-variant(
@panel-info-border; @panel-info-text; @panel-info-heading-bg;
@panel-info-border
);
}
.panel-warning {
.panel-variant(
@panel-warning-border; @panel-warning-text; @panel-warning-heading-bg;
@panel-warning-border
);
}
.panel-danger {
.panel-variant(
@panel-danger-border; @panel-danger-text; @panel-danger-heading-bg;
@panel-danger-border
);
}
| overleaf/web/frontend/stylesheets/components/panels.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/panels.less",
"repo_id": "overleaf",
"token_count": 2390
} | 547 |
@ieee-blue: #00629b;
@ieee-dark-blue: #002855;
@ieee-cyan: #00b5e2;
@ieee-dark-cyan: #009ca6;
@ieee-red: #ba0c2f;
@ieee-orange: #ffa300;
@ieee-yellow: #ffd100;
@ieee-light-green: #78be20;
@ieee-dark-green: #00843d;
@ieee-purple: #981d97;
@ol-blue-gray-0: #f4f5f8;
@ol-blue-gray-1: #d8e0e6;
@ol-blue-gray-2: #8195a1;
@ol-blue-gray-3: #425e6e;
@ol-blue-gray-4: #26425f;
@ol-blue-gray-5: #1e3048;
@ol-blue-gray-6: #112437;
@ol-green: @ieee-dark-green;
@ol-dark-green: darken(@ieee-dark-green, 15%);
@ol-blue: @ieee-blue;
@ol-dark-blue: @ieee-dark-blue;
@ol-red: @ieee-red;
@ol-dark-red: darken(@ieee-red, 15%);
@brand-primary: @ieee-blue;
@brand-secondary: @ieee-dark-blue;
@brand-success: @ol-blue;
@brand-info: @ieee-dark-cyan;
@brand-warning: @ieee-orange;
@brand-danger: @ol-red;
@btn-primary-bg: @ieee-blue;
@link-color: @ieee-blue;
@link-hover-color: @ieee-dark-blue;
@toolbar-btn-active-bg-color: @ieee-blue;
@file-tree-item-selected-bg: @ieee-blue;
@file-tree-multiselect-bg: @ieee-cyan;
@editor-toggler-hover-bg-color: @ieee-blue;
@toggle-switch-highlight-color: @ieee-blue;
@footer-link-color: @link-color;
@footer-link-hover-color: @link-hover-color;
@navbar-subdued-hover-color: @ieee-blue;
@navbar-default-link-hover-bg: @ieee-blue;
@navbar-default-link-hover-color: @ieee-blue;
@navbar-default-link-active-bg: @ieee-blue;
| overleaf/web/frontend/stylesheets/core/ol-ieee-variables.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/core/ol-ieee-variables.less",
"repo_id": "overleaf",
"token_count": 670
} | 548 |
.plv-page-view {
position: relative;
}
.plv-text-layer {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
color: #000;
font-family: sans-serif;
overflow: hidden;
pointer-events: none;
}
.plv-text-layer > span {
color: transparent;
position: absolute;
line-height: 1;
white-space: pre;
cursor: text;
pointer-events: auto;
-webkit-transform-origin: 0% 0%;
-moz-transform-origin: 0% 0%;
-o-transform-origin: 0% 0%;
-ms-transform-origin: 0% 0%;
transform-origin: 0% 0%;
}
.plv-text-layer > span::selection {
background: rgba(0, 0, 255, 0.3);
}
.plv-text-layer > span::-moz-selection {
background: rgba(0, 0, 255, 0.3);
}
| overleaf/web/frontend/stylesheets/vendor/pdfListView/TextLayer.css/0 | {
"file_path": "overleaf/web/frontend/stylesheets/vendor/pdfListView/TextLayer.css",
"repo_id": "overleaf",
"token_count": 276
} | 549 |
{
"find_out_more": "더 알아보기",
"compare_plan_features": "플랜 비교",
"in_good_company": "좋은 회사에 다니시네요",
"unlimited": "무제한",
"priority_support": "우선권 지원",
"dropbox_integration_lowercase": "Dropbox 통합",
"github_integration_lowercase": "GitHub 통합",
"discounted_group_accounts": "디스카운트 그룹 계정",
"referring_your_friends": "친구에게 알리기",
"still_have_questions": "궁금하신 점이 남아 있나요?",
"quote_erdogmus": "변경 내용 추적과 실시간 콜레버레이션은 ShareLaTeX만의 특별한 기능입니다.",
"quote_henderson": "ShareLaTeX은 강력하고 안정적인 콜레버레이션 툴이라는 것이 증명되었고 우리 학교에서 널리 쓰이고 있습니다.",
"faq_change_plans_question": "나중에 플랜을 바꿀 수 있나요?",
"faq_do_collab_need_premium_question": "공저자들도 프리미엄 계정이 필요한가요?",
"faq_need_more_collab_question": "공저자가 더 필요하면 어떻게 해야하나요?",
"faq_purchase_more_licenses_question": "동료들을 위해 추가적으로 라이센스를 구입할 수 있나요?",
"faq_monthly_or_annual_question": "월간 혹은 연간 청구를 선택해야하나요?",
"faq_how_to_pay_question": "신용카드나 직불카드, PayPal 등으로 온라인 결재를 할 수 있나요?",
"reference_search": "고급 레퍼런스 검색",
"reference_search_info": "Citation key로 검색할 수도 있고 저자나, 제목, 연도, 저널명 등을 고급 검색으로 찾아볼 수도 있습니다.",
"reference_sync": "레퍼런스 매니저 동기화",
"powerful_latex_editor": "강력한 LaTeX 편집기",
"realtime_track_changes": "실시간 변경 내용 추적",
"change_plans_any_time": "언제든 플랜이나 계정을 바꿀 수 있습니다.",
"number_collab": "공저자 수",
"unlimited_private": "무제한 개인 프로젝트",
"realtime_collab": "실시간 협업",
"hundreds_templates": "수백개의 양식",
"all_premium_features": "모든 프리미엄 기능",
"sync_dropbox_github": "Dropbox와 GitHub 연동",
"track_changes": "변경 내용 추적",
"tooltip_hide_pdf": "PDF를 숨기려면 클릭",
"tooltip_show_pdf": "PDF를 보려면 클릭",
"tooltip_hide_filetree": "파일 트리를 숨기려면 클릭",
"tooltip_show_filetree": "파일 트리를 보려면 클릭",
"cannot_verify_user_not_robot": "죄송합니다. 로봇이 아니라고 확신할 수 없습니다. 애드블록이나 방화벽에 의해 Google reCAPTCHA가 차단되지 않았는지 확인해주십시오.",
"uncompiled_changes": "컴파일되지 않은 변경 사항",
"code_check_failed": "코드 체크 실패",
"code_check_failed_explanation": "자동 컴파일 실행 전에 에러를 수정해야합니다.",
"tags_slash_folders": "태그/폴더",
"file_already_exists": "동일한 이름의 파일 혹은 폴더가 존재합니다.",
"import_project_to_v2": "프로젝트를 V2로 가져오기",
"open_in_v1": "V1에서 열기",
"import_to_v2": "V2에서 열기",
"never_mind_open_in_v1": "무시하고 V1에서 열기",
"yes_im_sure": "예, 확실합니다.",
"drop_files_here_to_upload": "여기에 파일 드랍 후 업로드",
"drag_here": "여기로 드래그",
"creating_project": "프로젝트 생성",
"select_a_zip_file": ".zip 파일 선택",
"drag_a_zip_file": ".zip 파일 드래그",
"v1_badge": "V1 뱃지",
"v1_projects": "V1 프로젝트",
"open_your_billing_details_page": "영수증 자세히 보기",
"try_out_link_sharing": "새로운 링크 공유 기능을 사용해보세요!",
"try_link_sharing": "링크 공유 해보기",
"try_link_sharing_description": "링크 공유를 이용해서 쉽게 프로젝트 접근 권한을 주세요.",
"learn_more_about_link_sharing": "링크 공유 더 알아보기",
"link_sharing": "링크 공유",
"tc_switch_everyone_tip": "모두에게 변경 사항 추적 고정",
"tc_switch_user_tip": "이 사용자에게 변경 사항 추적 고정",
"tc_switch_guests_tip": "링크를 공유하는 모든 게스트에게 변경 사항 추적 고정",
"tc_guests": "게스트",
"select_all_projects": "전체 선택",
"select_project": "선택",
"main_file_not_found": "main 도큐멘트 알 수 없음 ",
"please_set_main_file": "프로젝트 메뉴에서 이 프로젝트의 main 파일을 선택하세요. ",
"link_sharing_is_off": "링크 공유를 끄고 초대된 사용자만 볼 수 있습니다.",
"turn_on_link_sharing": "링크 공유 켜기",
"link_sharing_is_on": "링크 공유 중",
"turn_off_link_sharing": "링크 공유 끄기",
"anyone_with_link_can_edit": "이 링크에 있는 사람은 프로젝트 편집 가능",
"anyone_with_link_can_view": "이 링크에 있는 사람은 프로젝트를 볼 수 있음",
"turn_on_link_sharing_consequences": "링크 공유를 설정하면 관련된 사람들은 프로젝트에 접근 및 편집이 가능합니다.",
"turn_off_link_sharing_consequences": "링크 공유를 끄면 초대받은 사람들만 프로젝트에 접근할 수 있습니다.",
"autocompile_disabled": "자동 컴파일 불가",
"autocompile_disabled_reason": "서버에 부하가 많이 걸려서 백그라운드 재컴파일이 잠시 불가능했습니다. 위의 버튼을 다시 클릭해서 재컴파일 하십시오.",
"auto_compile_onboarding_description": "자동컴파일을 실행하면 타이핑하는대로 프로젝트를 컴파일 합니다.",
"try_out_auto_compile_setting": "새로운 자동 컴파일 세팅을 사용해보세요!",
"got_it": "알겠습니다.",
"pdf_compile_in_progress_error": "다른 창에서 컴파일 중",
"pdf_compile_try_again": "재시도 전에 현재 진행 중인 컴파일이 끝날 때까지 기다려주세요.",
"invalid_email": "이메일 주소가 잘못되었습니다.",
"auto_compile": "자동 컴파일",
"tc_everyone": "모든 사람",
"per_user_tc_title": "개인별 변경 내용 추적",
"you_can_use_per_user_tc": "이제 개인별 변경 내용 추적을 사용할 수 있습니다.",
"turn_tc_on_individuals": "개인별 변경 내용 추적 사용하기",
"keep_tc_on_like_before": "또는 이전처럼 모두를 위해 유지함",
"auto_close_brackets": "괄호 자동완성",
"auto_pair_delimiters": "구분문자 자동완성",
"successfull_dropbox_link": "Dropbox에 성공적으로 연결되었습니다. 설정 페이지로 이동합니다.",
"show_link": "링크 보기",
"hide_link": "링크 숨기기",
"aggregate_changed": "변경:",
"aggregate_to": "-->",
"confirm_password_to_continue": "계속 진행을 위해 비밀번호 확인",
"confirm_password_footer": "한 동안 비밀번호를 다시 묻지 않겠습니다.",
"accept_all": "모두 승락",
"reject_all": "모두 거절",
"bulk_accept_confirm": "선택하신 __nChanges__개의 변경 사항을 승락하시겠습니까?",
"bulk_reject_confirm": "선택하신 __nChanges__개의 변경 사항을 거절하시겠습니까?",
"uncategorized": "기타",
"pdf_compile_rate_limit_hit": "컴파일 빈도 제한 초과",
"project_flagged_too_many_compiles": "이 프로젝트에서 컴파일 플래그가 너무 자주 있었습니다. 곧 제한이 풀립니다.",
"reauthorize_github_account": "GitHub 계정 재확인",
"github_credentials_expired": "GitHub 아이디와 비밀번호가 만료되었습니다.",
"hit_enter_to_reply": "답을 하시려면 엔터를 누르세요.",
"add_your_comment_here": "여기에 코멘트 추가",
"resolved_comments": "해결된 코멘트",
"try_it_for_free": "무료로 사용해보세요",
"please_ask_the_project_owner_to_upgrade_to_track_changes": "변경 내용 추적을 사용하시려면 프로젝트 소유자에게 업그레이드를 요구하세요.",
"mark_as_resolved": "해결됨으로 표시",
"reopen": "다시 열기",
"add_comment": "코멘트 추가",
"no_resolved_threads": "해결된 코멘트 없음",
"upgrade_to_track_changes": "변경 내용 추적을 위해 업그레이드",
"see_changes_in_your_documents_live": "문서 변경사항 실시간으로 보기",
"track_any_change_in_real_time": "실시간으로 모든 변경 사항 추적",
"review_your_peers_work": "동료의 작업 검토",
"accept_or_reject_each_changes_individually": "각각의 변경 사항 승락 또는 거절",
"accept": "승락",
"reject": "거절",
"no_comments": "코멘트 없음",
"edit": "편집",
"are_you_sure": "확실한가요?",
"resolve": "해결",
"reply": "대답",
"quoted_text_in": "인용문",
"review": "검토",
"track_changes_is_on": "변경 내용 추적 <strong>사용</strong>",
"track_changes_is_off": "변경 내용 추적 <strong>꺼짐</strong>",
"current_file": "현재 파일",
"overview": "개요",
"tracked_change_added": "추가됨",
"tracked_change_deleted": "삭제됨",
"show_all": "모두 보기",
"show_less": "적게 보기",
"dropbox_sync_error": "Dropbox 동기 오류",
"send": "발신",
"sending": "발신 중",
"invalid_password": "비밀번호 틀림",
"error": "오류",
"other_actions": "다른 방법들",
"send_test_email": "테스트 이메일 보내기",
"email_sent": "이메일 보냄",
"create_first_admin_account": "첫 관리 계정 생성",
"ldap": "LDAP",
"ldap_create_admin_instructions": "__appName__ 관리 계정으로 사용할 이메일 주소를 선택하십시오. 사용하실 이메일 주소는 LDAP 시스템에서 사용하는 계정이어야합니다. 이 계정으로의 로그인을 요청받으실 것입니다.",
"saml": "SAML",
"saml_create_admin_instructions": "__appName__ 관리 계정으로 사용할 이메일 주소를 선택하십시오. 사용하실 이메일 주소는 LDAP 시스템에서 사용하는 계정이어야합니다. 이 계정으로의 로그인을 요청받으실 것입니다.",
"admin_user_created_message": "생성된 관리 계정으로 <a href=\"__link__\">로그인</a>",
"status_checks": "상태 확인",
"editor_resources": "에디터 리소스",
"checking": "확인하기",
"cannot_invite_self": "자신을 초대할 수는 없습니다.",
"cannot_invite_non_user": "초대할 수 없습니다. 수신자는 반드시 __appName__ 계정을 보유하고 있어야 합니다.",
"log_in_with": "__provider__(으)로 로그인",
"return_to_login_page": "로그인 페이지로 이동",
"login_failed": "로그인 실패",
"delete_account_warning_message_3": "프로젝트와 설정을 포함한 <strong>계정의 모든 것을 영구 삭제</strong>를 하시겠습니까. 계속 진행하시려면 계정 이메일 주소와 비밀번호를 아래 상자에 입력하십시오.",
"delete_account_warning_message_2": "프로젝트와 설정을 포함한 <strong>계정의 모든 것을 영구 삭제</strong>를 하시겠습니까. 계속 진행하시려면 계정 이메일 주소를 아래 상자에 입력하십시오.",
"your_sessions": "나의 세션",
"clear_sessions_description": "이 리스트는 다른 (로그인) 세션입니다. 이 세션들은 활성화되어 있지만 현재 세션에는 포함되어 있지 않습니다. 이들을 로그아웃하시려면 \"세션 클리어\" 버튼을 클릭하십시오.",
"no_other_sessions": "활성화된 세션이 없습니다.",
"ip_address": "IP 주소",
"session_created_at": "생성된 세션",
"clear_sessions": "세션 클리어",
"clear_sessions_success": "세션 클리어 완료",
"sessions": "세션",
"manage_sessions": "나의 세션 관리",
"syntax_validation": "코드 확인",
"history": "히스토리",
"joining": "참여하기",
"open_project": "프로젝트 열기",
"files_cannot_include_invalid_characters": "파일에 '*'과 '/'은 사용할 수 없습니다.",
"invalid_file_name": "파일 이름이 부적절합니다.",
"autocomplete_references": "레퍼런스 자동완성 (<code>\\cite{}</code> 블록 안에서)",
"autocomplete": "자동 완성",
"failed_compile_check": "프로젝트에 심각한 문법 오류가 있는 것으로 보입니다. 완료하기 전 수정하십시오.",
"failed_compile_check_try": "무시하고 컴파일하기",
"failed_compile_option_or": "또는",
"failed_compile_check_ignore": "문법 확인 끄기",
"compile_time_checks": "문법 확인",
"stop_on_validation_error": "컴파일 전에 문법 확인",
"ignore_validation_errors": "문법 확인 안 함",
"run_syntax_check_now": "문법 확인 실행",
"your_billing_details_were_saved": "청구서 세부사항이 저장되었습니다.",
"security_code": "보안 코드",
"paypal_upgrade": "업그레이드하시려면 밑의 버튼을 클릭하시고 이메일 계정과 비밀번호를 이용해서 PayPal에 로그인 하십시오.",
"upgrade_cc_btn": "지금 업그레이드하고 7일 후 지불",
"upgrade_paypal_btn": "계속",
"notification_project_invite": "<b>__userName__</b>님이 <b>__projectName__</b>에 참여하고자 합니다. <a class=\"btn btn-sm btn-info pull-right\" href=\"/project/__projectId__/invite/token/__token__\">Join Project</a>",
"file_restored": "(__filename__) 파일이 삭제되었습니다.",
"file_restored_back_to_editor": "에디터로 돌아가서 다시 할 수 있습니다.",
"file_restored_back_to_editor_btn": "편집기로 돌아가기",
"view_project": "프로젝트 보기",
"join_project": "프로젝트 참여",
"invite_not_accepted": "받지 않은 초대장",
"resend": "다시 보냄",
"syntax_check": "문법 확인",
"revoke_invite": "초대 취소",
"pending": "보류",
"invite_not_valid": "프로젝트 초대가 유효하지 않습니다.",
"invite_not_valid_description": "초대가 만료되었습니다. 프로젝트 소유자에게 연락하십시오.",
"accepting_invite_as": "다음 이메일로 온 초대를 승락합니다.",
"accept_invite": "초대 승락",
"log_hint_ask_extra_feedback": "왜 이 힌트가 도움이 되지 않는지 알려주십시오.",
"log_hint_extra_feedback_didnt_understand": "힌트를 이해할 수 없습니다.",
"log_hint_extra_feedback_not_applicable": "이 방법으로 해결되지 않습니다.",
"log_hint_extra_feedback_incorrect": "오류를 해결할 수 없습니다.",
"log_hint_extra_feedback_other": "기타:",
"log_hint_extra_feedback_submit": "제출",
"if_you_are_registered": "이미 등록하셨다면",
"stop_compile": "컴파일 중지",
"terminated": "컴파일 취소됨",
"compile_terminated_by_user": "'컴파일 중지' 버튼을 사용하여 컴파일이 취소되었습니다. Raw log를 보시면 어디에서 중지 되었는지 확인할 수 있습니다.",
"site_description": "사용하기 쉬운 온라인 LaTex 편집기. 설치 필요없음. 실시간 협업. 버전 관리. 수백 개의 LaTex 템플릿. 그리고 그 이상.",
"knowledge_base": "지식 베이스",
"contact_message_label": "문의 사항",
"kb_suggestions_enquiry": "<0>__kbLink__</0>를 확신하셨습니까?",
"answer_yes": "예",
"answer_no": "아니오",
"log_hint_extra_info": "더 알아보기",
"log_hint_feedback_label": "힌트가 도움이 되었나요?",
"log_hint_feedback_gratitude": "피드백에 감사드립니다.",
"recompile_pdf": "PDF 다시 컴파일하기",
"about_paulo_reis": "포르투갈 Aveiro에서 살고 있는 front-end 소프트웨어 개발자이자 사용자 경험(user experience)를 연구합니다. 사용자 경험 연구로 박사 학위를 취득했고 디자인과 사용법에서 보다 인간적인 기술을 만들거나 제안하고 시험/검증하는 일에 매우 관심이 많습니다.",
"login_or_password_wrong_try_again": "계정 또는 비밀번호가 틀렸습니다. 다시 입력하세요.",
"manage_beta_program_membership": "베타 프로그램 멤버십 관리",
"beta_program_opt_out_action": "베타 프로그램에서 나옴",
"disable_beta": "베타 사용하지 않음",
"beta_program_badge_description": "__appName__을 사용하는 동안 다음과 같은 뱃지로 표시된 베타 기능을 보실 수 있습니다.",
"beta_program_current_beta_features_description": "현재 다음과 같은 새로운 기능을 베타 테스트하고 있습니다:",
"enable_beta": "베타 사용하기",
"user_in_beta_program": "베타 프로그램 참여중",
"beta_program_already_participating": "당신은 베타 프로그램에 등록되었습니다.",
"sharelatex_beta_program": "__appName__ 베타 프로그램",
"beta_program_benefits": "저희는 지금도 __appName__을 개선하고 있습니다. 베타 프로그램에 참여하여 새로운 기능을 먼저 사용해보시고 더 필요한 것을 알려주십시오.",
"beta_program_opt_in_action": "베타 프로그램 들어가기",
"conflicting_paths_found": "경로 충돌 발견",
"following_paths_conflict": "다음 파일과 폴더의 경로가 충돌합니다.",
"open_a_file_on_the_left": "왼쪽에서 파일 열기",
"reference_error_relink_hint": "이 에러가 지속되면 여기에서 계정을 다시 연결하십시오:",
"pdf_rendering_error": "PDF 렌더링 오류",
"something_went_wrong_rendering_pdf": "PDF 렌더링 중 무언가 잘못되었습니다.",
"mendeley_reference_loading_error_expired": "Mendeley 토큰이 만료되었습니다. 계정을 다시 연결해주세요.",
"mendeley_reference_loading_error_forbidden": "Mendeley에서 레퍼런스를 가져올 수 없습니다. 계정을 다시 연결한 후 다시 시도해주세요.",
"mendeley_integration": "Mendeley 통합",
"mendeley_sync_description": "Mendeley 통합을 이용해서 __appName__ 프로젝트로 mendeley 레퍼런스를 가져올 수 있습니다.",
"mendeley_is_premium": "Mendeley 통합은 프리미엄 기능입니다.",
"link_to_mendeley": "Mendeley 연결",
"unlink_to_mendeley": "Mendeley 연결해제",
"mendeley_reference_loading": "Mendeley에서 레퍼런스 가져오기",
"mendeley_reference_loading_success": "Mendeley에서 레퍼런스 가져옴",
"mendeley_reference_loading_error": "오류. Mendeley에서 레퍼런스를 가져올 수 없습니다.",
"reference_import_button": "레퍼런스 보내기",
"unlink_reference": "레퍼렌스 제공자 연결 해제",
"unlink_warning_reference": "경고: 이 공급자로부터의 계정을 해제하면 레퍼런스를 프로젝트로 가져올 수 없습니다.",
"mendeley": "Mendeley",
"suggest_new_doc": "새 문서 제안",
"request_sent_thank_you": "요청을 보냈습니다. 감사합니다.",
"suggestion": "제안",
"project_url": "관련 프로젝트 URL",
"subject": "제목",
"confirm": "확인",
"cancel_personal_subscription_first": "이미 개인 구독을 하고 있습니다. 그룹 라이센스를 사용하기 전에 개인 구독을 취소하시겠습니까?",
"delete_projects": "프로젝트 삭제",
"leave_projects": "프로젝트 나가기",
"delete_and_leave_projects": "프로젝트를 나가면서 삭제",
"too_recently_compiled": "이 프로젝트는 방금에 컴파일 되었기 때문에 컴파일을 생략합니다.",
"clsi_maintenance": "서버 유지를 위해 컴파일 서버를 다운했습니다. 금방 돌아오겠습니다.",
"references_search_hint": "CTRL-Space를 눌러 검색",
"ask_proj_owner_to_upgrade_for_references_search": "레퍼런스 탐색 기능을 사용하시려면 프로젝트 소유자에게 업그레이드를 요청하십시오.",
"ask_proj_owner_to_upgrade_for_faster_compiles": "더 빠른 컴파일과 타임아웃 한계를 연장하시려면 프로젝트 소유자에게 업그레이드를 요청하십시오.",
"search_bib_files": "저자, 제목, 연도로 검색",
"leave_group": "그룹 떠나기",
"leave_now": "지금 떠나기",
"sure_you_want_to_leave_group": "이 그룹을 떠나시겠습니까?",
"notification_group_invite": "__groupName__에 참여 초대를 받으셨습니다. <a href=\"/user/subscription/__subscription_id__/group/invited\">참여하기</a>.",
"search_references": "이 프로젝트에서 .bib 파일 검색",
"no_search_results": "검색 결과 없음",
"email_already_registered": "이 이메일은 이미 등록되어있습니다.",
"compile_mode": "컴파일 모드",
"normal": "보통",
"fast": "고속",
"rename_folder": "폴더 이름 재설정",
"delete_folder": "폴더 삭제",
"about_to_delete_folder": "당신은 다음 폴더들을 삭제하려고 하십니다 (안에 있는 프로젝트는 삭제되지 않습니다):",
"to_modify_your_subscription_go_to": "구독 변경하러 가기",
"manage_subscription": "구독 관리",
"activate_account": "계정 활성화",
"yes_please": "예!",
"nearly_activated": "__appName__ 계정 활성화를 거의 마쳤습니다.",
"please_set_a_password": "비밀번호를 설정하세요.",
"activation_token_expired": "활성화 토큰이 만료되었습니다. 새로 받은 토큰을 사용하셔야 합니다.",
"activate": "활성화하기",
"activating": "활성화중",
"ill_take_it": "이걸로 할게요.",
"cancel_your_subscription": "구독 그만하기",
"no_thanks_cancel_now": "괜찮습니다. 지금 취소합니다.",
"cancel_my_account": "구독 취소하기",
"sure_you_want_to_cancel": "정말 취소 하시겠습니까?",
"i_want_to_stay": "계속하겠습니다.",
"have_more_days_to_try": "<strong>__days__ days</strong>일 더 사용해 보십시오!",
"interested_in_cheaper_plan": "저 저렴한 <strong>__price__</strong> student plan에 관심이 있습니까?",
"session_expired_redirecting_to_login": "세션 종료. __seconds__ seconds 초 후 다시 로그인",
"maximum_files_uploaded_together": "최대 __max__ 파일 업로드됨",
"too_many_files_uploaded_throttled_short_period": "너무 많은 파일이 업로드되어 잠시 보류되었습니다.",
"compile_larger_projects": "큰 프로젝트 컴파일",
"upgrade_to_get_feature": "__feature__와 다음 기능 사용을 위해 업그레이드:",
"new_group": "새로운 그룹",
"about_to_delete_groups": "이 그룹에 대한 팔로우를 삭제하려고 합니다:",
"removing": "삭제하기",
"adding": "추가하기",
"groups": "그룹",
"rename_group": "그룹 이름 재설정",
"renaming": "이름 재설정",
"create_group": "그룹 생성",
"delete_group": "그룹 삭제",
"delete_groups": "여러 그룹 삭제",
"your_groups": "나의 그룹",
"group_name": "그룹 이름",
"no_groups": "그룹 없음",
"Subscription": "구독",
"Documentation": "참고 문서",
"Universities": "대학교",
"Account Settings": "계정 설정",
"Projects": "프로젝트",
"Account": "계정",
"global": "글로벌",
"Terms": "약관",
"Security": "보안",
"About": "소개",
"editor_disconected_click_to_reconnect": "에디터 접속 끊김. 재접속하려면 아무곳이나 클릭.",
"word_count": "단어 수 세기",
"please_compile_pdf_before_word_count": "단어 수 세기를 실행하기 전에 프로젝트를 컴파일 하십시오.",
"total_words": "총 단어 수",
"headers": "헤더",
"math_inline": "수식 갯수",
"math_display": "수식 표시",
"connected_users": "접속한 사용자",
"projects": "프로젝트",
"upload_project": "프로젝트 업로드",
"all_projects": "전체 프로젝트",
"your_projects": "나의 프로젝트",
"shared_with_you": "공유받은 프로젝트",
"deleted_projects": "삭제된 프로젝트",
"templates": "템플릿",
"new_folder": "새로운 폴더",
"create_your_first_project": "첫 프로젝트를 만드세요!",
"complete": "완료",
"on_free_sl": "__appName__ 무료버전을 사용하고 있습니다.",
"upgrade": "업그레이드",
"or_unlock_features_bonus": "또는 다음 기능을 무료로 사용하세요",
"sharing_sl": "__appName__ 공유하기",
"add_to_folder": "폴더에 추가하기",
"create_new_folder": "새로운 폴더 만들기",
"more": "더보기",
"rename": "이름 바꾸기",
"make_copy": "복사하기",
"restore": "복원하기",
"title": "제목",
"last_modified": "마지막 수정",
"no_projects": "프로젝트 없음",
"welcome_to_sl": "__appName__에 오신걸 환영합니다!",
"new_to_latex_look_at": "LaTex에 새로 오셨나요? 다음을 둘러보면서 시작해보세요",
"or": "또는",
"or_create_project_left": "또는 왼쪽에 첫 프로젝트를 만드세요.",
"thanks_settings_updated": "감사합니다, 당신의 설정사항이 업데이트되었습니다.",
"update_account_info": "계정 정보 업데이트",
"must_be_email_address": "반드시 이메일주소여야 합니다",
"first_name": "이름",
"last_name": "성",
"update": "업데이트",
"change_password": "암호 변경",
"current_password": "현재 암호",
"new_password": "새로운 암호",
"confirm_new_password": "새로운 암호 확인하기",
"required": "필수",
"doesnt_match": "일치하지 않습니다",
"dropbox_integration": "Dropbox 통합",
"learn_more": "더 배우기",
"dropbox_is_premium": "Dropbox 동기화는 프리미엄 기능입니다",
"account_is_linked": "계정이 연결되었습니다",
"unlink_dropbox": "Dropbox 연결끊기",
"link_to_dropbox": "Dropbox에 연결하기",
"newsletter_info_and_unsubscribe": "우리는 매달 새롭게 이용가능한 기능을 요약하여 뉴스레터를 전송합니다. 이메일을 받길 원치 않는다면 언제든지 구독을 해제하십시오:",
"unsubscribed": "구독해제",
"unsubscribing": "구독해제중",
"unsubscribe": "구독해제",
"need_to_leave": "떠나시나요?",
"delete_your_account": "나의 계정 삭제",
"delete_account": "계정 삭제",
"delete_account_warning_message": "프로젝트와 설정을 포함한 <strong>모든 계정 데이터에 대한 영구 삭제</strong>를 하려고 하시는군요. 계정 이메일을 아래 박스에 입력한 후 진행하십시오.",
"deleting": "삭제중",
"delete": "삭제",
"sl_benefits_plans": "__appName__는 전 세계에서 가장 쉬운 LaTeX 편집기입니다. 가장 최신의 문서를 협업자들과 공유하면서 모든 변경사항을 추적할 수 있고 전 세계 어디에서나 LaTeX 환경을 사용할 수 있습니다.",
"monthly": "매달",
"personal": "개인",
"free": "무료",
"one_collaborator": "1명 공유 가능",
"collaborator": "콜라보레이터",
"collabs_per_proj": "프로젝트 당 __collabcount__명까지 공유 가능",
"full_doc_history": "전체 문서 히스토리",
"sync_to_dropbox": "Dropbox 동기화",
"start_free_trial": "무료로 사용해보세요!",
"professional": "전문가",
"unlimited_collabs": "공유 무제한",
"name": "이름",
"student": "학생",
"university": "대학교",
"position": "직책",
"choose_plan_works_for_you": "필요한 플랜을 선택하세요. __len__일간 무료이며 언제든지 취소할수 있습니다.",
"interested_in_group_licence": "그룹, 팀 또는 부서 계정으로 __appName__를 사용하시겠습니까?",
"get_in_touch_for_details": "세부사항을 원하신다면 연락주세요!",
"group_plan_enquiry": "그룹 플랜 문의",
"enjoy_these_features": "이 모든 기능을 즐기세요",
"create_unlimited_projects": "필요하다면 얼마든지 만드세요.",
"never_loose_work": "절대 네버 어떤 것도 잃어버리지 않습니다. 모든 것을 백업하니까요.",
"access_projects_anywhere": "아무데서나 접속하세요.",
"log_in": "로그인",
"login": "로그인",
"logging_in": "로그인중",
"forgot_your_password": "암호를 잊어버리셨나요",
"password_reset": "암호 재설정",
"password_reset_email_sent": "암호 재설정을 완료하기위해 이메일을 전송하였습니다.",
"please_enter_email": "이메일 주소를 입력해주세요",
"request_password_reset": "암호 재설정 요청",
"reset_your_password": "암호 재설정",
"password_has_been_reset": "암호가 재설정되었습니다",
"login_here": "이곳에서 로그인하세요",
"set_new_password": "새로운 암호 설정",
"user_wants_you_to_see_project": "__username__ 님이 __projectname__에 참여하길 원합니다",
"join_sl_to_view_project": "이 프로젝트를 보시려면 __appName__에 참여하세요",
"register_to_edit_template": "__templateName__ 템플릿을 편집하기위해 등록해주세요",
"already_have_sl_account": "__appName__계정을 이미 보유하고 계신가요?",
"register": "등록",
"password": "암호",
"registering": "등록중",
"planned_maintenance": "플랜 유지",
"no_planned_maintenance": "플랜 유지가 현재 없습니다",
"cant_find_page": "죄송합니다. 찾으시려는 페이지를 발견하지 못했습니다.",
"take_me_home": "홈으로!",
"no_preview_available": "죄송합니다, 미리보기를 이용하실 수 없습니다.",
"no_messages": "메시지 없음",
"send_first_message": "첫 메시지를 전송하세요",
"account_not_linked_to_dropbox": "계정이 Dropbox에 연결되지 않았습니다",
"update_dropbox_settings": "Dropbox 설정 업데이트",
"refresh_page_after_starting_free_trial": "무료 시험 시작 후 이 페이지를 새로고침하세요.",
"checking_dropbox_status": "Dropbox 상태를 확인중",
"dismiss": "해제",
"new_file": "새로운 파일",
"upload_file": "파일 업로드",
"create": "만들기",
"creating": "만드는 중",
"upload_files": "파일 업로드",
"sure_you_want_to_delete": "정말 <strong>{{ entity.name }}</strong>을 영구삭제하시겠습니까?",
"common": "일반",
"navigation": "네비게이션",
"editing": "편집",
"ok": "OK",
"source": "소스",
"actions": "실행",
"copy_project": "프로젝트 복사",
"publish_as_template": "템플릿으로 공개",
"sync": "동기화",
"settings": "설정",
"main_document": "주 문서",
"off": "끄기",
"auto_complete": "자동 완성",
"theme": "테마",
"font_size": "글자 크기",
"pdf_viewer": "PDF 뷰어",
"built_in": "빌트인",
"native": "기본",
"show_hotkeys": "단축키보기",
"new_name": "새로운 이름",
"copying": "복사중",
"copy": "복사하기",
"compiling": "컴파일링",
"click_here_to_preview_pdf": "PDF로 미리보기 하시려면 이곳을 클릭하세요.",
"server_error": "서버 오류",
"somthing_went_wrong_compiling": "죄송합니다. 무언가 잘못되어 프로젝트가 컴파일되지 않았습니다. 나중에 다시 시도해주세요.",
"timedout": "시간초과",
"proj_timed_out_reason": "죄송합니다, 컴파일이 작동하는데 너무 오래걸려서 타임아웃되었습니다. 고해상도 이미지 또는 복잡한 다이어그램으로 인해 발생한 문제로 보입니다.",
"no_errors_good_job": "오류가 없습니다, 훌륭합니다!",
"compile_error": "오류 컴파일",
"generic_failed_compile_message": "죄송합니다, 어떠한 이유에서인지 LaTeX 코드를 컴파일 할 수 없습니다. 오류에 대해선 아래의 세부사항을 참조하시거나 Raw log를 보십시오.",
"other_logs_and_files": "기타 로그 및 파일 출력",
"view_raw_logs": "Raw log 보기",
"hide_raw_logs": "Raw log 숨기기",
"clear_cache": "캐시 지우기",
"clear_cache_explanation": "컴파일 서버의 모든 숨겨진 LaTeX 파일 (.aux, .bbl, 등)를 지울것입니다. 일반적으로, 참조사항과 문제를 가지고 있지 않는한 지우기를 실행하실 필요가 없습니다.",
"clear_cache_is_safe": "프로젝트 파일은 삭제되거나 변경되지 않을 것 입니다.",
"clearing": "지우는 중",
"template_description": "템플릿 설명",
"project_last_published_at": "프로젝트 마지막 게시일:",
"problem_talking_to_publishing_service": "서비스 게시에 문제가 있습니다, 몇 분 후에 다시 시도해주세요",
"unpublishing": "비공개",
"republish": "다시 공개하기",
"publishing": "공개중",
"share_project": "프로젝트 공유",
"this_project_is_private": "이 프로젝트는 비공개이며 아래에 있는 사람들만 접속할 수 있습니다",
"make_public": "공개하기",
"this_project_is_public": "이 프로젝트는 공개되어 있으며, URL에 접근한 모든 사람들이 편집할 수 있습니다.",
"make_private": "비공개로 만들기",
"can_edit": "편집가능",
"share_with_your_collabs": "콜레보레이터와 공유",
"share": "공유",
"need_to_upgrade_for_more_collabs": "더 많은 콜레보레이터를 추가하기위해 계정을 업그레이드하셔야 합니다",
"make_project_public": "프로젝트 공개하기",
"make_project_public_consequences": "프로젝트를 공개하신다면 URL로 접속하는 모든분들의 프로젝트 접근이 가능해지게 됩니다.",
"allow_public_editing": "공개 편집 허가",
"allow_public_read_only": "접속하는 경우마나 공개 읽기 허가",
"make_project_private": "프로젝트 비공개하기",
"make_project_private_consequences": "프로젝트를 비공개로하신다면, 당신이 프로젝트를 공유하는 사람만 접속할 수 있습니다.",
"need_to_upgrade_for_history": "히스토리 기능을 사용하시려면 계정을 업그레이드 하셔야 합니다.",
"ask_proj_owner_to_upgrade_for_history": "히스토리 기능을 사용하시려면, 업그레이드 할 프로젝트 소유자에게 문의하세요.",
"anonymous": "익명",
"generic_something_went_wrong": "죄송합니다. 문제가 생겼습니다.",
"restoring": "복원중",
"restore_to_before_these_changes": "변경 전으로 복원하기",
"profile_complete_percentage": "프로필이 __percentval__% 완료되었습니다",
"file_has_been_deleted": "__filename__파일이 삭제되었습니다",
"sure_you_want_to_restore_before": "__date__날짜를 변경하기 전에, <0>__filename__</0> 복원을 원하시나요?",
"rename_project": "프로젝트 이름 바꾸기",
"about_to_delete_projects": "다음과 같은 프로젝트를 삭제하려 합니다:",
"about_to_leave_projects": "다음과 같은 프로젝트를 나가려고합니다:",
"upload_zipped_project": "압축된 프로젝트 업로드",
"upload_a_zipped_project": "압축된 프로젝트 업로드",
"your_profile": "나의 프로필",
"institution": "기관",
"role": "역할",
"folders": "폴더",
"disconnected": "연결끊김",
"please_refresh": "계속하시려면 페이지를 새로고침하세요.",
"lost_connection": "연결이 끊겼습니다",
"reconnecting_in_x_secs": "__seconds__초에 재연결",
"try_now": "지금 시도하세요",
"reconnecting": "재연결중",
"saving_notification_with_seconds": "__docname__문서를 저장중 입니다... (저장되지않은 변경사항 중 __seconds__초)",
"help_us_spread_word": "__appName__을 널리 알려주세요.",
"share_sl_to_get_rewards": "친구 및 동료들과 __appName__(을)를 공유하시고, 아래의 보상을 열어보세요",
"post_on_facebook": "페이스북에 글올리기",
"share_us_on_googleplus": "Google+에 공유하기",
"email_us_to_your_friends": "친구들에게 이메일 보내기",
"link_to_us": "웹사이트에 연결하기",
"direct_link": "바로 연결 링크",
"sl_gives_you_free_stuff_see_progress_below": "추천 후에 누군가 __appName__사용을 시작했을 때, 감사함을 전하기 위해 몇가지 <strong>무료 선물</strong>을 드리고자 합니다! 아래의 진행과정을 확인해주세요.",
"spread_the_word_and_fill_bar": "다른 이들에게 많이 알려주고, 이 줄을 채우세요",
"one_free_collab": "콜레보레이터 1명 무료",
"three_free_collab": "콜레버레이터 3명 무료",
"free_dropbox_and_history": "무료 Dropbox 및 히스토리",
"you_not_introed_anyone_to_sl": "__appName__(을)를 아직 아무도 소개하지 않으셨군요. 공유해보세요!",
"you_introed_small_number": "<0>__numberOfPeople__</0>명의 분들께 __appName__를 소개하셨군요. 훌륭합니다, 더 소개 하시겠습니까?",
"you_introed_high_number": " <0>__numberOfPeople__</0>명의 분들께 __appName__를 소개하셨습니다. 훌륭합니다!",
"link_to_sl": "__appName__에 연결하기",
"can_link_to_sl_with_html": "다음의 HTML에 __appName__(을)를 연결하실 수 있습니다:",
"year": "년",
"month": "월",
"subscribe_to_this_plan": "이 플랜을 구독하기",
"your_plan": "나의 플랜",
"your_subscription": "나의 구독",
"on_free_trial_expiring_at": "지금 사용하시는 무료 시험 버전이 __expiresAt__에 만료됩니다.",
"choose_a_plan_below": "구독하시려면 아래의 플랜을 선택하세요.",
"currently_subscribed_to_plan": "현재 <0>__planName__</0>플랜을 구독중입니다.",
"change_plan": "플랜 선택하기",
"next_payment_of_x_collectected_on_y": "<1>__collectionDate__</1>에 <0>__paymentAmmount__</0>원이 지불됩니다.",
"update_your_billing_details": "청구서 세부사항 업데이트",
"subscription_canceled_and_terminate_on_x": " 구독이 취소되고 <0>__terminateDate__</0>에 만기될 것 입니다. 더이상 지불해야 하는 금액은 없습니다.",
"your_subscription_has_expired": "구독이 만료되었습니다.",
"create_new_subscription": "새로운 구독 만들기",
"problem_with_subscription_contact_us": "구독에 문제가 있습니다. 더 많은 정보를위해 저희에게 연락해주세요.",
"manage_group": "그룹 관리",
"loading_billing_form": "청구서 세부사항 양식 로딩중",
"you_have_added_x_of_group_size_y": "이용가능한<1>__groupSize__</1>멤버 중 <0>__addedUsersSize__</0>멤버가 추가되었습니다",
"remove_from_group": "그룹에서 삭제하기",
"group_account": "그룹 계정",
"registered": "등록됨",
"no_members": "멤버없음",
"add_more_members": "더많은 멤버 추가",
"add": "추가",
"thanks_for_subscribing": "구독해주셔서 감사합니다!",
"your_card_will_be_charged_soon": "카드가 곧 변경될 것입니다.",
"if_you_dont_want_to_be_charged": "다시 지불하는걸 원치않으시는 경우 ",
"add_your_first_group_member_now": "지금 첫 그룹 멤버 추가",
"thanks_for_subscribing_you_help_sl": "__planName__ 플랜을 구독해주셔서 감사합니다. __appName__(이)가 지속적으로 성장하고 향상될 수 있도록 사람들에게 많이 알려주세요.",
"back_to_your_projects": "프로젝트로 돌아가기",
"goes_straight_to_our_inboxes": "우리 편지함으로 바로 가기",
"need_anything_contact_us_at": "필요하신게 있으시다면, 언제든지 연락주시기 바랍니다:",
"regards": "감사합니다",
"about": "소개",
"comment": "댓글",
"restricted_no_permission": "이 페이지를 불러올 권한이 없습니다.",
"online_latex_editor": "온라인 LaTex 편집기",
"meet_team_behind_latex_editor": "가장좋은 온라인 LaTex 편집기인 __appName__ 개발 팀을 만나보세요.",
"follow_me_on_twitter": "Twitter에서 팔로우하기",
"motivation": "우리의 비젼",
"evolved": "진화하다",
"the_easy_online_collab_latex_editor": "쉬운 온라인 콜레보레이터형 LaTeX 편집기",
"get_started_now": "지금 시작하기",
"sl_used_over_x_people_at": "__numberOfUsers__ 이상의 학생과 교육기관이 __appName__(을)를 사용하고 있습니다.",
"collaboration": "콜라보레이션",
"work_on_single_version": "단일 버전으로 함께 작업하기",
"view_collab_edits": "콜라보레이터 편집 보기 ",
"ease_of_use": " 쉬운 사용법",
"no_complicated_latex_install": "LaTex 설치 필요없음",
"all_packages_and_templates": "전체 패키지와 <0>__templatesLink__</0>",
"document_history": "문서 히스토리",
"see_what_has_been": "기록 보기 ",
"added": "추가완료",
"and": "및",
"removed": "제거완료",
"restore_to_any_older_version": "이전 버전으로 복원하기",
"work_from_anywhere": "어디에서든지 작업 가능",
"acces_work_from_anywhere": "전 세계 어디에서든지 작업하세요",
"work_offline_and_sync_with_dropbox": "오프라인으로 작업하고 Dropbox 및 GitHub을 통해서 파일을 동기화하세요",
"over": "더 많은",
"view_templates": "템플릿 보기",
"nothing_to_install_ready_to_go": "설치가 필요없습니다. 전혀 경험이 없어도 바로 <0>__start_now__</0>(을)를 시작 하실 수 있습니다. __appName__(은)는 완벽하게 준비된 LaTex환경을 갖춘 서버를 사용합니다.",
"start_using_latex_now": "LaTeX를 지금 바로 사용하세요",
"get_same_latex_setup": "어디에서든 동일한 LaTex 문서를 사용할 수 있습니다. __appName__은 동료들이나 학생들과 협업을 하는 중에도 전체 버전을 일관되게 유지하며 충돌을 일으키지 않습니다.",
"support_lots_of_features": "이미지, 참고문헌, 방정식 등을 포함한 거의 모든 LaTeX 기능을 지원합니다! <0>__help_guides_link__</0>에서 __appName__에 대한 모든 흥미로운 것들에 대해 알아보세요.",
"latex_guides": "LaTeX 가이드",
"reset_password": "암호 재설정",
"set_password": "암호 설정",
"updating_site": "사이트 업데이트",
"bonus_please_recommend_us": "보너스 - 저희를 추천하세요",
"admin": "관리",
"subscribe": "구독",
"update_billing_details": "청구서 세부사항 업데이트",
"group_admin": "그룹 관리",
"all_templates": "모든 템플릿",
"your_settings": "나의 설정",
"maintenance": "유지",
"to_many_login_requests_2_mins": "이 계정으로 너무 많은 로그인을 시도했습니다. 다시 로그인 하기 전에 2분만 기다려주세요",
"email_or_password_wrong_try_again": "이메일 또는 암호가 부정확합니다. 다시 시도해주세요",
"rate_limit_hit_wait": "Rate(이)가 한계에 도달했습니다. 다시 시도하기 전에 잠시만 기다려주세요",
"problem_changing_email_address": "이메일 주소 변경에 문제가 있었습니다. 잠시후에 다시 시도해주세요. 문제가 계속되면 저희에게 연락주시기 바랍니다.",
"single_version_easy_collab_blurb": "__appName__는 콜라보레이터의 최신날짜를 갖추고 있는지와 잘 작동하는지를 확인합니다. 모두가 접속할 수 있는 각 문서의 단일 마스터 버전만 있습니다. 변경사항 충돌이 절대 없으며, 계속 진행하기 전에 가장 최신 도안을 동료들에게 보내는 것을 기다릴 필요가 없습니다.",
"can_see_collabs_type_blurb": "여러 사람들이 동일한 시간에 문서를 작업해, 아무런 문제가 없습니다. 편집기에 동료들이 타이핑하는 것을 바로 볼 수 있으며, 즉시 화면에 변경사항들이 표시됩니다.",
"work_directly_with_collabs": "공동 연구자와 작업하기",
"work_with_word_users": "Word 사용자와 작업하기",
"work_with_word_users_blurb": "__appName__는 당신의 LaTeX 문서에 직접적으로 기여하도록 LaTeX를 가입하지 않은 동료를 초대할 수 있어서 시작하기 쉽습니다. 이분들은 생산적이게되며 LaTeX의 소량을 골라낼 수 있습니다.",
"view_which_changes": "변경사항들 보기",
"sl_included_history_of_changes_blurb": "__appName__는 전체 변경사항들에대한 히스토리를 포함하고 있어서, 무엇을 언제 누가 변경하였는지를 볼 수 있습니다. 이것은 공동 연구자들이 모든 진행사항들을 만드는데 최신형으로 쉽게 유지할 수 있도록 해주며, 당신은 최신 작업을 리뷰할 수 있습니다.",
"can_revert_back_blurb": "공동 연구자와 함께하거나 혼자 작업하면서 실수가 생길 수 있습니다. 이전으로 돌아가기를 사용하십시오. 작업 손실 위험이 없으며 후회하지 않으실 것입니다.",
"start_using_sl_now": "__appName__를 지금 사용하여 시작하세요",
"over_x_templates_easy_getting_started": "400개 이상의 템플릿으로 저널 논문(journal article)과 학위 논문(thesis), 자기소개서(CV) 등 여러 문서를 쉽게 작성할 수 있습니다.",
"done": "완료",
"change": "변경",
"page_not_found": "페이지를 찾을 수 없습니다",
"please_see_help_for_more_info": "더 많은 정보를 원하신다면 저희 도움말 가이드를 확인해주세요",
"this_project_will_appear_in_your_dropbox_folder_at": "이 프로젝트는 Dropbox 폴더에 나타날 것 입니다 ",
"member_of_group_subscription": "__admin_email__은 이 그룹 구독 멤버를 관리합니다. 구독을 관리하시려면 멤버들에게 연락하세요.\n",
"about_henry_oswald": "런던에 거주하는 소프트웨어 엔지니어 입니다. __appName__에서 오리지널 포트폴리오를 만들었으며 안정적이고 조절가능한 플랫폼을 만드는 업무를 맡고 있습니다. 헨리는 Test Driven Development 신봉자이며 저희가 __appName__ 코드를 간략하고 쉽게 유지하도록 해줍니다.",
"about_james_allen": "이론 물리학 박사이며 LaTeX에 대한 열정을 갖고 있습니다. 최초의 온라인 LaTeX 편집기인 ScribTeX을 만들었으며, __appName__를 가능하게 만드는 기술을 개발하는 매우 큰 역할을 맡고 있습니다.",
"two_strong_principles_behind_sl": "저희는 다음과 같은 두 가지 비젼을 가지고 __appName__을 개발합니다.",
"want_to_improve_workflow_of_as_many_people_as_possible": "우리는 가능한 많은분들이 더 수월하게 작업할 수 있기를 바랍니다.",
"detail_on_improve_peoples_workflow": "LaTeX는 사용하기 어렵기로 악명높고 공동 연구자들은 협업에 어려움을 겪습니다. 저희는 이러한 문제들을 해결하기위해 훌륭한 솔루션을 개발해왔으며, 많은 분들이 __appName__에 보다 쉽게 접근할 수 있다고 확신합니다. 저희의 구독료가 공정하다고 느끼도록 하기 위해 노력했으며 수많은 __appName__ 버전을 오픈 소스로 공개하여 누구든 사용할 수 있도록 했습니다.",
"want_to_create_sustainable_lasting_legacy": "오랫동안 지속될 레거시를 만들고자 합니다.",
"details_on_legacy": "__appName__과 같은 제품의 개발과 유지에는 많은 시간과 작업이 필요하기 때문에 장기적으로 이 두 가지를 모두 충족하는 비즈니스 모델을 찾아야합니다. 저희는 __appName__이 외부 자본에 의존하거나 비즈니스 모델의 실패로 인해 사라지는 것을 원치 않습니다. 지속적으로 수익성을 창출하며 __appName__을 운영할 수 있어 기쁘게 생각하며 앞으로도 오랫동안 계속되길 바랍니다.",
"get_in_touch": "연락하기",
"want_to_hear_from_you_email_us_at": "저희는 누구든 __appName__을 사용하는 분의 이야기를 듣고 싶고 저희 일에 대해 대화를 나누길 원합니다. 연락주십시오: ",
"cant_find_email": "해당 이메일 주소는 등록되지 않았습니다, 죄송합니다.",
"plans_amper_pricing": "플랜 & 가격",
"documentation": "참고 문서",
"account": "계정",
"subscription": "구독",
"log_out": "로그아웃",
"en": "English",
"pt": "Português",
"es": "Espagnol",
"fr": "Le français",
"de": "Deutsch",
"it": "Italiano",
"da": "Dansk",
"sv": "Svenska",
"no": "Norsk",
"nl": "Nederlands",
"pl": "폴란드어",
"ru": "Русский",
"uk": "우크라이나어",
"ro": "로마니아어",
"click_here_to_view_sl_in_lng": "<0>__lngName__</0>로 __appName__을 사용하시려면 이곳을 클릭하세요",
"language": "언어",
"upload": "업로드",
"menu": "메뉴",
"full_screen": "크게보기",
"logs_and_output_files": "로그 및 파일 출력",
"download_pdf": "PDF 다운로드",
"split_screen": "화면 분할",
"clear_cached_files": "캐시 파일 정리하기",
"go_to_code_location_in_pdf": "PDF의 코드 위치로 가기",
"please_compile_pdf_before_download": "PDF를 다운로드하기 전에 프로젝트를 컴파일하세요",
"remove_collaborator": "공동 연구자 삭제",
"add_to_folders": "폴더 추가",
"download_zip_file": ".zip 파일 다운로드",
"price": "가격",
"close": "닫기",
"keybindings": "키바인딩",
"restricted": "권한 없음",
"start_x_day_trial": "__len__일간 무료로 경험하세요. 오늘부터!",
"buy_now": "지금 구매하세요!",
"cs": "Čeština",
"view_all": "모두 보기",
"terms": "약관",
"privacy": "개인정보",
"contact": "문의하기",
"change_to_this_plan": "이 플랜으로 변경하기",
"processing": "처리중",
"sure_you_want_to_change_plan": "<0>__planName__</0>에 계획을 변경하길 원하시나요?",
"move_to_annual_billing": "연간 청구서로 옮기기",
"annual_billing_enabled": "연간 청구서 켜기",
"move_to_annual_billing_now": "지금 연간 청구서로 이동하기",
"change_to_annual_billing_and_save": "매년 <0>__percentage__</0>%를 할인받습니다 . 지금 변경하신다면, 매년<1>__yearlySaving__</1> 을 절약하십니다.",
"missing_template_question": "템플릿이 없나요?",
"tell_us_about_the_template": "템플릿이 없는 경우: 템플릿 복사본이나 해당 __appName__ 템플릿의 url을 저희에게 보내시거나 템플렛을 찾을 수 있는 곳을 알려주십시오. 템플렛에 대해 간략한 정보를 알려주시면 많은 도움이 됩니다.",
"email_us": "이메일 문의",
"this_project_is_public_read_only": "이 프로젝트는 공개여서 모든 사람들이 볼 수 있지만 URL로 접속한 분들은 편집할 수 없습니다.",
"tr": "Türkçe",
"select_files": "파일 선택",
"drag_files": "파일 끌기",
"upload_failed_sorry": "죄송합니다, 업로드를 실패했습니다 :(",
"inserting_files": "파일 넣는중...",
"password_reset_token_expired": "암호 재설정 토큰이 만료되었습니다. 새로운 암호 재설정 이메일을 요청하시고 그곳의 링크를 따르세요.",
"merge_project_with_github": "프로젝트를 GitHub과 합치세요",
"pull_github_changes_into_sharelatex": "GitHub 변경사항들을 __appName__로 당겨주세요",
"push_sharelatex_changes_to_github": "__appName__ 변경사항을 GitHub으로 밀어주세요",
"features": "기능",
"commit": "커밋",
"commiting": "커밋중",
"importing_and_merging_changes_in_github": "GitHub의 변경사항들을 불러오고 합칩니다",
"upgrade_for_faster_compiles": "더 빠른 컴파일을위해 업그레이드하시고 시간제한을 증가시킵니다",
"free_accounts_have_timeout_upgrade_to_increase": "무료 계정은 1분 시간제한을 가지고 있습니다. 시간제한을 증가시키시려면 업그레이드하세요.",
"learn_how_to_make_documents_compile_quickly": "문서 컴파일을 더 빠르게 만드는 방법을 배우세요",
"zh-CN": "中國語",
"cn": "중국어(간체)",
"sync_to_github": "GitHub 동기화",
"sync_to_dropbox_and_github": "Dropbox 및 GitHub 동기화",
"project_too_large": "프로젝트가 너무 큽니다",
"project_too_large_please_reduce": "이 프로젝트는 글자가 너무 많습니다. 글자수를 줄여주세요.",
"please_ask_the_project_owner_to_link_to_github": "GitHub 저장소로 이 프로젝트를 연결하려면 프로젝트 소유자에게 문의하세요",
"go_to_pdf_location_in_code": "코드에서 PDF 위치로 가세요",
"ko": "한국어",
"ja": "日本語",
"about_brian_gough": "현재는 소프트웨어 개발자이며 이전에는 Fermilab과 Los Alamos에서 고에너지 이론 물리학자로 일했습니다. 수년간 프리 소프트웨어 매뉴얼들을 TeX과 LaTex을 이용하여 출판했고 GNU Scientific Library의 관리자이기도 했습니다.",
"first_few_days_free": "첫 __trialLen__일 동안 무료",
"every": "매",
"credit_card": "신용카드",
"credit_card_number": "신용카드 번호",
"invalid": "번호 틀림",
"expiry": "유효기간",
"january": "1월",
"february": "2월",
"march": "3월",
"april": "4월",
"may": "5월",
"june": "6월",
"july": "7월",
"august": "8월",
"september": "9월",
"october": "10월",
"november": "11월",
"december": "12월",
"zip_post_code": "우편번호",
"city": "시/도",
"address": "주소",
"coupon_code": "쿠폰 코드",
"country": "국가",
"billing_address": "청구서 주소",
"upgrade_now": "지금 업그레이드",
"state": "주",
"vat_number": "VAT 번호",
"you_have_joined": "__groupName__에 참여했습니다.",
"claim_premium_account": "__groupName__로부터 제공되는 프리미엄 계정을 요청하셨습니다.",
"you_are_invited_to_group": "__groupName__에서 참여 초대를 받았습니다.",
"you_can_claim_premium_account": "이메일 확인을 통해 __groupName__로부터 제공되는 프리미엄 계정을 요청하실 수 있습니다.",
"not_now": "지금은 안 함",
"verify_email_join_group": "이메일 확인 후 그룹 참여",
"check_email_to_complete_group": "그룹 참여 완료를 위해 이메일을 확인해주십시오.",
"verify_email_address": "이메일 주소 확인",
"group_provides_you_with_premium_account": "__groupName__이(가) 당신에게 프리미엄 계정을 제공합니다. 계정 업그레이드를 위해 이메일 주소를 확인하십시오.",
"check_email_to_complete_the_upgrade": "업그레이드 완료를 위해 이메일을 확인해주세요.",
"email_link_expired": "이메일 연결이 만료되었습니다. 새로운 계정을 요청하십시오.",
"services": "서비스",
"about_shane_kilkelly": "에딘버러에서 살고 있는 소프트웨어 개발자입니다. Functional Programming과 Test Driven Development 신봉자이며 고품질의 소프트웨어를 만드는 것에 자부심을 가지고 있습니다.",
"this_is_your_template": "당신의 프로젝트에서 가져온 템플릿입니다.",
"links": "연결",
"account_settings": "계정 설정",
"search_projects": "프로젝트 검색",
"clone_project": "프로젝트 복사",
"delete_project": "프로젝트 삭제",
"download_zip": "압축 다운로드",
"new_project": "신규 프로젝트",
"blank_project": "빈 프로젝트",
"example_project": "견본 프로젝트",
"from_template": "템플릿",
"cv_or_resume": "CV 및 이력서",
"cover_letter": "Cover letter",
"journal_article": "저널 논문",
"presentation": "프레젠테이션",
"thesis": "학위 논문",
"bibliographies": "서지(bibliography)",
"terms_of_service": "이용약관",
"privacy_policy": "개인정보보호",
"plans_and_pricing": "플랜 및 가격",
"university_licences": "대학교 라이센스",
"security": "보안",
"contact_us": "문의하기",
"thanks": "감사합니다",
"blog": "블로그",
"latex_editor": "LaTeX 편집기",
"get_free_stuff": "무료로 받기",
"chat": "채팅",
"your_message": "나의 메시지",
"loading": "로딩중",
"connecting": "연결중",
"recompile": "다시 컴파일하기",
"download": "다운로드",
"email": "이메일",
"owner": "소유자",
"read_and_write": "읽기 및 쓰기",
"read_only": "읽기만 허용",
"publish": "공개",
"view_in_template_gallery": "템플릿 갤러리에서 보기",
"unpublish": "비공개",
"hotkeys": "단축키",
"saving": "저장중",
"cancel": "취소",
"project_name": "프로젝트 이름",
"root_document": "원본 파일",
"spell_check": "철자 확인",
"compiler": "컴파일러",
"private": "비공개",
"public": "공개",
"delete_forever": "영구적으로 삭제",
"support_and_feedback": "지원 및 피드백",
"help": "도움말",
"latex_templates": "LaTeX 템플릿",
"info": "정보",
"latex_help_guide": "LaTeX 도움말",
"choose_your_plan": "나만의 플랜을 선택하세요",
"indvidual_plans": "개인 플랜",
"free_forever": "평생 무료",
"low_priority_compile": "컴파일링 우선순위 낮음",
"unlimited_projects": "무제한 프로젝트",
"unlimited_compiles": "무제한 컴파일",
"full_history_of_changes": "변경사항 전체 히스토리",
"highest_priority_compiling": "최우선 컴파일링 우선순위",
"dropbox_sync": "Dropbox 동기화",
"beta": "베타",
"sign_up_now": "지금 가입하기",
"annual": "매년",
"half_price_student": "반 값 학생 플랜",
"about_us": "회사 소개",
"loading_recent_github_commits": "최근 커밋 로딩 중",
"no_new_commits_in_github": "지난번에 합친 이후로 GitHub에 새로운 명령이 없습니다.",
"dropbox_sync_description": "Dropbox 동기화로 __appName__프로젝트를 저장하세요. __appName__ 변경사항들은 자동적으로 Dropbox에 전송됩니다.",
"github_sync_description": "GitHub 동기화로, __appName__ 프로젝트를 GitHub 저장소로 연결하실 수 있습니다. __appName__의 새로운 커밋을 만들고, 오프라인이나 GitHub에서 만들어진 커밋과 합치세요.",
"github_import_description": "GitHub 동기화로, GitHub 저장사항들을 __appName__로 불러오실 수 있습니다. __appName__의 새로운 커밋을 만들고, 오프라인이나 GitHub에서 만들어진 커밋과 합치세요.",
"link_to_github_description": "프로젝트를 동기화할 수 있도록 GitHub 계정에 접속할 수 있는 __appName__ 권한이 필요합니다.",
"unlink": "연결해제",
"unlink_github_warning": "GitHub로 동기화한 모든 프로젝트는 연결이 끊길 것이며 GitHub과 더이상 동기화되지 않을 것 입니다. GitHub 계정 연결을 정말로 해지하시겠습니까?",
"github_account_successfully_linked": "GitHub 계정이 성공적으로 연결되었습니다!",
"github_successfully_linked_description": "감사합니다, __appName__로 GitHub 계정을 성공적으로 연결하였습니다. __appName__ 프로젝트를 GitHub으로 전송하시거나 GitHub 저장소의 프로젝트를 불러올 수 있습니다.",
"import_from_github": "GitHub에서 불러오기",
"github_sync_error": "죄송합니다, GitHub 서비스에 대한 에러가 있었습니다. 잠시 후 다시 시도해주시기 바랍니다.",
"loading_github_repositories": "GitHub 저장소를 불러오는 중입니다",
"select_github_repository": "__appName__에 불러올 GitHub 저장소를 선택합니다.",
"import_to_sharelatex": "__appName__에 불러오기",
"importing": "불러오는 중",
"github_sync": "GitHub 동기화",
"checking_project_github_status": "GitHub에 프로젝트 상태 확인 중",
"account_not_linked_to_github": "계정이 GitHub에 연결되어 있지 않습니다",
"project_not_linked_to_github": "이 프로젝트는 GitHub 저장소에 연결되어있지 않습니다. GitHub에 프로젝트를위한 저장소를 만드실 수 있습니다:",
"create_project_in_github": "GitHub 저장소 만들기",
"project_synced_with_git_repo_at": "이 프로젝트는 다음 위치에 GitHub 저장소와 동기화 됩니다:",
"recent_commits_in_github": "GitHub의 최근 커밋",
"sync_project_to_github": "GitHub에 프로젝트 동기화",
"sync_project_to_github_explanation": "__appName__에 만들어진 모든 변경사항이 GitHub의 모든 업데이트와 통합될 것 입니다.",
"github_merge_failed": "__appName__와 GitHub의 변경사항들은 자동적으로 병합될 수 없습니다. <0>__sharelatex_branch__</0> 브랜치를 git의<1>__master_branch__</1>브랜치로 수동적으로 병합해주시기 바랍니다. 수동적으로 합병된 후에, 계속하시려면 아래를 클릭하세요.",
"continue_github_merge": "수동으로 합병했습니다. 계속하기",
"export_project_to_github": "GitHub으로 프로젝트 보내기",
"github_validation_check": "저장소 이름이 유효한지 확인하시기 바랍니다, 그리고 저장소를 만들기위해 허가를 가지셔야 합니다.",
"repository_name": "저장소 이름",
"optional": "선택사항",
"github_public_description": "모두가 이 저장소를 볼 수 있습니다. 커밋할 수 있는 분을 선택하실 수 있습니다.",
"github_commit_message_placeholder": "__appName__로 만들어진 변경사항에 대한 메시지 커밋...",
"merge": "합치기",
"merging": "합치는중",
"github_account_is_linked": "GitHub 계정이 성공적으로 연결되었습니다.",
"unlink_github": "GitHub 계정 연결끊기",
"link_to_github": "GitHub 계정에 연결하기",
"github_integration": "GitHub 통합",
"github_is_premium": "GitHub 동기화는 프리미엄 기능입니다",
"thank_you": "감사합니다"
}
| overleaf/web/locales/ko.json/0 | {
"file_path": "overleaf/web/locales/ko.json",
"repo_id": "overleaf",
"token_count": 41236
} | 550 |
/* eslint-disable no-unused-vars */
const Helpers = require('./lib/helpers')
exports.tags = ['server-ce', 'server-pro', 'saas']
const indexes = [
{
unique: true,
key: {
doc_id: 1,
},
name: 'doc_id_1',
},
]
exports.migrate = async client => {
const { db } = client
await Helpers.addIndexesToCollection(db.docOps, indexes)
}
exports.rollback = async client => {
const { db } = client
try {
await Helpers.dropIndexesFromCollection(db.docOps, indexes)
} catch (err) {
console.error('Something went wrong rolling back the migrations', err)
}
}
| overleaf/web/migrations/20190912145006_create_docOps_indexes.js/0 | {
"file_path": "overleaf/web/migrations/20190912145006_create_docOps_indexes.js",
"repo_id": "overleaf",
"token_count": 228
} | 551 |
/* eslint-disable no-unused-vars */
const Helpers = require('./lib/helpers')
exports.tags = ['saas']
const indexes = [
{
key: {
v1_project_id: 1,
},
name: 'v1_project_id_1',
},
]
exports.migrate = async client => {
const { db } = client
await Helpers.addIndexesToCollection(db.projectImportFailures, indexes)
}
exports.rollback = async client => {
const { db } = client
try {
await Helpers.dropIndexesFromCollection(db.projectImportFailures, indexes)
} catch (err) {
console.error('Something went wrong rolling back the migrations', err)
}
}
| overleaf/web/migrations/20190912145022_create_projectImportFailures_indexes.js/0 | {
"file_path": "overleaf/web/migrations/20190912145022_create_projectImportFailures_indexes.js",
"repo_id": "overleaf",
"token_count": 220
} | 552 |
/* eslint-disable no-unused-vars */
exports.tags = ['server-ce', 'server-pro', 'saas']
async function removeDuplicates(collection, field) {
const duplicates = await collection.aggregate(
[
{
$group: {
_id: { projectId: `$deleterData.${field}` },
dups: { $addToSet: '$_id' },
count: { $sum: 1 },
},
},
{ $match: { count: { $gt: 1 } } },
],
{ allowDiskUse: true }
)
let duplicate
while ((duplicate = await duplicates.next())) {
// find duplicate items, ignore the most recent and delete the rest
const items = await collection
.find(
{ _id: { $in: duplicate.dups } },
{ projection: { _id: 1 }, sort: { 'deleterData.deletedAt': -1 } }
)
.toArray()
items.pop()
const ids = items.map(item => item._id)
await collection.deleteMany({ _id: { $in: ids } })
}
}
exports.migrate = async client => {
const { db } = client
await removeDuplicates(db.deletedProjects, 'deletedProjectId')
await removeDuplicates(db.deletedUsers, 'deletedUserId')
}
exports.rollback = async client => {
// can't really do anything here
}
| overleaf/web/migrations/20200210084301_remove-duplicate-deleted-things.js/0 | {
"file_path": "overleaf/web/migrations/20200210084301_remove-duplicate-deleted-things.js",
"repo_id": "overleaf",
"token_count": 481
} | 553 |
# Migrations
Migrations for the app environment live in this folder, and use the [East](https://github.com/okv/east) migration
framework.
We have an npm script which wraps east: `npm run migrations -- ...`
For example:
``` sh
npm run migrations -- list -t 'saas'
```
### Environments and Tags
Overleaf is deployed in three different environments:
- `server-ce`: community edition installations (the base system)
- `server-pro`: server pro installations
- `saas`: the production overleaf site
All migrations are tagged with the environments they should run in.
For example, a migration that should run in every environment would be tagged with `['server-ce', 'server-pro', 'saas']`.
When invoking east, we specify the relevant tags with the `-t` or `--tags` flag.
Our adapter will refuse to run if this flag is not set.
### Creating new migrations
To create a new migration, run:
```
npm run migrations -- create <migration name>
```
This command will create a new migration file in the migrations folder, based on a template. The template provides
`migrate` and `rollback` methods, which are run by the `east` binary when running the migrations. `rollback` should
undo the changes made in `migrate`.
#### Running scripts as a migration
To run a script in a migration file, look at `migrations/20190730093801_script_example.js`, which runs the script
`scripts/example/script_for_migration.js`. This uses a method where the script can be run standalone via `node`, or
through the migrations mechanism.
### Running migrations
To run all migrations in a server-ce environment:
``` sh
npm run migrations -- migrate -t 'server-ce'
```
To run all migrations in a saas environment:
``` sh
npm run migrations -- migrate -t 'saas'
```
The `-t` flag also works with other `east` commands like `rollback`, and `list`.
For other options, or for information on how to roll migrations back, take a look at the
[East](https://github.com/okv/east) documentation.
### Tips
Try to use Mongo directly via the `db` object instead of using Mongoose models. Migrations will need to run in the
future, and model files can change. It's unwise to make the migrations depend on code which might change.
**Note:** Running `east rollback` without any arguments rolls back *all* migrations, which you may well not want.
| overleaf/web/migrations/README.md/0 | {
"file_path": "overleaf/web/migrations/README.md",
"repo_id": "overleaf",
"token_count": 642
} | 554 |
module.exports = {}
| overleaf/web/modules/server-ce-scripts/index.js/0 | {
"file_path": "overleaf/web/modules/server-ce-scripts/index.js",
"repo_id": "overleaf",
"token_count": 7
} | 555 |
const { promisify } = require('util')
const { ObjectId, ReadPreference } = require('mongodb')
const { db, waitForDb } = require('../app/src/infrastructure/mongodb')
const sleep = promisify(setTimeout)
const _ = require('lodash')
const NOW_IN_S = Date.now() / 1000
const ONE_WEEK_IN_S = 60 * 60 * 24 * 7
const TEN_SECONDS = 10 * 1000
const DUMMY_NAME = 'unknown.tex'
const DUMMY_TIME = new Date('2021-04-12T00:00:00.000Z')
const LRUCache = require('lru-cache')
let deletedProjectsCache = null
function getSecondsFromObjectId(id) {
return id.getTimestamp().getTime() / 1000
}
async function main(options) {
if (!options) {
options = {}
}
_.defaults(options, {
dryRun: process.env.DRY_RUN === 'true',
cacheSize: parseInt(process.env.CACHE_SIZE, 10) || 100,
firstProjectId: ObjectId(process.env.FIRST_PROJECT_ID),
incrementByS: parseInt(process.env.INCREMENT_BY_S, 10) || ONE_WEEK_IN_S,
batchSize: parseInt(process.env.BATCH_SIZE, 10) || 1000,
stopAtS: parseInt(process.env.STOP_AT_S, 10) || NOW_IN_S,
letUserDoubleCheckInputsFor:
parseInt(process.env.LET_USER_DOUBLE_CHECK_INPUTS_FOR, 10) || TEN_SECONDS,
})
if (!options.firstProjectId) {
console.error('Set FIRST_PROJECT_ID and re-run.')
process.exit(1)
}
deletedProjectsCache = new LRUCache({
max: options.cacheSize,
})
await letUserDoubleCheckInputs(options)
await waitForDb()
let startId = options.firstProjectId
let nProcessed = 0
while (getSecondsFromObjectId(startId) <= options.stopAtS) {
const end = getSecondsFromObjectId(startId) + options.incrementByS
let endId = ObjectId.createFromTime(end)
const query = {
project_id: {
// include edge
$gte: startId,
// exclude edge
$lt: endId,
},
deleted: true,
name: {
$exists: false,
},
}
const docs = await db.docs
.find(query, { readPreference: ReadPreference.SECONDARY })
.project({ _id: 1, project_id: 1 })
.limit(options.batchSize)
.toArray()
if (docs.length) {
const docIds = docs.map(doc => doc._id)
console.log('Back filling dummy meta data for', JSON.stringify(docIds))
await processBatch(docs, options)
nProcessed += docIds.length
if (docs.length === options.batchSize) {
endId = docs[docs.length - 1].project_id
}
}
console.error('Processed %d until %s', nProcessed, endId)
startId = endId
}
}
async function getDeletedProject(projectId) {
const cacheKey = projectId.toString()
if (deletedProjectsCache.has(cacheKey)) {
return deletedProjectsCache.get(cacheKey)
}
const deletedProject = await db.deletedProjects.findOne(
{ 'deleterData.deletedProjectId': projectId },
{
projection: {
_id: 1,
'project.deletedDocs': 1,
},
}
)
deletedProjectsCache.set(cacheKey, deletedProject)
return deletedProject
}
async function processBatch(docs, options) {
for (const doc of docs) {
const { _id: docId, project_id: projectId } = doc
const deletedProject = await getDeletedProject(projectId)
let name = DUMMY_NAME
let deletedAt = DUMMY_TIME
if (deletedProject) {
const project = deletedProject.project
if (project) {
const deletedDoc =
project.deletedDocs &&
project.deletedDocs.find(deletedDoc => docId.equals(deletedDoc._id))
if (deletedDoc) {
console.log('Found deletedDoc for %s', docId)
name = deletedDoc.name
deletedAt = deletedDoc.deletedAt
} else {
console.log('Missing deletedDoc for %s', docId)
}
} else {
console.log('Orphaned deleted doc %s (failed hard deletion)', docId)
}
} else {
console.log('Orphaned deleted doc %s (no deletedProjects entry)', docId)
}
if (options.dryRun) continue
await db.docs.updateOne({ _id: docId }, { $set: { name, deletedAt } })
}
}
async function letUserDoubleCheckInputs(options) {
console.error('Options:', JSON.stringify(options, null, 2))
console.error(
'Waiting for you to double check inputs for',
options.letUserDoubleCheckInputsFor,
'ms'
)
await sleep(options.letUserDoubleCheckInputsFor)
}
module.exports = main
if (require.main === module) {
main()
.then(() => {
console.error('Done.')
process.exit(0)
})
.catch(error => {
console.error({ error })
process.exit(1)
})
}
| overleaf/web/scripts/back_fill_dummy_doc_meta.js/0 | {
"file_path": "overleaf/web/scripts/back_fill_dummy_doc_meta.js",
"repo_id": "overleaf",
"token_count": 1823
} | 556 |
const { ReadPreference, ObjectId } = require('mongodb')
const { db, waitForDb } = require('../../app/src/infrastructure/mongodb')
const BATCH_SIZE = parseInt(process.env.BATCH_SIZE, 10) || 1000
let BATCH_LAST_ID
if (process.env.BATCH_LAST_ID) {
BATCH_LAST_ID = ObjectId(process.env.BATCH_LAST_ID)
}
async function getNextBatch(collection, query, maxId, projection, options) {
maxId = maxId || BATCH_LAST_ID
if (maxId) {
query._id = { $gt: maxId }
}
const entries = await collection
.find(query, options)
.project(projection)
.sort({ _id: 1 })
.limit(BATCH_SIZE)
.toArray()
return entries
}
async function performUpdate(collection, nextBatch, update) {
return collection.updateMany(
{ _id: { $in: nextBatch.map(entry => entry._id) } },
update
)
}
async function batchedUpdate(
collectionName,
query,
update,
projection,
options
) {
await waitForDb()
const collection = db[collectionName]
options = options || {}
options.readPreference = ReadPreference.SECONDARY
projection = projection || { _id: 1 }
let nextBatch
let updated = 0
let maxId
while (
(nextBatch = await getNextBatch(
collection,
query,
maxId,
projection,
options
)).length
) {
maxId = nextBatch[nextBatch.length - 1]._id
updated += nextBatch.length
console.log(
`Running update on batch with ids ${JSON.stringify(
nextBatch.map(entry => entry._id)
)}`
)
if (typeof update === 'function') {
await update(collection, nextBatch)
} else {
await performUpdate(collection, nextBatch, update)
}
console.error(`Completed batch ending ${maxId}`)
}
return updated
}
function batchedUpdateWithResultHandling(collection, query, update) {
batchedUpdate(collection, query, update)
.then(updated => {
console.error({ updated })
process.exit(0)
})
.catch(error => {
console.error({ error })
process.exit(1)
})
}
module.exports = {
getNextBatch,
batchedUpdate,
batchedUpdateWithResultHandling,
}
| overleaf/web/scripts/helpers/batchedUpdate.js/0 | {
"file_path": "overleaf/web/scripts/helpers/batchedUpdate.js",
"repo_id": "overleaf",
"token_count": 801
} | 557 |
const { db, waitForDb } = require('../app/src/infrastructure/mongodb')
const minimist = require('minimist')
const _ = require('lodash')
const async = require('async')
const FeaturesUpdater = require('../app/src/Features/Subscription/FeaturesUpdater')
const UserFeaturesUpdater = require('../app/src/Features/Subscription/UserFeaturesUpdater')
const ScriptLogger = {
checkedUsersCount: 0,
mismatchUsersCount: 0,
allDaysSinceLastLoggedIn: [],
allMismatchReasons: {},
recordMismatch: (user, mismatchReasons) => {
const mismatchReasonsString = JSON.stringify(mismatchReasons)
if (ScriptLogger.allMismatchReasons[mismatchReasonsString]) {
ScriptLogger.allMismatchReasons[mismatchReasonsString].push(user._id)
} else {
ScriptLogger.allMismatchReasons[mismatchReasonsString] = [user._id]
}
ScriptLogger.mismatchUsersCount += 1
if (user.lastLoggedIn) {
const daysSinceLastLoggedIn =
(new Date() - user.lastLoggedIn) / 1000 / 3600 / 24
ScriptLogger.allDaysSinceLastLoggedIn.push(daysSinceLastLoggedIn)
}
},
printProgress: () => {
console.warn(
`Users checked: ${ScriptLogger.checkedUsersCount}. Mismatches: ${ScriptLogger.mismatchUsersCount}`
)
},
printSummary: () => {
console.log('All Mismatch Reasons:', ScriptLogger.allMismatchReasons)
console.log('Mismatch Users Count', ScriptLogger.mismatchUsersCount)
console.log(
'Average Last Logged In (Days):',
_.sum(ScriptLogger.allDaysSinceLastLoggedIn) /
ScriptLogger.allDaysSinceLastLoggedIn.length
)
console.log(
'Recent Logged In (Last 7 Days):',
_.filter(ScriptLogger.allDaysSinceLastLoggedIn, a => a < 7).length
)
console.log(
'Recent Logged In (Last 30 Days):',
_.filter(ScriptLogger.allDaysSinceLastLoggedIn, a => a < 30).length
)
},
}
const checkAndUpdateUser = (user, callback) =>
FeaturesUpdater._computeFeatures(user._id, (error, freshFeatures) => {
if (error) {
return callback(error)
}
const mismatchReasons = FeaturesUpdater.compareFeatures(
user.features,
freshFeatures
)
if (Object.keys(mismatchReasons).length === 0) {
// features are matching; nothing else to do
return callback()
}
ScriptLogger.recordMismatch(user, mismatchReasons)
if (!COMMIT) {
// not saving features; nothing else to do
return callback()
}
UserFeaturesUpdater.overrideFeatures(user._id, freshFeatures, callback)
})
const checkAndUpdateUsers = (users, callback) =>
async.eachLimit(users, ASYNC_LIMIT, checkAndUpdateUser, callback)
const loopForUsers = (skip, callback) => {
db.users
.find({})
.project({ features: 1, lastLoggedIn: 1 })
.sort({ _id: 1 })
.skip(skip)
.limit(FETCH_LIMIT)
.toArray((error, users) => {
if (error) {
return callback(error)
}
if (users.length === 0) {
console.warn('DONE')
return callback()
}
checkAndUpdateUsers(users, error => {
if (error) {
return callback(error)
}
ScriptLogger.checkedUsersCount += users.length
retryCounter = 0
ScriptLogger.printProgress()
ScriptLogger.printSummary()
loopForUsers(MONGO_SKIP + ScriptLogger.checkedUsersCount, callback)
})
})
}
let retryCounter = 0
const run = () =>
loopForUsers(MONGO_SKIP + ScriptLogger.checkedUsersCount, error => {
if (error) {
if (retryCounter < 3) {
console.error(error)
retryCounter += 1
console.warn(`RETRYING IN 60 SECONDS. (${retryCounter}/3)`)
return setTimeout(run, 6000)
}
throw error
}
process.exit()
})
let FETCH_LIMIT, ASYNC_LIMIT, COMMIT, MONGO_SKIP
const setup = () => {
const argv = minimist(process.argv.slice(2))
FETCH_LIMIT = argv.fetch ? argv.fetch : 100
ASYNC_LIMIT = argv.async ? argv.async : 10
MONGO_SKIP = argv.skip ? argv.skip : 0
COMMIT = argv.commit !== undefined
if (!COMMIT) {
console.warn('Doing dry run without --commit')
}
if (MONGO_SKIP) {
console.warn(`Skipping first ${MONGO_SKIP} records`)
}
}
waitForDb().then(() => {
setup()
run()
})
| overleaf/web/scripts/refresh_features.js/0 | {
"file_path": "overleaf/web/scripts/refresh_features.js",
"repo_id": "overleaf",
"token_count": 1690
} | 558 |
\documentclass[12pt]{article}
\usepackage[german,english]{babel}
\usepackage[utf8x]{inputenc}
\begin{document}
\title{Untitled}
\selectlanguage{german}
Der schnelle braune Fuchs sprang träge über den Hund.
\end{document}
| overleaf/web/test/acceptance/files/charsets/test-german-utf8x.tex/0 | {
"file_path": "overleaf/web/test/acceptance/files/charsets/test-german-utf8x.tex",
"repo_id": "overleaf",
"token_count": 93
} | 559 |
const { expect } = require('chai')
const { ObjectId } = require('mongodb')
const User = require('./helpers/User').promises
describe('Authentication', function () {
let user
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) {
user.logout(err => {
if (err) {
return done(err)
}
user.getCsrfToken(err => {
if (err) {
return done(err)
}
const oldToken = user.csrfToken
user.login(err => {
if (err) {
return done(err)
}
expect(oldToken === user.csrfToken).to.equal(false)
user.request.post(
{
headers: {
'x-csrf-token': oldToken,
},
url: '/project/new',
json: { projectName: 'test' },
},
(err, response, body) => {
expect(err).to.not.exist
expect(response.statusCode).to.equal(403)
expect(body).to.equal('Forbidden')
done()
}
)
})
})
})
})
})
describe('login', function () {
beforeEach('doLogin', async function () {
await user.login()
})
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 () {
const {
auditLog: [auditLogEntry],
} = await user.get()
expect(auditLogEntry).to.exist
expect(auditLogEntry.timestamp).to.exist
delete auditLogEntry.timestamp
expect(auditLogEntry).to.deep.equal({
operation: 'login',
ipAddress: '127.0.0.1',
initiatorId: ObjectId(user.id),
})
})
})
})
| overleaf/web/test/acceptance/src/AuthenticationTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/AuthenticationTests.js",
"repo_id": "overleaf",
"token_count": 1001
} | 560 |
const { expect } = require('chai')
const { User } = require('../../../app/src/models/User')
const { Subscription } = require('../../../app/src/models/Subscription')
describe('mongoose', function () {
describe('User', function () {
const email = 'wombat@potato.net'
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 () {
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 () {
let user
beforeEach(async function () {
user = await User.create({ email: 'wombat@potato.net' })
})
it('allows the creation of a subscription', async function () {
await expect(
Subscription.create({ admin_id: user._id, manager_ids: [user._id] })
).to.be.fulfilled
await expect(Subscription.findOne({ admin_id: user._id })).to.eventually
.exist
})
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
})
})
})
| overleaf/web/test/acceptance/src/ModelTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/ModelTests.js",
"repo_id": "overleaf",
"token_count": 500
} | 561 |
const { expect } = require('chai')
const async = require('async')
const User = require('./helpers/User')
const redis = require('./helpers/redis')
describe('Sessions', function () {
beforeEach(function (done) {
this.timeout(20000)
this.user1 = new User()
this.site_admin = new User({ email: 'admin@example.com' })
async.series(
[cb => this.user1.login(cb), cb => this.user1.logout(cb)],
done
)
})
describe('one session', function () {
it('should have one session in UserSessions set', function (done) {
async.series(
[
next => {
redis.clearUserSessions(this.user1, next)
},
// login, should add session to set
next => {
this.user1.login(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(1)
expect(sessions[0].slice(0, 5)).to.equal('sess:')
next()
})
},
// should be able to access project list page
next => {
this.user1.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(200)
next()
})
},
// logout, should remove session from set
next => {
this.user1.logout(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(0)
next()
})
},
],
(err, result) => {
if (err) {
throw err
}
done()
}
)
})
})
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) {
async.series(
[
next => {
redis.clearUserSessions(this.user1, next)
},
// login, should add session to set
next => {
this.user1.login(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(1)
expect(sessions[0].slice(0, 5)).to.equal('sess:')
next()
})
},
// login again, should add the second session to set
next => {
this.user2.login(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(2)
expect(sessions[0].slice(0, 5)).to.equal('sess:')
expect(sessions[1].slice(0, 5)).to.equal('sess:')
next()
})
},
// both should be able to access project list page
next => {
this.user1.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(200)
next()
})
},
next => {
this.user2.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(200)
next()
})
},
// logout first session, should remove session from set
next => {
this.user1.logout(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(1)
next()
})
},
// first session should not have access to project list page
next => {
this.user1.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(302)
next()
})
},
// second session should still have access to settings
next => {
this.user2.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(200)
next()
})
},
// logout second session, should remove last session from set
next => {
this.user2.logout(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(0)
next()
})
},
// second session should not have access to project list page
next => {
this.user2.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(302)
next()
})
},
],
(err, result) => {
if (err) {
throw err
}
done()
}
)
})
})
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
this.user2.password = this.user1.password
this.user3 = new User()
this.user3.email = this.user1.email
this.user3.password = this.user1.password
})
it('should erase both sessions when password is reset', function (done) {
async.series(
[
next => {
redis.clearUserSessions(this.user1, next)
},
// login, should add session to set
next => {
this.user1.login(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(1)
expect(sessions[0].slice(0, 5)).to.equal('sess:')
next()
})
},
// login again, should add the second session to set
next => {
this.user2.login(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(2)
expect(sessions[0].slice(0, 5)).to.equal('sess:')
expect(sessions[1].slice(0, 5)).to.equal('sess:')
next()
})
},
// login third session, should add the second session to set
next => {
this.user3.login(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(3)
expect(sessions[0].slice(0, 5)).to.equal('sess:')
expect(sessions[1].slice(0, 5)).to.equal('sess:')
next()
})
},
// password reset from second session, should erase two of the three sessions
next => {
this.user2.changePassword(err => next(err))
},
next => {
redis.getUserSessions(this.user2, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(1)
next()
})
},
// users one and three should not be able to access project list page
next => {
this.user1.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(302)
next()
})
},
next => {
this.user3.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(302)
next()
})
},
// user two should still be logged in, and able to access project list page
next => {
this.user2.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(200)
next()
})
},
// logout second session, should remove last session from set
next => {
this.user2.logout(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(0)
next()
})
},
],
(err, result) => {
if (err) {
throw err
}
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
this.user2.password = this.user1.password
this.user3 = new User()
this.user3.email = this.user1.email
this.user3.password = this.user1.password
async.series([this.user2.login.bind(this.user2)], done)
})
it('should allow the user to erase the other two sessions', function (done) {
async.series(
[
next => {
redis.clearUserSessions(this.user1, next)
},
// login, should add session to set
next => {
this.user1.login(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(1)
expect(sessions[0].slice(0, 5)).to.equal('sess:')
next()
})
},
// login again, should add the second session to set
next => {
this.user2.login(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(2)
expect(sessions[0].slice(0, 5)).to.equal('sess:')
expect(sessions[1].slice(0, 5)).to.equal('sess:')
next()
})
},
// login third session, should add the second session to set
next => {
this.user3.login(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(3)
expect(sessions[0].slice(0, 5)).to.equal('sess:')
expect(sessions[1].slice(0, 5)).to.equal('sess:')
next()
})
},
// check the sessions page
next => {
this.user2.request.get(
{
uri: '/user/sessions',
},
(err, response, body) => {
expect(err).to.be.oneOf([null, undefined])
expect(response.statusCode).to.equal(200)
next()
}
)
},
// clear sessions from second session, should erase two of the three sessions
next => {
this.user2.getCsrfToken(err => {
expect(err).to.be.oneOf([null, undefined])
this.user2.request.post(
{
uri: '/user/sessions/clear',
},
err => next(err)
)
})
},
next => {
redis.getUserSessions(this.user2, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(1)
next()
})
},
// users one and three should not be able to access project list page
next => {
this.user1.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(302)
next()
})
},
next => {
this.user3.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(302)
next()
})
},
// user two should still be logged in, and able to access project list page
next => {
this.user2.getProjectListPage((err, statusCode) => {
expect(err).to.equal(null)
expect(statusCode).to.equal(200)
next()
})
},
// logout second session, should remove last session from set
next => {
this.user2.logout(err => next(err))
},
next => {
redis.getUserSessions(this.user1, (err, sessions) => {
expect(err).to.not.exist
expect(sessions.length).to.equal(0)
next()
})
},
// the user audit log should have been updated
next => {
this.user1.getAuditLogWithoutNoise((error, auditLog) => {
expect(error).not.to.exist
expect(auditLog).to.exist
expect(auditLog[0].operation).to.equal('clear-sessions')
expect(auditLog[0].ipAddress).to.exist
expect(auditLog[0].initiatorId).to.exist
expect(auditLog[0].timestamp).to.exist
expect(auditLog[0].info.sessions.length).to.equal(2)
next()
})
},
],
(err, result) => {
if (err) {
throw err
}
done()
}
)
})
})
})
| overleaf/web/test/acceptance/src/SessionTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/SessionTests.js",
"repo_id": "overleaf",
"token_count": 7617
} | 562 |
const RateLimiter = require('../../../../app/src/infrastructure/RateLimiter')
async function clearOverleafLoginRateLimit() {
await RateLimiter.promises.clearRateLimit('overleaf-login', '127.0.0.1')
}
module.exports = {
initialize() {
before(clearOverleafLoginRateLimit)
},
}
| overleaf/web/test/acceptance/src/helpers/RedisHelper.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/helpers/RedisHelper.js",
"repo_id": "overleaf",
"token_count": 97
} | 563 |
const AbstractMockApi = require('./AbstractMockApi')
// Currently there is nothing implemented here as we have no acceptance tests
// for the notifications API. This does however stop errors appearing in the
// output when the acceptance tests try to connect.
class MockNotificationsApi extends AbstractMockApi {
applyRoutes() {
this.app.get('/*', (req, res) => res.sendStatus(200))
this.app.post('/*', (req, res) => res.sendStatus(200))
}
}
module.exports = MockNotificationsApi
// type hint for the inherited `instance` method
/**
* @function instance
* @memberOf MockNotificationsApi
* @static
* @returns {MockNotificationsApi}
*/
| overleaf/web/test/acceptance/src/mocks/MockNotificationsApi.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/mocks/MockNotificationsApi.js",
"repo_id": "overleaf",
"token_count": 197
} | 564 |
import { expect } from 'chai'
import sinon from 'sinon'
import { fireEvent, render, screen } from '@testing-library/react'
import OnlineUsersWidget from '../../../../../frontend/js/features/editor-navigation-toolbar/components/online-users-widget'
describe('<OnlineUsersWidget />', function () {
const defaultProps = {
onlineUsers: [
{
user_id: 'test_user',
name: 'test_user',
},
{
user_id: 'another_test_user',
name: 'another_test_user',
},
],
goToUser: () => {},
}
describe('with less than 4 users', function () {
it('displays user initials', function () {
render(<OnlineUsersWidget {...defaultProps} />)
screen.getByText('t')
screen.getByText('a')
})
it('displays user name in a tooltip', function () {
render(<OnlineUsersWidget {...defaultProps} />)
const icon = screen.getByText('t')
fireEvent.mouseOver(icon)
screen.getByRole('tooltip', { name: 'test_user' })
})
it('calls "goToUser" when the user initial is clicked', function () {
const props = {
...defaultProps,
goToUser: sinon.stub(),
}
render(<OnlineUsersWidget {...props} />)
const icon = screen.getByText('t')
fireEvent.click(icon)
expect(props.goToUser).to.be.calledWith({
name: 'test_user',
user_id: 'test_user',
})
})
})
describe('with 4 users and more', function () {
const props = {
...defaultProps,
onlineUsers: defaultProps.onlineUsers.concat([
{
user_id: 'user_3',
name: 'user_3',
},
{
user_id: 'user_4',
name: 'user_4',
},
]),
}
it('displays the count of users', function () {
render(<OnlineUsersWidget {...props} />)
screen.getByText('4')
})
it('displays user names on hover', function () {
render(<OnlineUsersWidget {...props} />)
const toggleButton = screen.getByRole('button')
fireEvent.click(toggleButton)
screen.getByText('test_user')
screen.getByText('another_test_user')
screen.getByText('user_3')
screen.getByText('user_4')
})
it('calls "goToUser" when the user name is clicked', function () {
const testProps = {
...props,
goToUser: sinon.stub(),
}
render(<OnlineUsersWidget {...testProps} />)
const toggleButton = screen.getByRole('button')
fireEvent.click(toggleButton)
const icon = screen.getByText('user_3')
fireEvent.click(icon)
expect(testProps.goToUser).to.be.calledWith({
name: 'user_3',
user_id: 'user_3',
})
})
})
})
| overleaf/web/test/frontend/features/editor-navigation-toolbar/components/online-users-widget.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/editor-navigation-toolbar/components/online-users-widget.test.js",
"repo_id": "overleaf",
"token_count": 1179
} | 565 |
import { expect } from 'chai'
import sinon from 'sinon'
import { screen, fireEvent, waitFor } from '@testing-library/react'
import fetchMock from 'fetch-mock'
import MockedSocket from 'socket.io-mock'
import {
renderWithEditorContext,
cleanUpContext,
} from '../../../helpers/render-with-context'
import FileTreeRoot from '../../../../../frontend/js/features/file-tree/components/file-tree-root'
describe('FileTree Delete Entity Flow', function () {
const onSelect = sinon.stub()
const onInit = sinon.stub()
afterEach(function () {
fetchMock.restore()
onSelect.reset()
onInit.reset()
cleanUpContext()
})
describe('single entity', function () {
beforeEach(function () {
const rootFolder = [
{
_id: 'root-folder-id',
docs: [{ _id: '456def', name: 'main.tex' }],
folders: [],
fileRefs: [],
},
]
renderWithEditorContext(
<FileTreeRoot
rootFolder={rootFolder}
projectId="123abc"
hasWritePermissions
userHasFeature={() => true}
refProviders={{}}
reindexReferences={() => null}
setRefProviderEnabled={() => null}
setStartedFreeTrial={() => null}
onSelect={onSelect}
onInit={onInit}
isConnected
/>,
{ socket: new MockedSocket() }
)
const treeitem = screen.getByRole('treeitem', { name: 'main.tex' })
fireEvent.click(treeitem)
const toggleButton = screen.getByRole('button', { name: 'Menu' })
fireEvent.click(toggleButton)
const deleteButton = screen.getByRole('menuitem', { name: 'Delete' })
fireEvent.click(deleteButton)
})
it('removes item', async function () {
const fetchMatcher = /\/project\/\w+\/doc\/\w+/
fetchMock.delete(fetchMatcher, 204)
const modalDeleteButton = await getModalDeleteButton()
fireEvent.click(modalDeleteButton)
window._ide.socket.socketClient.emit('removeEntity', '456def')
await waitFor(() => {
expect(
screen.queryByRole('treeitem', {
name: 'main.tex',
hidden: true, // treeitem might be hidden behind the modal
})
).to.not.exist
expect(
screen.queryByRole('treeitem', {
name: 'main.tex',
})
).to.not.exist
// check that the confirmation modal is closed
expect(screen.queryByText(/Are you sure/)).to.not.exist
})
const [lastFetchPath] = fetchMock.lastCall(fetchMatcher)
expect(lastFetchPath).to.equal('/project/123abc/doc/456def')
})
it('continues delete on 404s', async function () {
fetchMock.delete(/\/project\/\w+\/doc\/\w+/, 404)
const modalDeleteButton = await getModalDeleteButton()
fireEvent.click(modalDeleteButton)
window._ide.socket.socketClient.emit('removeEntity', '456def')
// check that the confirmation modal is open
screen.getByText(/Are you sure/)
await waitFor(() => {
expect(
screen.queryByRole('treeitem', {
name: 'main.tex',
hidden: true, // treeitem might be hidden behind the modal
})
).to.not.exist
expect(
screen.queryByRole('treeitem', {
name: 'main.tex',
})
).to.not.exist
// check that the confirmation modal is closed
// is not, the 404 probably triggered a bug
expect(screen.queryByText(/Are you sure/)).to.not.exist
})
})
it('aborts delete on error', async function () {
const fetchMatcher = /\/project\/\w+\/doc\/\w+/
fetchMock.delete(fetchMatcher, 500)
const modalDeleteButton = await getModalDeleteButton()
fireEvent.click(modalDeleteButton)
// The modal should still be open, but the file should not be deleted
await screen.findByRole('treeitem', { name: 'main.tex', hidden: true })
})
})
describe('folders', function () {
beforeEach(function () {
const rootFolder = [
{
docs: [{ _id: '456def', name: 'main.tex' }],
folders: [
{
_id: '123abc',
name: 'folder',
docs: [],
folders: [],
fileRefs: [{ _id: '789ghi', name: 'my.bib' }],
},
],
fileRefs: [],
},
]
renderWithEditorContext(
<FileTreeRoot
rootFolder={rootFolder}
projectId="123abc"
hasWritePermissions
userHasFeature={() => true}
refProviders={{}}
reindexReferences={() => null}
setRefProviderEnabled={() => null}
setStartedFreeTrial={() => null}
onSelect={onSelect}
onInit={onInit}
isConnected
/>,
{ socket: new MockedSocket() }
)
const expandButton = screen.queryByRole('button', { name: 'Expand' })
if (expandButton) fireEvent.click(expandButton)
const treeitemDoc = screen.getByRole('treeitem', { name: 'main.tex' })
fireEvent.click(treeitemDoc)
const treeitemFile = screen.getByRole('treeitem', { name: 'my.bib' })
fireEvent.click(treeitemFile, { ctrlKey: true })
window._ide.socket.socketClient.emit('removeEntity', '123abc')
})
it('removes the folder', function () {
expect(screen.queryByRole('treeitem', { name: 'folder' })).to.not.exist
})
it('leaves the main file selected', function () {
screen.getByRole('treeitem', { name: 'main.tex', selected: true })
})
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.
const toggleButton = screen.getByRole('button', { name: 'Menu' })
fireEvent.click(toggleButton)
const deleteButton = screen.getByRole('menuitem', { name: 'Delete' })
fireEvent.click(deleteButton)
await waitFor(() => screen.getByRole('button', { name: 'Cancel' }))
})
})
describe('multiple entities', function () {
beforeEach(async function () {
const rootFolder = [
{
_id: 'root-folder-id',
docs: [{ _id: '456def', name: 'main.tex' }],
folders: [],
fileRefs: [{ _id: '789ghi', name: 'my.bib' }],
},
]
renderWithEditorContext(
<FileTreeRoot
rootFolder={rootFolder}
projectId="123abc"
hasWritePermissions
userHasFeature={() => true}
refProviders={{}}
reindexReferences={() => null}
setRefProviderEnabled={() => null}
setStartedFreeTrial={() => null}
onSelect={onSelect}
onInit={onInit}
isConnected
/>,
{ socket: new MockedSocket() }
)
// select two files
const treeitemDoc = screen.getByRole('treeitem', { name: 'main.tex' })
fireEvent.click(treeitemDoc)
const treeitemFile = screen.getByRole('treeitem', { name: 'my.bib' })
fireEvent.click(treeitemFile, { ctrlKey: true })
// open the context menu
const treeitemButton = screen.getByRole('button', { name: 'my.bib' })
fireEvent.contextMenu(treeitemButton)
// make sure the menu has opened, with only a "Delete" item (as multiple files are selected)
screen.getByRole('menu')
const menuItems = await screen.findAllByRole('menuitem')
expect(menuItems.length).to.equal(1)
// select the Delete menu item
const deleteButton = screen.getByRole('menuitem', { name: 'Delete' })
fireEvent.click(deleteButton)
})
it('removes all items', async function () {
const fetchMatcher = /\/project\/\w+\/(doc|file)\/\w+/
fetchMock.delete(fetchMatcher, 204)
const modalDeleteButton = await getModalDeleteButton()
fireEvent.click(modalDeleteButton)
window._ide.socket.socketClient.emit('removeEntity', '456def')
window._ide.socket.socketClient.emit('removeEntity', '789ghi')
await waitFor(() => {
for (const name of ['main.tex', 'my.bib']) {
expect(
screen.queryByRole('treeitem', {
name,
hidden: true, // treeitem might be hidden behind the modal
})
).to.not.exist
expect(
screen.queryByRole('treeitem', {
name,
})
).to.not.exist
// check that the confirmation modal is closed
expect(screen.queryByText(/Are you sure/)).to.not.exist
}
})
const [firstFetchPath, secondFetchPath] = fetchMock
.calls()
.map(([url]) => url)
expect(firstFetchPath).to.equal('/project/123abc/doc/456def')
expect(secondFetchPath).to.equal('/project/123abc/file/789ghi')
})
})
async function getModalDeleteButton() {
return waitFor(() => screen.getByRole('button', { name: 'Delete' }))
}
})
| overleaf/web/test/frontend/features/file-tree/flows/delete-entity.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/file-tree/flows/delete-entity.test.js",
"repo_id": "overleaf",
"token_count": 3953
} | 566 |
import { expect } from 'chai'
import sinon from 'sinon'
import { screen, render, fireEvent } from '@testing-library/react'
import PreviewLogsPaneEntry from '../../../../../frontend/js/features/preview/components/preview-logs-pane-entry.js'
describe('<PreviewLogsPaneEntry />', function () {
const level = 'error'
it('renders a configurable aria-label', function () {
const sampleAriaLabel = 'lorem ipsum dolor sit amet'
render(
<PreviewLogsPaneEntry entryAriaLabel={sampleAriaLabel} level={level} />
)
screen.getByLabelText(sampleAriaLabel)
})
describe('logs pane source location link', function () {
const file = 'foo.tex'
const line = 42
const column = 21
const onSourceLocationClick = sinon.stub()
afterEach(function () {
onSourceLocationClick.reset()
})
it('renders both file and line', function () {
render(
<PreviewLogsPaneEntry sourceLocation={{ file, line }} level={level} />
)
screen.getByRole('button', {
name: `Navigate to log position in source code: ${file}, ${line}`,
})
})
it('renders only file when line information is not available', function () {
render(<PreviewLogsPaneEntry sourceLocation={{ file }} level={level} />)
screen.getByRole('button', {
name: `Navigate to log position in source code: ${file}`,
})
})
it('does not render when file information is not available', function () {
render(<PreviewLogsPaneEntry level={level} />)
expect(
screen.queryByRole('button', {
name: `Navigate to log position in source code: `,
})
).to.not.exist
})
it('calls the callback with file, line and column on click', function () {
render(
<PreviewLogsPaneEntry
sourceLocation={{ file, line, column }}
level={level}
onSourceLocationClick={onSourceLocationClick}
/>
)
const linkToSourceButton = screen.getByRole('button', {
name: `Navigate to log position in source code: ${file}, ${line}`,
})
fireEvent.click(linkToSourceButton)
expect(onSourceLocationClick).to.be.calledOnce
expect(onSourceLocationClick).to.be.calledWith({
file,
line,
column,
})
})
})
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
// Here we are simulating that the content is bigger than the `collapsedSize`, so
// the expand-collapse widget is used
const originalScrollHeight = Object.getOwnPropertyDescriptor(
HTMLElement.prototype,
'offsetHeight'
)
const originalScrollWidth = Object.getOwnPropertyDescriptor(
HTMLElement.prototype,
'offsetWidth'
)
beforeEach(function () {
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {
configurable: true,
value: 500,
})
Object.defineProperty(HTMLElement.prototype, 'scrollWidth', {
configurable: true,
value: 500,
})
})
afterEach(function () {
Object.defineProperty(
HTMLElement.prototype,
'scrollHeight',
originalScrollHeight
)
Object.defineProperty(
HTMLElement.prototype,
'scrollWidth',
originalScrollWidth
)
})
it('renders collapsed contents by default', function () {
render(<PreviewLogsPaneEntry rawContent={rawContent} level={level} />)
screen.getByText(rawContent)
screen.getByRole('button', {
name: 'Expand',
})
})
it('supports expanding contents', function () {
render(<PreviewLogsPaneEntry rawContent={rawContent} level={level} />)
screen.getByText(rawContent)
const expandCollapseBtn = screen.getByRole('button', {
name: 'Expand',
})
fireEvent.click(expandCollapseBtn)
screen.getByRole('button', {
name: 'Collapse',
})
})
it('should not render at all when there are no log contents', function () {
const { container } = render(<PreviewLogsPaneEntry level={level} />)
expect(container.querySelector('.log-entry-content')).to.not.exist
})
})
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 () {
render(
<PreviewLogsPaneEntry
rawContent={rawContent}
formattedContent={formattedContent}
extraInfoURL={infoURL}
level={level}
/>
)
screen.getByText(formattedContentText)
})
it('renders the link to learn more', function () {
render(
<PreviewLogsPaneEntry
rawContent={rawContent}
formattedContent={formattedContent}
extraInfoURL={infoURL}
level={level}
/>
)
screen.getByRole('link', { name: 'Learn more' })
})
it('does not render the link when it is not available', function () {
render(
<PreviewLogsPaneEntry
rawContent={rawContent}
formattedContent={formattedContent}
level={level}
/>
)
expect(screen.queryByRole('link', { name: 'Learn more' })).to.not.exist
})
})
})
| overleaf/web/test/frontend/features/preview/components/preview-logs-pane-entry.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/preview/components/preview-logs-pane-entry.test.js",
"repo_id": "overleaf",
"token_count": 2173
} | 567 |
import { expect } from 'chai'
import { render } from '@testing-library/react'
import Processing from '../../../../frontend/js/shared/components/processing'
describe('<Processing />', function () {
it('renders processing UI when isProcessing is true', function () {
const { container } = render(<Processing isProcessing />)
const element = container.querySelector('i.fa.fa-refresh')
expect(element).to.exist
})
it('does not render processing UI when isProcessing is false', function () {
const { container } = render(<Processing isProcessing={false} />)
const element = container.querySelector('i.fa.fa-refresh')
expect(element).to.not.exist
})
})
| overleaf/web/test/frontend/shared/components/processing.test.js/0 | {
"file_path": "overleaf/web/test/frontend/shared/components/processing.test.js",
"repo_id": "overleaf",
"token_count": 212
} | 568 |
const OError = require('@overleaf/o-error')
const { assertHasStatusCode } = require('./requestHelper')
const CSRF_REGEX = /<meta name="ol-csrfToken" content="(.+?)">/
function _parseCsrf(body) {
const match = CSRF_REGEX.exec(body)
if (!match) {
throw new Error('Cannot find csrfToken in HTML')
}
return match[1]
}
function getCsrfTokenForFactory({ request }) {
return async function getCsrfTokenFor(endpoint) {
try {
const response = await request(endpoint)
assertHasStatusCode(response, 200)
return _parseCsrf(response.body)
} catch (err) {
throw new OError(`error fetching csrf token on ${endpoint}`, {}, err)
}
}
}
module.exports = {
getCsrfTokenForFactory,
}
| overleaf/web/test/smoke/src/support/Csrf.js/0 | {
"file_path": "overleaf/web/test/smoke/src/support/Csrf.js",
"repo_id": "overleaf",
"token_count": 274
} | 569 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const assert = require('assert')
const path = require('path')
const sinon = require('sinon')
const modulePath = path.join(
__dirname,
'../../../../app/src/Features/Chat/ChatController'
)
const { expect } = require('chai')
describe('ChatController', function () {
beforeEach(function () {
this.user_id = 'mock-user-id'
this.settings = {}
this.ChatApiHandler = {}
this.EditorRealTimeController = { emitToRoom: sinon.stub() }
this.SessionManager = {
getLoggedInUserId: sinon.stub().returns(this.user_id),
}
this.ChatController = SandboxedModule.require(modulePath, {
requires: {
'@overleaf/settings': this.settings,
'./ChatApiHandler': this.ChatApiHandler,
'../Editor/EditorRealTimeController': this.EditorRealTimeController,
'../Authentication/SessionManager': this.SessionManager,
'../User/UserInfoManager': (this.UserInfoManager = {}),
'../User/UserInfoController': (this.UserInfoController = {}),
},
})
this.req = {
params: {
project_id: this.project_id,
},
}
this.res = {
json: sinon.stub(),
send: sinon.stub(),
sendStatus: sinon.stub(),
}
})
describe('sendMessage', function () {
beforeEach(function () {
this.req.body = { content: (this.content = 'message-content') }
this.UserInfoManager.getPersonalInfo = sinon
.stub()
.yields(null, (this.user = { unformatted: 'user' }))
this.UserInfoController.formatPersonalInfo = sinon
.stub()
.returns((this.formatted_user = { formatted: 'user' }))
this.ChatApiHandler.sendGlobalMessage = sinon
.stub()
.yields(
null,
(this.message = { mock: 'message', user_id: this.user_id })
)
return this.ChatController.sendMessage(this.req, this.res)
})
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 () {
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 () {
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 () {
return this.EditorRealTimeController.emitToRoom
.calledWith(this.project_id, 'new-chat-message', this.message)
.should.equal(true)
})
it('should return a 204 status code', function () {
return this.res.sendStatus.calledWith(204).should.equal(true)
})
})
describe('getMessages', function () {
beforeEach(function () {
this.req.query = {
limit: (this.limit = '30'),
before: (this.before = '12345'),
}
this.ChatController._injectUserInfoIntoThreads = sinon.stub().yields()
this.ChatApiHandler.getGlobalMessages = sinon
.stub()
.yields(null, (this.messages = ['mock', 'messages']))
return this.ChatController.getMessages(this.req, this.res)
})
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 () {
return this.res.json.calledWith(this.messages).should.equal(true)
})
})
describe('_injectUserInfoIntoThreads', function () {
beforeEach(function () {
this.users = {
user_id_1: {
mock: 'user_1',
},
user_id_2: {
mock: 'user_2',
},
}
this.UserInfoManager.getPersonalInfo = (user_id, callback) => {
return callback(null, this.users[user_id])
}
sinon.spy(this.UserInfoManager, 'getPersonalInfo')
return (this.UserInfoController.formatPersonalInfo = user => ({
formatted: user.mock,
}))
})
it('should inject a user object into messaged and resolved data', function (done) {
return this.ChatController._injectUserInfoIntoThreads(
{
thread1: {
resolved: true,
resolved_by_user_id: 'user_id_1',
messages: [
{
user_id: 'user_id_1',
content: 'foo',
},
{
user_id: 'user_id_2',
content: 'bar',
},
],
},
thread2: {
messages: [
{
user_id: 'user_id_1',
content: 'baz',
},
],
},
},
(error, threads) => {
expect(threads).to.deep.equal({
thread1: {
resolved: true,
resolved_by_user_id: 'user_id_1',
resolved_by_user: { formatted: 'user_1' },
messages: [
{
user_id: 'user_id_1',
user: { formatted: 'user_1' },
content: 'foo',
},
{
user_id: 'user_id_2',
user: { formatted: 'user_2' },
content: 'bar',
},
],
},
thread2: {
messages: [
{
user_id: 'user_id_1',
user: { formatted: 'user_1' },
content: 'baz',
},
],
},
})
return done()
}
)
})
it('should only need to look up each user once', function (done) {
return this.ChatController._injectUserInfoIntoThreads(
[
{
messages: [
{
user_id: 'user_id_1',
content: 'foo',
},
{
user_id: 'user_id_1',
content: 'bar',
},
],
},
],
(error, threads) => {
this.UserInfoManager.getPersonalInfo.calledOnce.should.equal(true)
return done()
}
)
})
})
})
| overleaf/web/test/unit/src/Chat/ChatControllerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Chat/ChatControllerTests.js",
"repo_id": "overleaf",
"token_count": 3318
} | 570 |
/* eslint-disable
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const sinon = require('sinon')
const { expect } = require('chai')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Cooldown/CooldownMiddleware'
)
describe('CooldownMiddleware', function () {
beforeEach(function () {
this.CooldownManager = { isProjectOnCooldown: sinon.stub() }
return (this.CooldownMiddleware = SandboxedModule.require(modulePath, {
requires: {
'./CooldownManager': this.CooldownManager,
},
}))
})
describe('freezeProject', function () {
describe('when project is on cooldown', function () {
beforeEach(function () {
this.CooldownManager.isProjectOnCooldown = sinon
.stub()
.callsArgWith(1, null, true)
this.req = { params: { Project_id: 'abc' } }
this.res = { sendStatus: sinon.stub() }
return (this.next = sinon.stub())
})
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
.calledWith('abc')
.should.equal(true)
})
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 () {
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 () {
this.CooldownManager.isProjectOnCooldown = sinon
.stub()
.callsArgWith(1, null, false)
this.req = { params: { Project_id: 'abc' } }
this.res = { sendStatus: sinon.stub() }
return (this.next = sinon.stub())
})
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
.calledWith('abc')
.should.equal(true)
})
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 () {
this.CooldownManager.isProjectOnCooldown = sinon
.stub()
.callsArgWith(1, new Error('woops'))
this.req = { params: { Project_id: 'abc' } }
this.res = { sendStatus: sinon.stub() }
return (this.next = sinon.stub())
})
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
.calledWith('abc')
.should.equal(true)
})
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 () {
this.CooldownManager.isProjectOnCooldown = sinon
.stub()
.callsArgWith(1, null, true)
this.req = { params: { lol: 'abc' } }
this.res = { sendStatus: sinon.stub() }
return (this.next = sinon.stub())
})
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 () {
this.CooldownMiddleware.freezeProject(this.req, this.res, this.next)
return this.CooldownManager.isProjectOnCooldown.callCount.should.equal(
0
)
})
})
})
})
| overleaf/web/test/unit/src/Cooldown/CooldownMiddlewareTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Cooldown/CooldownMiddlewareTests.js",
"repo_id": "overleaf",
"token_count": 1978
} | 571 |
/* eslint-disable
camelcase,
max-len,
no-return-assign,
no-unused-vars,
no-useless-escape,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const assert = require('assert')
const { expect } = require('chai')
const sinon = require('sinon')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Exports/ExportsController.js'
)
describe('ExportsController', function () {
const project_id = '123njdskj9jlk'
const user_id = '123nd3ijdks'
const brand_variation_id = 22
const firstName = 'first'
const lastName = 'last'
const title = 'title'
const description = 'description'
const author = 'author'
const license = 'other'
const show_source = true
beforeEach(function () {
this.handler = { getUserNotifications: sinon.stub().callsArgWith(1) }
this.req = {
params: {
project_id,
brand_variation_id,
},
body: {
firstName,
lastName,
},
session: {
user: {
_id: user_id,
},
},
i18n: {
translate() {},
},
}
this.res = {
json: sinon.stub(),
status: sinon.stub(),
}
this.res.status.returns(this.res)
this.next = sinon.stub()
this.AuthenticationController = {
getLoggedInUserId: sinon.stub().returns(this.req.session.user._id),
}
return (this.controller = SandboxedModule.require(modulePath, {
requires: {
'./ExportsHandler': this.handler,
'../Authentication/AuthenticationController': this
.AuthenticationController,
},
}))
})
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 })
const expected = {
project_id,
user_id,
brand_variation_id,
first_name: firstName,
last_name: lastName,
}
return this.controller.exportProject(this.req, {
json: body => {
expect(this.handler.exportProject.args[0][0]).to.deep.equal(expected)
expect(body).to.deep.equal({ export_v1_id: 897, message: undefined })
return 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,
message: 'RESUBMISSION',
})
const expected = {
project_id,
user_id,
brand_variation_id,
first_name: firstName,
last_name: lastName,
}
return this.controller.exportProject(this.req, {
json: body => {
expect(this.handler.exportProject.args[0][0]).to.deep.equal(expected)
expect(body).to.deep.equal({
export_v1_id: 897,
message: 'RESUBMISSION',
})
return done()
},
})
})
})
describe('with gallery fields', function () {
beforeEach(function () {
this.req.body.title = title
this.req.body.description = description
this.req.body.author = author
this.req.body.license = license
return (this.req.body.showSource = true)
})
it('should ask the handler to perform the export', function (done) {
this.handler.exportProject = sinon
.stub()
.yields(null, { iAmAnExport: true, v1_id: 897 })
const expected = {
project_id,
user_id,
brand_variation_id,
first_name: firstName,
last_name: lastName,
title,
description,
author,
license,
show_source,
}
return this.controller.exportProject(this.req, {
json: body => {
expect(this.handler.exportProject.args[0][0]).to.deep.equal(expected)
expect(body).to.deep.equal({ export_v1_id: 897, message: undefined })
return 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()
.yields({ forwardResponse: this.error_json })
this.controller.exportProject(this.req, this.res, this.next)
expect(this.res.json.args[0][0]).to.deep.equal(this.error_json)
expect(this.res.status.args[0][0]).to.equal(this.error_json.status)
return done()
})
})
it('should ask the handler to return the status of an export', function (done) {
this.handler.fetchExport = sinon.stub().yields(
null,
`{ \
\"id\":897, \
\"status_summary\":\"completed\", \
\"status_detail\":\"all done\", \
\"partner_submission_id\":\"abc123\", \
\"v2_user_email\":\"la@tex.com\", \
\"v2_user_first_name\":\"Arthur\", \
\"v2_user_last_name\":\"Author\", \
\"title\":\"my project\", \
\"token\":\"token\" \
}`
)
this.req.params = { project_id, export_id: 897 }
return this.controller.exportStatus(this.req, {
json: body => {
expect(body).to.deep.equal({
export_json: {
status_summary: 'completed',
status_detail: 'all done',
partner_submission_id: 'abc123',
v2_user_email: 'la@tex.com',
v2_user_first_name: 'Arthur',
v2_user_last_name: 'Author',
title: 'my project',
token: 'token',
},
})
return done()
},
})
})
})
| overleaf/web/test/unit/src/Exports/ExportsControllerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Exports/ExportsControllerTests.js",
"repo_id": "overleaf",
"token_count": 2613
} | 572 |
/* eslint-disable
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const assert = require('assert')
const { expect } = require('chai')
const sinon = require('sinon')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Institutions/InstitutionsFeatures.js'
)
describe('InstitutionsFeatures', function () {
beforeEach(function () {
this.UserGetter = { getUserFullEmails: sinon.stub() }
this.PlansLocator = { findLocalPlanInSettings: sinon.stub() }
this.institutionPlanCode = 'institution_plan_code'
this.InstitutionsFeatures = SandboxedModule.require(modulePath, {
requires: {
'../User/UserGetter': this.UserGetter,
'../Subscription/PlansLocator': this.PlansLocator,
'@overleaf/settings': {
institutionPlanCode: this.institutionPlanCode,
},
},
})
return (this.userId = '12345abcde')
})
describe('hasLicence', function () {
it('should handle error', function (done) {
this.UserGetter.getUserFullEmails.yields(new Error('Nope'))
return this.InstitutionsFeatures.hasLicence(
this.userId,
(error, hasLicence) => {
expect(error).to.exist
return 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(
this.userId,
(error, hasLicence) => {
expect(error).to.not.exist
expect(hasLicence).to.be.false
return done()
}
)
})
it('should return true if user has confirmed paid affiliation', function (done) {
const emailData = [
{ emailHasInstitutionLicence: true },
{ emailHasInstitutionLicence: false },
]
this.UserGetter.getUserFullEmails.yields(null, emailData)
return this.InstitutionsFeatures.hasLicence(
this.userId,
(error, hasLicence) => {
expect(error).to.not.exist
expect(hasLicence).to.be.true
return done()
}
)
})
})
describe('getInstitutionsFeatures', function () {
beforeEach(function () {
this.InstitutionsFeatures.getInstitutionsPlan = sinon.stub()
this.testFeatures = { features: { institution: 'all' } }
return this.PlansLocator.findLocalPlanInSettings
.withArgs(this.institutionPlanCode)
.returns(this.testFeatures)
})
it('should handle error', function (done) {
this.InstitutionsFeatures.getInstitutionsPlan.yields(new Error('Nope'))
return this.InstitutionsFeatures.getInstitutionsFeatures(
this.userId,
(error, features) => {
expect(error).to.exist
return 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,
(error, features) => {
expect(error).to.not.exist
expect(features).to.deep.equal({})
return done()
}
)
})
it('should return feaures if user has affiliations plan code', function (done) {
this.InstitutionsFeatures.getInstitutionsPlan.yields(
null,
this.institutionPlanCode
)
return this.InstitutionsFeatures.getInstitutionsFeatures(
this.userId,
(error, features) => {
expect(error).to.not.exist
expect(features).to.deep.equal(this.testFeatures.features)
return done()
}
)
})
})
describe('getInstitutionsPlan', function () {
beforeEach(function () {
return (this.InstitutionsFeatures.hasLicence = sinon.stub())
})
it('should handle error', function (done) {
this.InstitutionsFeatures.hasLicence.yields(new Error('Nope'))
return this.InstitutionsFeatures.getInstitutionsPlan(
this.userId,
error => {
expect(error).to.exist
return 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,
(error, plan) => {
expect(error).to.not.exist
expect(plan).to.equal(null)
return done()
}
)
})
it('should return plan if user has licence', function (done) {
this.InstitutionsFeatures.hasLicence.yields(null, true)
return this.InstitutionsFeatures.getInstitutionsPlan(
this.userId,
(error, plan) => {
expect(error).to.not.exist
expect(plan).to.equal(this.institutionPlanCode)
return done()
}
)
})
})
})
| overleaf/web/test/unit/src/Institutions/InstitutionsFeaturesTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Institutions/InstitutionsFeaturesTests.js",
"repo_id": "overleaf",
"token_count": 2218
} | 573 |
const SandboxedModule = require('sandboxed-module')
const path = require('path')
const sinon = require('sinon')
const { expect } = require('chai')
const { ObjectId } = require('mongodb')
const Errors = require('../../../../app/src/Features/Errors/Errors')
const MODULE_PATH = path.join(
__dirname,
'../../../../app/src/Features/Project/ProjectController'
)
describe('ProjectController', function () {
beforeEach(function () {
this.project_id = ObjectId('abcdefabcdefabcdefabcdef')
this.user = {
_id: ObjectId('123456123456123456123456'),
email: 'test@overleaf.com',
first_name: 'bjkdsjfk',
features: {},
emails: [{ email: 'test@overleaf.com' }],
}
this.settings = {
apis: {
chat: {
url: 'chat.com',
},
},
siteUrl: 'mysite.com',
algolia: {},
}
this.brandVariationDetails = {
id: '12',
active: true,
brand_name: 'The journal',
home_url: 'http://www.thejournal.com/',
publish_menu_link_html: 'Submit your paper to the <em>The Journal</em>',
}
this.token = 'some-token'
this.ProjectDeleter = {
deleteProject: sinon.stub().callsArg(2),
restoreProject: sinon.stub().callsArg(1),
findArchivedProjects: sinon.stub(),
}
this.ProjectDuplicator = {
duplicate: sinon.stub().callsArgWith(3, null, { _id: this.project_id }),
}
this.ProjectCreationHandler = {
createExampleProject: sinon
.stub()
.callsArgWith(2, null, { _id: this.project_id }),
createBasicProject: sinon
.stub()
.callsArgWith(2, null, { _id: this.project_id }),
}
this.SubscriptionLocator = { getUsersSubscription: sinon.stub() }
this.LimitationsManager = { hasPaidSubscription: sinon.stub() }
this.TagsHandler = { getAllTags: sinon.stub() }
this.NotificationsHandler = { getUserNotifications: sinon.stub() }
this.UserModel = { findById: sinon.stub() }
this.AuthorizationManager = {
getPrivilegeLevelForProject: sinon.stub(),
isRestrictedUser: sinon.stub().returns(false),
}
this.EditorController = { renameProject: sinon.stub() }
this.InactiveProjectManager = { reactivateProjectIfRequired: sinon.stub() }
this.ProjectUpdateHandler = { markAsOpened: sinon.stub() }
this.ProjectGetter = {
findAllUsersProjects: sinon.stub(),
getProject: sinon.stub(),
}
this.ProjectHelper = {
isArchived: sinon.stub(),
isTrashed: sinon.stub(),
isArchivedOrTrashed: sinon.stub(),
getAllowedImagesForUser: sinon.stub().returns([]),
}
this.SessionManager = {
getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user),
getLoggedInUserId: sinon.stub().returns(this.user._id),
getSessionUser: sinon.stub().returns(this.user),
isUserLoggedIn: sinon.stub().returns(true),
}
this.UserController = {
logout: sinon.stub(),
}
this.TokenAccessHandler = {
getRequestToken: sinon.stub().returns(this.token),
protectTokens: sinon.stub(),
}
this.CollaboratorsGetter = {
userIsTokenMember: sinon.stub().callsArgWith(2, null, false),
}
this.ProjectEntityHandler = {}
this.NotificationBuilder = {
ipMatcherAffiliation: sinon.stub().returns({ create: sinon.stub() }),
}
this.UserGetter = {
getUserFullEmails: sinon.stub().yields(null, []),
getUser: sinon
.stub()
.callsArgWith(2, null, { lastLoginIp: '192.170.18.2' }),
}
this.Features = {
hasFeature: sinon.stub(),
}
this.BrandVariationsHandler = {
getBrandVariationById: sinon
.stub()
.callsArgWith(1, null, this.brandVariationDetails),
}
this.TpdsProjectFlusher = {
flushProjectToTpdsIfNeeded: sinon.stub().yields(),
}
this.Metrics = {
Timer: class {
done() {}
},
inc: sinon.stub(),
}
this.NewLogsUIHelper = {
getNewLogsUIVariantForUser: sinon
.stub()
.returns({ newLogsUI: false, subvariant: null }),
}
this.SplitTestHandler = {
promises: {
getTestSegmentation: sinon.stub().resolves({ enabled: false }),
},
getTestSegmentation: sinon.stub().yields(null, { enabled: false }),
}
this.ProjectController = SandboxedModule.require(MODULE_PATH, {
requires: {
mongodb: { ObjectId },
'@overleaf/settings': this.settings,
'@overleaf/metrics': this.Metrics,
'../SplitTests/SplitTestHandler': this.SplitTestHandler,
'./ProjectDeleter': this.ProjectDeleter,
'./ProjectDuplicator': this.ProjectDuplicator,
'./ProjectCreationHandler': this.ProjectCreationHandler,
'../Editor/EditorController': this.EditorController,
'../User/UserController': this.UserController,
'./ProjectHelper': this.ProjectHelper,
'../Subscription/SubscriptionLocator': this.SubscriptionLocator,
'../Subscription/LimitationsManager': this.LimitationsManager,
'../Tags/TagsHandler': this.TagsHandler,
'../Notifications/NotificationsHandler': this.NotificationsHandler,
'../../models/User': { User: this.UserModel },
'../Authorization/AuthorizationManager': this.AuthorizationManager,
'../InactiveData/InactiveProjectManager': this.InactiveProjectManager,
'./ProjectUpdateHandler': this.ProjectUpdateHandler,
'./ProjectGetter': this.ProjectGetter,
'./ProjectDetailsHandler': this.ProjectDetailsHandler,
'../Authentication/SessionManager': this.SessionManager,
'../TokenAccess/TokenAccessHandler': this.TokenAccessHandler,
'../Collaborators/CollaboratorsGetter': this.CollaboratorsGetter,
'./ProjectEntityHandler': this.ProjectEntityHandler,
'../../infrastructure/Features': this.Features,
'../Notifications/NotificationsBuilder': this.NotificationBuilder,
'../User/UserGetter': this.UserGetter,
'../BrandVariations/BrandVariationsHandler': this
.BrandVariationsHandler,
'../ThirdPartyDataStore/TpdsProjectFlusher': this.TpdsProjectFlusher,
'../../models/Project': {},
'../Analytics/AnalyticsManager': { recordEvent: () => {} },
'../../infrastructure/Modules': {
hooks: { fire: sinon.stub().yields(null, []) },
},
'../Helpers/NewLogsUI': this.NewLogsUIHelper,
},
})
this.projectName = '£12321jkj9ujkljds'
this.req = {
query: {},
params: {
Project_id: this.project_id,
},
headers: {},
connection: {
remoteAddress: '192.170.18.1',
},
session: {
user: this.user,
},
body: {
projectName: this.projectName,
},
i18n: {
translate() {},
},
ip: '192.170.18.1',
}
this.res = {
locals: {
jsPath: 'js path here',
},
setTimeout: sinon.stub(),
}
})
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 => {
this.EditorController.renameProject
.calledWith(this.project_id, this.name)
.should.equal(true)
code.should.equal(204)
done()
}
this.ProjectController.updateProjectSettings(this.req, this.res)
})
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 => {
this.EditorController.setCompiler
.calledWith(this.project_id, this.compiler)
.should.equal(true)
code.should.equal(204)
done()
}
this.ProjectController.updateProjectSettings(this.req, this.res)
})
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 => {
this.EditorController.setImageName
.calledWith(this.project_id, this.imageName)
.should.equal(true)
code.should.equal(204)
done()
}
this.ProjectController.updateProjectSettings(this.req, this.res)
})
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 => {
this.EditorController.setSpellCheckLanguage
.calledWith(this.project_id, this.languageCode)
.should.equal(true)
code.should.equal(204)
done()
}
this.ProjectController.updateProjectSettings(this.req, this.res)
})
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 => {
this.EditorController.setRootDoc
.calledWith(this.project_id, this.rootDocId)
.should.equal(true)
code.should.equal(204)
done()
}
this.ProjectController.updateProjectSettings(this.req, this.res)
})
})
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'),
}
this.res.sendStatus = code => {
this.EditorController.setPublicAccessLevel
.calledWith(this.project_id, this.publicAccessLevel)
.should.equal(true)
code.should.equal(204)
done()
}
this.ProjectController.updateProjectAdminSettings(this.req, this.res)
})
})
describe('deleteProject', function () {
it('should call the project deleter', function (done) {
this.res.sendStatus = code => {
this.ProjectDeleter.deleteProject
.calledWith(this.project_id, {
deleterUser: this.user,
ipAddress: this.req.ip,
})
.should.equal(true)
code.should.equal(200)
done()
}
this.ProjectController.deleteProject(this.req, this.res)
})
})
describe('restoreProject', function () {
it('should tell the project deleter', function (done) {
this.res.sendStatus = code => {
this.ProjectDeleter.restoreProject
.calledWith(this.project_id)
.should.equal(true)
code.should.equal(200)
done()
}
this.ProjectController.restoreProject(this.req, this.res)
})
})
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)
.should.equal(true)
json.project_id.should.equal(this.project_id)
done()
}
this.ProjectController.cloneProject(this.req, this.res)
})
})
describe('newProject', function () {
it('should call the projectCreationHandler with createExampleProject', function (done) {
this.req.body.template = 'example'
this.res.send = json => {
this.ProjectCreationHandler.createExampleProject
.calledWith(this.user._id, this.projectName)
.should.equal(true)
this.ProjectCreationHandler.createBasicProject.called.should.equal(
false
)
done()
}
this.ProjectController.newProject(this.req, this.res)
})
it('should call the projectCreationHandler with createBasicProject', function (done) {
this.req.body.template = 'basic'
this.res.send = json => {
this.ProjectCreationHandler.createExampleProject.called.should.equal(
false
)
this.ProjectCreationHandler.createBasicProject
.calledWith(this.user._id, this.projectName)
.should.equal(true)
done()
}
this.ProjectController.newProject(this.req, this.res)
})
})
describe('projectListPage', function () {
beforeEach(function () {
this.tags = [
{ name: 1, project_ids: ['1', '2', '3'] },
{ name: 2, project_ids: ['a', '1'] },
{ name: 3, project_ids: ['a', 'b', 'c', 'd'] },
]
this.notifications = [
{
_id: '1',
user_id: '2',
templateKey: '3',
messageOpts: '4',
key: '5',
},
]
this.projects = [
{ _id: 1, lastUpdated: 1, owner_ref: 'user-1' },
{
_id: 2,
lastUpdated: 2,
owner_ref: 'user-2',
lastUpdatedBy: 'user-1',
},
]
this.collabertions = [{ _id: 5, lastUpdated: 5, owner_ref: 'user-1' }]
this.readOnly = [{ _id: 3, lastUpdated: 3, owner_ref: 'user-1' }]
this.tokenReadAndWrite = [{ _id: 6, lastUpdated: 5, owner_ref: 'user-4' }]
this.tokenReadOnly = [{ _id: 7, lastUpdated: 4, owner_ref: 'user-5' }]
this.allProjects = {
owned: this.projects,
readAndWrite: this.collabertions,
readOnly: this.readOnly,
tokenReadAndWrite: this.tokenReadAndWrite,
tokenReadOnly: this.tokenReadOnly,
}
this.users = {
'user-1': {
first_name: 'James',
},
'user-2': {
first_name: 'Henry',
},
}
this.users[this.user._id] = this.user // Owner
this.UserModel.findById = (id, fields, callback) => {
callback(null, this.users[id])
}
this.UserGetter.getUser = (id, fields, callback) => {
callback(null, this.users[id])
}
this.LimitationsManager.hasPaidSubscription.callsArgWith(1, null, false)
this.TagsHandler.getAllTags.callsArgWith(1, null, this.tags)
this.NotificationsHandler.getUserNotifications = sinon
.stub()
.callsArgWith(1, null, this.notifications, {})
this.ProjectGetter.findAllUsersProjects.callsArgWith(
2,
null,
this.allProjects
)
})
it('should render the project/list page', function (done) {
this.res.render = (pageName, opts) => {
pageName.should.equal('project/list')
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
it('should send the tags', function (done) {
this.res.render = (pageName, opts) => {
opts.tags.length.should.equal(this.tags.length)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
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)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
it('should send the projects', function (done) {
this.res.render = (pageName, opts) => {
opts.projects.length.should.equal(
this.projects.length +
this.collabertions.length +
this.readOnly.length +
this.tokenReadAndWrite.length +
this.tokenReadOnly.length
)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
it('should send the user', function (done) {
this.res.render = (pageName, opts) => {
opts.user.should.deep.equal(this.user)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
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]
)
opts.projects[1].owner.should.equal(
this.users[this.projects[1].owner_ref]
)
opts.projects[1].lastUpdatedBy.should.equal(
this.users[this.projects[1].lastUpdatedBy]
)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
it('should send hasSubscription == false when no subscription', function (done) {
this.res.render = (pageName, opts) => {
opts.hasSubscription.should.equal(false)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
it('should send hasSubscription == true when there is a subscription', function (done) {
this.LimitationsManager.hasPaidSubscription = sinon
.stub()
.callsArgWith(1, null, true)
this.res.render = (pageName, opts) => {
opts.hasSubscription.should.equal(true)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
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) {
this.user.features.github = true
this.user.features.dropbox = true
this.res.render = (pageName, opts) => {
opts.frontChatWidgetRoomId.should.equal(
this.settings.overleaf.front_chat_widget_room_id
)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
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(
this.settings.overleaf.front_chat_widget_room_id
)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
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)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
})
describe('With Institution SSO feature', function () {
beforeEach(function (done) {
this.institutionEmail = 'test@overleaf.com'
this.institutionName = 'Overleaf'
this.Features.hasFeature.withArgs('saml').returns(true)
this.Features.hasFeature.withArgs('affiliations').returns(true)
this.Features.hasFeature.withArgs('overleaf-integration').returns(true)
done()
})
it('should show institution SSO available notification for confirmed domains', function () {
this.UserGetter.getUserFullEmails.yields(null, [
{
email: 'test@overleaf.com',
affiliation: {
institution: {
id: 1,
confirmed: true,
name: 'Overleaf',
ssoBeta: false,
ssoEnabled: true,
},
},
},
])
this.res.render = (pageName, opts) => {
expect(opts.notificationsInstitution).to.deep.include({
email: this.institutionEmail,
institutionId: 1,
institutionName: this.institutionName,
templateKey: 'notification_institution_sso_available',
})
}
this.ProjectController.projectListPage(this.req, this.res)
})
it('should show a linked notification', function () {
this.req.session.saml = {
institutionEmail: this.institutionEmail,
linked: {
hasEntitlement: false,
universityName: this.institutionName,
},
}
this.res.render = (pageName, opts) => {
expect(opts.notificationsInstitution).to.deep.include({
email: this.institutionEmail,
institutionName: this.institutionName,
templateKey: 'notification_institution_sso_linked',
})
}
this.ProjectController.projectListPage(this.req, this.res)
})
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) => {
expect(opts.notificationsInstitution).to.deep.include({
institutionEmail: this.institutionEmail,
requestedEmail: 'requested@overleaf.com',
templateKey: 'notification_institution_sso_non_canonical',
})
}
this.req.session.saml = {
emailNonCanonical: this.institutionEmail,
institutionEmail: this.institutionEmail,
requestedEmail: 'requested@overleaf.com',
linked: {
hasEntitlement: false,
universityName: this.institutionName,
},
}
this.ProjectController.projectListPage(this.req, this.res)
})
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,
templateKey: 'notification_institution_sso_already_registered',
})
}
this.req.session.saml = {
institutionEmail: this.institutionEmail,
linked: {
hasEntitlement: false,
universityName: 'Overleaf',
},
registerIntercept: {
id: 1,
name: 'Example University',
},
}
this.ProjectController.projectListPage(this.req, this.res)
})
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) => {
expect(opts.notificationsInstitution).to.deep.not.include({
email: 'test@overleaf.com',
templateKey: 'notification_institution_sso_already_registered',
})
}
this.req.session.saml = {
registerIntercept: {
id: 1,
name: 'Example University',
},
}
this.ProjectController.projectListPage(this.req, this.res)
})
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(
'notification_institution_sso_error'
)
expect(opts.notificationsInstitution[0].error).to.be.instanceof(
Errors.SAMLAlreadyLinkedError
)
}
this.req.session.saml = {
institutionEmail: this.institutionEmail,
error: new Errors.SAMLAlreadyLinkedError(),
}
this.ProjectController.projectListPage(this.req, this.res)
})
describe('for an unconfirmed domain for an SSO institution', function () {
beforeEach(function (done) {
this.UserGetter.getUserFullEmails.yields(null, [
{
email: 'test@overleaf-uncofirmed.com',
affiliation: {
institution: {
id: 1,
confirmed: false,
name: 'Overleaf',
ssoBeta: false,
ssoEnabled: true,
},
},
},
])
done()
})
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 () {
// 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) => {
expect(opts.notificationsInstitution).to.not.deep.include({
institutionEmail: this.institutionEmail,
requestedEmail: undefined,
templateKey: 'notification_institution_sso_non_canonical',
})
}
this.req.session.saml = {
emailNonCanonical: this.institutionEmail,
institutionEmail: this.institutionEmail,
linked: {
hasEntitlement: false,
universityName: this.institutionName,
},
}
this.ProjectController.projectListPage(this.req, this.res)
})
})
describe('Institution with SSO beta testable', function () {
beforeEach(function (done) {
this.UserGetter.getUserFullEmails.yields(null, [
{
email: 'beta@beta.com',
affiliation: {
institution: {
id: 2,
confirmed: true,
name: 'Beta University',
ssoBeta: true,
ssoEnabled: false,
},
},
},
])
done()
})
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({
email: 'beta@beta.com',
institutionId: 2,
institutionName: 'Beta University',
templateKey: 'notification_institution_sso_available',
})
}
this.ProjectController.projectListPage(this.req, this.res)
})
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({
email: 'test@overleaf.com',
institutionId: 1,
institutionName: 'Overleaf',
templateKey: 'notification_institution_sso_available',
})
}
this.ProjectController.projectListPage(this.req, this.res)
})
})
})
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 () {
this.res.render = (pageName, opts) => {
expect(opts.notificationsInstitution).to.deep.not.include({
email: 'test@overleaf.com',
institutionId: 1,
institutionName: 'Overleaf',
templateKey: 'notification_institution_sso_available',
})
}
this.ProjectController.projectListPage(this.req, this.res)
})
})
})
describe('projectListPage with duplicate projects', function () {
beforeEach(function () {
this.tags = [
{ name: 1, project_ids: ['1', '2', '3'] },
{ name: 2, project_ids: ['a', '1'] },
{ name: 3, project_ids: ['a', 'b', 'c', 'd'] },
]
this.notifications = [
{
_id: '1',
user_id: '2',
templateKey: '3',
messageOpts: '4',
key: '5',
},
]
this.projects = [
{ _id: 1, lastUpdated: 1, owner_ref: 'user-1' },
{ _id: 2, lastUpdated: 2, owner_ref: 'user-2' },
]
this.collabertions = [{ _id: 5, lastUpdated: 5, owner_ref: 'user-1' }]
this.readOnly = [{ _id: 3, lastUpdated: 3, owner_ref: 'user-1' }]
this.tokenReadAndWrite = [{ _id: 6, lastUpdated: 5, owner_ref: 'user-4' }]
this.tokenReadOnly = [
{ _id: 6, lastUpdated: 5, owner_ref: 'user-4' }, // Also in tokenReadAndWrite
{ _id: 7, lastUpdated: 4, owner_ref: 'user-5' },
]
this.allProjects = {
owned: this.projects,
readAndWrite: this.collabertions,
readOnly: this.readOnly,
tokenReadAndWrite: this.tokenReadAndWrite,
tokenReadOnly: this.tokenReadOnly,
}
this.users = {
'user-1': {
first_name: 'James',
},
'user-2': {
first_name: 'Henry',
},
}
this.users[this.user._id] = this.user // Owner
this.UserModel.findById = (id, fields, callback) => {
callback(null, this.users[id])
}
this.LimitationsManager.hasPaidSubscription.callsArgWith(1, null, false)
this.TagsHandler.getAllTags.callsArgWith(1, null, this.tags)
this.NotificationsHandler.getUserNotifications = sinon
.stub()
.callsArgWith(1, null, this.notifications, {})
this.ProjectGetter.findAllUsersProjects.callsArgWith(
2,
null,
this.allProjects
)
})
it('should render the project/list page', function (done) {
this.res.render = (pageName, opts) => {
pageName.should.equal('project/list')
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
it('should omit one of the projects', function (done) {
this.res.render = (pageName, opts) => {
opts.projects.length.should.equal(
this.projects.length +
this.collabertions.length +
this.readOnly.length +
this.tokenReadAndWrite.length +
this.tokenReadOnly.length -
1
)
done()
}
this.ProjectController.projectListPage(this.req, this.res)
})
})
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) {
this.EditorController.renameProject.callsArgWith(2)
this.res.sendStatus = code => {
code.should.equal(200)
this.EditorController.renameProject
.calledWith(this.project_id, this.newProjectName)
.should.equal(true)
done()
}
this.ProjectController.renameProject(this.req, this.res)
})
it('should send an error to next() if there is a problem', function (done) {
let error
this.EditorController.renameProject.callsArgWith(
2,
(error = new Error('problem'))
)
const next = e => {
e.should.equal(error)
done()
}
this.ProjectController.renameProject(this.req, this.res, next)
})
})
describe('loadEditor', function () {
beforeEach(function () {
this.settings.editorIsOpen = true
this.project = {
name: 'my proj',
_id: '213123kjlkj',
owner_ref: '59fc84d5fbea77482d436e1b',
}
this.brandedProject = {
name: 'my branded proj',
_id: '3252332',
owner_ref: '59fc84d5fbea77482d436e1b',
brandVariationId: '12',
}
this.user = {
_id: '588f3ddae8ebc1bac07c9fa4',
ace: {
fontSize: 'massive',
theme: 'sexy',
},
email: 'bob@bob.com',
refProviders: {
mendeley: { encrypted: 'aaaa' },
zotero: { encrypted: 'bbbb' },
},
}
this.ProjectGetter.getProject.callsArgWith(2, null, this.project)
this.UserModel.findById.callsArgWith(2, null, this.user)
this.SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, {})
this.AuthorizationManager.getPrivilegeLevelForProject.callsArgWith(
3,
null,
'owner'
)
this.ProjectDeleter.unmarkAsDeletedByExternalSource = sinon.stub()
this.InactiveProjectManager.reactivateProjectIfRequired.callsArgWith(1)
this.ProjectUpdateHandler.markAsOpened.callsArgWith(1)
})
it('should render the project/editor page', function (done) {
this.res.render = (pageName, opts) => {
pageName.should.equal('project/editor')
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
it('should add user', function (done) {
this.res.render = (pageName, opts) => {
opts.user.email.should.equal(this.user.email)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
it('should sanitize refProviders', function (done) {
this.res.render = (_pageName, opts) => {
expect(opts.user.refProviders).to.deep.equal({
mendeley: true,
zotero: true,
})
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
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)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
it('should add isRestrictedTokenMember', function (done) {
this.res.render = (pageName, opts) => {
opts.isRestrictedTokenMember.should.exist
opts.isRestrictedTokenMember.should.equal(false)
return done()
}
return this.ProjectController.loadEditor(this.req, this.res)
})
it('should set isRestrictedTokenMember when appropriate', function (done) {
this.AuthorizationManager.isRestrictedUser.returns(true)
this.res.render = (pageName, opts) => {
opts.isRestrictedTokenMember.should.exist
opts.isRestrictedTokenMember.should.equal(true)
return done()
}
return this.ProjectController.loadEditor(this.req, this.res)
})
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')
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
it('should not render the page if the project can not be accessed', function (done) {
this.AuthorizationManager.getPrivilegeLevelForProject = sinon
.stub()
.callsArgWith(3, null, null)
this.res.sendStatus = (resCode, opts) => {
resCode.should.equal(401)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
it('should reactivateProjectIfRequired', function (done) {
this.res.render = (pageName, opts) => {
this.InactiveProjectManager.reactivateProjectIfRequired
.calledWith(this.project_id)
.should.equal(true)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
it('should mark project as opened', function (done) {
this.res.render = (pageName, opts) => {
this.ProjectUpdateHandler.markAsOpened
.calledWith(this.project_id)
.should.equal(true)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
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
.calledWith()
.should.equal(true)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
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
)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
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)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
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
)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
describe('pdf caching feature flags', function () {
/* eslint-disable mocha/no-identical-title */
function showNoVariant() {
beforeEach(function () {
this.SplitTestHandler.getTestSegmentation = sinon
.stub()
.yields(null, { enabled: false })
})
}
function showVariant(variant) {
beforeEach(function () {
this.SplitTestHandler.getTestSegmentation = sinon
.stub()
.yields(null, { enabled: true, variant })
})
}
function expectBandwidthTrackingEnabled() {
it('should track pdf bandwidth', function (done) {
this.res.render = (pageName, opts) => {
expect(opts.trackPdfDownload).to.equal(true)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
}
function expectPDFCachingEnabled() {
it('should enable pdf caching', function (done) {
this.res.render = (pageName, opts) => {
expect(opts.enablePdfCaching).to.equal(true)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
}
function expectBandwidthTrackingDisabled() {
it('should not track pdf bandwidth', function (done) {
this.res.render = (pageName, opts) => {
expect(opts.trackPdfDownload).to.equal(false)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
}
function expectPDFCachingDisabled() {
it('should disable pdf caching', function (done) {
this.res.render = (pageName, opts) => {
expect(opts.enablePdfCaching).to.equal(false)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
}
function expectToCollectMetricsAndCachePDF() {
describe('with no query', function () {
expectBandwidthTrackingEnabled()
expectPDFCachingEnabled()
})
describe('with enable_pdf_caching=false', function () {
beforeEach(function () {
this.req.query.enable_pdf_caching = 'false'
})
expectBandwidthTrackingDisabled()
expectPDFCachingDisabled()
})
describe('with enable_pdf_caching=true', function () {
beforeEach(function () {
this.req.query.enable_pdf_caching = 'true'
})
expectBandwidthTrackingEnabled()
expectPDFCachingEnabled()
})
}
function expectToCollectMetricsOnly() {
describe('with no query', function () {
expectBandwidthTrackingEnabled()
expectPDFCachingDisabled()
})
describe('with enable_pdf_caching=false', function () {
beforeEach(function () {
this.req.query.enable_pdf_caching = 'false'
})
expectBandwidthTrackingDisabled()
expectPDFCachingDisabled()
})
describe('with enable_pdf_caching=true', function () {
beforeEach(function () {
this.req.query.enable_pdf_caching = 'true'
})
expectBandwidthTrackingEnabled()
expectPDFCachingDisabled()
})
}
function expectToCachePDFOnly() {
describe('with no query', function () {
expectBandwidthTrackingDisabled()
expectPDFCachingEnabled()
})
describe('with enable_pdf_caching=false', function () {
beforeEach(function () {
this.req.query.enable_pdf_caching = 'false'
})
expectBandwidthTrackingDisabled()
expectPDFCachingDisabled()
})
describe('with enable_pdf_caching=true', function () {
beforeEach(function () {
this.req.query.enable_pdf_caching = 'true'
})
expectBandwidthTrackingDisabled()
expectPDFCachingEnabled()
})
}
function expectToNotBeEnrolledAtAll() {
describe('with no query', function () {
expectBandwidthTrackingDisabled()
expectPDFCachingDisabled()
})
describe('with enable_pdf_caching=false', function () {
beforeEach(function () {
this.req.query.enable_pdf_caching = 'false'
})
expectBandwidthTrackingDisabled()
expectPDFCachingDisabled()
})
describe('with enable_pdf_caching=true', function () {
beforeEach(function () {
this.req.query.enable_pdf_caching = 'true'
})
expectBandwidthTrackingDisabled()
expectPDFCachingDisabled()
})
}
function tagAnonymous() {
beforeEach(function () {
this.SessionManager.isUserLoggedIn = sinon.stub().returns(false)
})
}
beforeEach(function () {
this.settings.enablePdfCaching = true
})
describe('during regular roll-out', function () {
describe('disabled', function () {
showNoVariant()
describe('regular user', function () {
expectToNotBeEnrolledAtAll()
})
describe('anonymous user', function () {
tagAnonymous()
expectToCachePDFOnly()
})
})
describe('variant=collect-metrics', function () {
showVariant('collect-metrics')
describe('regular user', function () {
expectToCollectMetricsOnly()
})
describe('anonymous user', function () {
tagAnonymous()
expectToCachePDFOnly()
})
})
describe('variant=collect-metrics-and-enable-caching', function () {
showVariant('collect-metrics-and-enable-caching')
describe('regular user', function () {
expectToCollectMetricsAndCachePDF()
})
describe('anonymous user', function () {
tagAnonymous()
expectToCachePDFOnly()
})
})
describe('variant=enable-caching-only', function () {
showVariant('enable-caching-only')
describe('regular user', function () {
expectToCachePDFOnly()
})
describe('anonymous user', function () {
tagAnonymous()
expectToCachePDFOnly()
})
})
})
})
describe('wsUrl', function () {
function checkLoadEditorWsMetric(metric) {
it(`should inc metric ${metric}`, function (done) {
this.res.render = () => {
this.Metrics.inc.calledWith(metric).should.equal(true)
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
}
function checkWsFallback(isBeta, isV2) {
describe('with ws=fallback', function () {
beforeEach(function () {
this.req.query = {}
this.req.query.ws = 'fallback'
})
it('should unset the wsUrl', function (done) {
this.res.render = (pageName, opts) => {
;(opts.wsUrl || '/socket.io').should.equal('/socket.io')
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
checkLoadEditorWsMetric(
`load-editor-ws${isBeta ? '-beta' : ''}${
isV2 ? '-v2' : ''
}-fallback`
)
})
}
beforeEach(function () {
this.settings.wsUrl = '/other.socket.io'
})
it('should set the custom wsUrl', function (done) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/other.socket.io')
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
checkLoadEditorWsMetric('load-editor-ws')
checkWsFallback(false)
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) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/other.socket.io')
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
checkLoadEditorWsMetric('load-editor-ws')
checkWsFallback(false)
})
describe('for a beta user', function () {
beforeEach(function () {
this.user.betaProgram = true
})
it('should set the beta wsUrl', function (done) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/beta.socket.io')
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
checkLoadEditorWsMetric('load-editor-ws-beta')
checkWsFallback(true)
})
})
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) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/other.socket.io')
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
checkLoadEditorWsMetric('load-editor-ws')
checkWsFallback(false)
}
function checkMatch() {
it('should set the v2 wsUrl', function (done) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/socket.io.v2')
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
checkLoadEditorWsMetric('load-editor-ws-v2')
checkWsFallback(false, true)
}
function checkForBetaUser() {
describe('for a beta user', function () {
beforeEach(function () {
this.user.betaProgram = true
})
it('should set the beta wsUrl', function (done) {
this.res.render = (pageName, opts) => {
opts.wsUrl.should.equal('/beta.socket.io')
done()
}
this.ProjectController.loadEditor(this.req, this.res)
})
checkLoadEditorWsMetric('load-editor-ws-beta')
checkWsFallback(true)
})
}
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 () {
this.req.params.Project_id = ObjectId.createFromTime(0)
})
checkNonMatch()
})
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 () {
this.settings.wsUrlV2Percentage = 1
})
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 () {
this.req.params.Project_id = ObjectId.createFromTime(1)
})
checkNonMatch()
checkForBetaUser()
})
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 () {
this.settings.wsUrlV2Percentage = 10
})
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 () {
this.req.params.Project_id = ObjectId.createFromTime(9)
})
checkMatch()
checkForBetaUser()
})
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 () {
this.req.params.Project_id = ObjectId.createFromTime(42)
})
checkNonMatch()
checkForBetaUser()
})
})
describe('when the roll out percentage is 100', function () {
beforeEach(function () {
this.settings.wsUrlV2Percentage = 100
})
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 () {
this.req.params.Project_id = ObjectId.createFromTime(10)
})
checkMatch()
})
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 () {
this.req.params.Project_id = ObjectId.createFromTime(99)
})
checkMatch()
})
})
})
})
})
describe('userProjectsJson', function () {
beforeEach(function (done) {
const projects = [
{
archived: true,
trashed: true,
id: 'a',
name: 'A',
accessLevel: 'a',
somethingElse: 1,
},
{
archived: false,
id: 'b',
name: 'B',
accessLevel: 'b',
somethingElse: 1,
},
{
archived: false,
trashed: true,
id: 'c',
name: 'C',
accessLevel: 'c',
somethingElse: 1,
},
{
archived: false,
trashed: false,
id: 'd',
name: 'D',
accessLevel: 'd',
somethingElse: 1,
},
]
this.ProjectHelper.isArchivedOrTrashed
.withArgs(projects[0], this.user._id)
.returns(true)
this.ProjectHelper.isArchivedOrTrashed
.withArgs(projects[1], this.user._id)
.returns(false)
this.ProjectHelper.isArchivedOrTrashed
.withArgs(projects[2], this.user._id)
.returns(true)
this.ProjectHelper.isArchivedOrTrashed
.withArgs(projects[3], this.user._id)
.returns(false)
this.ProjectGetter.findAllUsersProjects = sinon
.stub()
.callsArgWith(2, null, [])
this.ProjectController._buildProjectList = sinon.stub().returns(projects)
this.SessionManager.getLoggedInUserId = sinon
.stub()
.returns(this.user._id)
done()
})
it('should produce a list of projects', function (done) {
this.res.json = data => {
expect(data).to.deep.equal({
projects: [
{ _id: 'b', name: 'B', accessLevel: 'b' },
{ _id: 'd', name: 'D', accessLevel: 'd' },
],
})
done()
}
this.ProjectController.userProjectsJson(this.req, this.res, this.next)
})
})
describe('projectEntitiesJson', function () {
beforeEach(function () {
this.SessionManager.getLoggedInUserId = sinon.stub().returns('abc')
this.req.params = { Project_id: 'abcd' }
this.project = { _id: 'abcd' }
this.docs = [
{ path: '/things/b.txt', doc: true },
{ path: '/main.tex', doc: true },
]
this.files = [{ path: '/things/a.txt' }]
this.ProjectGetter.getProject = sinon
.stub()
.callsArgWith(1, null, this.project)
this.ProjectEntityHandler.getAllEntitiesFromProject = sinon
.stub()
.callsArgWith(1, null, this.docs, this.files)
})
it('should produce a list of entities', function (done) {
this.res.json = data => {
expect(data).to.deep.equal({
project_id: 'abcd',
entities: [
{ path: '/main.tex', type: 'doc' },
{ path: '/things/a.txt', type: 'file' },
{ path: '/things/b.txt', type: 'doc' },
],
})
expect(this.ProjectGetter.getProject.callCount).to.equal(1)
expect(
this.ProjectEntityHandler.getAllEntitiesFromProject.callCount
).to.equal(1)
done()
}
this.ProjectController.projectEntitiesJson(this.req, this.res, this.next)
})
})
describe('_buildProjectViewModel', function () {
beforeEach(function () {
this.ProjectHelper.isArchived.returns(false)
this.ProjectHelper.isTrashed.returns(false)
this.project = {
_id: 'abcd',
name: 'netsenits',
lastUpdated: 1,
lastUpdatedBy: 2,
publicAccesLevel: 'private',
archived: false,
owner_ref: 'defg',
tokens: {
readAndWrite: '1abcd',
readAndWritePrefix: '1',
readOnly: 'neiotsranteoia',
},
}
})
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',
'owner',
this.user._id
)
expect(result).to.exist
expect(result).to.be.an('object')
expect(result).to.deep.equal({
id: 'abcd',
name: 'netsenits',
lastUpdated: 1,
lastUpdatedBy: 2,
publicAccessLevel: 'private',
accessLevel: 'readAndWrite',
source: 'owner',
archived: false,
trashed: false,
owner_ref: 'defg',
isV1Project: false,
})
})
})
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 () {
const result = this.ProjectController._buildProjectViewModel(
this.project,
'readAndWrite',
'owner',
this.user._id
)
expect(result).to.exist
expect(result).to.be.an('object')
expect(result).to.deep.equal({
id: 'abcd',
name: 'netsenits',
lastUpdated: 1,
lastUpdatedBy: 2,
publicAccessLevel: 'private',
accessLevel: 'readAndWrite',
source: 'owner',
archived: true,
trashed: false,
owner_ref: 'defg',
isV1Project: false,
})
})
})
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',
'token',
this.user._id
)
expect(result).to.exist
expect(result).to.be.an('object')
expect(result).to.deep.equal({
id: 'abcd',
name: 'netsenits',
lastUpdated: 1,
lastUpdatedBy: null,
publicAccessLevel: 'private',
accessLevel: 'readOnly',
source: 'token',
archived: false,
trashed: false,
owner_ref: null,
isV1Project: false,
})
})
})
})
describe('_isInPercentageRollout', function () {
before(function () {
this.ids = [
'5a05cd7621f9fe22be131740',
'5a05cd7821f9fe22be131741',
'5a05cd7921f9fe22be131742',
'5a05cd7a21f9fe22be131743',
'5a05cd7b21f9fe22be131744',
'5a05cd7c21f9fe22be131745',
'5a05cd7d21f9fe22be131746',
'5a05cd7e21f9fe22be131747',
'5a05cd7f21f9fe22be131748',
'5a05cd8021f9fe22be131749',
'5a05cd8021f9fe22be13174a',
'5a05cd8121f9fe22be13174b',
'5a05cd8221f9fe22be13174c',
'5a05cd8221f9fe22be13174d',
'5a05cd8321f9fe22be13174e',
'5a05cd8321f9fe22be13174f',
'5a05cd8421f9fe22be131750',
'5a05cd8421f9fe22be131751',
'5a05cd8421f9fe22be131752',
'5a05cd8521f9fe22be131753',
]
})
it('should produce the expected results', function () {
expect(
this.ids.map(i =>
this.ProjectController._isInPercentageRollout('abcd', i, 50)
)
).to.deep.equal([
false,
false,
false,
false,
false,
false,
true,
false,
true,
true,
true,
true,
true,
true,
false,
false,
false,
true,
false,
true,
])
expect(
this.ids.map(i =>
this.ProjectController._isInPercentageRollout('efgh', i, 50)
)
).to.deep.equal([
false,
false,
false,
false,
true,
false,
false,
true,
false,
false,
true,
true,
true,
false,
true,
false,
true,
true,
false,
false,
])
})
})
})
| overleaf/web/test/unit/src/Project/ProjectControllerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Project/ProjectControllerTests.js",
"repo_id": "overleaf",
"token_count": 27886
} | 574 |
/* eslint-disable
node/handle-callback-err,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const { expect } = require('chai')
const sinon = require('sinon')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Publishers/PublishersGetter.js'
)
describe('PublishersGetter', function () {
beforeEach(function () {
this.publisher = {
_id: 'mock-publsiher-id',
slug: 'ieee',
fetchV1Data: sinon.stub(),
}
this.PublishersGetter = SandboxedModule.require(modulePath, {
requires: {
'../User/UserGetter': this.UserGetter,
'../UserMembership/UserMembershipsHandler': (this.UserMembershipsHandler = {
getEntitiesByUser: sinon
.stub()
.callsArgWith(2, null, [this.publisher]),
}),
'../UserMembership/UserMembershipEntityConfigs': (this.UserMembershipEntityConfigs = {
publisher: {
modelName: 'Publisher',
canCreate: true,
fields: {
primaryKey: 'slug',
},
},
}),
},
})
return (this.userId = '12345abcde')
})
describe('getManagedPublishers', function () {
it('fetches v1 data before returning publisher list', function (done) {
return this.PublishersGetter.getManagedPublishers(
this.userId,
(error, publishers) => {
publishers.length.should.equal(1)
return done()
}
)
})
})
})
| overleaf/web/test/unit/src/Publishers/PublishersGetterTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Publishers/PublishersGetterTests.js",
"repo_id": "overleaf",
"token_count": 774
} | 575 |
const SandboxedModule = require('sandboxed-module')
const { expect } = require('chai')
const sinon = require('sinon')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Spelling/SpellingHandler.js'
)
const TIMEOUT = 1000 * 10
const SPELLING_HOST = 'http://spelling.service.test'
const SPELLING_URL = 'http://spelling.service.test'
describe('SpellingHandler', function () {
let userId, word, dictionary, dictionaryString, request, SpellingHandler
beforeEach(function () {
userId = 'wombat'
word = 'potato'
dictionary = ['wombaat', 'woombat']
dictionaryString = JSON.stringify(dictionary)
request = {
get: sinon
.stub()
.yields(null, { statusCode: 200, body: dictionaryString }),
post: sinon.stub().yields(null, { statusCode: 204 }),
delete: sinon.stub().yields(null, { statusCode: 204 }),
}
SpellingHandler = SandboxedModule.require(modulePath, {
requires: {
request: request,
'@overleaf/settings': {
apis: { spelling: { host: SPELLING_HOST, url: SPELLING_URL } },
},
},
})
})
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',
timeout: TIMEOUT,
})
done()
})
})
it('returns the dictionary', function (done) {
SpellingHandler.getUserDictionary(userId, (err, dictionary) => {
expect(err).not.to.exist
expect(dictionary).to.deep.equal(dictionary)
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
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',
json: {
word: word,
},
timeout: TIMEOUT,
})
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) {
request.post = sinon.stub().yields(new Error('ugh'))
SpellingHandler.deleteWordFromUserDictionary(userId, word, err => {
expect(err).to.exist
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',
timeout: TIMEOUT,
})
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) {
request.delete = sinon.stub().yields(new Error('ugh'))
SpellingHandler.deleteUserDictionary(userId, err => {
expect(err).to.exist
done()
})
})
})
})
| overleaf/web/test/unit/src/Spelling/SpellingHandlerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Spelling/SpellingHandlerTests.js",
"repo_id": "overleaf",
"token_count": 1518
} | 576 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const assert = require('assert')
const path = require('path')
const modulePath = path.join(
__dirname,
'../../../../app/src/Features/Subscription/V1SubscriptionManager'
)
const sinon = require('sinon')
const { expect } = require('chai')
describe('V1SubscriptionManager', function () {
beforeEach(function () {
this.V1SubscriptionManager = SandboxedModule.require(modulePath, {
requires: {
'../User/UserGetter': (this.UserGetter = {}),
'@overleaf/settings': (this.Settings = {
apis: {
v1: {
host: (this.host = 'http://overleaf.example.com'),
url: 'v1.url',
},
},
v1GrandfatheredFeaturesUidCutoff: 10,
v1GrandfatheredFeatures: {
github: true,
mendeley: true,
},
}),
request: (this.request = sinon.stub()),
},
})
this.userId = 'abcd'
this.v1UserId = 42
return (this.user = {
_id: this.userId,
email: 'user@example.com',
overleaf: {
id: this.v1UserId,
},
})
})
describe('getPlanCodeFromV1', function () {
beforeEach(function () {
this.responseBody = {
id: 32,
plan_name: 'pro',
}
this.V1SubscriptionManager._v1Request = sinon
.stub()
.yields(null, this.responseBody)
return (this.call = cb => {
return this.V1SubscriptionManager.getPlanCodeFromV1(this.userId, cb)
})
})
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(
this.V1SubscriptionManager._v1Request.calledWith(this.userId)
).to.equal(true)
return done()
})
})
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) {
return this.call((err, planCode) => {
expect(err).to.not.exist
expect(planCode).to.equal('v1_pro')
return done()
})
})
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) {
return this.call((err, planCode) => {
expect(err).to.not.exist
expect(planCode).to.equal(null)
return 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({})
return 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({
github: true,
mendeley: true,
})
return done()
})
})
})
describe('_v1Request', function () {
beforeEach(function () {
return (this.UserGetter.getUser = sinon.stub().yields(null, this.user))
})
describe('when v1IdForUser produces an error', function () {
beforeEach(function () {
this.V1SubscriptionManager.v1IdForUser = sinon
.stub()
.yields(new Error('woops'))
return (this.call = cb => {
return this.V1SubscriptionManager._v1Request(
this.user_id,
{
url() {
return '/foo'
},
},
cb
)
})
})
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) {
return this.call((err, planCode) => {
expect(err).to.exist
return done()
})
})
})
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(
this.user_id,
{
url() {
return '/foo'
},
},
cb
)
})
})
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) {
return this.call(err => {
expect(err).to.not.exist
return done()
})
})
})
describe('when the request to v1 fails', function () {
beforeEach(function () {
this.request.yields(new Error('woops'))
return (this.call = cb => {
return this.V1SubscriptionManager._v1Request(
this.user_id,
{
url() {
return '/foo'
},
},
cb
)
})
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.exist
return done()
})
})
})
describe('when the call succeeds', function () {
beforeEach(function () {
this.V1SubscriptionManager.v1IdForUser = sinon
.stub()
.yields(null, this.v1UserId)
this.request.yields(null, { statusCode: 200 }, '{}')
return (this.call = cb => {
return this.V1SubscriptionManager._v1Request(
this.user_id,
{
url() {
return '/foo'
},
},
cb
)
})
})
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) {
return this.call((err, body, v1Id) => {
expect(v1Id).to.equal(this.v1UserId)
return done()
})
})
it('should return the http response body', function (done) {
return this.call((err, body, v1Id) => {
expect(body).to.equal('{}')
return done()
})
})
})
describe('when the call returns an http error status code', function () {
beforeEach(function () {
this.V1SubscriptionManager.v1IdForUser = sinon
.stub()
.yields(null, this.v1UserId)
this.request.yields(null, { statusCode: 500 }, '{}')
return (this.call = cb => {
return this.V1SubscriptionManager._v1Request(
this.user_id,
{
url() {
return '/foo'
},
},
cb
)
})
})
it('should produce an error', function (done) {
return this.call((err, body, v1Id) => {
expect(err).to.exist
return done()
})
})
})
describe('when the call returns an http not-found status code', function () {
beforeEach(function () {
this.V1SubscriptionManager.v1IdForUser = sinon
.stub()
.yields(null, this.v1UserId)
this.request.yields(null, { statusCode: 404 }, '{}')
return (this.call = cb => {
return this.V1SubscriptionManager._v1Request(
this.user_id,
{
url() {
return '/foo'
},
},
cb
)
})
})
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')
return done()
})
})
})
})
describe('v1IdForUser', function () {
beforeEach(function () {
return (this.UserGetter.getUser = sinon.stub().yields(null, this.user))
})
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) {
return this.call(err => {
expect(err).to.exist
return done()
})
})
})
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) {
return this.call((err, user_id) => {
expect(err).to.not.exist
return done()
})
})
})
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) {
return this.call((err, user_id) => {
expect(err).to.not.exist
return done()
})
})
it('should return the v1 user id', function (done) {
return this.call((err, user_id) => {
expect(user_id).to.eql(42)
return done()
})
})
})
})
})
| overleaf/web/test/unit/src/Subscription/V1SusbcriptionManagerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Subscription/V1SusbcriptionManagerTests.js",
"repo_id": "overleaf",
"token_count": 5188
} | 577 |
const sinon = require('sinon')
const { expect } = require('chai')
const timekeeper = require('timekeeper')
const SandboxedModule = require('sandboxed-module')
const { ObjectId } = require('mongodb')
const MODULE_PATH =
'../../../../app/src/Features/Uploads/ProjectUploadManager.js'
describe('ProjectUploadManager', function () {
beforeEach(function () {
this.now = Date.now()
timekeeper.freeze(this.now)
this.rootFolderId = new ObjectId()
this.ownerId = new ObjectId()
this.zipPath = '/path/to/zip/file-name.zip'
this.extractedZipPath = `/path/to/zip/file-name-${this.now}`
this.mainContent = 'Contents of main.tex'
this.projectName = 'My project*'
this.fixedProjectName = 'My project'
this.uniqueProjectName = 'My project (1)'
this.project = {
_id: new ObjectId(),
rootFolder: [{ _id: this.rootFolderId }],
overleaf: { history: { id: 12345 } },
}
this.doc = {
_id: new ObjectId(),
name: 'main.tex',
}
this.docFsPath = '/path/to/doc'
this.docLines = ['My thesis', 'by A. U. Thor']
this.file = {
_id: new ObjectId(),
name: 'image.png',
}
this.fileFsPath = '/path/to/file'
this.topLevelDestination = '/path/to/zip/file-extracted/nested'
this.newProjectVersion = 123
this.importEntries = [
{
type: 'doc',
projectPath: '/main.tex',
lines: this.docLines,
},
{
type: 'file',
projectPath: `/${this.file.name}`,
fsPath: this.fileFsPath,
},
]
this.docEntries = [
{
doc: this.doc,
path: `/${this.doc.name}`,
docLines: this.docLines.join('\n'),
},
]
this.fileEntries = [
{ file: this.file, path: `/${this.file.name}`, url: this.fileStoreUrl },
]
this.fs = {
remove: sinon.stub().resolves(),
}
this.ArchiveManager = {
promises: {
extractZipArchive: sinon.stub().resolves(),
findTopLevelDirectory: sinon
.stub()
.withArgs(this.extractedZipPath)
.resolves(this.topLevelDestination),
},
}
this.Doc = sinon.stub().returns(this.doc)
this.DocstoreManager = {
promises: {
updateDoc: sinon.stub().resolves(),
},
}
this.DocumentHelper = {
getTitleFromTexContent: sinon
.stub()
.withArgs(this.mainContent)
.returns(this.projectName),
}
this.DocumentUpdaterHandler = {
promises: {
updateProjectStructure: sinon.stub().resolves(),
},
}
this.FileStoreHandler = {
promises: {
uploadFileFromDisk: sinon
.stub()
.resolves({ fileRef: this.file, url: this.fileStoreUrl }),
},
}
this.FileSystemImportManager = {
promises: {
importDir: sinon
.stub()
.withArgs(this.topLevelDestination)
.resolves(this.importEntries),
},
}
this.ProjectCreationHandler = {
promises: {
createBlankProject: sinon.stub().resolves(this.project),
},
}
this.ProjectEntityMongoUpdateHandler = {
promises: {
createNewFolderStructure: sinon.stub().resolves(this.newProjectVersion),
},
}
this.ProjectRootDocManager = {
promises: {
setRootDocAutomatically: sinon.stub().resolves(),
findRootDocFileFromDirectory: sinon
.stub()
.resolves({ path: 'main.tex', content: this.mainContent }),
setRootDocFromName: sinon.stub().resolves(),
},
}
this.ProjectDetailsHandler = {
fixProjectName: sinon
.stub()
.withArgs(this.projectName)
.returns(this.fixedProjectName),
promises: {
generateUniqueName: sinon.stub().resolves(this.uniqueProjectName),
},
}
this.ProjectDeleter = {
promises: {
deleteProject: sinon.stub().resolves(),
},
}
this.TpdsProjectFlusher = {
promises: {
flushProjectToTpds: sinon.stub().resolves(),
},
}
this.ProjectUploadManager = SandboxedModule.require(MODULE_PATH, {
requires: {
'fs-extra': this.fs,
'./ArchiveManager': this.ArchiveManager,
'../../models/Doc': { Doc: this.Doc },
'../Docstore/DocstoreManager': this.DocstoreManager,
'../Documents/DocumentHelper': this.DocumentHelper,
'../DocumentUpdater/DocumentUpdaterHandler': this
.DocumentUpdaterHandler,
'../FileStore/FileStoreHandler': this.FileStoreHandler,
'./FileSystemImportManager': this.FileSystemImportManager,
'../Project/ProjectCreationHandler': this.ProjectCreationHandler,
'../Project/ProjectEntityMongoUpdateHandler': this
.ProjectEntityMongoUpdateHandler,
'../Project/ProjectRootDocManager': this.ProjectRootDocManager,
'../Project/ProjectDetailsHandler': this.ProjectDetailsHandler,
'../Project/ProjectDeleter': this.ProjectDeleter,
'../ThirdPartyDataStore/TpdsProjectFlusher': this.TpdsProjectFlusher,
},
})
})
afterEach(function () {
timekeeper.reset()
})
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,
this.zipPath
)
})
it('should extract the archive', function () {
this.ArchiveManager.promises.extractZipArchive.should.have.been.calledWith(
this.zipPath,
this.extractedZipPath
)
})
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 () {
this.ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure.should.have.been.calledWith(
this.project._id,
this.docEntries,
this.fileEntries
)
})
it('should notify document updater', function () {
this.DocumentUpdaterHandler.promises.updateProjectStructure.should.have.been.calledWith(
this.project._id,
this.project.overleaf.history.id,
this.ownerId,
{
newDocs: this.docEntries,
newFiles: this.fileEntries,
newProject: { version: this.newProjectVersion },
}
)
})
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 () {
this.ProjectRootDocManager.promises.setRootDocFromName.should.have.been.calledWith(
this.project._id,
'main.tex'
)
})
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 () {
this.ProjectRootDocManager.promises.findRootDocFileFromDirectory.resolves(
{}
)
await this.ProjectUploadManager.promises.createProjectFromZipArchive(
this.ownerId,
this.projectName,
this.zipPath
)
})
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 () {
await this.ProjectUploadManager.promises.createProjectFromZipArchiveWithName(
this.ownerId,
this.projectName,
this.zipPath
)
})
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 () {
this.ProjectCreationHandler.promises.createBlankProject.should.have.been.calledWith(
this.ownerId,
this.uniqueProjectName
)
})
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 () {
this.ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure.should.have.been.calledWith(
this.project._id,
this.docEntries,
this.fileEntries
)
})
it('should notify document updater', function () {
this.DocumentUpdaterHandler.promises.updateProjectStructure.should.have.been.calledWith(
this.project._id,
this.project.overleaf.history.id,
this.ownerId,
{
newDocs: this.docEntries,
newFiles: this.fileEntries,
newProject: { version: this.newProjectVersion },
}
)
})
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 () {
this.fs.remove.should.have.been.calledWith(this.extractedZipPath)
})
describe('when initializing the folder structure fails', function () {
beforeEach(async function () {
this.ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure.rejects()
await expect(
this.ProjectUploadManager.promises.createProjectFromZipArchiveWithName(
this.ownerId,
this.projectName,
this.zipPath
)
).to.be.rejected
})
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 () {
this.ProjectRootDocManager.promises.setRootDocAutomatically.rejects()
await expect(
this.ProjectUploadManager.promises.createProjectFromZipArchiveWithName(
this.ownerId,
this.projectName,
this.zipPath
)
).to.be.rejected
})
it('should cleanup the blank project created', function () {
this.ProjectDeleter.promises.deleteProject.should.have.been.calledWith(
this.project._id
)
})
})
})
})
| overleaf/web/test/unit/src/Uploads/ProjectUploadManagerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Uploads/ProjectUploadManagerTests.js",
"repo_id": "overleaf",
"token_count": 4671
} | 578 |
/* eslint-disable
node/handle-callback-err,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const sinon = require('sinon')
const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/User/UserSessionsManager.js'
const SandboxedModule = require('sandboxed-module')
describe('UserSessionsManager', function () {
beforeEach(function () {
this.user = {
_id: 'abcd',
email: 'user@example.com',
}
this.sessionId = 'some_session_id'
this.rclient = {
multi: sinon.stub(),
exec: sinon.stub(),
get: sinon.stub(),
del: sinon.stub(),
sadd: sinon.stub(),
srem: sinon.stub(),
smembers: sinon.stub(),
mget: sinon.stub(),
pexpire: sinon.stub(),
}
this.rclient.multi.returns(this.rclient)
this.rclient.get.returns(this.rclient)
this.rclient.del.returns(this.rclient)
this.rclient.sadd.returns(this.rclient)
this.rclient.srem.returns(this.rclient)
this.rclient.smembers.returns(this.rclient)
this.rclient.pexpire.returns(this.rclient)
this.rclient.exec.callsArgWith(0, null)
this.UserSessionsRedis = {
client: () => this.rclient,
sessionSetKey: user => `UserSessions:{${user._id}}`,
}
this.settings = {
redis: {
web: {},
},
}
return (this.UserSessionsManager = SandboxedModule.require(modulePath, {
requires: {
'@overleaf/settings': this.settings,
'./UserSessionsRedis': this.UserSessionsRedis,
},
}))
})
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 () {
this.call = callback => {
return this.UserSessionsManager.trackSession(
this.user,
this.sessionId,
callback
)
}
this.rclient.exec.callsArgWith(0, null)
return (this._checkSessions = sinon
.stub(this.UserSessionsManager, '_checkSessions')
.returns(null))
})
afterEach(function () {
return this._checkSessions.restore()
})
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) {
return this.call(err => {
this.rclient.multi.callCount.should.equal(1)
this.rclient.sadd.callCount.should.equal(1)
this.rclient.pexpire.callCount.should.equal(1)
this.rclient.exec.callCount.should.equal(1)
return 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 () {
return this.rclient.exec.callsArgWith(0, new Error('woops'))
})
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) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
})
})
})
describe('when no user is supplied', function () {
beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.trackSession(
null,
this.sessionId,
callback
)
})
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return 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)
this.rclient.pexpire.callCount.should.equal(0)
this.rclient.exec.callCount.should.equal(0)
return done()
})
})
it('should not call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
})
})
})
describe('when no sessionId is supplied', function () {
beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.trackSession(
this.user,
null,
callback
)
})
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return 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)
this.rclient.pexpire.callCount.should.equal(0)
this.rclient.exec.callCount.should.equal(0)
return done()
})
})
it('should not call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
})
})
})
})
describe('untrackSession', function () {
beforeEach(function () {
this.call = callback => {
return this.UserSessionsManager.untrackSession(
this.user,
this.sessionId,
callback
)
}
this.rclient.exec.callsArgWith(0, null)
return (this._checkSessions = sinon
.stub(this.UserSessionsManager, '_checkSessions')
.returns(null))
})
afterEach(function () {
return this._checkSessions.restore()
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(undefined)
return 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)
this.rclient.pexpire.callCount.should.equal(1)
this.rclient.exec.callCount.should.equal(1)
return 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 () {
return this.rclient.exec.callsArgWith(0, new Error('woops'))
})
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) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
})
})
})
describe('when no user is supplied', function () {
beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.untrackSession(
null,
this.sessionId,
callback
)
})
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return 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)
this.rclient.pexpire.callCount.should.equal(0)
this.rclient.exec.callCount.should.equal(0)
return done()
})
})
it('should not call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
})
})
})
describe('when no sessionId is supplied', function () {
beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.untrackSession(
this.user,
null,
callback
)
})
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return 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)
this.rclient.pexpire.callCount.should.equal(0)
this.rclient.exec.callCount.should.equal(0)
return done()
})
})
it('should not call _checkSessions', function (done) {
return this.call(err => {
this._checkSessions.callCount.should.equal(0)
return done()
})
})
})
})
describe('revokeAllUserSessions', function () {
beforeEach(function () {
this.sessionKeys = ['sess:one', 'sess:two']
this.retain = []
this.rclient.smembers.callsArgWith(1, null, this.sessionKeys)
this.rclient.del = sinon.stub().callsArgWith(1, null)
this.rclient.srem = sinon.stub().callsArgWith(2, null)
return (this.call = callback => {
return this.UserSessionsManager.revokeAllUserSessions(
this.user,
this.retain,
callback
)
})
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return 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(2)
expect(this.rclient.del.firstCall.args[0]).to.deep.equal(
this.sessionKeys[0]
)
expect(this.rclient.del.secondCall.args[0]).to.deep.equal(
this.sessionKeys[1]
)
this.rclient.srem.callCount.should.equal(1)
expect(this.rclient.srem.firstCall.args[1]).to.deep.equal(
this.sessionKeys
)
return done()
})
})
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)
this.rclient.del = sinon.stub().callsArgWith(1, null)
return (this.call = callback => {
return this.UserSessionsManager.revokeAllUserSessions(
this.user,
this.retain,
callback
)
})
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return 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)
this.rclient.srem.callCount.should.equal(1)
return 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(
'sess:three'
)
expect(this.rclient.del.thirdCall.args[0]).to.deep.equal('sess:four')
expect(this.rclient.srem.firstCall.args[1]).to.deep.equal([
'sess:one',
'sess:three',
'sess:four',
])
return done()
})
})
})
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) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
it('should not call rclient.srem', function (done) {
return this.call(err => {
this.rclient.srem.callCount.should.equal(0)
return done()
})
})
})
describe('when no user is supplied', function () {
beforeEach(function () {
return (this.call = callback => {
return this.UserSessionsManager.revokeAllUserSessions(
null,
this.retain,
callback
)
})
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return 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)
this.rclient.srem.callCount.should.equal(0)
return done()
})
})
})
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) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return 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)
this.rclient.srem.callCount.should.equal(0)
return done()
})
})
})
})
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) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return 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 () {
return this.rclient.pexpire.callsArgWith(2, new Error('woops'))
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
})
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) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return done()
})
})
it('should not call pexpire', function (done) {
return this.call(err => {
this.rclient.pexpire.callCount.should.equal(0)
return done()
})
})
})
})
describe('getAllUserSessions', function () {
beforeEach(function () {
this.sessionKeys = ['sess:one', 'sess:two', 'sess:three']
this.sessions = [
'{"user": {"ip_address": "a", "session_created": "b"}}',
'{"passport": {"user": {"ip_address": "c", "session_created": "d"}}}',
]
this.exclude = ['two']
this.rclient.smembers.callsArgWith(1, null, this.sessionKeys)
this.rclient.get = sinon.stub()
this.rclient.get.onCall(0).callsArgWith(1, null, this.sessions[0])
this.rclient.get.onCall(1).callsArgWith(1, null, this.sessions[1])
return (this.call = callback => {
return this.UserSessionsManager.getAllUserSessions(
this.user,
this.exclude,
callback
)
})
})
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) {
return this.call((err, sessions) => {
expect(sessions).to.deep.equal([
{ ip_address: 'a', session_created: 'b' },
{ ip_address: 'c', session_created: 'd' },
])
return 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) {
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 () {
this.sessionKeys = ['sess:two']
return this.rclient.smembers.callsArgWith(1, null, this.sessionKeys)
})
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) {
return this.call((err, sessions) => {
expect(sessions).to.deep.equal([])
return 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) {
return this.call((err, sessions) => {
this.rclient.mget.callCount.should.equal(0)
return done()
})
})
})
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) {
return this.call((err, sessions) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
return done()
})
})
it('should not have called rclient.mget', function (done) {
return this.call((err, sessions) => {
this.rclient.mget.callCount.should.equal(0)
return done()
})
})
})
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) {
return this.call((err, sessions) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
return done()
})
})
})
})
describe('_checkSessions', function () {
beforeEach(function () {
this.call = callback => {
return this.UserSessionsManager._checkSessions(this.user, callback)
}
this.sessionKeys = ['one', 'two']
this.rclient.smembers.callsArgWith(1, null, this.sessionKeys)
this.rclient.get.callsArgWith(1, null, 'some-value')
return this.rclient.srem.callsArgWith(2, null, {})
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(undefined)
return 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)
this.rclient.srem.callCount.should.equal(0)
return done()
})
})
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) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(undefined)
return 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)
this.rclient.srem.callCount.should.equal(1)
this.rclient.srem.firstCall.args[1].should.equal('two')
return done()
})
})
})
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) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.equal(null)
return 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)
return done()
})
})
})
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) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return 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)
this.rclient.srem.callCount.should.equal(0)
return done()
})
})
})
})
})
| overleaf/web/test/unit/src/User/UserSessionsManagerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/User/UserSessionsManagerTests.js",
"repo_id": "overleaf",
"token_count": 10857
} | 579 |
const mockModel = require('../MockModel')
module.exports = mockModel('Project', {
'./Folder': require('./Folder'),
})
| overleaf/web/test/unit/src/helpers/models/Project.js/0 | {
"file_path": "overleaf/web/test/unit/src/helpers/models/Project.js",
"repo_id": "overleaf",
"token_count": 39
} | 580 |
const webpack = require('webpack')
const merge = require('webpack-merge')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const base = require('./webpack.config')
module.exports = merge(base, {
mode: 'development',
// Enable accurate source maps for dev
devtool: 'source-map',
plugins: [
// Extract CSS to a separate file (rather than inlining to a <style> tag)
new MiniCssExtractPlugin({
// Output to public/stylesheets directory
filename: 'stylesheets/[name].css',
}),
// Disable React DevTools if DISABLE_REACT_DEVTOOLS is set to "true"
process.env.DISABLE_REACT_DEVTOOLS === 'true' &&
new webpack.DefinePlugin({
__REACT_DEVTOOLS_GLOBAL_HOOK__: '({ isDisabled: true })',
}),
].filter(Boolean),
devServer: {
// Expose dev server at www.dev-overleaf.com
host: '0.0.0.0',
port: 3808,
public: 'www.dev-overleaf.com:443',
// Customise output to the (node) console
stats: {
colors: true, // Enable some coloured highlighting
// Hide some overly verbose output
performance: false, // Disable as code is uncompressed in dev mode
hash: false,
version: false,
chunks: false,
modules: false,
// Hide copied assets from output
excludeAssets: [/^js\/ace/, /^js\/libs/, /^js\/cmaps/],
},
},
})
| overleaf/web/webpack.config.dev.js/0 | {
"file_path": "overleaf/web/webpack.config.dev.js",
"repo_id": "overleaf",
"token_count": 514
} | 581 |
{
// See https://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"esbenp.prettier-vscode",
"EditorConfig.EditorConfig",
"Orta.vscode-jest",
"Vue.volar",
"Vue.vscode-typescript-vue-plugin",
"alexkrechik.cucumberautocomplete"
]
}
| owncloud/web/.vscode/extensions.json/0 | {
"file_path": "owncloud/web/.vscode/extensions.json",
"repo_id": "owncloud",
"token_count": 142
} | 582 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.