text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
--- title: Vehicle Sync date: "2019-11-09T11:33:00" author: Southclaws --- Короткий допис, що демонструє еволюцію транспортної синхронізації. <video autoPlay loop width="100%" controls> <source src="https://assets.open.mp/assets/images/videos/vehicle_sync_01.mp4" type="video/mp4" /> На жаль, ваш браузер не підтримує вбудовані відео. </video> <video autoPlay loop width="100%" controls> <source src="https://assets.open.mp/assets/images/videos/vehicle_sync_02.mp4" type="video/mp4" /> На жаль, ваш браузер не підтримує вбудовані відео. </video> <video autoPlay loop width="100%" controls> <source src="https://assets.open.mp/assets/images/videos/vehicle_sync_03.mp4" type="video/mp4" /> На жаль, ваш браузер не підтримує вбудовані відео. </video>
openmultiplayer/web/frontend/content/uk/blog/vehicle-sync.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/uk/blog/vehicle-sync.mdx", "repo_id": "openmultiplayer", "token_count": 460 }
480
# Open Multiplayer 这是一个 _侠盗猎车手 : 圣安地列斯_ 的联机模组,并且与当前的联机模组 _San Andreas Multiplayer_ 有着完全的兼容性。 <br /> 这代表 **现有的 SA:MP 客户端以及所有的服务器脚本完全可以使用在 open.mp 上** ,且服务器的 bug 将会得到修正,不需要再从脚本或是另外使用插件修正。 若您对该项目有兴趣,想知道何时发布,或是想要帮助开发,请查看 <a href="https://forum.open.mp/showthread.php?tid=99">这篇论坛文章</a> 以获得更多资讯。 # [问答集](/faq)
openmultiplayer/web/frontend/content/zh-cn/index.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/zh-cn/index.mdx", "repo_id": "openmultiplayer", "token_count": 381 }
481
{ "name": "", "short_name": "", "icons": [ { "src": "/static/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/static/android-chrome-512x512.png", "sizes": "512x512", "type": "image/png" } ], "theme_color": "#161f2b", "background_color": "#161f2b", "display": "standalone" }
openmultiplayer/web/frontend/public/images/assets/site.webmanifest/0
{ "file_path": "openmultiplayer/web/frontend/public/images/assets/site.webmanifest", "repo_id": "openmultiplayer", "token_count": 252 }
482
import { FC } from "react"; import NextLink, { LinkProps } from "next/link"; import { Link } from "@chakra-ui/layout"; type Props = LinkProps; const Anchor: FC<Props> = (props) => { return ( <> <NextLink {...props} passHref> <Link sx={{ color: "hsl(252.2, 30.8%, 59.2%)", fontWeight: 600, }} _hover={{ color: "#9689db", textDecor: "none", }} > {props.children} </Link> </NextLink> </> ); }; export default Anchor;
openmultiplayer/web/frontend/src/components/generic/Anchor.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/generic/Anchor.tsx", "repo_id": "openmultiplayer", "token_count": 304 }
483
import { useCallback } from "react"; import { useMutationAPI } from "src/fetcher/hooks"; import { User } from "src/types/_generated_User"; type UpdateUserFn = (user: User) => void; export const useUpdateUser = (): UpdateUserFn => { const api = useMutationAPI<User>(); return useCallback( async (user: User) => api("PATCH", `/users/${user.id}`, { mutate: `/users/${user.id}`, toast: { title: `Profile updated!`, status: "success", }, })(user), [api] ); }; type BanStatusFn = (id: string, banned: boolean) => void; export const useBanStatus = (): BanStatusFn => { const api = useMutationAPI(); return useCallback( async (id: string, banned: boolean) => { api("PUT", `/users/banstatus/${id}`, { mutate: `/users/${id}`, toast: { title: `User ${banned ? "banned" : "unbanned"}!`, status: "success", }, })({ banned }); }, [api] ); };
openmultiplayer/web/frontend/src/components/member/hooks.ts/0
{ "file_path": "openmultiplayer/web/frontend/src/components/member/hooks.ts", "repo_id": "openmultiplayer", "token_count": 422 }
484
import Admonition from "../../../Admonition"; export default function NoteLowercase({ name = "function" }) { return ( <Admonition type="warning"> <p>Esta {name} inicia con letra minúscula.</p> </Admonition> ); }
openmultiplayer/web/frontend/src/components/templates/translations/es/lowercase-note.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/templates/translations/es/lowercase-note.tsx", "repo_id": "openmultiplayer", "token_count": 86 }
485
export const API_ADDRESS = process.env.NEXT_PUBLIC_API_ADDRESS ?? "https://api.open.mp"; export const WEB_ADDRESS = process.env.NEXT_PUBLIC_WEB_ADDRESS ?? "https://open.mp"; console.log(API_ADDRESS, WEB_ADDRESS);
openmultiplayer/web/frontend/src/config.ts/0
{ "file_path": "openmultiplayer/web/frontend/src/config.ts", "repo_id": "openmultiplayer", "token_count": 92 }
486
import React from "react"; import { API_ADDRESS } from "src/config"; const Page = () => { return ( <div className="measure center pa4 "> <form className="flex" action={`${API_ADDRESS}/users/dev`} method="get"> <input type="text" name="id" id="id" placeholder="id" /> <input type="text" name="secret" id="secret" placeholder="secret" /> <button type="submit">Login</button> </form> </div> ); }; export default Page;
openmultiplayer/web/frontend/src/pages/auth/dev.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/pages/auth/dev.tsx", "repo_id": "openmultiplayer", "token_count": 182 }
487
import { NextPage } from "next"; const Page: NextPage = () => { return ( <main className="measure-wide center"> <section id="text"> <header> <h1>Text</h1> </header> <article id="text__headings"> <header> <h2>Headings</h2> </header> <div> <h1>Heading 1</h1> <h2>Heading 2</h2> <h3>Heading 3</h3> <h4>Heading 4</h4> <h5>Heading 5</h5> <h6>Heading 6</h6> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="text__paragraphs"> <header> <h2>Paragraphs</h2> </header> <div> <p> A paragraph (from the Greek paragraphos, “to write beside” or “written beside”) is a self-contained unit of a discourse in writing dealing with a particular point or idea. A paragraph consists of one or more sentences. Though not required by the syntax of any language, paragraphs are usually an expected part of formal writing, used to organize longer prose. </p> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="text__blockquotes"> <header> <h2>Blockquotes</h2> </header> <div> <blockquote> <p> A block quotation (also known as a long quotation or extract) is a quotation in a written document, that is set off from the main text as a paragraph, or block of text. </p> <p> It is typically distinguished visually using indentation and a different typeface or smaller size quotation. It may or may not include a citation, usually placed at the bottom. </p> <cite> <a href="#!">Said no one, ever.</a> </cite> </blockquote> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="text__lists"> <header> <h2>Lists</h2> </header> <div> <h3>Definition list</h3> <dl> <dt>Definition List Title</dt> <dd>This is a definition list division.</dd> </dl> <h3>Ordered List</h3> <ol type="1"> <li>List Item 1</li> <li> List Item 2 <ol type="A"> <li>List Item 1</li> <li> List Item 2 <ol type="a"> <li>List Item 1</li> <li> List Item 2 <ol type="I"> <li>List Item 1</li> <li> List Item 2 <ol type="i"> <li>List Item 1</li> <li>List Item 2</li> <li>List Item 3</li> </ol> </li> <li>List Item 3</li> </ol> </li> <li>List Item 3</li> </ol> </li> <li>List Item 3</li> </ol> </li> <li>List Item 3</li> </ol> <h3>Unordered List</h3> <ul> <li>List Item 1</li> <li> List Item 2 <ul> <li>List Item 1</li> <li> List Item 2 <ul> <li>List Item 1</li> <li> List Item 2 <ul> <li>List Item 1</li> <li> List Item 2 <ul> <li>List Item 1</li> <li>List Item 2</li> <li>List Item 3</li> </ul> </li> <li>List Item 3</li> </ul> </li> <li>List Item 3</li> </ul> </li> <li>List Item 3</li> </ul> </li> <li>List Item 3</li> </ul> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="text__blockquotes"> <header> <h1>Blockquotes</h1> </header> <div> <blockquote> <p> A block quotation (also known as a long quotation or extract) is a quotation in a written document, that is set off from the main text as a paragraph, or block of text. </p> <p> It is typically distinguished visually using indentation and a different typeface or smaller size quotation. It may or may not include a citation, usually placed at the bottom. </p> <cite> <a href="#!">Said no one, ever.</a> </cite> </blockquote> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="text__details"> <header> <h1>Details / Summary</h1> </header> <details> <summary>Expand for details</summary> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Cum, odio! Odio natus ullam ad quaerat, eaque necessitatibus, aliquid distinctio similique voluptatibus dicta consequuntur animi. Quaerat facilis quidem unde eos! Ipsa. </p> </details> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="text__address"> <header> <h1>Address</h1> </header> <address> Written by <a href="mailto:webmaster@example.com">Jon Doe</a>.<br /> Visit us at: <br /> Example.com <br /> Box 564, Disneyland <br /> USA </address> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="text__hr"> <header> <h2>Horizontal rules</h2> </header> <div> <hr /> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="text__tables"> <header> <h2>Tabular data</h2> </header> <table> <caption>Table Caption</caption> <thead> <tr> <th>Table Heading 1</th> <th>Table Heading 2</th> <th>Table Heading 3</th> <th>Table Heading 4</th> <th>Table Heading 5</th> </tr> </thead> <tfoot> <tr> <th>Table Footer 1</th> <th>Table Footer 2</th> <th>Table Footer 3</th> <th>Table Footer 4</th> <th>Table Footer 5</th> </tr> </tfoot> <tbody> <tr> <td>Table Cell 1</td> <td>Table Cell 2</td> <td>Table Cell 3</td> <td>Table Cell 4</td> <td>Table Cell 5</td> </tr> <tr> <td>Table Cell 1</td> <td>Table Cell 2</td> <td>Table Cell 3</td> <td>Table Cell 4</td> <td>Table Cell 5</td> </tr> <tr> <td>Table Cell 1</td> <td>Table Cell 2</td> <td>Table Cell 3</td> <td>Table Cell 4</td> <td>Table Cell 5</td> </tr> <tr> <td>Table Cell 1</td> <td>Table Cell 2</td> <td>Table Cell 3</td> <td>Table Cell 4</td> <td>Table Cell 5</td> </tr> </tbody> </table> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="text__code"> <header> <h2>Code</h2> </header> <div> <p> <strong>Keyboard input:</strong> <kbd>Cmd</kbd> </p> <p> <strong>Inline code:</strong>{" "} <code>&lt;div&gt;code&lt;/div&gt;</code> </p> <p> <strong>Sample output:</strong>{" "} <samp>This is sample output from a computer program.</samp> </p> <h2>Pre-formatted text</h2> <pre> P R E F O R M A T T E D T E X T ! " # $ % &amp; ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; &lt; = &gt; ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z ~{" "} </pre> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="text__inline"> <header> <h2>Inline elements</h2> </header> <div> <p> <a href="#!">This is a text link</a>. </p> <p> <strong>Strong is used to indicate strong importance.</strong> </p> <p> <em>This text has added emphasis.</em> </p> <p> The <b>b element</b> is stylistically different text from normal text, without any special importance. </p> <p> The <i>i element</i> is text that is offset from the normal text. </p> <p> The <u>u element</u> is text with an unarticulated, though explicitly rendered, non-textual annotation. </p> <p> <del>This text is deleted</del> and{" "} <ins>This text is inserted</ins>. </p> <p> <s>This text has a strikethrough</s>. </p> <p> Superscript<sup>®</sup>. </p> <p> Subscript for things like H<sub>2</sub>O. </p> <p> <small>This small text is small for fine print, etc.</small> </p> <p> Abbreviation: <abbr title="HyperText Markup Language">HTML</abbr> </p> <p> <q cite="https://developer.mozilla.org/en-US/docs/HTML/Element/q"> This text is a short inline quotation. </q> </p> <p> <cite>This is a citation.</cite> </p> <p> The <dfn>dfn element</dfn> indicates a definition. </p> <p> The <mark>mark element</mark> indicates a highlight. </p> <p> The <var>variable element</var>, such as <var>x</var> ={" "} <var>y</var>. </p> <p> The time element:{" "} <time dateTime="2013-04-06T12:32+00:00">2 weeks ago</time> </p> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> </section> <section id="embedded"> <header> <h2>Embedded content</h2> </header> <article id="embedded__images"> <header> <h2>Images</h2> </header> <div> <h3> Plain <code>&lt;img&gt;</code> element </h3> <p> <img src="https://placekitten.com/480/480" alt="Photo of a kitten" /> </p> <h3> <code>&lt;figure&gt;</code> element with <code>&lt;img&gt;</code>{" "} element </h3> <figure> <img src="https://placekitten.com/420/420" alt="Photo of a kitten" /> </figure> <h3> <code>&lt;figure&gt;</code> element with <code>&lt;img&gt;</code>{" "} and <code>&lt;figcaption&gt;</code> elements </h3> <figure> <img src="https://placekitten.com/420/420" alt="Photo of a kitten" /> <figcaption>Here is a caption for this image.</figcaption> </figure> <h3> <code>&lt;figure&gt;</code> element with a{" "} <code>&lt;picture&gt;</code> element </h3> <figure> <picture> <source srcSet="https://placekitten.com/800/800" media="(min-width: 800px)" /> <img src="https://placekitten.com/420/420" alt="Photo of a kitten" /> </picture> </figure> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="embedded__canvas"> <header> <h2>Canvas</h2> </header> <div> <canvas></canvas> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="embedded__meter"> <header> <h2>Meter</h2> </header> <div> <meter value="2" min="0" max="10"> 2 out of 10 </meter> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="embedded__progress"> <header> <h2>Progress</h2> </header> <div> <progress>progress</progress> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="embedded__svg"> <header> <h2>Inline SVG</h2> </header> <div> <svg width="100px" height="100px"> <circle cx="100" cy="100" r="100" fill="#1fa3ec"></circle> </svg> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="embedded__iframe"> <header> <h2>IFrame</h2> </header> <div> <iframe src="/" height="300"></iframe> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="embedded__embed"> <header> <h2>Embed</h2> </header> <div> <embed src="/" height="300" /> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> <article id="embedded__object"> <header> <h2>Object</h2> </header> <div> <object data="/" height="300"></object> </div> <footer> <p> <a href="#top">[Top]</a> </p> </footer> </article> </section> <section id="forms"> <header> <h2>Form elements</h2> </header> <form> <fieldset id="forms__input"> <legend>Input fields</legend> <p> <label htmlFor="input__text">Text Input</label> <input id="input__text" type="text" placeholder="Text Input" /> </p> <p> <label htmlFor="input__password">Password</label> <input id="input__password" type="password" placeholder="Type your Password" /> </p> <p> <label htmlFor="input__webaddress">Web Address</label> <input id="input__webaddress" type="url" placeholder="https://yoursite.com" /> </p> <p> <label htmlFor="input__emailaddress">Email Address</label> <input id="input__emailaddress" type="email" placeholder="name@email.com" /> </p> <p> <label htmlFor="input__phone">Phone Number</label> <input id="input__phone" type="tel" placeholder="(999) 999-9999" /> </p> <p> <label htmlFor="input__search">Search</label> <input id="input__search" type="search" placeholder="Enter Search Term" /> </p> <p> <label htmlFor="input__text2">Number Input</label> <input id="input__text2" type="number" placeholder="Enter a Number" /> </p> <p> <label htmlFor="input__file">File Input</label> <input id="input__file" type="file" /> </p> </fieldset> <p> <a href="#top">[Top]</a> </p> <fieldset id="forms__select"> <legend>Select menus</legend> <p> <label htmlFor="select">Select</label> <select id="select"> <optgroup label="Option Group"> <option>Option One</option> <option>Option Two</option> <option>Option Three</option> </optgroup> </select> </p> <p> <label htmlFor="select_multiple">Select (multiple)</label> <select id="select_multiple" multiple> <optgroup label="Option Group"> <option>Option One</option> <option>Option Two</option> <option>Option Three</option> </optgroup> </select> </p> </fieldset> <p> <a href="#top">[Top]</a> </p> <fieldset id="forms__checkbox"> <legend>Checkboxes</legend> <ul> <li> <label htmlFor="checkbox1"> <input id="checkbox1" name="checkbox" type="checkbox" checked={true} />{" "} Choice A </label> </li> <li> <label htmlFor="checkbox2"> <input id="checkbox2" name="checkbox" type="checkbox" />{" "} Choice B </label> </li> <li> <label htmlFor="checkbox3"> <input id="checkbox3" name="checkbox" type="checkbox" />{" "} Choice C </label> </li> </ul> </fieldset> <p> <a href="#top">[Top]</a> </p> <fieldset id="forms__radio"> <legend>Radio buttons</legend> <ul> <li> <label htmlFor="radio1"> <input id="radio1" name="radio" type="radio" checked={true} />{" "} Option 1 </label> </li> <li> <label htmlFor="radio2"> <input id="radio2" name="radio" type="radio" /> Option 2 </label> </li> <li> <label htmlFor="radio3"> <input id="radio3" name="radio" type="radio" /> Option 3 </label> </li> </ul> </fieldset> <p> <a href="#top">[Top]</a> </p> <fieldset id="forms__textareas"> <legend>Textareas</legend> <p> <label htmlFor="textarea">Textarea</label> <textarea id="textarea" rows={8} cols={48} placeholder="Enter your message here" ></textarea> </p> </fieldset> <p> <a href="#top">[Top]</a> </p> <fieldset id="forms__html5"> <legend>HTML5 inputs</legend> <p> <label htmlFor="ic">Color input</label> <input type="color" id="ic" value="#000000" /> </p> <p> <label htmlFor="in">Number input</label> <input type="number" id="in" min="0" max="10" value="5" /> </p> <p> <label htmlFor="ir">Range input</label> <input type="range" id="ir" value="10" /> </p> <p> <label htmlFor="idd">Date input</label> <input type="date" id="idd" value="1970-01-01" /> </p> <p> <label htmlFor="idm">Month input</label> <input type="month" id="idm" value="1970-01" /> </p> <p> <label htmlFor="idw">Week input</label> <input type="week" id="idw" value="1970-W01" /> </p> <p> <label htmlFor="idt">Datetime input</label> <input type="dateTime" id="idt" value="1970-01-01T00:00:00Z" /> </p> <p> <label htmlFor="idtl">Datetime-local input</label> <input type="dateTime-local" id="idtl" value="1970-01-01T00:00" /> </p> <p> <label htmlFor="idl">Datalist</label> <input type="text" id="idl" list="example-list" /> <datalist id="example-list"> <option value="Example #1" /> <option value="Example #2" /> <option value="Example #3" /> </datalist> </p> </fieldset> <p> <a href="#top">[Top]</a> </p> <fieldset id="forms__action"> <legend>Action buttons</legend> <p> <input type="submit" value="<input type=submit>" /> <input type="button" value="<input type=button>" /> <input type="reset" value="<input type=reset>" /> <input type="submit" value="<input disabled>" disabled /> </p> <p> <button type="submit">&lt;button type=submit&gt;</button> <button type="button">&lt;button type=button&gt;</button> <button type="reset">&lt;button type=reset&gt;</button> <button type="button" disabled> &lt;button disabled&gt; </button> </p> </fieldset> <p> <a href="#top">[Top]</a> </p> </form> </section> </main> ); }; export default Page;
openmultiplayer/web/frontend/src/pages/typography.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/pages/typography.tsx", "repo_id": "openmultiplayer", "token_count": 15721 }
488
export type Content = { title: string; description?: string; date?: string; author?: string; slug?: string; }; export type RawContent = { source: string; fallback: boolean; };
openmultiplayer/web/frontend/src/types/content.ts/0
{ "file_path": "openmultiplayer/web/frontend/src/types/content.ts", "repo_id": "openmultiplayer", "token_count": 61 }
489
package cache import ( "time" cache "github.com/victorspringer/http-cache" "github.com/victorspringer/http-cache/adapter/memory" "go.uber.org/fx" ) func Build() fx.Option { return fx.Provide( func() (*cache.Client, error) { memory, err := memory.NewAdapter( memory.AdapterWithAlgorithm(memory.LRU), memory.AdapterWithCapacity(10000000), ) if err != nil { return nil, err } cacheClient, err := cache.NewClient( cache.ClientWithAdapter(memory), cache.ClientWithTTL(10*time.Minute), cache.ClientWithRefreshKey("opn"), ) if err != nil { return nil, err } return cacheClient, nil }, ) }
openmultiplayer/web/internal/cache/cache.go/0
{ "file_path": "openmultiplayer/web/internal/cache/cache.go", "repo_id": "openmultiplayer", "token_count": 276 }
490
package web import ( "encoding/json" "fmt" "net/http" "github.com/pkg/errors" ) func Write(w http.ResponseWriter, data interface{}) { bytes, err := json.Marshal(data) if err != nil { StatusInternalServerError(w, errors.Wrap(err, "failed to encode payload")) return } w.Header().Add("Content-Length", fmt.Sprint(len(bytes))) w.Write(bytes) }
openmultiplayer/web/internal/web/write_json.go/0
{ "file_path": "openmultiplayer/web/internal/web/write_json.go", "repo_id": "openmultiplayer", "token_count": 138 }
491
datasource db { provider = "cockroachdb" url = env("DATABASE_URL") } generator client { provider = "go run github.com/steebchen/prisma-client-go" output = "../internal/db" package = "db" binaryTargets = ["native"] previewFeatures = ["fullTextSearch"] } enum AuthMethod { GITHUB DISCORD UNDEFINED } model User { id String @id @default(uuid()) email String @unique authMethod AuthMethod github GitHub? discord Discord? name String @db.String(64) bio String? admin Boolean @default(false) servers Server[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? } model GitHub { userId String @id user User @relation(fields: [userId], references: [id]) accountId String @unique username String @unique email String @unique } model Discord { userId String @id user User @relation(fields: [userId], references: [id]) accountId String @unique username String @unique email String @unique } model Server { id String @id @default(uuid()) // essential data (short names to save data!) ip String @unique hn String pc BigInt pm BigInt gm String la String pa Boolean vn String ru Rule[] // domain name for de-duplication purposes domain String? // rich data (entered by server owners via the web UI) description String? banner String? // user who owns this server User User? @relation(fields: [userId], references: [id]) userId String? active Boolean updatedAt DateTime @updatedAt deletedAt DateTime? lastActive DateTime? omp Boolean @default(false) partner Boolean @default(false) pending Boolean @default(false) } model Rule { id BigInt @id @default(autoincrement()) name String value String Server Server? @relation(fields: [serverId], references: [id]) serverId String? @@unique([name, serverId], name: "Rule_serverId_rule_name_index") } model ServerIPBlacklist { id String @id @default(uuid()) ip String @unique }
openmultiplayer/web/prisma/schema.prisma/0
{ "file_path": "openmultiplayer/web/prisma/schema.prisma", "repo_id": "openmultiplayer", "token_count": 766 }
492
let AuthorizationMiddleware const AuthorizationManager = require('./AuthorizationManager') const async = require('async') const logger = require('logger-sharelatex') const { ObjectId } = require('mongodb') const Errors = require('../Errors/Errors') const HttpErrorHandler = require('../Errors/HttpErrorHandler') const AuthenticationController = require('../Authentication/AuthenticationController') const SessionManager = require('../Authentication/SessionManager') const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler') module.exports = AuthorizationMiddleware = { ensureUserCanReadMultipleProjects(req, res, next) { const projectIds = (req.query.project_ids || '').split(',') AuthorizationMiddleware._getUserId(req, function (error, userId) { if (error) { return next(error) } // Remove the projects we have access to. Note rejectSeries doesn't use // errors in callbacks async.rejectSeries( projectIds, function (projectId, cb) { const token = TokenAccessHandler.getRequestToken(req, projectId) AuthorizationManager.canUserReadProject( userId, projectId, token, function (error, canRead) { if (error) { return next(error) } cb(canRead) } ) }, function (unauthorizedProjectIds) { if (unauthorizedProjectIds.length > 0) { return AuthorizationMiddleware.redirectToRestricted(req, res, next) } next() } ) }) }, blockRestrictedUserFromProject(req, res, next) { AuthorizationMiddleware._getUserAndProjectId( req, function (error, userId, projectId) { if (error) { return next(error) } const token = TokenAccessHandler.getRequestToken(req, projectId) AuthorizationManager.isRestrictedUserForProject( userId, projectId, token, (err, isRestrictedUser) => { if (err) { return next(err) } if (isRestrictedUser) { return res.sendStatus(403) } next() } ) } ) }, ensureUserCanReadProject(req, res, next) { AuthorizationMiddleware._getUserAndProjectId( req, function (error, userId, projectId) { if (error) { return next(error) } const token = TokenAccessHandler.getRequestToken(req, projectId) AuthorizationManager.canUserReadProject( userId, projectId, token, function (error, canRead) { if (error) { return next(error) } if (canRead) { logger.log( { userId, projectId }, 'allowing user read access to project' ) return next() } logger.log( { userId, projectId }, 'denying user read access to project' ) HttpErrorHandler.forbidden(req, res) } ) } ) }, ensureUserCanWriteProjectSettings(req, res, next) { AuthorizationMiddleware._getUserAndProjectId( req, function (error, userId, projectId) { if (error) { return next(error) } const token = TokenAccessHandler.getRequestToken(req, projectId) AuthorizationManager.canUserWriteProjectSettings( userId, projectId, token, function (error, canWrite) { if (error) { return next(error) } if (canWrite) { logger.log( { userId, projectId }, 'allowing user write access to project settings' ) return next() } logger.log( { userId, projectId }, 'denying user write access to project settings' ) HttpErrorHandler.forbidden(req, res) } ) } ) }, ensureUserCanWriteProjectContent(req, res, next) { AuthorizationMiddleware._getUserAndProjectId( req, function (error, userId, projectId) { if (error) { return next(error) } const token = TokenAccessHandler.getRequestToken(req, projectId) AuthorizationManager.canUserWriteProjectContent( userId, projectId, token, function (error, canWrite) { if (error) { return next(error) } if (canWrite) { logger.log( { userId, projectId }, 'allowing user write access to project content' ) return next() } logger.log( { userId, projectId }, 'denying user write access to project settings' ) HttpErrorHandler.forbidden(req, res) } ) } ) }, ensureUserCanAdminProject(req, res, next) { AuthorizationMiddleware._getUserAndProjectId( req, function (error, userId, projectId) { if (error) { return next(error) } const token = TokenAccessHandler.getRequestToken(req, projectId) AuthorizationManager.canUserAdminProject( userId, projectId, token, function (error, canAdmin) { if (error) { return next(error) } if (canAdmin) { logger.log( { userId, projectId }, 'allowing user admin access to project' ) return next() } logger.log( { userId, projectId }, 'denying user admin access to project' ) HttpErrorHandler.forbidden(req, res) } ) } ) }, ensureUserIsSiteAdmin(req, res, next) { AuthorizationMiddleware._getUserId(req, function (error, userId) { if (error) { return next(error) } AuthorizationManager.isUserSiteAdmin(userId, function (error, isAdmin) { if (error) { return next(error) } if (isAdmin) { logger.log({ userId }, 'allowing user admin access to site') return next() } logger.log({ userId }, 'denying user admin access to site') AuthorizationMiddleware.redirectToRestricted(req, res, next) }) }) }, _getUserAndProjectId(req, callback) { const projectId = req.params.project_id || req.params.Project_id if (!projectId) { return callback(new Error('Expected project_id in request parameters')) } if (!ObjectId.isValid(projectId)) { return callback( new Errors.NotFoundError(`invalid projectId: ${projectId}`) ) } AuthorizationMiddleware._getUserId(req, function (error, userId) { if (error) { return callback(error) } callback(null, userId, projectId) }) }, _getUserId(req, callback) { const userId = SessionManager.getLoggedInUserId(req.session) || (req.oauth_user && req.oauth_user._id) || null callback(null, userId) }, redirectToRestricted(req, res, next) { // TODO: move this to throwing ForbiddenError res.redirect( `/restricted?from=${encodeURIComponent(res.locals.currentUrl)}` ) }, restricted(req, res, next) { if (SessionManager.isUserLoggedIn(req.session)) { return res.render('user/restricted', { title: 'restricted' }) } const { from } = req.query logger.log({ from }, 'redirecting to login') if (from) { AuthenticationController.setRedirectInSession(req, from) } res.redirect('/login') }, }
overleaf/web/app/src/Features/Authorization/AuthorizationMiddleware.js/0
{ "file_path": "overleaf/web/app/src/Features/Authorization/AuthorizationMiddleware.js", "repo_id": "overleaf", "token_count": 3749 }
493
const CollaboratorsController = require('./CollaboratorsController') const AuthenticationController = require('../Authentication/AuthenticationController') const AuthorizationMiddleware = require('../Authorization/AuthorizationMiddleware') const PrivilegeLevels = require('../Authorization/PrivilegeLevels') const CollaboratorsInviteController = require('./CollaboratorsInviteController') const RateLimiterMiddleware = require('../Security/RateLimiterMiddleware') const CaptchaMiddleware = require('../Captcha/CaptchaMiddleware') const AnalyticsRegistrationSourceMiddleware = require('../Analytics/AnalyticsRegistrationSourceMiddleware') const { Joi, validate } = require('../../infrastructure/Validation') module.exports = { apply(webRouter, apiRouter) { webRouter.post( '/project/:Project_id/leave', AuthenticationController.requireLogin(), CollaboratorsController.removeSelfFromProject ) webRouter.put( '/project/:Project_id/users/:user_id', AuthenticationController.requireLogin(), validate({ params: Joi.object({ Project_id: Joi.objectId(), user_id: Joi.objectId(), }), body: Joi.object({ privilegeLevel: Joi.string() .valid(PrivilegeLevels.READ_ONLY, PrivilegeLevels.READ_AND_WRITE) .required(), }), }), AuthorizationMiddleware.ensureUserCanAdminProject, CollaboratorsController.setCollaboratorInfo ) webRouter.delete( '/project/:Project_id/users/:user_id', AuthenticationController.requireLogin(), AuthorizationMiddleware.ensureUserCanAdminProject, CollaboratorsController.removeUserFromProject ) webRouter.get( '/project/:Project_id/members', AuthenticationController.requireLogin(), AuthorizationMiddleware.ensureUserCanAdminProject, CollaboratorsController.getAllMembers ) webRouter.post( '/project/:Project_id/transfer-ownership', AuthenticationController.requireLogin(), validate({ params: Joi.object({ Project_id: Joi.objectId(), }), body: Joi.object({ user_id: Joi.objectId(), }), }), AuthorizationMiddleware.ensureUserCanAdminProject, CollaboratorsController.transferOwnership ) // invites webRouter.post( '/project/:Project_id/invite', RateLimiterMiddleware.rateLimit({ endpointName: 'invite-to-project-by-project-id', params: ['Project_id'], maxRequests: 100, timeInterval: 60 * 10, }), RateLimiterMiddleware.rateLimit({ endpointName: 'invite-to-project-by-ip', ipOnly: true, maxRequests: 100, timeInterval: 60 * 10, }), CaptchaMiddleware.validateCaptcha('invite'), AuthenticationController.requireLogin(), AuthorizationMiddleware.ensureUserCanAdminProject, CollaboratorsInviteController.inviteToProject ) webRouter.get( '/project/:Project_id/invites', AuthenticationController.requireLogin(), AuthorizationMiddleware.ensureUserCanAdminProject, CollaboratorsInviteController.getAllInvites ) webRouter.delete( '/project/:Project_id/invite/:invite_id', AuthenticationController.requireLogin(), AuthorizationMiddleware.ensureUserCanAdminProject, CollaboratorsInviteController.revokeInvite ) webRouter.post( '/project/:Project_id/invite/:invite_id/resend', RateLimiterMiddleware.rateLimit({ endpointName: 'resend-invite', params: ['Project_id'], maxRequests: 200, timeInterval: 60 * 10, }), AuthenticationController.requireLogin(), AuthorizationMiddleware.ensureUserCanAdminProject, CollaboratorsInviteController.resendInvite ) webRouter.get( '/project/:Project_id/invite/token/:token', AnalyticsRegistrationSourceMiddleware.setSource('project-invite'), AuthenticationController.requireLogin(), CollaboratorsInviteController.viewInvite, AnalyticsRegistrationSourceMiddleware.clearSource() ) webRouter.post( '/project/:Project_id/invite/token/:token/accept', AnalyticsRegistrationSourceMiddleware.setSource('project-invite'), AuthenticationController.requireLogin(), CollaboratorsInviteController.acceptInvite, AnalyticsRegistrationSourceMiddleware.clearSource() ) }, }
overleaf/web/app/src/Features/Collaborators/CollaboratorsRouter.js/0
{ "file_path": "overleaf/web/app/src/Features/Collaborators/CollaboratorsRouter.js", "repo_id": "overleaf", "token_count": 1654 }
494
/* eslint-disable max-len, no-cond-assign, */ // 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 DocumentHelper module.exports = DocumentHelper = { getTitleFromTexContent(content, maxContentToScan) { if (maxContentToScan == null) { maxContentToScan = 30000 } const TITLE_WITH_CURLY_BRACES = /\\[tT]itle\*?\s*{([^}]+)}/ const TITLE_WITH_SQUARE_BRACES = /\\[tT]itle\s*\[([^\]]+)\]/ for (const line of Array.from( DocumentHelper._getLinesFromContent(content, maxContentToScan) )) { var match if ( (match = line.match(TITLE_WITH_CURLY_BRACES) || line.match(TITLE_WITH_SQUARE_BRACES)) ) { return DocumentHelper.detex(match[1]) } } return null }, contentHasDocumentclass(content, maxContentToScan) { if (maxContentToScan == null) { maxContentToScan = 30000 } for (const line of Array.from( DocumentHelper._getLinesFromContent(content, maxContentToScan) )) { // We've had problems with this regex locking up CPU. // Previously /.*\\documentclass/ would totally lock up on lines of 500kb (data text files :() // This regex will only look from the start of the line, including whitespace so will return quickly // regardless of line length. if (line.match(/^\s*\\documentclass/)) { return true } } return false }, detex(string) { return string .replace(/\\LaTeX/g, 'LaTeX') .replace(/\\TeX/g, 'TeX') .replace(/\\TikZ/g, 'TikZ') .replace(/\\BibTeX/g, 'BibTeX') .replace(/\\\[[A-Za-z0-9. ]*\]/g, ' ') // line spacing .replace(/\\(?:[a-zA-Z]+|.|)/g, '') .replace(/{}|~/g, ' ') .replace(/[${}]/g, '') .replace(/ +/g, ' ') .trim() }, _getLinesFromContent(content, maxContentToScan) { if (typeof content === 'string') { return content.substring(0, maxContentToScan).split('\n') } else { return content } }, }
overleaf/web/app/src/Features/Documents/DocumentHelper.js/0
{ "file_path": "overleaf/web/app/src/Features/Documents/DocumentHelper.js", "repo_id": "overleaf", "token_count": 985 }
495
let ErrorController const Errors = require('./Errors') const logger = require('logger-sharelatex') const SessionManager = require('../Authentication/SessionManager') const SamlLogHandler = require('../SamlLog/SamlLogHandler') const HttpErrorHandler = require('./HttpErrorHandler') module.exports = ErrorController = { notFound(req, res) { res.status(404) res.render('general/404', { title: 'page_not_found' }) }, forbidden(req, res) { res.status(403) res.render('user/restricted') }, serverError(req, res) { res.status(500) res.render('general/500', { title: 'Server Error' }) }, handleError(error, req, res, next) { const user = SessionManager.getSessionUser(req.session) // log errors related to SAML flow if (req.session && req.session.saml) { SamlLogHandler.log(req.session.saml.universityId, req.sessionID, { error: { message: error && error.message, stack: error && error.stack, }, body: req.body, path: req.path, query: req.query, saml: req.session.saml, user_id: user && user._id, }) } if (error.code === 'EBADCSRFTOKEN') { logger.warn( { err: error, url: req.url, method: req.method, user }, 'invalid csrf' ) res.sendStatus(403) } else if (error instanceof Errors.NotFoundError) { logger.warn({ err: error, url: req.url }, 'not found error') ErrorController.notFound(req, res) } else if ( error instanceof URIError && error.message.match(/^Failed to decode param/) ) { logger.warn({ err: error, url: req.url }, 'Express URIError') res.status(400) res.render('general/500', { title: 'Invalid Error' }) } else if (error instanceof Errors.ForbiddenError) { logger.error({ err: error }, 'forbidden error') ErrorController.forbidden(req, res) } else if (error instanceof Errors.TooManyRequestsError) { logger.warn({ err: error, url: req.url }, 'too many requests error') res.sendStatus(429) } else if (error instanceof Errors.InvalidError) { logger.warn({ err: error, url: req.url }, 'invalid error') res.status(400) res.send(error.message) } else if (error instanceof Errors.InvalidNameError) { logger.warn({ err: error, url: req.url }, 'invalid name error') res.status(400) res.send(error.message) } else if (error instanceof Errors.SAMLSessionDataMissing) { logger.warn( { err: error, url: req.url }, 'missing SAML session data error' ) HttpErrorHandler.badRequest(req, res, error.message) } else { logger.error( { err: error, url: req.url, method: req.method, user }, 'error passed to top level next middleware' ) ErrorController.serverError(req, res) } }, handleApiError(error, req, res, next) { if (error instanceof Errors.NotFoundError) { logger.warn({ err: error, url: req.url }, 'not found error') res.sendStatus(404) } else if ( error instanceof URIError && error.message.match(/^Failed to decode param/) ) { logger.warn({ err: error, url: req.url }, 'Express URIError') res.sendStatus(400) } else { logger.error( { err: error, url: req.url, method: req.method }, 'error passed to top level next middleware' ) res.sendStatus(500) } }, }
overleaf/web/app/src/Features/Errors/ErrorController.js/0
{ "file_path": "overleaf/web/app/src/Features/Errors/ErrorController.js", "repo_id": "overleaf", "token_count": 1385 }
496
/* eslint-disable max-len, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. let StringHelper const JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/g const JSON_ESCAPE = { '&': '\\u0026', '>': '\\u003e', '<': '\\u003c', '\u2028': '\\u2028', '\u2029': '\\u2029', } module.exports = StringHelper = { // stringifies and escapes a json object for use in a script. This ensures that &, < and > characters are escaped, // along with quotes. This ensures that the string can be safely rendered into HTML. See rationale at: // https://api.rubyonrails.org/classes/ERB/Util.html#method-c-json_escape // and implementation lifted from: // https://github.com/ember-fastboot/fastboot/blob/cafd96c48564d8384eb83dc908303dba8ece10fd/src/ember-app.js#L496-L510 stringifyJsonForScript(object) { return JSON.stringify(object).replace( JSON_ESCAPE_REGEXP, match => JSON_ESCAPE[match] ) }, }
overleaf/web/app/src/Features/Helpers/StringHelper.js/0
{ "file_path": "overleaf/web/app/src/Features/Helpers/StringHelper.js", "repo_id": "overleaf", "token_count": 386 }
497
/* 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 */ const AuthorizationMiddleware = require('../Authorization/AuthorizationMiddleware') const AuthenticationController = require('../Authentication/AuthenticationController') const RateLimiterMiddleware = require('../Security/RateLimiterMiddleware') const LinkedFilesController = require('./LinkedFilesController') module.exports = { apply(webRouter) { webRouter.post( '/project/:project_id/linked_file', AuthenticationController.requireLogin(), AuthorizationMiddleware.ensureUserCanWriteProjectContent, RateLimiterMiddleware.rateLimit({ endpointName: 'create-linked-file', params: ['project_id'], maxRequests: 100, timeInterval: 60, }), LinkedFilesController.createLinkedFile ) return webRouter.post( '/project/:project_id/linked_file/:file_id/refresh', AuthenticationController.requireLogin(), AuthorizationMiddleware.ensureUserCanWriteProjectContent, RateLimiterMiddleware.rateLimit({ endpointName: 'refresh-linked-file', params: ['project_id'], maxRequests: 100, timeInterval: 60, }), LinkedFilesController.refreshLinkedFile ) }, }
overleaf/web/app/src/Features/LinkedFiles/LinkedFilesRouter.js/0
{ "file_path": "overleaf/web/app/src/Features/LinkedFiles/LinkedFilesRouter.js", "repo_id": "overleaf", "token_count": 526 }
498
/* eslint-disable camelcase, 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 */ const ProjectDetailsHandler = require('./ProjectDetailsHandler') const logger = require('logger-sharelatex') module.exports = { getProjectDetails(req, res, next) { const { project_id } = req.params return ProjectDetailsHandler.getDetails( project_id, function (err, projDetails) { if (err != null) { return next(err) } return res.json(projDetails) } ) }, }
overleaf/web/app/src/Features/Project/ProjectApiController.js/0
{ "file_path": "overleaf/web/app/src/Features/Project/ProjectApiController.js", "repo_id": "overleaf", "token_count": 302 }
499
const { Project } = require('../../models/Project') const settings = require('@overleaf/settings') const { promisifyAll } = require('../../util/promises') const safeCompilers = ['xelatex', 'pdflatex', 'latex', 'lualatex'] const ProjectOptionsHandler = { setCompiler(projectId, compiler, callback) { if (!compiler) { return callback() } compiler = compiler.toLowerCase() if (!safeCompilers.includes(compiler)) { return callback(new Error(`invalid compiler: ${compiler}`)) } const conditions = { _id: projectId } const update = { compiler } Project.updateOne(conditions, update, {}, callback) }, setImageName(projectId, imageName, callback) { if (!imageName || !Array.isArray(settings.allowedImageNames)) { return callback() } imageName = imageName.toLowerCase() const isAllowed = settings.allowedImageNames.find( allowed => imageName === allowed.imageName ) if (!isAllowed) { return callback(new Error(`invalid imageName: ${imageName}`)) } const conditions = { _id: projectId } const update = { imageName: settings.imageRoot + '/' + imageName } Project.updateOne(conditions, update, {}, callback) }, setSpellCheckLanguage(projectId, languageCode, callback) { if (!Array.isArray(settings.languages)) { return callback() } const language = settings.languages.find( language => language.code === languageCode ) if (languageCode && !language) { return callback(new Error(`invalid languageCode: ${languageCode}`)) } const conditions = { _id: projectId } const update = { spellCheckLanguage: languageCode } Project.updateOne(conditions, update, {}, callback) }, setBrandVariationId(projectId, brandVariationId, callback) { if (!brandVariationId) { return callback() } const conditions = { _id: projectId } const update = { brandVariationId } Project.updateOne(conditions, update, {}, callback) }, unsetBrandVariationId(projectId, callback) { const conditions = { _id: projectId } const update = { $unset: { brandVariationId: 1 } } Project.updateOne(conditions, update, {}, callback) }, } ProjectOptionsHandler.promises = promisifyAll(ProjectOptionsHandler) module.exports = ProjectOptionsHandler
overleaf/web/app/src/Features/Project/ProjectOptionsHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/Project/ProjectOptionsHandler.js", "repo_id": "overleaf", "token_count": 784 }
500
/* 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 * 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 */ const metrics = require('@overleaf/metrics') const logger = require('logger-sharelatex') const _ = require('underscore') const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler') const Settings = require('@overleaf/settings') const TpdsUpdateSender = require('../ThirdPartyDataStore/TpdsUpdateSender') const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher') const EditorRealTimeController = require('../Editor/EditorRealTimeController') const SystemMessageManager = require('../SystemMessages/SystemMessageManager') const oneMinInMs = 60 * 1000 var updateOpenConnetionsMetrics = function () { metrics.gauge( 'open_connections.socketio', __guard__( __guard__( __guard__(require('../../infrastructure/Server').io, x2 => x2.sockets), x1 => x1.clients() ), x => x.length ) ) metrics.gauge( 'open_connections.http', _.size(__guard__(require('http').globalAgent, x3 => x3.sockets)) ) metrics.gauge( 'open_connections.https', _.size(__guard__(require('https').globalAgent, x4 => x4.sockets)) ) return setTimeout(updateOpenConnetionsMetrics, oneMinInMs) } setTimeout(updateOpenConnetionsMetrics, oneMinInMs) const AdminController = { index: (req, res, next) => { let agents, url let agent const openSockets = {} const object = require('http').globalAgent.sockets for (url in object) { agents = object[url] openSockets[`http://${url}`] = (() => { const result = [] for (agent of Array.from(agents)) { result.push(agent._httpMessage.path) } return result })() } const object1 = require('https').globalAgent.sockets for (url in object1) { agents = object1[url] openSockets[`https://${url}`] = (() => { const result1 = [] for (agent of Array.from(agents)) { result1.push(agent._httpMessage.path) } return result1 })() } return SystemMessageManager.getMessagesFromDB(function ( error, systemMessages ) { if (error != null) { return next(error) } return res.render('admin/index', { title: 'System Admin', openSockets, systemMessages, }) }) }, registerNewUser(req, res, next) { return res.render('admin/register') }, disconnectAllUsers: (req, res) => { logger.warn('disconecting everyone') const delay = (req.query && req.query.delay) > 0 ? req.query.delay : 10 EditorRealTimeController.emitToAll( 'forceDisconnect', 'Sorry, we are performing a quick update to the editor and need to close it down. Please refresh the page to continue.', delay ) return res.sendStatus(200) }, unregisterServiceWorker: (req, res) => { logger.warn('unregistering service worker for all users') EditorRealTimeController.emitToAll('unregisterServiceWorker') return res.sendStatus(200) }, openEditor(req, res) { logger.warn('opening editor') Settings.editorIsOpen = true return res.sendStatus(200) }, closeEditor(req, res) { logger.warn('closing editor') Settings.editorIsOpen = req.body.isOpen return res.sendStatus(200) }, writeAllToMongo(req, res) { logger.log('writing all docs to mongo') Settings.mongo.writeAll = true return DocumentUpdaterHandler.flushAllDocsToMongo(function () { logger.log('all docs have been saved to mongo') return res.sendStatus(200) }) }, flushProjectToTpds(req, res) { return TpdsProjectFlusher.flushProjectToTpds(req.body.project_id, err => res.sendStatus(200) ) }, pollDropboxForUser(req, res) { const { user_id } = req.body return TpdsUpdateSender.pollDropboxForUser(user_id, () => res.sendStatus(200) ) }, createMessage(req, res, next) { return SystemMessageManager.createMessage( req.body.content, function (error) { if (error != null) { return next(error) } return res.sendStatus(200) } ) }, clearMessages(req, res, next) { return SystemMessageManager.clearMessages(function (error) { if (error != null) { return next(error) } return res.sendStatus(200) }) }, } function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) : undefined } module.exports = AdminController
overleaf/web/app/src/Features/ServerAdmin/AdminController.js/0
{ "file_path": "overleaf/web/app/src/Features/ServerAdmin/AdminController.js", "repo_id": "overleaf", "token_count": 1924 }
501
const recurly = require('recurly') const Settings = require('@overleaf/settings') const logger = require('logger-sharelatex') const { callbackify } = require('util') const UserGetter = require('../User/UserGetter') const recurlySettings = Settings.apis.recurly const recurlyApiKey = recurlySettings ? recurlySettings.apiKey : undefined const client = new recurly.Client(recurlyApiKey) async function getAccountForUserId(userId) { try { return await client.getAccount(`code-${userId}`) } catch (err) { if (err instanceof recurly.errors.NotFoundError) { // An expected error, we don't need to handle it, just return nothing logger.debug({ userId }, 'no recurly account found for user') } else { throw err } } } async function createAccountForUserId(userId) { const user = await UserGetter.promises.getUser(userId, { _id: 1, first_name: 1, last_name: 1, email: 1, }) const accountCreate = { code: user._id.toString(), email: user.email, firstName: user.first_name, lastName: user.last_name, } const account = await client.createAccount(accountCreate) logger.log({ userId, account }, 'created recurly account') return account } async function getSubscription(subscriptionId) { return await client.getSubscription(subscriptionId) } async function changeSubscription(subscriptionId, body) { const change = await client.createSubscriptionChange(subscriptionId, body) logger.log( { subscriptionId, changeId: change.id }, 'created subscription change' ) return change } async function changeSubscriptionByUuid(subscriptionUuid, ...args) { return await changeSubscription('uuid-' + subscriptionUuid, ...args) } async function removeSubscriptionChange(subscriptionId) { const removed = await client.removeSubscriptionChange(subscriptionId) logger.log({ subscriptionId }, 'removed pending subscription change') return removed } async function removeSubscriptionChangeByUuid(subscriptionUuid) { return await removeSubscriptionChange('uuid-' + subscriptionUuid) } async function reactivateSubscriptionByUuid(subscriptionUuid) { return await client.reactivateSubscription('uuid-' + subscriptionUuid) } async function cancelSubscriptionByUuid(subscriptionUuid) { try { return await client.cancelSubscription('uuid-' + subscriptionUuid) } catch (err) { if (err instanceof recurly.errors.ValidationError) { if ( err.message === 'Only active and future subscriptions can be canceled.' ) { logger.log( { subscriptionUuid }, 'subscription cancellation failed, subscription not active' ) } } else { throw err } } } module.exports = { errors: recurly.errors, getAccountForUserId: callbackify(getAccountForUserId), createAccountForUserId: callbackify(createAccountForUserId), getSubscription: callbackify(getSubscription), changeSubscription: callbackify(changeSubscription), changeSubscriptionByUuid: callbackify(changeSubscriptionByUuid), removeSubscriptionChange: callbackify(removeSubscriptionChange), removeSubscriptionChangeByUuid: callbackify(removeSubscriptionChangeByUuid), reactivateSubscriptionByUuid: callbackify(reactivateSubscriptionByUuid), cancelSubscriptionByUuid: callbackify(cancelSubscriptionByUuid), promises: { getSubscription, getAccountForUserId, createAccountForUserId, changeSubscription, changeSubscriptionByUuid, removeSubscriptionChange, removeSubscriptionChangeByUuid, reactivateSubscriptionByUuid, cancelSubscriptionByUuid, }, }
overleaf/web/app/src/Features/Subscription/RecurlyClient.js/0
{ "file_path": "overleaf/web/app/src/Features/Subscription/RecurlyClient.js", "repo_id": "overleaf", "token_count": 1183 }
502
/* 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 * 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 */ let V1SubscriptionManager const UserGetter = require('../User/UserGetter') const request = require('request') const settings = require('@overleaf/settings') const { V1ConnectionError, NotFoundError } = require('../Errors/Errors') module.exports = V1SubscriptionManager = { // Returned planCode = 'v1_pro' | 'v1_pro_plus' | 'v1_student' | 'v1_free' | null // For this to work, we need plans in settings with plan-codes: // - 'v1_pro' // - 'v1_pro_plus' // - 'v1_student' // - 'v1_free' getPlanCodeFromV1(userId, callback) { if (callback == null) { callback = function (err, planCode, v1Id) {} } return V1SubscriptionManager._v1Request( userId, { method: 'GET', url(v1Id) { return `/api/v1/sharelatex/users/${v1Id}/plan_code` }, }, function (error, body, v1Id) { if (error != null) { return callback(error) } let planName = body != null ? body.plan_name : undefined if (['pro', 'pro_plus', 'student', 'free'].includes(planName)) { planName = `v1_${planName}` } else { // Throw away 'anonymous', etc as being equivalent to null planName = null } return callback(null, planName, v1Id) } ) }, getSubscriptionsFromV1(userId, callback) { if (callback == null) { callback = function (err, subscriptions, v1Id) {} } return V1SubscriptionManager._v1Request( userId, { method: 'GET', url(v1Id) { return `/api/v1/sharelatex/users/${v1Id}/subscriptions` }, }, callback ) }, getSubscriptionStatusFromV1(userId, callback) { if (callback == null) { callback = function (err, status) {} } return V1SubscriptionManager._v1Request( userId, { method: 'GET', url(v1Id) { return `/api/v1/sharelatex/users/${v1Id}/subscription_status` }, }, callback ) }, cancelV1Subscription(userId, callback) { if (callback == null) { callback = function (err) {} } return V1SubscriptionManager._v1Request( userId, { method: 'DELETE', url(v1Id) { return `/api/v1/sharelatex/users/${v1Id}/subscription` }, }, callback ) }, v1IdForUser(userId, callback) { if (callback == null) { callback = function (err, v1Id) {} } return UserGetter.getUser( userId, { 'overleaf.id': 1 }, function (err, user) { if (err != null) { return callback(err) } const v1Id = __guard__( user != null ? user.overleaf : undefined, x => x.id ) return callback(null, v1Id) } ) }, // v1 accounts created before migration to v2 had github and mendeley for free // but these are now paid-for features for new accounts (v1id > cutoff) getGrandfatheredFeaturesForV1User(v1Id) { const cutoff = settings.v1GrandfatheredFeaturesUidCutoff if (cutoff == null) { return {} } if (v1Id == null) { return {} } if (v1Id < cutoff) { return settings.v1GrandfatheredFeatures || {} } else { return {} } }, _v1Request(userId, options, callback) { if (callback == null) { callback = function (err, body, v1Id) {} } if (!settings.apis.v1.url) { return callback(null, null) } return V1SubscriptionManager.v1IdForUser(userId, function (err, v1Id) { if (err != null) { return callback(err) } if (v1Id == null) { return callback(null, null, null) } const url = options.url(v1Id) return request( { baseUrl: settings.apis.v1.url, url, method: options.method, auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass, sendImmediately: true, }, json: true, timeout: 15 * 1000, }, function (error, response, body) { if (error != null) { return callback( new V1ConnectionError({ message: 'no v1 connection', info: { url }, }).withCause(error) ) } if (response && response.statusCode >= 500) { return callback( new V1ConnectionError({ message: 'error from v1', info: { status: response.statusCode, body: body, }, }) ) } if (response.statusCode >= 200 && response.statusCode < 300) { return callback(null, body, v1Id) } else { if (response.statusCode === 404) { return callback(new NotFoundError(`v1 user not found: ${userId}`)) } else { return callback( new Error( `non-success code from v1: ${response.statusCode} ${ options.method } ${options.url(v1Id)}` ) ) } } } ) }) }, } function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) : undefined }
overleaf/web/app/src/Features/Subscription/V1SubscriptionManager.js/0
{ "file_path": "overleaf/web/app/src/Features/Subscription/V1SubscriptionManager.js", "repo_id": "overleaf", "token_count": 2780 }
503
const AuthenticationController = require('../Authentication/AuthenticationController') const SessionManager = require('../Authentication/SessionManager') const TokenAccessHandler = require('./TokenAccessHandler') const Errors = require('../Errors/Errors') const logger = require('logger-sharelatex') const settings = require('@overleaf/settings') const OError = require('@overleaf/o-error') const { expressify } = require('../../util/promises') const AuthorizationManager = require('../Authorization/AuthorizationManager') const PrivilegeLevels = require('../Authorization/PrivilegeLevels') const orderedPrivilegeLevels = [ PrivilegeLevels.NONE, PrivilegeLevels.READ_ONLY, PrivilegeLevels.READ_AND_WRITE, PrivilegeLevels.OWNER, ] async function _userAlreadyHasHigherPrivilege( userId, projectId, token, tokenType ) { if (!Object.values(TokenAccessHandler.TOKEN_TYPES).includes(tokenType)) { throw new Error('bad token type') } const privilegeLevel = await AuthorizationManager.promises.getPrivilegeLevelForProject( userId, projectId, token ) return ( orderedPrivilegeLevels.indexOf(privilegeLevel) >= orderedPrivilegeLevels.indexOf(tokenType) ) } const makePostUrl = token => { if (TokenAccessHandler.isReadAndWriteToken(token)) { return `/${token}/grant` } else if (TokenAccessHandler.isReadOnlyToken(token)) { return `/read/${token}/grant` } else { throw new Error('invalid token type') } } async function _handleV1Project(token, userId) { if (!userId) { return { v1Import: { status: 'mustLogin' } } } else { const docInfo = await TokenAccessHandler.promises.getV1DocInfo( token, userId ) // This should not happen anymore, but it does show // a nice "contact support" message, so it can stay if (!docInfo) { return { v1Import: { status: 'cannotImport' } } } if (!docInfo.exists) { return null } if (docInfo.exported) { return null } return { v1Import: { status: 'canDownloadZip', projectId: token, hasOwner: docInfo.has_owner, name: docInfo.name || 'Untitled', brandInfo: docInfo.brand_info, }, } } } async function tokenAccessPage(req, res, next) { const { token } = req.params if (!TokenAccessHandler.isValidToken(token)) { return next(new Errors.NotFoundError()) } try { if (TokenAccessHandler.isReadOnlyToken(token)) { const docPublishedInfo = await TokenAccessHandler.promises.getV1DocPublishedInfo( token ) if (docPublishedInfo.allow === false) { return res.redirect(302, docPublishedInfo.published_path) } } res.render('project/token/access', { postUrl: makePostUrl(token), }) } catch (err) { return next( OError.tag(err, 'error while rendering token access page', { token }) ) } } async function checkAndGetProjectOrResponseAction( tokenType, token, userId, req, res, next ) { // Try to get the project, and/or an alternative action to take. // Returns a tuple of [project, action] const project = await TokenAccessHandler.promises.getProjectByToken( tokenType, token ) if (!project) { if (settings.overleaf) { const v1ImportData = await _handleV1Project(token, userId) return [ null, () => { if (v1ImportData) { res.json(v1ImportData) } else { res.sendStatus(404) } }, ] } else { return [null, null] } } const projectId = project._id const isAnonymousUser = !userId const tokenAccessEnabled = TokenAccessHandler.tokenAccessEnabledForProject( project ) if (isAnonymousUser && tokenAccessEnabled) { if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE) { if (TokenAccessHandler.ANONYMOUS_READ_AND_WRITE_ENABLED) { logger.info({ projectId }, 'granting read-write anonymous access') TokenAccessHandler.grantSessionTokenAccess(req, projectId, token) return [ null, () => { res.json({ redirect: `/project/${projectId}`, grantAnonymousAccess: tokenType, }) }, ] } else { logger.warn( { token, projectId }, '[TokenAccess] deny anonymous read-and-write token access' ) AuthenticationController.setRedirectInSession( req, TokenAccessHandler.makeTokenUrl(token) ) return [ null, () => { res.json({ redirect: '/restricted', anonWriteAccessDenied: true, }) }, ] } } else if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_ONLY) { logger.info({ projectId }, 'granting read-only anonymous access') TokenAccessHandler.grantSessionTokenAccess(req, projectId, token) return [ null, () => { res.json({ redirect: `/project/${projectId}`, grantAnonymousAccess: tokenType, }) }, ] } else { throw new Error('unreachable') } } const userHasPrivilege = await _userAlreadyHasHigherPrivilege( userId, projectId, token, tokenType ) if (userHasPrivilege) { return [ null, () => { res.json({ redirect: `/project/${project._id}`, higherAccess: true }) }, ] } if (!tokenAccessEnabled) { return [ null, () => { next(new Errors.NotFoundError()) }, ] } return [project, null] } async function grantTokenAccessReadAndWrite(req, res, next) { const { token } = req.params const userId = SessionManager.getLoggedInUserId(req.session) if (!TokenAccessHandler.isReadAndWriteToken(token)) { return res.sendStatus(400) } const tokenType = TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE try { const [project, action] = await checkAndGetProjectOrResponseAction( tokenType, token, userId, req, res, next ) if (action) { return action() } if (!project) { return next(new Errors.NotFoundError()) } await TokenAccessHandler.promises.addReadAndWriteUserToProject( userId, project._id ) return res.json({ redirect: `/project/${project._id}`, tokenAccessGranted: tokenType, }) } catch (err) { return next( OError.tag( err, 'error while trying to grant read-and-write token access', { token } ) ) } } async function grantTokenAccessReadOnly(req, res, next) { const { token } = req.params const userId = SessionManager.getLoggedInUserId(req.session) if (!TokenAccessHandler.isReadOnlyToken(token)) { return res.sendStatus(400) } const tokenType = TokenAccessHandler.TOKEN_TYPES.READ_ONLY const docPublishedInfo = await TokenAccessHandler.promises.getV1DocPublishedInfo( token ) if (docPublishedInfo.allow === false) { return res.json({ redirect: docPublishedInfo.published_path }) } try { const [project, action] = await checkAndGetProjectOrResponseAction( tokenType, token, userId, req, res, next ) if (action) { return action() } if (!project) { return next(new Errors.NotFoundError()) } await TokenAccessHandler.promises.addReadOnlyUserToProject( userId, project._id ) return res.json({ redirect: `/project/${project._id}`, tokenAccessGranted: tokenType, }) } catch (err) { return next( OError.tag(err, 'error while trying to grant read-only token access', { token, }) ) } } module.exports = { READ_ONLY_TOKEN_PATTERN: TokenAccessHandler.READ_ONLY_TOKEN_PATTERN, READ_AND_WRITE_TOKEN_PATTERN: TokenAccessHandler.READ_AND_WRITE_TOKEN_PATTERN, tokenAccessPage: expressify(tokenAccessPage), grantTokenAccessReadOnly: expressify(grantTokenAccessReadOnly), grantTokenAccessReadAndWrite: expressify(grantTokenAccessReadAndWrite), }
overleaf/web/app/src/Features/TokenAccess/TokenAccessController.js/0
{ "file_path": "overleaf/web/app/src/Features/TokenAccess/TokenAccessController.js", "repo_id": "overleaf", "token_count": 3301 }
504
const EmailHelper = require('../Helpers/EmailHelper') const EmailHandler = require('../Email/EmailHandler') const OneTimeTokenHandler = require('../Security/OneTimeTokenHandler') const settings = require('@overleaf/settings') const Errors = require('../Errors/Errors') const UserUpdater = require('./UserUpdater') const UserGetter = require('./UserGetter') const { callbackify, promisify } = require('util') // Reject email confirmation tokens after 90 days const TOKEN_EXPIRY_IN_S = 90 * 24 * 60 * 60 const TOKEN_USE = 'email_confirmation' function sendConfirmationEmail(userId, email, emailTemplate, callback) { if (arguments.length === 3) { callback = emailTemplate emailTemplate = 'confirmEmail' } // when force-migrating accounts to v2 from v1, we don't want to send confirmation messages - // setting this env var allows us to turn this behaviour off if (process.env.SHARELATEX_NO_CONFIRMATION_MESSAGES != null) { return callback(null) } email = EmailHelper.parseEmail(email) if (!email) { return callback(new Error('invalid email')) } const data = { user_id: userId, email } OneTimeTokenHandler.getNewToken( TOKEN_USE, data, { expiresIn: TOKEN_EXPIRY_IN_S }, function (err, token) { if (err) { return callback(err) } const emailOptions = { to: email, confirmEmailUrl: `${settings.siteUrl}/user/emails/confirm?token=${token}`, sendingUser_id: userId, } EmailHandler.sendEmail(emailTemplate, emailOptions, callback) } ) } async function sendReconfirmationEmail(userId, email) { email = EmailHelper.parseEmail(email) if (!email) { throw new Error('invalid email') } const data = { user_id: userId, email } const token = await OneTimeTokenHandler.promises.getNewToken( TOKEN_USE, data, { expiresIn: TOKEN_EXPIRY_IN_S } ) const emailOptions = { to: email, confirmEmailUrl: `${settings.siteUrl}/user/emails/confirm?token=${token}`, sendingUser_id: userId, } await EmailHandler.promises.sendEmail('reconfirmEmail', emailOptions) } const UserEmailsConfirmationHandler = { sendConfirmationEmail, sendReconfirmationEmail: callbackify(sendReconfirmationEmail), confirmEmailFromToken(token, callback) { OneTimeTokenHandler.getValueFromTokenAndExpire( TOKEN_USE, token, function (error, data) { if (error) { return callback(error) } if (!data) { return callback(new Errors.NotFoundError('no token found')) } const userId = data.user_id const email = data.email if (!userId || email !== EmailHelper.parseEmail(email)) { return callback(new Errors.NotFoundError('invalid data')) } UserGetter.getUser(userId, {}, function (error, user) { if (error) { return callback(error) } if (!user) { return callback(new Errors.NotFoundError('user not found')) } const emailExists = user.emails.some( emailData => emailData.email === email ) if (!emailExists) { return callback(new Errors.NotFoundError('email missing for user')) } UserUpdater.confirmEmail(userId, email, callback) }) } ) }, } UserEmailsConfirmationHandler.promises = { sendConfirmationEmail: promisify(sendConfirmationEmail), } module.exports = UserEmailsConfirmationHandler
overleaf/web/app/src/Features/User/UserEmailsConfirmationHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/User/UserEmailsConfirmationHandler.js", "repo_id": "overleaf", "token_count": 1347 }
505
/* eslint-disable 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: * 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 */ const { ObjectId } = require('mongodb') const async = require('async') const { promisifyAll } = require('../../util/promises') const Errors = require('../Errors/Errors') const EntityModels = { Institution: require('../../models/Institution').Institution, Subscription: require('../../models/Subscription').Subscription, Publisher: require('../../models/Publisher').Publisher, } const UserMembershipViewModel = require('./UserMembershipViewModel') const UserGetter = require('../User/UserGetter') const logger = require('logger-sharelatex') const UserMembershipEntityConfigs = require('./UserMembershipEntityConfigs') const UserMembershipHandler = { getEntityWithoutAuthorizationCheck(entityId, entityConfig, callback) { if (callback == null) { callback = function (error, entity) {} } const query = buildEntityQuery(entityId, entityConfig) return EntityModels[entityConfig.modelName].findOne(query, callback) }, createEntity(entityId, entityConfig, callback) { if (callback == null) { callback = function (error, entity) {} } const data = buildEntityQuery(entityId, entityConfig) return EntityModels[entityConfig.modelName].create(data, callback) }, getUsers(entity, entityConfig, callback) { if (callback == null) { callback = function (error, users) {} } const attributes = entityConfig.fields.read return getPopulatedListOfMembers(entity, attributes, callback) }, addUser(entity, entityConfig, email, callback) { if (callback == null) { callback = function (error, user) {} } const attribute = entityConfig.fields.write return UserGetter.getUserByAnyEmail(email, function (error, user) { if (error != null) { return callback(error) } if (!user) { return callback({ userNotFound: true }) } if (entity[attribute].some(managerId => managerId.equals(user._id))) { return callback({ alreadyAdded: true }) } return addUserToEntity(entity, attribute, user, error => callback(error, UserMembershipViewModel.build(user)) ) }) }, removeUser(entity, entityConfig, userId, callback) { if (callback == null) { callback = function (error) {} } const attribute = entityConfig.fields.write if (entity.admin_id != null ? entity.admin_id.equals(userId) : undefined) { return callback({ isAdmin: true }) } return removeUserFromEntity(entity, attribute, userId, callback) }, } UserMembershipHandler.promises = promisifyAll(UserMembershipHandler) module.exports = UserMembershipHandler var getPopulatedListOfMembers = function (entity, attributes, callback) { if (callback == null) { callback = function (error, users) {} } const userObjects = [] for (const attribute of Array.from(attributes)) { for (const userObject of Array.from(entity[attribute] || [])) { // userObject can be an email as String, a user id as ObjectId or an // invite as Object with an email attribute as String. We want to pass to // UserMembershipViewModel either an email as (String) or a user id (ObjectId) const userIdOrEmail = userObject.email || userObject userObjects.push(userIdOrEmail) } } return async.map(userObjects, UserMembershipViewModel.buildAsync, callback) } var addUserToEntity = function (entity, attribute, user, callback) { if (callback == null) { callback = function (error) {} } const fieldUpdate = {} fieldUpdate[attribute] = user._id return entity.updateOne({ $addToSet: fieldUpdate }, callback) } var removeUserFromEntity = function (entity, attribute, userId, callback) { if (callback == null) { callback = function (error) {} } const fieldUpdate = {} fieldUpdate[attribute] = userId return entity.updateOne({ $pull: fieldUpdate }, callback) } var buildEntityQuery = function (entityId, entityConfig, loggedInUser) { if (ObjectId.isValid(entityId.toString())) { entityId = ObjectId(entityId) } const query = Object.assign({}, entityConfig.baseQuery) query[entityConfig.fields.primaryKey] = entityId return query }
overleaf/web/app/src/Features/UserMembership/UserMembershipHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/UserMembership/UserMembershipHandler.js", "repo_id": "overleaf", "token_count": 1486 }
506
const { callbackify, promisify } = require('util') const metrics = require('@overleaf/metrics') const RedisWrapper = require('./RedisWrapper') const rclient = RedisWrapper.client('lock') const logger = require('logger-sharelatex') const os = require('os') const crypto = require('crypto') const async = require('async') const settings = require('@overleaf/settings') const HOST = os.hostname() const PID = process.pid const RND = crypto.randomBytes(4).toString('hex') let COUNT = 0 const LOCK_QUEUES = new Map() // queue lock requests for each name/id so they get the lock on a first-come first-served basis logger.log( { lockManagerSettings: settings.lockManager }, 'LockManager initialising' ) const LockManager = { // ms between each test of the lock LOCK_TEST_INTERVAL: settings.lockManager.lockTestInterval || 50, // back off to ms between each test of the lock MAX_TEST_INTERVAL: settings.lockManager.maxTestInterval || 1000, // ms maximum time to spend trying to get the lock MAX_LOCK_WAIT_TIME: settings.lockManager.maxLockWaitTime || 10000, // seconds. Time until lock auto expires in redis REDIS_LOCK_EXPIRY: settings.lockManager.redisLockExpiry || 30, // ms, if execution takes longer than this then log SLOW_EXECUTION_THRESHOLD: settings.lockManager.slowExecutionThreshold || 5000, // Use a signed lock value as described in // http://redis.io/topics/distlock#correct-implementation-with-a-single-instance // to prevent accidental unlocking by multiple processes randomLock() { const time = Date.now() return `locked:host=${HOST}:pid=${PID}:random=${RND}:time=${time}:count=${COUNT++}` }, unlockScript: 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end', runWithLock(namespace, id, runner, callback) { // runner must be a function accepting a callback, e.g. runner = (cb) -> // This error is defined here so we get a useful stacktrace const slowExecutionError = new Error('slow execution during lock') const timer = new metrics.Timer(`lock.${namespace}`) const key = `lock:web:${namespace}:${id}` LockManager._getLock(key, namespace, (error, lockValue) => { if (error != null) { return callback(error) } // The lock can expire in redis but the process carry on. This setTimeout call // is designed to log if this happens. function countIfExceededLockTimeout() { metrics.inc(`lock.${namespace}.exceeded_lock_timeout`) logger.log('exceeded lock timeout', { namespace, id, slowExecutionError, }) } const exceededLockTimeout = setTimeout( countIfExceededLockTimeout, LockManager.REDIS_LOCK_EXPIRY * 1000 ) runner((error1, ...values) => LockManager._releaseLock(key, lockValue, error2 => { clearTimeout(exceededLockTimeout) const timeTaken = new Date() - timer.start if (timeTaken > LockManager.SLOW_EXECUTION_THRESHOLD) { logger.log('slow execution during lock', { namespace, id, timeTaken, slowExecutionError, }) } timer.done() error = error1 || error2 if (error != null) { return callback(error) } callback(null, ...values) }) ) }) }, _tryLock(key, namespace, callback) { const lockValue = LockManager.randomLock() rclient.set( key, lockValue, 'EX', LockManager.REDIS_LOCK_EXPIRY, 'NX', (err, gotLock) => { if (err != null) { return callback(err) } if (gotLock === 'OK') { metrics.inc(`lock.${namespace}.try.success`) callback(err, true, lockValue) } else { metrics.inc(`lock.${namespace}.try.failed`) logger.log({ key, redis_response: gotLock }, 'lock is locked') callback(err, false) } } ) }, // it's sufficient to serialize within a process because that is where the parallel operations occur _getLock(key, namespace, callback) { // this is what we need to do for each lock we want to request const task = next => LockManager._getLockByPolling(key, namespace, (error, lockValue) => { // tell the queue to start trying to get the next lock (if any) next() // we have got a lock result, so we can continue with our own execution callback(error, lockValue) }) // create a queue for this key if needed const queueName = `${key}:${namespace}` let queue = LOCK_QUEUES.get(queueName) if (queue == null) { const handler = (fn, cb) => fn(cb) // set up a new queue for this key queue = async.queue(handler, 1) queue.push(task) // remove the queue object when queue is empty queue.drain = () => LOCK_QUEUES.delete(queueName) // store the queue in our global map LOCK_QUEUES.set(queueName, queue) } else { // queue the request to get the lock queue.push(task) } }, _getLockByPolling(key, namespace, callback) { const startTime = Date.now() const testInterval = LockManager.LOCK_TEST_INTERVAL let attempts = 0 function attempt() { if (Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME) { metrics.inc(`lock.${namespace}.get.failed`) return callback(new Error('Timeout')) } attempts += 1 LockManager._tryLock(key, namespace, (error, gotLock, lockValue) => { if (error != null) { return callback(error) } if (gotLock) { metrics.gauge(`lock.${namespace}.get.success.tries`, attempts) callback(null, lockValue) } else { setTimeout(attempt, testInterval) } }) } attempt() }, _releaseLock(key, lockValue, callback) { rclient.eval(LockManager.unlockScript, 1, key, lockValue, (err, result) => { if (err != null) { callback(err) } else if (result != null && result !== 1) { // successful unlock should release exactly one key logger.warn( { key, lockValue, redis_err: err, redis_result: result }, 'unlocking error' ) metrics.inc('unlock-error') callback(new Error('tried to release timed out lock')) } else { callback(null, result) } }) }, } module.exports = LockManager const promisifiedRunWithLock = promisify(LockManager.runWithLock) LockManager.promises = { runWithLock(namespace, id, runner) { const cbRunner = callbackify(runner) return promisifiedRunWithLock(namespace, id, cbRunner) }, }
overleaf/web/app/src/infrastructure/LockManager.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/LockManager.js", "repo_id": "overleaf", "token_count": 2687 }
507
const i18n = require('i18next') const fsBackend = require('i18next-fs-backend') const middleware = require('i18next-http-middleware') const path = require('path') const Settings = require('@overleaf/settings') const { URL } = require('url') const fallbackLanguageCode = Settings.i18n.defaultLng || 'en' const availableLanguageCodes = [] const availableHosts = new Map() const subdomainConfigs = new Map() Object.values(Settings.i18n.subdomainLang || {}).forEach(function (spec) { availableLanguageCodes.push(spec.lngCode) // prebuild a host->lngCode mapping for the usage at runtime in the // middleware availableHosts.set(new URL(spec.url).host, spec.lngCode) // prebuild a lngCode -> language config mapping; some subdomains should // not appear in the language picker if (!spec.hide) { subdomainConfigs.set(spec.lngCode, spec) } }) if (!availableLanguageCodes.includes(fallbackLanguageCode)) { // always load the fallback locale availableLanguageCodes.push(fallbackLanguageCode) } i18n .use(fsBackend) .use(middleware.LanguageDetector) .init({ backend: { loadPath: path.join(__dirname, '../../../locales/__lng__.json'), }, // Load translation files synchronously: https://www.i18next.com/overview/configuration-options#initimmediate initImmediate: false, // We use the legacy v1 JSON format, so configure interpolator to use // underscores instead of curly braces interpolation: { prefix: '__', suffix: '__', unescapeSuffix: 'HTML', // Disable escaping of interpolated values for backwards compatibility. // We escape the value after it's translated in web, so there's no // security risk escapeValue: Settings.i18n.escapeHTMLInVars, // Disable nesting in interpolated values, preventing user input // injection via another nested value skipOnVariables: true, }, preload: availableLanguageCodes, supportedLngs: availableLanguageCodes, fallbackLng: fallbackLanguageCode, }) // Make custom language detector for Accept-Language header const headerLangDetector = new middleware.LanguageDetector(i18n.services, { order: ['header'], }) function setLangBasedOnDomainMiddleware(req, res, next) { // Determine language from subdomain const lang = availableHosts.get(req.headers.host) if (lang) { req.i18n.changeLanguage(lang) } // expose the language code to pug res.locals.currentLngCode = req.language // If the set language is different from the language detection (based on // the Accept-Language header), then set flag which will show a banner // offering to switch to the appropriate library const detectedLanguageCode = headerLangDetector.detect(req, res) if (req.language !== detectedLanguageCode) { res.locals.suggestedLanguageSubdomainConfig = subdomainConfigs.get( detectedLanguageCode ) } // Decorate req.i18n with translate function alias for backwards // compatibility usage in requests req.i18n.translate = req.i18n.t next() } // Decorate i18n with translate function alias for backwards compatibility // in direct usage i18n.translate = i18n.t module.exports = { i18nMiddleware: middleware.handle(i18n), setLangBasedOnDomainMiddleware, i18n, }
overleaf/web/app/src/infrastructure/Translations.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/Translations.js", "repo_id": "overleaf", "token_count": 1047 }
508
const mongoose = require('../infrastructure/Mongoose') const { Schema } = mongoose const { ObjectId } = Schema const OauthAuthorizationCodeSchema = new Schema( { authorizationCode: String, expiresAt: Date, oauthApplication_id: { type: ObjectId, ref: 'OauthApplication' }, redirectUri: String, scope: String, user_id: { type: ObjectId, ref: 'User' }, }, { collection: 'oauthAuthorizationCodes', } ) exports.OauthAuthorizationCode = mongoose.model( 'OauthAuthorizationCode', OauthAuthorizationCodeSchema ) exports.OauthAuthorizationCodeSchema = OauthAuthorizationCodeSchema
overleaf/web/app/src/models/OauthAuthorizationCode.js/0
{ "file_path": "overleaf/web/app/src/models/OauthAuthorizationCode.js", "repo_id": "overleaf", "token_count": 216 }
509
\documentclass{article} \usepackage[utf8]{inputenc} \title{<%= project_name %>} \author{<%= user.first_name %> <%= user.last_name %>} \date{<%= month %> <%= year %>} \usepackage{natbib} \usepackage{graphicx} \begin{document} \maketitle \section{Introduction} There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable. There is another theory which states that this has already happened. \begin{figure}[h!] \centering \includegraphics[scale=1.7]{universe} \caption{The Universe} \label{fig:universe} \end{figure} \section{Conclusion} ``I always thought something was fundamentally wrong with the universe'' \citep{adams1995hitchhiker} \bibliographystyle{plain} \bibliography{references} \end{document}
overleaf/web/app/templates/project_files/main.tex/0
{ "file_path": "overleaf/web/app/templates/project_files/main.tex", "repo_id": "overleaf", "token_count": 276 }
510
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 I'm sorry, Dave. I'm afraid I can't do that. p.error-description There was a problem with your latest request if(message) |: #{message} |. br | Please go back and try again. p.error-description | If the problem persists, please contact us at | a(href="mailto:" + settings.adminEmail) #{settings.adminEmail} | . a.error-btn(href="javascript:history.back()") Back | &nbsp; a.btn.btn-default(href="/") Home
overleaf/web/app/views/general/400.pug/0
{ "file_path": "overleaf/web/app/views/general/400.pug", "repo_id": "overleaf", "token_count": 337 }
511
div.full-size( ng-show="ui.view == 'editor'" layout="pdf" layout-disabled="ui.pdfLayout != 'sideBySide'" mask-iframes-on-resize="true" resize-on="layout:main:resize" resize-proportionally="true" initial-size-east="'50%'" minimum-restore-size-east="300" allow-overflow-on="'center'" custom-toggler-pane=hasFeature('custom-togglers') ? "east" : false custom-toggler-msg-when-open=hasFeature('custom-togglers') ? translate("tooltip_hide_pdf") : false custom-toggler-msg-when-closed=hasFeature('custom-togglers') ? translate("tooltip_show_pdf") : false ) if showSymbolPalette include ./editor-with-symbol-palette else include ./editor-no-symbol-palette .ui-layout-east div(ng-if="ui.pdfLayout == 'sideBySide'") include ./pdf .ui-layout-resizer-controls.synctex-controls( ng-show="!!pdf.url && settings.pdfViewer == 'pdfjs'" ng-controller="PdfSynctexController" ) a.btn.btn-default.btn-xs.synctex-control.synctex-control-goto-pdf( tooltip=translate('go_to_code_location_in_pdf') tooltip-placement="right" tooltip-append-to-body="true" ng-click="syncToPdf()" ng-disabled="syncToPdfInFlight" ) i.synctex-control-icon(ng-show="!syncToPdfInFlight") i.synctex-spin-icon.fa.fa-refresh.fa-spin(ng-show="syncToPdfInFlight") a.btn.btn-default.btn-xs.synctex-control.synctex-control-goto-code( tooltip=translate('go_to_pdf_location_in_code') tooltip-placement="right" tooltip-append-to-body="true" ng-click="syncToCode()" ng-disabled="syncToCodeInFlight" ) i.synctex-control-icon(ng-show="!syncToCodeInFlight") i.synctex-spin-icon.fa.fa-refresh.fa-spin(ng-show="syncToCodeInFlight") div.full-size( ng-if="ui.pdfLayout == 'flat'" ng-show="ui.view == 'pdf'" ) include ./pdf // fallback, shown when no file/view is selected div.full-size.no-file-selection( ng-if="!ui.view" ) .no-file-selection-message( ng-if="rootFolder.children && rootFolder.children.length > 0" ) h3 | #{translate('no_selection_select_file')} .no-file-selection-message( ng-if="rootFolder.children && rootFolder.children.length === 0" ) h3 | #{translate('no_selection_create_new_file')} div( ng-controller="FileTreeController" ) button.btn.btn-primary( ng-click="openNewDocModal()" ) | #{translate('new_file')}
overleaf/web/app/views/project/editor/editor.pug/0
{ "file_path": "overleaf/web/app/views/project/editor/editor.pug", "repo_id": "overleaf", "token_count": 970 }
512
div.full-size.pdf(ng-controller="PdfController") if showNewLogsUI preview-pane( compiler-state=`{ autoCompileHasChanges: changesToAutoCompile, autoCompileHasLintingError: autoCompileLintingError, isAutoCompileOn: autocompile_enabled, isClearingCache: pdf.clearingCache, isCompiling: pdf.compiling, isDraftModeOn: draft, isSyntaxCheckOn: stop_on_validation_error, lastCompileTimestamp: pdf.lastCompileTimestamp, logEntries: pdf.logEntries, validationIssues: pdf.validation, rawLog: pdf.rawLog, compileFailed: pdf.compileFailed, errors: { error: pdf.error, renderingError: pdf.renderingError, clsiMaintenance: pdf.clsiMaintenance, clsiUnavailable: pdf.clsiUnavailable, tooRecentlyCompiled: pdf.tooRecentlyCompiled, compileTerminated: pdf.compileTerminated, rateLimited: pdf.rateLimited, compileInProgress: pdf.compileInProgress, timedout: pdf.timedout, projectTooLarge: pdf.projectTooLarge, autoCompileDisabled: pdf.autoCompileDisabled, failure: pdf.failure } }` on-clear-cache="clearCache" on-recompile="recompile" on-recompile-from-scratch="recompileFromScratch" on-run-syntax-check-now="runSyntaxCheckNow" on-set-auto-compile="setAutoCompile" on-set-draft-mode="setDraftMode" on-set-syntax-check="setSyntaxCheck" on-toggle-logs="toggleLogs" output-files="pdf.outputFiles" pdf-download-url="pdf.downloadUrl" split-layout="ui.pdfLayout === 'sideBySide'" on-set-split-layout="setPdfSplitLayout" on-set-full-layout="setPdfFullLayout" on-stop-compilation="stop" variant-with-first-error-popup="logsUISubvariant === 'new-logs-ui-with-popup'" show-logs="shouldShowLogs" on-log-entry-location-click="openInEditor" ) else .toolbar.toolbar-pdf(ng-class="{ 'changes-to-autocompile': changesToAutoCompile && !autoCompileLintingError }") .btn-group.btn-recompile-group#recompile( dropdown, tooltip-html="'"+translate('recompile_pdf')+" <span class=\"keyboard-shortcut\">({{modifierKey}} + Enter)</span>'" tooltip-class="keyboard-tooltip" tooltip-popup-delay="500" tooltip-append-to-body="true" tooltip-placement="bottom" ) a.btn.btn-recompile( href, ng-disabled="pdf.compiling", ng-click="recompile()" ) i.fa.fa-refresh( ng-class="{'fa-spin': pdf.compiling }" ) span.btn-recompile-label(ng-show="!pdf.compiling") #{translate("recompile")} span.btn-recompile-label(ng-show="pdf.compiling") #{translate("compiling")}… a.btn.btn-recompile.dropdown-toggle( href, ng-disabled="pdf.compiling", dropdown-toggle ) span.caret ul.dropdown-menu.dropdown-menu-left li.dropdown-header #{translate("auto_compile")} li a(href, ng-click="autocompile_enabled = true") i.fa.fa-fw(ng-class="{'fa-check': autocompile_enabled}") | &nbsp;#{translate('on')} li a(href, ng-click="autocompile_enabled = false") i.fa.fa-fw(ng-class="{'fa-check': !autocompile_enabled}") | &nbsp;#{translate('off')} li.dropdown-header #{translate("compile_mode")} li a(href, ng-click="draft = false") i.fa.fa-fw(ng-class="{'fa-check': !draft}") | &nbsp;#{translate("normal")} li a(href, ng-click="draft = true") i.fa.fa-fw(ng-class="{'fa-check': draft}") | &nbsp;#{translate("fast")}&nbsp; span.subdued [draft] li.dropdown-header #{translate("compile_time_checks")} li a(href, ng-click="stop_on_validation_error = true") i.fa.fa-fw(ng-class="{'fa-check': stop_on_validation_error}") | &nbsp;#{translate("stop_on_validation_error")} li a(href, ng-click="stop_on_validation_error = false") i.fa.fa-fw(ng-class="{'fa-check': !stop_on_validation_error}") | &nbsp;#{translate("ignore_validation_errors")} li a(href, ng-click="recompile({check:true})") i.fa.fa-fw() | &nbsp;#{translate("run_syntax_check_now")} a( href ng-click="stop()" ng-show="pdf.compiling", tooltip=translate('stop_compile') tooltip-placement="bottom" ) i.fa.fa-fw.fa-stop() a.log-btn( href ng-click="toggleLogs()" ng-class="{ 'active': shouldShowLogs == true }" tooltip=translate('logs_and_output_files') tooltip-placement="bottom" ) i.fa.fa-fw.fa-file-text-o span.label( ng-show="pdf.logEntries.warnings.length + pdf.logEntries.errors.length > 0" ng-class="{\ 'label-warning': pdf.logEntries.errors.length == 0,\ 'label-danger': pdf.logEntries.errors.length > 0\ }" ) {{ pdf.logEntries.errors.length + pdf.logEntries.warnings.length }} a( ng-if="!pdf.downloadUrl" disabled href="#" tooltip=translate('please_compile_pdf_before_download') tooltip-placement="bottom" ) i.fa.fa-fw.fa-download a( ng-href="{{pdf.downloadUrl || pdf.url}}" target="_blank" ng-if="pdf.url" tooltip=translate('download_pdf') tooltip-placement="bottom" ) i.fa.fa-fw.fa-download .toolbar-right span.auto-compile-status.small( ng-show="changesToAutoCompile && !compiling && !autoCompileLintingError" ) #{translate('uncompiled_changes')} span.auto-compile-status.auto-compile-error.small( ng-show="autoCompileLintingError" tooltip-placement="bottom" tooltip=translate("code_check_failed_explanation") tooltip-append-to-body="true" ) i.fa.fa-fw.fa-exclamation-triangle | | #{translate("code_check_failed")} a( href, ng-click="switchToFlatLayout('pdf')" ng-show="ui.pdfLayout == 'sideBySide'" tooltip=translate('full_screen') tooltip-placement="bottom" tooltip-append-to-body="true" ) i.fa.fa-expand a( href, ng-click="switchToSideBySideLayout('editor')" ng-show="ui.pdfLayout == 'flat'" tooltip=translate('split_screen') tooltip-placement="bottom" tooltip-append-to-body="true" ) i.fa.fa-compress // end of toolbar // logs view .pdf-logs(ng-show="shouldShowLogs") .alert.alert-success(ng-show="pdf.logEntries.all.length == 0 && !pdf.failure") | #{translate("no_errors_good_job")} .alert.alert-danger(ng-show="pdf.failure") strong #{translate("compile_error")}. span #{translate("generic_failed_compile_message")}. .alert.alert-danger(ng-show="pdf.failedCheck") strong #{translate("failed_compile_check")}. p p.text-center(ng-show="!check") a.text-info( href, ng-disabled="pdf.compiling", ng-click="recompile({try:true})" ) #{translate("failed_compile_check_try")} | &#32;#{translate("failed_compile_option_or")}&#32; a.text-info( href, ng-disabled="pdf.compiling", ng-click="recompile({force:true})" ) #{translate("failed_compile_check_ignore")} | . div(ng-repeat="entry in pdf.logEntries.all") .alert( ng-class="{\ 'alert-danger': entry.level == 'error',\ 'alert-warning': entry.level == 'warning',\ 'alert-info': entry.level == 'typesetting'\ }" ng-click="openInEditor(entry)" ) span.line-no i.fa.fa-link(aria-hidden="true") | &nbsp; span(ng-show="entry.file") {{ entry.file }} span(ng-show="entry.line") , line {{ entry.line }} p.entry-message(ng-show="entry.message") | {{ entry.type }} {{ entry.message }} .card.card-hint( ng-if="entry.humanReadableHint" stop-propagation="click" ) figure.card-hint-icon-container i.fa.fa-lightbulb-o(aria-hidden="true") p.card-hint-text( ng-show="entry.humanReadableHint", ng-bind-html="entry.humanReadableHint") .card-hint-footer.clearfix .card-hint-ext-link(ng-if="entry.extraInfoURL") a( ng-href="{{ entry.extraInfoURL }}", ng-click="trackLogHintsLearnMore()" target="_blank" ) i.fa.fa-external-link |&nbsp;#{translate("log_hint_extra_info")} p.entry-content(ng-show="entry.content") {{ entry.content.trim() }} div .files-dropdown-container a.btn.btn-default.btn-sm( href, tooltip=translate('clear_cached_files'), tooltip-placement="top", tooltip-append-to-body="true", ng-click="openClearCacheModal()" ) i.fa.fa-trash-o | &nbsp; div.files-dropdown( ng-class="shouldDropUp ? 'dropup' : 'dropdown'" dropdown ) a.btn.btn-default.btn-sm( href dropdown-toggle ) | #{translate("other_logs_and_files")} span.caret ul.dropdown-menu.dropdown-menu-right li(ng-repeat="file in pdf.outputFiles") a( ng-href="{{file.url}}" target="_blank" ) {{ file.name }} a.btn.btn-info.btn-sm(href, ng-click="toggleRawLog()") span(ng-show="!pdf.showRawLog") #{translate("view_raw_logs")} span(ng-show="pdf.showRawLog") #{translate("hide_raw_logs")} pre(ng-bind="pdf.rawLog", ng-show="pdf.showRawLog") // non-log views (pdf and errors) div(ng-show="!shouldShowLogs", ng-switch on="pdf.view") .pdf-uncompiled(ng-switch-when="uncompiled" ng-show="!pdf.compiling") | &nbsp; i.fa.fa-level-up.fa-flip-horizontal.fa-2x | &nbsp;&nbsp;#{translate('click_here_to_preview_pdf')} .pdf-viewer(ng-switch-when="pdf") div( pdfng ng-if="settings.pdfViewer == 'pdfjs'" pdf-src="pdf.url" key="{{ project_id }}" resize-on="layout:main:resize,layout:pdf:resize" highlights="pdf.highlights" position="pdf.position" first-render-done="pdf.firstRenderDone" update-consumed-bandwidth="pdf.updateConsumedBandwidth" dbl-click-callback="syncToCode" ) iframe( ng-src="{{ pdf.url | trusted }}" ng-if="settings.pdfViewer == 'native'" ) if !showNewLogsUI .pdf-validation-problems(ng-switch-when="validation-problems") .alert.alert-danger(ng-show="pdf.validation.sizeCheck") strong #{translate("project_too_large")} div #{translate("project_too_large_please_reduce")} div li(ng-repeat="entry in pdf.validation.sizeCheck.resources") {{ '/'+entry['path'] }} - {{entry['kbSize']}}kb .alert.alert-danger(ng-show="pdf.validation.conflictedPaths") div strong #{translate("conflicting_paths_found")} div !{translate("following_paths_conflict")} div li(ng-repeat="entry in pdf.validation.conflictedPaths") {{ '/'+entry['path'] }} .alert.alert-danger(ng-show="pdf.validation.mainFile") strong #{translate("main_file_not_found")} span #{translate("please_set_main_file")} .pdf-errors(ng-switch-when="errors") .alert.alert-danger(ng-show="pdf.error") strong #{translate("server_error")} span #{translate("somthing_went_wrong_compiling")} .alert.alert-danger(ng-show="pdf.renderingError") strong #{translate("pdf_rendering_error")} span #{translate("something_went_wrong_rendering_pdf")} .alert.alert-danger(ng-show="pdf.clsiMaintenance") strong #{translate("server_error")} span #{translate("clsi_maintenance")} .alert.alert-danger(ng-show="pdf.clsiUnavailable") strong #{translate("server_error")} span #{translate("clsi_unavailable")} .alert.alert-danger(ng-show="pdf.tooRecentlyCompiled") strong #{translate("server_error")} span #{translate("too_recently_compiled")} .alert.alert-danger(ng-show="pdf.compileTerminated") strong #{translate("terminated")}. span #{translate("compile_terminated_by_user")} .alert.alert-danger(ng-show="pdf.rateLimited") strong #{translate("pdf_compile_rate_limit_hit")} span #{translate("project_flagged_too_many_compiles")} .alert.alert-danger(ng-show="pdf.compileInProgress") strong #{translate("pdf_compile_in_progress_error")}. span #{translate("pdf_compile_try_again")} .alert.alert-danger(ng-show="pdf.timedout") p strong #{translate("timedout")}. span #{translate("proj_timed_out_reason")} p a.text-info(href="https://www.sharelatex.com/learn/Debugging_Compilation_timeout_errors", target="_blank") | #{translate("learn_how_to_make_documents_compile_quickly")} if settings.enableSubscriptions .alert.alert-success(ng-show="pdf.timedout && !hasPremiumCompile") p(ng-if="project.owner._id == user.id") strong #{translate("upgrade_for_longer_compiles")} p(ng-if="project.owner._id != user.id") strong #{translate("ask_proj_owner_to_upgrade_for_longer_compiles")} p #{translate("free_accounts_have_timeout_upgrade_to_increase")} p #{translate("plus_upgraded_accounts_receive")}: div ul.list-unstyled li i.fa.fa-check &nbsp; | #{translate("unlimited_projects")} li i.fa.fa-check &nbsp; | #{translate("collabs_per_proj", {collabcount:'Multiple'})} li i.fa.fa-check &nbsp; | #{translate("full_doc_history")} li i.fa.fa-check &nbsp; | #{translate("sync_to_dropbox")} li i.fa.fa-check &nbsp; | #{translate("sync_to_github")} li i.fa.fa-check &nbsp; |#{translate("compile_larger_projects")} p(ng-controller="FreeTrialModalController", ng-if="project.owner._id == user.id") a.btn.btn-success.row-spaced-small( href ng-class="buttonClass" ng-click="startFreeTrial('compile-timeout')" ) #{translate("start_free_trial")} .alert.alert-danger(ng-show="pdf.autoCompileDisabled") p strong #{translate("autocompile_disabled")}. span #{translate("autocompile_disabled_reason")} .alert.alert-danger(ng-show="pdf.projectTooLarge") strong #{translate("project_too_large")} span #{translate("project_too_much_editable_text")} script(type='text/ng-template', id='clearCacheModalTemplate') .modal-header h3 #{translate("clear_cache")}? .modal-body p #{translate("clear_cache_explanation")} p #{translate("clear_cache_is_safe")} .alert.alert-danger(ng-if="state.error") #{translate("generic_something_went_wrong")}. .modal-footer button.btn.btn-default( ng-click="cancel()" ng-disabled="state.inflight" ) #{translate("cancel")} button.btn.btn-info( ng-click="clear()" ng-disabled="state.inflight" ) span(ng-show="!state.inflight") #{translate("clear_cache")} span(ng-show="state.inflight") #{translate("clearing")}…
overleaf/web/app/views/project/editor/pdf.pug/0
{ "file_path": "overleaf/web/app/views/project/editor/pdf.pug", "repo_id": "overleaf", "token_count": 6927 }
513
script(type="text/ng-template", id="groupPlanModalPurchaseTemplate") .modal-header h3 Save 30% or more with a group license .modal-body.plans .container-fluid .row .col-md-6.text-center .circle.circle-lg | {{ displayPrice }} span.small / year br span.circle-subtext For {{ selected.size }} users ul.list-unstyled li Each user will have access to: li &nbsp; li(ng-if="selected.plan_code == 'collaborator'") strong #{translate("collabs_per_proj", {collabcount:10})} li(ng-if="selected.plan_code == 'professional'") strong #{translate("unlimited_collabs")} +features_premium .col-md-6 form.form .form-group label(for='plan_code') | Plan select.form-control(id="plan_code", ng-model="selected.plan_code") option(ng-repeat="plan_code in options.plan_codes", value="{{plan_code.code}}") {{ plan_code.display }} .form-group label(for='size') | Number of users select.form-control(id="size", ng-model="selected.size") option(ng-repeat="size in options.sizes", value="{{size}}") {{ size }} .form-group label(for='currency') | Currency select.form-control(id="currency", ng-model="selected.currency") option(ng-repeat="currency in options.currencies", value="{{currency.code}}") {{ currency.display }} .form-group label(for='usage') | Usage select.form-control(id="usage", ng-model="selected.usage") option(ng-repeat="usage in options.usages", value="{{usage.code}}") {{ usage.display }} p.small.text-center.row-spaced-small(ng-show="selected.usage == 'educational'") | The 40% educational discount can be used by students or faculty using Overleaf for teaching p.small.text-center.row-spaced-small(ng-show="selected.usage == 'enterprise'") | Save an additional 40% on groups of 10 or more with our educational discount .modal-footer .text-center button.btn.btn-primary.btn-lg(ng-click="purchase()") Purchase Now hr.thin a( href ng-controller="ContactGeneralModal" ng-click="openModal()" ) Need more than 50 licenses? Please get in touch
overleaf/web/app/views/subscriptions/_modal_group_purchase.pug/0
{ "file_path": "overleaf/web/app/views/subscriptions/_modal_group_purchase.pug", "repo_id": "overleaf", "token_count": 943 }
514
div(ng-controller="RecurlySubscriptionController") div(ng-show="!showCancellation") if (personalSubscription.recurly.account.has_past_due_invoice && personalSubscription.recurly.account.has_past_due_invoice._ == 'true') .alert.alert-danger #{translate("account_has_past_due_invoice_change_plan_warning")} | &nbsp; a(href=personalSubscription.recurly.accountManagementLink, target="_blank") #{translate("view_your_invoices")}. case personalSubscription.recurly.state when "active" p !{translate("currently_subscribed_to_plan", {planName: personalSubscription.plan.name}, ['strong'])} if (personalSubscription.pendingPlan) if (personalSubscription.pendingPlan.name != personalSubscription.plan.name) | | !{translate("your_plan_is_changing_at_term_end", {pendingPlanName: personalSubscription.pendingPlan.name}, ['strong'])} if (personalSubscription.recurly.pendingAdditionalLicenses > 0 || personalSubscription.recurly.additionalLicenses > 0) | | !{translate("pending_additional_licenses", {pendingAdditionalLicenses: personalSubscription.recurly.pendingAdditionalLicenses, pendingTotalLicenses: personalSubscription.recurly.pendingTotalLicenses}, ['strong', 'strong'])} else if (personalSubscription.recurly.additionalLicenses > 0) | | !{translate("additional_licenses", {additionalLicenses: personalSubscription.recurly.additionalLicenses, totalLicenses: personalSubscription.recurly.totalLicenses}, ['strong', 'strong'])} | &nbsp; a(href, ng-click="switchToChangePlanView()", ng-if="showChangePlanButton") !{translate("change_plan")}. if (personalSubscription.pendingPlan) p #{translate("want_change_to_apply_before_plan_end")} if (personalSubscription.recurly.trialEndsAtFormatted && personalSubscription.recurly.trial_ends_at > Date.now()) p You're on a free trial which ends on <strong ng-non-bindable>#{personalSubscription.recurly.trialEndsAtFormatted}</strong> p !{translate("next_payment_of_x_collectected_on_y", {paymentAmmount: personalSubscription.recurly.price, collectionDate: personalSubscription.recurly.nextPaymentDueAt}, ['strong', 'strong'])} include ./../_price_exceptions p.pull-right p a(href=personalSubscription.recurly.billingDetailsLink, target="_blank").btn.btn-info #{translate("update_your_billing_details")} | &nbsp; a(href=personalSubscription.recurly.accountManagementLink, target="_blank").btn.btn-info #{translate("view_your_invoices")} | &nbsp; a(href, ng-click="switchToCancellationView()", ng-hide="recurlyLoadError").btn.btn-danger !{translate("cancel_your_subscription")} when "canceled" p !{translate("currently_subscribed_to_plan", {planName: personalSubscription.plan.name}, ['strong'])} p !{translate("subscription_canceled_and_terminate_on_x", {terminateDate: personalSubscription.recurly.nextPaymentDueAt}, ['strong'])} p a(href=personalSubscription.recurly.accountManagementLink, target="_blank").btn.btn-info #{translate("view_your_invoices")} p: form(action="/user/subscription/reactivate",method="post") input(type="hidden", name="_csrf", value=csrfToken) input(type="submit",value="Reactivate your subscription").btn.btn-success when "expired" p !{translate("your_subscription_has_expired")} p a(href=personalSubscription.recurly.accountManagementLink, target="_blank").btn.btn-info #{translate("view_your_invoices")} | &nbsp; a(href="/user/subscription/plans").btn.btn-success !{translate("create_new_subscription")} default p !{translate("problem_with_subscription_contact_us")} .alert.alert-warning(ng-show="recurlyLoadError") strong #{translate('payment_provider_unreachable_error')} include ./_change_plans_mixins div(ng-show="showChangePlan", ng-cloak) h2 !{translate("change_plan")} p: table.table tr th !{translate("name")} th !{translate("price")} th +printPlans(plans.studentAccounts) +printPlans(plans.individualMonthlyPlans) +printPlans(plans.individualAnnualPlans) .div(ng-controller="RecurlyCancellationController", ng-show="showCancellation").text-center p strong #{translate("wed_love_you_to_stay")} div(ng-show="showExtendFreeTrial") p !{translate("have_more_days_to_try", {days:14})} p button(type="submit", ng-click="extendTrial()", ng-disabled='inflight').btn.btn-success #{translate("ill_take_it")} p a(href, ng-click="cancelSubscription()", ng-disabled='inflight') #{translate("no_thanks_cancel_now")} div(ng-show="showDowngradeToStudent") div(ng-controller="ChangePlanFormController") p !{translate("interested_in_cheaper_plan",{price:'{{studentPrice}}'})} p button(type="submit", ng-click="downgradeToStudent()", ng-disabled='inflight').btn.btn-success #{translate("yes_move_me_to_student_plan")} p a(href, ng-click="cancelSubscription()", ng-disabled='inflight') #{translate("no_thanks_cancel_now")} div(ng-show="showBasicCancel") p a(href, ng-click="switchToDefaultView()").btn.btn-info #{translate("i_want_to_stay")} p a(href, ng-click="cancelSubscription()", ng-disabled='inflight').btn.btn-primary #{translate("cancel_my_account")} script(type='text/ng-template', id='confirmChangePlanModalTemplate') .modal-header h3 #{translate("change_plan")} .modal-body .alert.alert-warning(ng-show="genericError") strong #{translate("generic_something_went_wrong")}. #{translate("try_again")}. #{translate("generic_if_problem_continues_contact_us")}. p !{translate("sure_you_want_to_change_plan", {planName: '{{plan.name}}'}, ['strong'])} div(ng-show="planChangesAtTermEnd") p #{translate("existing_plan_active_until_term_end")} p #{translate("want_change_to_apply_before_plan_end")} .modal-footer button.btn.btn-default( ng-disabled="inflight" ng-click="cancel()" ) #{translate("cancel")} button.btn.btn-success( ng-disabled="state.inflight" ng-click="confirmChangePlan()" ) span(ng-hide="inflight") #{translate("change_plan")} span(ng-show="inflight") #{translate("processing")}… script(type='text/ng-template', id='cancelPendingPlanChangeModalTemplate') .modal-header h3 #{translate("change_plan")} .modal-body .alert.alert-warning(ng-show="genericError") strong #{translate("generic_something_went_wrong")}. #{translate("try_again")}. #{translate("generic_if_problem_continues_contact_us")}. p !{translate("sure_you_want_to_cancel_plan_change", {planName: '{{plan.name}}'}, ['strong'])} .modal-footer button.btn.btn-default( ng-disabled="inflight" ng-click="cancel()" ) #{translate("cancel")} button.btn.btn-success( ng-disabled="state.inflight" ng-click="confirmCancelPendingPlanChange()" ) span(ng-hide="inflight") #{translate("revert_pending_plan_change")} span(ng-show="inflight") #{translate("processing")}…
overleaf/web/app/views/subscriptions/dashboard/_personal_subscription_recurly.pug/0
{ "file_path": "overleaf/web/app/views/subscriptions/dashboard/_personal_subscription_recurly.pug", "repo_id": "overleaf", "token_count": 2679 }
515
extends ../layout block vars - metadata = { viewport: true } block content - var showCaptcha = settings.recaptcha && settings.recaptcha.siteKey && !(settings.recaptcha.disabled && settings.recaptcha.disabled.passwordReset) if showCaptcha script(type="text/javascript", nonce=scriptNonce, src="https://www.recaptcha.net/recaptcha/api.js?render=explicit") div( id="recaptcha" class="g-recaptcha" data-sitekey=settings.recaptcha.siteKey data-size="invisible" data-badge="inline" ) main.content.content-alt#main-content .container .row .col-md-6.col-md-offset-3.col-lg-4.col-lg-offset-4 .card .page-header h1 #{translate("password_reset")} .messageArea form( async-form="password-reset-request", name="passwordResetForm" action="/user/password/reset", method="POST", captcha=(showCaptcha ? '' : false), captcha-action-name=(showCaptcha ? "passwordReset" : false), ng-cloak ) input(type="hidden", name="_csrf", value=csrfToken) form-messages(for="passwordResetForm" role="alert") .form-group label(for='email') #{translate("please_enter_email")} input.form-control#email( type='email', name='email', placeholder='email@example.com', required, autocomplete="username", ng-model="email", autofocus ) span.small.text-primary( ng-show="passwordResetForm.email.$invalid && passwordResetForm.email.$dirty" ) #{translate("must_be_email_address")} .actions button.btn.btn-primary( type='submit', ng-disabled="passwordResetForm.$invalid || passwordResetForm.inflight" ) span(ng-hide="passwordResetForm.inflight") #{translate("request_password_reset")} span(ng-show="passwordResetForm.inflight") #{translate("requesting_password_reset")}…
overleaf/web/app/views/user/passwordReset.pug/0
{ "file_path": "overleaf/web/app/views/user/passwordReset.pug", "repo_id": "overleaf", "token_count": 884 }
516
#!/bin/sh set -e TEMPLATES_EXTENDING_META_BLOCK=$(\ grep \ --files-with-matches \ --recursive app/views modules/*/app/views \ --regex 'block append meta' \ --regex 'block prepend meta' \ --regex 'append meta' \ --regex 'prepend meta' \ ) for file in ${TEMPLATES_EXTENDING_META_BLOCK}; do if ! grep "$file" --quiet --extended-regexp -e 'extends .+layout'; then cat <<MSG >&2 ERROR: $file is a partial template and extends 'block meta'. Using block append/prepend in a partial will duplicate the block contents into the <body> due to a bug in pug. Putting meta tags in the <body> can lead to Angular XSS. You will need to refactor the partial and move the block into the top level page template that extends the global layout.pug. MSG exit 1 fi done
overleaf/web/bin/lint_pug_templates/0
{ "file_path": "overleaf/web/bin/lint_pug_templates", "repo_id": "overleaf", "token_count": 291 }
517
@font-face { font-family: 'Source Code Pro'; font-style: normal; font-weight: 400; src: local('Source Code Pro Regular'), local('SourceCodePro-Regular'), url('source-code-pro-v13-latin-regular.woff2') format('woff2'), url('source-code-pro-v13-latin-regular.woff') format('woff'); }
overleaf/web/frontend/fonts/source-code-pro.css/0
{ "file_path": "overleaf/web/frontend/fonts/source-code-pro.css", "repo_id": "overleaf", "token_count": 112 }
518
/* 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' export default App.directive('updateScrollBottomOn', $timeout => ({ restrict: 'A', link(scope, element, attrs, ctrls) { // We keep the offset from the bottom fixed whenever the event fires // // ^ | ^ // | | | scrollTop // | | v // | |----------- // | | ^ // | | | // | | | clientHeight (viewable area) // | | | // | | | // | | v // | |----------- // | | ^ // | | | scrollBottom // v | v // \ // scrollHeight let scrollBottom = 0 element.on( 'scroll', e => (scrollBottom = element[0].scrollHeight - element[0].scrollTop - element[0].clientHeight) ) return scope.$on(attrs.updateScrollBottomOn, () => $timeout( () => element.scrollTop( element[0].scrollHeight - element[0].clientHeight - scrollBottom ), 0 ) ) }, }))
overleaf/web/frontend/js/directives/scroll.js/0
{ "file_path": "overleaf/web/frontend/js/directives/scroll.js", "repo_id": "overleaf", "token_count": 570 }
519
import App from '../../../base' import { react2angular } from 'react2angular' import CloneProjectModal from '../components/clone-project-modal' App.component('cloneProjectModal', react2angular(CloneProjectModal)) export default App.controller( 'LeftMenuCloneProjectModalController', function ($scope, ide) { $scope.show = false $scope.projectId = ide.$scope.project_id $scope.handleHide = () => { $scope.$applyAsync(() => { $scope.show = false }) } $scope.openProject = projectId => { window.location.assign(`/project/${projectId}`) } $scope.openCloneProjectModal = () => { $scope.$applyAsync(() => { const { project } = ide.$scope if (project) { $scope.projectId = project._id $scope.projectName = project.name $scope.show = true } }) } } )
overleaf/web/frontend/js/features/clone-project-modal/controllers/left-menu-clone-project-modal-controller.js/0
{ "file_path": "overleaf/web/frontend/js/features/clone-project-modal/controllers/left-menu-clone-project-modal-controller.js", "repo_id": "overleaf", "token_count": 357 }
520
import PropTypes from 'prop-types' import { FileTreeMainProvider } from '../contexts/file-tree-main' import { FileTreeActionableProvider } from '../contexts/file-tree-actionable' import { FileTreeMutableProvider } from '../contexts/file-tree-mutable' import { FileTreeSelectableProvider } from '../contexts/file-tree-selectable' import { FileTreeDraggableProvider } from '../contexts/file-tree-draggable' // renders all the contexts needed for the file tree: // FileTreeMain: generic store // FileTreeActionable: global UI state for actions (rename, delete, etc.) // FileTreeMutable: provides entities mutation operations // FileTreeSelectable: handles selection and multi-selection function FileTreeContext({ projectId, rootFolder, hasWritePermissions, rootDocId, userHasFeature, refProviders, reindexReferences, setRefProviderEnabled, setStartedFreeTrial, onSelect, children, }) { return ( <FileTreeMainProvider projectId={projectId} hasWritePermissions={hasWritePermissions} userHasFeature={userHasFeature} refProviders={refProviders} setRefProviderEnabled={setRefProviderEnabled} setStartedFreeTrial={setStartedFreeTrial} reindexReferences={reindexReferences} > <FileTreeMutableProvider rootFolder={rootFolder}> <FileTreeSelectableProvider hasWritePermissions={hasWritePermissions} rootDocId={rootDocId} onSelect={onSelect} > <FileTreeActionableProvider hasWritePermissions={hasWritePermissions}> <FileTreeDraggableProvider>{children}</FileTreeDraggableProvider> </FileTreeActionableProvider> </FileTreeSelectableProvider> </FileTreeMutableProvider> </FileTreeMainProvider> ) } FileTreeContext.propTypes = { projectId: PropTypes.string.isRequired, rootFolder: PropTypes.array.isRequired, hasWritePermissions: PropTypes.bool.isRequired, userHasFeature: PropTypes.func.isRequired, reindexReferences: PropTypes.func.isRequired, refProviders: PropTypes.object.isRequired, setRefProviderEnabled: PropTypes.func.isRequired, setStartedFreeTrial: PropTypes.func.isRequired, rootDocId: PropTypes.string, onSelect: PropTypes.func.isRequired, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, } export default FileTreeContext
overleaf/web/frontend/js/features/file-tree/components/file-tree-context.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-context.js", "repo_id": "overleaf", "token_count": 799 }
521
import { useEffect } from 'react' import PropTypes from 'prop-types' import { useTranslation } from 'react-i18next' import classNames from 'classnames' import Icon from '../../../shared/components/icon' import { useFileTreeSelectable, useSelectableEntity, } from '../contexts/file-tree-selectable' import { useDroppable } from '../contexts/file-tree-draggable' import FileTreeItemInner from './file-tree-item/file-tree-item-inner' import FileTreeFolderList from './file-tree-folder-list' import usePersistedState from '../../../shared/hooks/use-persisted-state' function FileTreeFolder({ name, id, folders, docs, files }) { const { t } = useTranslation() const { isSelected, props: selectableEntityProps } = useSelectableEntity(id) const { selectedEntityParentIds } = useFileTreeSelectable(id) const [expanded, setExpanded] = usePersistedState( `folder.${id}.expanded`, false ) useEffect(() => { if (selectedEntityParentIds.has(id)) { setExpanded(true) } }, [id, selectedEntityParentIds, setExpanded]) function handleExpandCollapseClick() { setExpanded(!expanded) } const { isOver: isOverRoot, dropRef: dropRefRoot } = useDroppable(id) const { isOver: isOverList, dropRef: dropRefList } = useDroppable(id) const icons = ( <> <button onClick={handleExpandCollapseClick} aria-label={expanded ? t('collapse') : t('expand')} > <Icon type={expanded ? 'angle-down' : 'angle-right'} modifier="fw" /> </button> <Icon type={expanded ? 'folder-open' : 'folder'} modifier="fw" /> </> ) return ( <> <li role="treeitem" {...selectableEntityProps} aria-expanded={expanded} aria-label={name} tabIndex="0" ref={dropRefRoot} className={classNames(selectableEntityProps.className, { 'dnd-droppable-hover': isOverRoot || isOverList, })} > <FileTreeItemInner id={id} name={name} isSelected={isSelected} icons={icons} /> </li> {expanded ? ( <FileTreeFolderList folders={folders} docs={docs} files={files} dropRef={dropRefList} /> ) : null} </> ) } FileTreeFolder.propTypes = { name: PropTypes.string.isRequired, id: PropTypes.string.isRequired, folders: PropTypes.array.isRequired, docs: PropTypes.array.isRequired, files: PropTypes.array.isRequired, } export default FileTreeFolder
overleaf/web/frontend/js/features/file-tree/components/file-tree-folder.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-folder.js", "repo_id": "overleaf", "token_count": 1035 }
522
import { createContext, useCallback, useReducer, useContext, useEffect, } from 'react' import PropTypes from 'prop-types' import { renameInTree, deleteInTree, moveInTree, createEntityInTree, } from '../util/mutate-in-tree' const FileTreeMutableContext = createContext() const ACTION_TYPES = { RENAME: 'RENAME', RESET: 'RESET', DELETE: 'DELETE', MOVE: 'MOVE', CREATE_ENTITY: 'CREATE_ENTITY', } function fileTreeMutableReducer({ fileTreeData }, action) { switch (action.type) { case ACTION_TYPES.RESET: { const newFileTreeData = action.fileTreeData return { fileTreeData: newFileTreeData, fileCount: countFiles(newFileTreeData), } } case ACTION_TYPES.RENAME: { const newFileTreeData = renameInTree(fileTreeData, action.id, { newName: action.newName, }) return { fileTreeData: newFileTreeData, fileCount: countFiles(newFileTreeData), } } case ACTION_TYPES.DELETE: { const newFileTreeData = deleteInTree(fileTreeData, action.id) return { fileTreeData: newFileTreeData, fileCount: countFiles(newFileTreeData), } } case ACTION_TYPES.MOVE: { const newFileTreeData = moveInTree( fileTreeData, action.entityId, action.toFolderId ) return { fileTreeData: newFileTreeData, fileCount: countFiles(newFileTreeData), } } case ACTION_TYPES.CREATE_ENTITY: { const newFileTreeData = createEntityInTree( fileTreeData, action.parentFolderId, action.entity ) return { fileTreeData: newFileTreeData, fileCount: countFiles(newFileTreeData), } } default: { throw new Error(`Unknown mutable file tree action type: ${action.type}`) } } } const initialState = rootFolder => ({ fileTreeData: rootFolder[0], fileCount: countFiles(rootFolder[0]), }) export const FileTreeMutableProvider = function ({ rootFolder, children }) { const [{ fileTreeData, fileCount }, dispatch] = useReducer( fileTreeMutableReducer, rootFolder, initialState ) useEffect(() => { dispatch({ type: ACTION_TYPES.RESET, fileTreeData: rootFolder[0], }) }, [rootFolder]) const dispatchCreateFolder = useCallback((parentFolderId, entity) => { entity.type = 'folder' dispatch({ type: ACTION_TYPES.CREATE_ENTITY, parentFolderId, entity, }) }, []) const dispatchCreateDoc = useCallback((parentFolderId, entity) => { entity.type = 'doc' dispatch({ type: ACTION_TYPES.CREATE_ENTITY, parentFolderId, entity, }) }, []) const dispatchCreateFile = useCallback((parentFolderId, entity) => { entity.type = 'fileRef' dispatch({ type: ACTION_TYPES.CREATE_ENTITY, parentFolderId, entity, }) }, []) const dispatchRename = useCallback((id, newName) => { dispatch({ type: ACTION_TYPES.RENAME, newName, id, }) }, []) const dispatchDelete = useCallback(id => { dispatch({ type: ACTION_TYPES.DELETE, id }) }, []) const dispatchMove = useCallback((entityId, toFolderId) => { dispatch({ type: ACTION_TYPES.MOVE, entityId, toFolderId }) }, []) const value = { dispatchCreateDoc, dispatchCreateFile, dispatchCreateFolder, dispatchDelete, dispatchMove, dispatchRename, fileCount, fileTreeData, } return ( <FileTreeMutableContext.Provider value={value}> {children} </FileTreeMutableContext.Provider> ) } FileTreeMutableProvider.propTypes = { rootFolder: PropTypes.array.isRequired, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, } export function useFileTreeMutable() { const context = useContext(FileTreeMutableContext) if (!context) { throw new Error( 'useFileTreeMutable is only available in FileTreeMutableProvider' ) } return context } function filesInFolder({ docs, folders, fileRefs }) { const files = [...docs, ...fileRefs] for (const folder of folders) { files.push(...filesInFolder(folder)) } return files } function countFiles(fileTreeData) { const files = filesInFolder(fileTreeData) // count all the non-deleted entities const value = files.filter(item => !item.deleted).length const limit = window.ExposedSettings.maxEntitiesPerProject const status = fileCountStatus(value, limit, Math.ceil(limit / 20)) return { value, status, limit } } function fileCountStatus(value, limit, range) { if (value >= limit) { return 'error' } if (value >= limit - range) { return 'warning' } return 'success' }
overleaf/web/frontend/js/features/file-tree/contexts/file-tree-mutable.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/contexts/file-tree-mutable.js", "repo_id": "overleaf", "token_count": 1861 }
523
import { useState, useCallback } from 'react' import PropTypes from 'prop-types' import { Trans, useTranslation } from 'react-i18next' import Icon from '../../../shared/components/icon' import { formatTime, relativeDate } from '../../utils/format-date' import { postJSON } from '../../../infrastructure/fetch-json' import { useProjectContext } from '../../../shared/context/project-context' import importOverleafModules from '../../../../macros/import-overleaf-module.macro' import useAbortController from '../../../shared/hooks/use-abort-controller' import BetaBadge from '../../../shared/components/beta-badge' const tprLinkedFileInfo = importOverleafModules('tprLinkedFileInfo') const tprLinkedFileRefreshError = importOverleafModules( 'tprLinkedFileRefreshError' ) const MAX_URL_LENGTH = 60 const FRONT_OF_URL_LENGTH = 35 const FILLER = '...' const TAIL_OF_URL_LENGTH = MAX_URL_LENGTH - FRONT_OF_URL_LENGTH - FILLER.length function shortenedUrl(url) { if (!url) { return } if (url.length > MAX_URL_LENGTH) { const front = url.slice(0, FRONT_OF_URL_LENGTH) const tail = url.slice(url.length - TAIL_OF_URL_LENGTH) return front + FILLER + tail } return url } export default function FileViewHeader({ file, storeReferencesKeys }) { const { _id: projectId } = useProjectContext({ _id: PropTypes.string.isRequired, }) const { t } = useTranslation() const [refreshing, setRefreshing] = useState(false) const [refreshError, setRefreshError] = useState(null) const { signal } = useAbortController() let fileInfo if (file.linkedFileData) { if (file.linkedFileData.provider === 'url') { fileInfo = ( <div> <UrlProvider file={file} /> </div> ) } else if (file.linkedFileData.provider === 'project_file') { fileInfo = ( <div> <ProjectFilePathProvider file={file} /> </div> ) } else if (file.linkedFileData.provider === 'project_output_file') { fileInfo = ( <div> <ProjectOutputFileProvider file={file} /> </div> ) } } const refreshFile = useCallback(() => { setRefreshing(true) // Replacement of the file handled by the file tree window.expectingLinkedFileRefreshedSocketFor = file.name postJSON(`/project/${projectId}/linked_file/${file.id}/refresh`, { signal }) .then(() => { setRefreshing(false) }) .catch(err => { setRefreshing(false) setRefreshError(err.data?.message || err.message) }) .finally(() => { if ( file.linkedFileData.provider === 'mendeley' || file.linkedFileData.provider === 'zotero' || file.name.match(/^.*\.bib$/) ) { reindexReferences() } }) function reindexReferences() { const opts = { body: { shouldBroadcast: true }, } postJSON(`/project/${projectId}/references/indexAll`, opts) .then(response => { // Later updated by the socket but also updated here for immediate use storeReferencesKeys(response.keys) }) .catch(error => { console.log(error) }) } }, [file, projectId, signal, storeReferencesKeys]) return ( <div> <BetaBadge tooltip={{ id: 'file-view-beta-tooltip', text: t('beta_badge_tooltip', { feature: 'file views' }), }} /> {file.linkedFileData && fileInfo} {file.linkedFileData && tprLinkedFileInfo.map(({ import: { LinkedFileInfo }, path }) => ( <LinkedFileInfo key={path} file={file} /> ))} {file.linkedFileData && ( <button className="btn btn-success" onClick={refreshFile} disabled={refreshing} > <Icon type="refresh" spin={refreshing} modifier="fw" /> <span>{refreshing ? t('refreshing') + '...' : t('refresh')}</span> </button> )} &nbsp; <a href={`/project/${projectId}/file/${file.id}`} className="btn btn-info" > <Icon type="download" modifier="fw" /> &nbsp; <span>{t('download')}</span> </a> {refreshError && ( <div className="row"> <br /> <div className="alert alert-danger col-md-6 col-md-offset-3"> {t('error')}: {refreshError} {tprLinkedFileRefreshError.map( ({ import: { LinkedFileRefreshError }, path }) => ( <LinkedFileRefreshError key={path} file={file} /> ) )} </div> </div> )} </div> ) } FileViewHeader.propTypes = { file: PropTypes.shape({ id: PropTypes.string, name: PropTypes.string, linkedFileData: PropTypes.object, }).isRequired, storeReferencesKeys: PropTypes.func.isRequired, } function UrlProvider({ file }) { return ( <p> <Icon type="external-link-square" modifier="rotate-180" classes={{ icon: 'linked-file-icon' }} /> &nbsp; <Trans i18nKey="imported_from_external_provider_at_date" components={ /* eslint-disable-next-line jsx-a11y/anchor-has-content, react/jsx-key */ [<a href={file.linkedFileData.url} />] } values={{ shortenedUrl: shortenedUrl(file.linkedFileData.url), formattedDate: formatTime(file.created), relativeDate: relativeDate(file.created), }} /> </p> ) } UrlProvider.propTypes = { file: PropTypes.shape({ linkedFileData: PropTypes.object, created: PropTypes.string, }).isRequired, } function ProjectFilePathProvider({ file }) { /* eslint-disable jsx-a11y/anchor-has-content, react/jsx-key */ return ( <p> <Icon type="external-link-square" modifier="rotate-180" classes={{ icon: 'linked-file-icon' }} /> &nbsp; <Trans i18nKey="imported_from_another_project_at_date" components={ file.linkedFileData.v1_source_doc_id ? [<span />] : [ <a href={`/project/${file.linkedFileData.source_project_id}`} target="_blank" />, ] } values={{ sourceEntityPath: file.linkedFileData.source_entity_path.slice(1), formattedDate: formatTime(file.created), relativeDate: relativeDate(file.created), }} /> </p> /* esline-enable jsx-a11y/anchor-has-content, react/jsx-key */ ) } ProjectFilePathProvider.propTypes = { file: PropTypes.shape({ linkedFileData: PropTypes.object, created: PropTypes.string, }).isRequired, } function ProjectOutputFileProvider({ file }) { return ( <p> <Icon type="external-link-square" modifier="rotate-180" classes={{ icon: 'linked-file-icon' }} /> &nbsp; <Trans i18nKey="imported_from_the_output_of_another_project_at_date" components={ file.linkedFileData.v1_source_doc_id ? [<span />] : [ <a href={`/project/${file.linkedFileData.source_project_id}`} target="_blank" />, ] } values={{ sourceOutputFilePath: file.linkedFileData.source_output_file_path, formattedDate: formatTime(file.created), relativeDate: relativeDate(file.created), }} /> </p> ) } ProjectOutputFileProvider.propTypes = { file: PropTypes.shape({ linkedFileData: PropTypes.object, created: PropTypes.string, }).isRequired, }
overleaf/web/frontend/js/features/file-view/components/file-view-header.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-view/components/file-view-header.js", "repo_id": "overleaf", "token_count": 3526 }
524
import PropTypes from 'prop-types' import { useTranslation, Trans } from 'react-i18next' import PreviewLogsPaneEntry from './preview-logs-pane-entry' import Icon from '../../../shared/components/icon' import { useEditorContext } from '../../../shared/context/editor-context' import StartFreeTrialButton from '../../../shared/components/start-free-trial-button' function PreviewError({ name }) { const { hasPremiumCompile, isProjectOwner } = useEditorContext({ isProjectOwner: PropTypes.bool, }) const { t } = useTranslation() let errorTitle let errorContent if (name === 'error') { errorTitle = t('server_error') errorContent = <>{t('somthing_went_wrong_compiling')}</> } else if (name === 'renderingError') { errorTitle = t('pdf_rendering_error') errorContent = <>{t('something_went_wrong_rendering_pdf')}</> } else if (name === 'clsiMaintenance') { errorTitle = t('server_error') errorContent = <>{t('clsi_maintenance')}</> } else if (name === 'clsiUnavailable') { errorTitle = t('server_error') errorContent = <>{t('clsi_unavailable')}</> } else if (name === 'tooRecentlyCompiled') { errorTitle = t('server_error') errorContent = <>{t('too_recently_compiled')}</> } else if (name === 'compileTerminated') { errorTitle = t('terminated') errorContent = <>{t('compile_terminated_by_user')}</> } else if (name === 'rateLimited') { errorTitle = t('pdf_compile_rate_limit_hit') errorContent = <>{t('project_flagged_too_many_compiles')}</> } else if (name === 'compileInProgress') { errorTitle = t('pdf_compile_in_progress_error') errorContent = <>{t('pdf_compile_try_again')}</> } else if (name === 'timedout') { errorTitle = t('timedout') errorContent = ( <> {t('proj_timed_out_reason')} <div> <a href="https://www.overleaf.com/learn/how-to/Why_do_I_keep_getting_the_compile_timeout_error_message%3F" target="_blank" > {t('learn_how_to_make_documents_compile_quickly')} </a> </div> </> ) } else if (name === 'autoCompileDisabled') { errorTitle = t('autocompile_disabled') errorContent = <>{t('autocompile_disabled_reason')}</> } else if (name === 'projectTooLarge') { errorTitle = t('project_too_large') errorContent = <>{t('project_too_much_editable_text')}</> } else if (name === 'failure') { errorTitle = t('no_pdf_error_title') errorContent = ( <> <Trans i18nKey="no_pdf_error_explanation" /> <ul className="log-entry-formatted-content-list"> <li> <Trans i18nKey="no_pdf_error_reason_unrecoverable_error" /> </li> <li> <Trans i18nKey="no_pdf_error_reason_no_content" components={{ code: <code /> }} /> </li> <li> <Trans i18nKey="no_pdf_error_reason_output_pdf_already_exists" components={{ code: <code /> }} /> </li> </ul> </> ) } return errorTitle ? ( <> <PreviewLogsPaneEntry headerTitle={errorTitle} formattedContent={errorContent} entryAriaLabel={t('compile_error_entry_description')} level="error" /> {name === 'timedout' && window.ExposedSettings.enableSubscriptions && !hasPremiumCompile ? ( <TimeoutUpgradePrompt isProjectOwner={isProjectOwner} /> ) : null} </> ) : null } function TimeoutUpgradePrompt({ isProjectOwner }) { const { t } = useTranslation() const timeoutUpgradePromptContent = ( <> <p>{t('free_accounts_have_timeout_upgrade_to_increase')}</p> <p>{t('plus_upgraded_accounts_receive')}:</p> <div> <ul className="list-unstyled"> <li> <Icon type="check" /> &nbsp; {t('unlimited_projects')} </li> <li> <Icon type="check" /> &nbsp; {t('collabs_per_proj', { collabcount: 'Multiple' })} </li> <li> <Icon type="check" /> &nbsp; {t('full_doc_history')} </li> <li> <Icon type="check" /> &nbsp; {t('sync_to_dropbox')} </li> <li> <Icon type="check" /> &nbsp; {t('sync_to_github')} </li> <li> <Icon type="check" /> &nbsp; {t('compile_larger_projects')} </li> </ul> </div> {isProjectOwner ? ( <p className="text-center"> <StartFreeTrialButton source="compile-timeout" buttonStyle="success" classes={{ button: 'row-spaced-small' }} /> </p> ) : null} </> ) return ( <PreviewLogsPaneEntry headerTitle={ isProjectOwner ? t('upgrade_for_longer_compiles') : t('ask_proj_owner_to_upgrade_for_longer_compiles') } formattedContent={timeoutUpgradePromptContent} entryAriaLabel={ isProjectOwner ? t('upgrade_for_longer_compiles') : t('ask_proj_owner_to_upgrade_for_longer_compiles') } level="success" /> ) } PreviewError.propTypes = { name: PropTypes.string.isRequired, } TimeoutUpgradePrompt.propTypes = { isProjectOwner: PropTypes.bool.isRequired, } export default PreviewError
overleaf/web/frontend/js/features/preview/components/preview-error.js/0
{ "file_path": "overleaf/web/frontend/js/features/preview/components/preview-error.js", "repo_id": "overleaf", "token_count": 2621 }
525
import { useEffect, useMemo, useState, useRef, useCallback } from 'react' import PropTypes from 'prop-types' import { Trans, useTranslation } from 'react-i18next' import { matchSorter } from 'match-sorter' import { useCombobox } from 'downshift' import classnames from 'classnames' import Icon from '../../../shared/components/icon' // Unicode characters in these Unicode groups: // "General Punctuation — Spaces" // "General Punctuation — Format character" (including zero-width spaces) const matchAllSpaces = /[\u061C\u2000-\u200F\u202A-\u202E\u2060\u2066-\u2069\u2028\u2029\u202F]/g export default function SelectCollaborators({ loading, options, placeholder, multipleSelectionProps, }) { const { getSelectedItemProps, getDropdownProps, addSelectedItem, removeSelectedItem, selectedItems, } = multipleSelectionProps const [inputValue, setInputValue] = useState('') const selectedEmails = useMemo(() => selectedItems.map(item => item.email), [ selectedItems, ]) const unselectedOptions = useMemo( () => options.filter(option => !selectedEmails.includes(option.email)), [options, selectedEmails] ) const filteredOptions = useMemo( () => matchSorter(unselectedOptions, inputValue, { keys: ['name', 'email'], threshold: matchSorter.rankings.CONTAINS, }), [unselectedOptions, inputValue] ) const inputRef = useRef(null) const focusInput = useCallback(() => { if (inputRef.current) { window.setTimeout(() => { inputRef.current.focus() }, 10) } }, [inputRef]) const isValidInput = useMemo(() => { if (inputValue.includes('@')) { for (const selectedItem of selectedItems) { if (selectedItem.email === inputValue) { return false } } } return true }, [inputValue, selectedItems]) const { isOpen, getLabelProps, getMenuProps, getInputProps, getComboboxProps, highlightedIndex, getItemProps, reset, } = useCombobox({ inputValue, defaultHighlightedIndex: 0, items: filteredOptions, itemToString: item => item && item.name, onStateChange: ({ inputValue, type, selectedItem }) => { switch (type) { // set inputValue when the input changes case useCombobox.stateChangeTypes.InputChange: setInputValue(inputValue) break // add a selected item on Enter (keypress), click or blur case useCombobox.stateChangeTypes.InputKeyDownEnter: case useCombobox.stateChangeTypes.ItemClick: case useCombobox.stateChangeTypes.InputBlur: if (selectedItem) { setInputValue('') addSelectedItem(selectedItem) } break } }, }) const addNewItem = useCallback( (_email, focus = true) => { const email = _email.replace(matchAllSpaces, '') if ( isValidInput && email.includes('@') && !selectedEmails.includes(email) ) { addSelectedItem({ email, display: email, type: 'user', }) setInputValue('') reset() if (focus) { focusInput() } return true } }, [addSelectedItem, selectedEmails, isValidInput, focusInput, reset] ) // close and reset the menu when there are no matching items useEffect(() => { if (isOpen && filteredOptions.length === 0) { reset() } }, [reset, isOpen, filteredOptions.length]) return ( <div className="tags-input"> {/* eslint-disable-next-line jsx-a11y/label-has-for */} <label className="small" {...getLabelProps()}> <Trans i18nKey="share_with_your_collabs" /> &nbsp; {loading && <Icon type="refresh" spin />} </label> <div className="host"> {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */} <div {...getComboboxProps()} className="tags" onClick={focusInput}> {selectedItems.map((selectedItem, index) => ( <SelectedItem key={`selected-item-${index}`} removeSelectedItem={removeSelectedItem} selectedItem={selectedItem} focusInput={focusInput} index={index} getSelectedItemProps={getSelectedItemProps} /> ))} <input {...getInputProps( getDropdownProps({ className: classnames({ input: true, 'invalid-tag': !isValidInput, }), type: 'email', placeholder, size: inputValue.length ? inputValue.length + 5 : placeholder.length, ref: inputRef, // preventKeyAction: showDropdown, onBlur: () => { // blur: if the dropdown isn't open, try to create a new item using inputValue if (!isOpen) { addNewItem(inputValue, false) } }, onKeyDown: event => { switch (event.key) { case 'Enter': // Enter: always prevent form submission event.preventDefault() event.stopPropagation() break case 'Tab': // Tab: if the dropdown isn't open, try to create a new item using inputValue and prevent blur if successful if (!isOpen && addNewItem(inputValue)) { event.preventDefault() event.stopPropagation() } break case ',': // comma: try to create a new item using inputValue event.preventDefault() addNewItem(inputValue) break } }, onPaste: event => { const data = // modern browsers event.clipboardData?.getData('text/plain') ?? // IE11 window.clipboardData?.getData('text') if (data) { const emails = data .split(/\s*,\s*/) .filter(item => item.includes('@')) if (emails.length) { // pasted comma-separated email addresses event.preventDefault() for (const email of emails) { addNewItem(email) } } } }, }) )} /> </div> <div className={classnames({ autocomplete: isOpen })}> <ul {...getMenuProps()} className="suggestion-list"> {isOpen && filteredOptions.map((item, index) => ( <Option key={item.email} index={index} item={item} selected={index === highlightedIndex} getItemProps={getItemProps} /> ))} </ul> </div> </div> </div> ) } SelectCollaborators.propTypes = { loading: PropTypes.bool.isRequired, options: PropTypes.array.isRequired, placeholder: PropTypes.string, multipleSelectionProps: PropTypes.shape({ getSelectedItemProps: PropTypes.func.isRequired, getDropdownProps: PropTypes.func.isRequired, addSelectedItem: PropTypes.func.isRequired, removeSelectedItem: PropTypes.func.isRequired, selectedItems: PropTypes.array.isRequired, }).isRequired, } function Option({ selected, item, getItemProps, index }) { return ( <li className={classnames('suggestion-item', { selected })} {...getItemProps({ item, index })} > <Icon type="user" modifier="fw" /> &nbsp; {item.display} </li> ) } Option.propTypes = { selected: PropTypes.bool.isRequired, item: PropTypes.shape({ display: PropTypes.string.isRequired, }), index: PropTypes.number.isRequired, getItemProps: PropTypes.func.isRequired, } function SelectedItem({ removeSelectedItem, selectedItem, focusInput, getSelectedItemProps, index, }) { const { t } = useTranslation() const handleClick = useCallback( event => { event.preventDefault() event.stopPropagation() removeSelectedItem(selectedItem) focusInput() }, [focusInput, removeSelectedItem, selectedItem] ) return ( <span className="tag-item" {...getSelectedItemProps({ selectedItem, index })} > <Icon type="user" modifier="fw" /> <span>{selectedItem.display}</span> <button type="button" className="remove-button btn-inline-link" aria-label={t('remove')} onClick={handleClick} > <Icon type="close" modifier="fw" /> </button> </span> ) } SelectedItem.propTypes = { focusInput: PropTypes.func.isRequired, removeSelectedItem: PropTypes.func.isRequired, selectedItem: PropTypes.shape({ display: PropTypes.string.isRequired, }), getSelectedItemProps: PropTypes.func.isRequired, index: PropTypes.number.isRequired, }
overleaf/web/frontend/js/features/share-project-modal/components/select-collaborators.js/0
{ "file_path": "overleaf/web/frontend/js/features/share-project-modal/components/select-collaborators.js", "repo_id": "overleaf", "token_count": 4517 }
526
import { useEffect, useRef } from 'react' import { OverlayTrigger, Tooltip } from 'react-bootstrap' import PropTypes from 'prop-types' export default function SymbolPaletteItem({ focused, handleSelect, handleKeyDown, symbol, }) { const buttonRef = useRef(null) // call focus() on this item when appropriate useEffect(() => { if ( focused && buttonRef.current && document.activeElement?.closest('.symbol-palette-items') ) { buttonRef.current.focus() } }, [focused]) return ( <OverlayTrigger placement="top" trigger={['hover', 'focus']} overlay={ <Tooltip id={`tooltip-symbol-${symbol.codepoint}`}> <div className="symbol-palette-item-description"> {symbol.description} </div> <div className="symbol-palette-item-command">{symbol.command}</div> {symbol.notes && ( <div className="symbol-palette-item-notes">{symbol.notes}</div> )} </Tooltip> } > <button key={symbol.codepoint} className="symbol-palette-item" onClick={() => handleSelect(symbol)} onKeyDown={handleKeyDown} tabIndex={focused ? 0 : -1} ref={buttonRef} role="option" aria-label={symbol.description} aria-selected={focused ? 'true' : 'false'} > {symbol.character} </button> </OverlayTrigger> ) } SymbolPaletteItem.propTypes = { symbol: PropTypes.shape({ codepoint: PropTypes.string.isRequired, description: PropTypes.string.isRequired, command: PropTypes.string.isRequired, character: PropTypes.string.isRequired, notes: PropTypes.string, }), handleKeyDown: PropTypes.func.isRequired, handleSelect: PropTypes.func.isRequired, focused: PropTypes.bool, }
overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-item.js/0
{ "file_path": "overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-item.js", "repo_id": "overleaf", "token_count": 775 }
527
import i18n from '../i18n' // Control the editor loading screen. We want to show the loading screen until // both the websocket connection has been established (so that the editor is in // the correct state) and the translations have been loaded (so we don't see a // flash of untranslated text). class LoadingManager { constructor($scope) { this.$scope = $scope const socketPromise = new Promise(resolve => { this.resolveSocketPromise = resolve }) Promise.all([socketPromise, i18n]) .then(() => { this.$scope.$apply(() => { this.$scope.state.load_progress = 100 this.$scope.state.loading = false }) }) // Note: this will only catch errors in from i18n setup. ConnectionManager // handles errors for the socket connection .catch(() => { this.$scope.$apply(() => { this.$scope.state.error = 'Could not load translations.' }) }) } socketLoaded() { this.resolveSocketPromise() } } export default LoadingManager
overleaf/web/frontend/js/ide/LoadingManager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/LoadingManager.js", "repo_id": "overleaf", "token_count": 371 }
528
/* 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 SafePath from './SafePath' export default App.directive('validFile', () => ({ require: 'ngModel', link(scope, element, attrs, ngModelCtrl) { return (ngModelCtrl.$validators.validFile = filename => SafePath.isCleanFilename(filename)) }, }))
overleaf/web/frontend/js/ide/directives/validFile.js/0
{ "file_path": "overleaf/web/frontend/js/ide/directives/validFile.js", "repo_id": "overleaf", "token_count": 208 }
529
/* 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 EditorShareJsCodec from '../../../EditorShareJsCodec' let CursorPositionAdapter export default CursorPositionAdapter = class CursorPositionAdapter { constructor(editor) { this.editor = editor } getCursor() { return this.editor.getCursorPosition() } getEditorScrollPosition() { return this.editor.getFirstVisibleRow() } setCursor(pos) { pos = pos.cursorPosition || { row: 0, column: 0 } return this.editor.moveCursorToPosition(pos) } setEditorScrollPosition(pos) { pos = pos.firstVisibleLine || 0 return this.editor.scrollToLine(pos) } clearSelection() { return this.editor.selection.clearSelection() } gotoLine(line, column) { this.editor.gotoLine(line, column) this.editor.scrollToLine(line, true, true) // centre and animate return this.editor.focus() } gotoOffset(offset) { const lines = this.editor.getSession().getDocument().getAllLines() const position = EditorShareJsCodec.shareJsOffsetToRowColumn(offset, lines) return this.gotoLine(position.row + 1, position.column) } }
overleaf/web/frontend/js/ide/editor/directives/aceEditor/cursor-position/CursorPositionAdapter.js/0
{ "file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/cursor-position/CursorPositionAdapter.js", "repo_id": "overleaf", "token_count": 479 }
530
let fileActionI18n if (window.fileActionI18n !== undefined) { fileActionI18n = window.fileActionI18n } fileActionI18n = { edited: 'edited', renamed: 'renamed', created: 'created', deleted: 'deleted', } export default fileActionI18n
overleaf/web/frontend/js/ide/file-tree/util/fileOperationI18nNames.js/0
{ "file_path": "overleaf/web/frontend/js/ide/file-tree/util/fileOperationI18nNames.js", "repo_id": "overleaf", "token_count": 90 }
531
/* 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('OnlineUsersController', function ($scope, ide) { $scope.gotoUser = function (user) { if (user.doc != null && user.row != null) { return ide.editorManager.openDoc(user.doc, { gotoLine: user.row + 1 }) } } return ($scope.userInitial = function (user) { if (user.user_id === 'anonymous-user') { return '?' } else { return user.name.slice(0, 1) } }) })
overleaf/web/frontend/js/ide/online-users/controllers/OnlineUsersController.js/0
{ "file_path": "overleaf/web/frontend/js/ide/online-users/controllers/OnlineUsersController.js", "repo_id": "overleaf", "token_count": 297 }
532
/* 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 * DS103: Rewrite code to no longer use __guard__ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../base' export default App.factory('preamble', function (ide) { var Preamble = { getPreambleText() { const text = ide.editorManager.getCurrentDocValue().slice(0, 5000) const preamble = __guard__(text.match(/([^]*)^\\begin\{document\}/m), x => x[1]) || '' return preamble }, getGraphicsPaths() { let match const preamble = Preamble.getPreambleText() const graphicsPathsArgs = __guard__(preamble.match(/\\graphicspath\{(.*)\}/), x => x[1]) || '' const paths = [] const re = /\{([^}]*)\}/g while ((match = re.exec(graphicsPathsArgs))) { paths.push(match[1]) } return paths }, } return Preamble }) function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) : undefined }
overleaf/web/frontend/js/ide/preamble/services/preamble.js/0
{ "file_path": "overleaf/web/frontend/js/ide/preamble/services/preamble.js", "repo_id": "overleaf", "token_count": 488 }
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 * 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.directive('reviewPanelToggle', () => ({ restrict: 'E', scope: { onToggle: '&', ngModel: '=', valWhenUndefined: '=?', isDisabled: '=?', onDisabledClick: '&?', description: '@', }, link(scope) { if (scope.disabled == null) { scope.disabled = false } scope.onChange = (...args) => scope.onToggle({ isOn: scope.localModel }) scope.handleClick = function () { if (scope.disabled && scope.onDisabledClick != null) { return scope.onDisabledClick() } } scope.localModel = scope.ngModel return scope.$watch('ngModel', function (value) { if (scope.valWhenUndefined != null && value == null) { value = scope.valWhenUndefined } return (scope.localModel = value) }) }, template: `\ <fieldset class="rp-toggle" ng-click="handleClick();"> <legend class="sr-only">{{description}}</legend> <input id="rp-toggle-{{$id}}" ng-disabled="isDisabled" type="checkbox" class="rp-toggle-hidden-input" ng-model="localModel" ng-change="onChange()" /> <label for="rp-toggle-{{$id}}" class="rp-toggle-btn"></label> </fieldset>\ `, }))
overleaf/web/frontend/js/ide/review-panel/directives/reviewPanelToggle.js/0
{ "file_path": "overleaf/web/frontend/js/ide/review-panel/directives/reviewPanelToggle.js", "repo_id": "overleaf", "token_count": 590 }
534
/** * sessionStorage can throw browser exceptions, for example if it is full. * We don't use sessionStorage for anything critical, so in that case just fail gracefully. */ /** * Catch, log and otherwise ignore errors. * * @param {function} fn sessionStorage function to call * @param {string?} key Key passed to the sessionStorage function (if any) * @param {any?} value Value passed to the sessionStorage function (if any) */ const callSafe = function (fn, key, value) { try { return fn(key, value) } catch (e) { console.error('sessionStorage exception', e) return null } } const getItem = function (key) { return JSON.parse(sessionStorage.getItem(key)) } const setItem = function (key, value) { sessionStorage.setItem(key, JSON.stringify(value)) } const clear = function () { sessionStorage.clear() } const removeItem = function (key) { return sessionStorage.removeItem(key) } const customSessionStorage = { getItem: key => callSafe(getItem, key), setItem: (key, value) => callSafe(setItem, key, value), clear: () => callSafe(clear), removeItem: key => callSafe(removeItem, key), } export default customSessionStorage
overleaf/web/frontend/js/infrastructure/session-storage.js/0
{ "file_path": "overleaf/web/frontend/js/infrastructure/session-storage.js", "repo_id": "overleaf", "token_count": 353 }
535
import App from '../base' App.controller( 'ImportingController', function ($interval, $scope, $timeout, $window) { $interval(function () { $scope.state.load_progress += 5 if ($scope.state.load_progress > 100) { $scope.state.load_progress = 20 } }, 500) $timeout(function () { $window.location.reload() }, 5000) $scope.state = { load_progress: 20, } } )
overleaf/web/frontend/js/main/importing.js/0
{ "file_path": "overleaf/web/frontend/js/main/importing.js", "repo_id": "overleaf", "token_count": 178 }
536
// 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.controller('ScribtexPopupController', ($scope, $modal) => $modal.open({ templateUrl: 'scribtexModalTemplate', }) )
overleaf/web/frontend/js/main/scribtex-popup.js/0
{ "file_path": "overleaf/web/frontend/js/main/scribtex-popup.js", "repo_id": "overleaf", "token_count": 141 }
537
import App from '../base' export default App.factory('validateCaptchaV3', function () { const grecaptcha = window.grecaptcha const ExposedSettings = window.ExposedSettings return function validateCaptchaV3(actionName, callback = () => {}) { if (!grecaptcha) { return } if (!ExposedSettings || !ExposedSettings.recaptchaSiteKeyV3) { return } grecaptcha.ready(function () { grecaptcha .execute(ExposedSettings.recaptchaSiteKeyV3, { action: actionName }) .then(callback) }) } })
overleaf/web/frontend/js/services/validateCaptchaV3.js/0
{ "file_path": "overleaf/web/frontend/js/services/validateCaptchaV3.js", "repo_id": "overleaf", "token_count": 209 }
538
import { createContext, useContext } from 'react' import PropTypes from 'prop-types' import useScopeValue from './util/scope-value-hook' const ProjectContext = createContext() ProjectContext.Provider.propTypes = { value: PropTypes.shape({ _id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, rootDoc_id: PropTypes.string, members: PropTypes.arrayOf( PropTypes.shape({ _id: PropTypes.string.isRequired, }) ), invites: PropTypes.arrayOf( PropTypes.shape({ _id: PropTypes.string.isRequired, }) ), features: PropTypes.shape({ collaborators: PropTypes.number, compileGroup: PropTypes.oneOf(['alpha', 'standard', 'priority']) .isRequired, }), publicAccesLevel: PropTypes.string, tokens: PropTypes.shape({ readOnly: PropTypes.string, readAndWrite: PropTypes.string, }), owner: PropTypes.shape({ _id: PropTypes.string.isRequired, email: PropTypes.string.isRequired, }), }), } export function useProjectContext(propTypes) { const context = useContext(ProjectContext) if (!context) { throw new Error( 'useProjectContext is only available inside ProjectProvider' ) } PropTypes.checkPropTypes( propTypes, context, 'data', 'ProjectContext.Provider' ) return context } export function ProjectProvider({ children }) { const [project] = useScopeValue('project', true) // when the provider is created the project is still not added to the Angular scope. // Name is also populated to prevent errors in existing React components const value = project || { _id: window.project_id, name: '' } return ( <ProjectContext.Provider value={value}>{children}</ProjectContext.Provider> ) } ProjectProvider.propTypes = { children: PropTypes.any, }
overleaf/web/frontend/js/shared/context/project-context.js/0
{ "file_path": "overleaf/web/frontend/js/shared/context/project-context.js", "repo_id": "overleaf", "token_count": 644 }
539
import getMeta from './meta' // Configure dynamically loaded assets (via webpack) to be downloaded from CDN // See: https://webpack.js.org/guides/public-path/#on-the-fly __webpack_public_path__ = getMeta('ol-baseAssetPath')
overleaf/web/frontend/js/utils/webpack-public-path.js/0
{ "file_path": "overleaf/web/frontend/js/utils/webpack-public-path.js", "repo_id": "overleaf", "token_count": 72 }
540
import { Dropdown, MenuItem } from 'react-bootstrap' import ControlledDropdown from '../js/shared/components/controlled-dropdown' export const Customized = args => { return ( <ControlledDropdown pullRight={args.pullRight} defaultOpen={args.defaultOpen} id="dropdown-story" > <Dropdown.Toggle noCaret={args.noCaret} className={args.className} bsStyle={args.bsStyle} > {args.title} </Dropdown.Toggle> <Dropdown.Menu> <MenuItem eventKey="1">Action</MenuItem> <MenuItem eventKey="2">Another action</MenuItem> <MenuItem eventKey="3" active> Active Item </MenuItem> <MenuItem divider /> <MenuItem eventKey="4">Separated link</MenuItem> </Dropdown.Menu> </ControlledDropdown> ) } Customized.args = { title: 'Toggle & Menu used separately', } export default { title: 'Dropdown', component: ControlledDropdown, args: { bsStyle: 'default', title: 'Dropdown', pullRight: false, noCaret: false, className: '', defaultOpen: true, }, }
overleaf/web/frontend/stories/dropdown.stories.js/0
{ "file_path": "overleaf/web/frontend/stories/dropdown.stories.js", "repo_id": "overleaf", "token_count": 473 }
541
import ErrorMessage from '../../../js/features/file-tree/components/file-tree-create/error-message' import { createFileModalDecorator } from './create-file-modal-decorator' import { FetchError } from '../../../js/infrastructure/fetch-json' import { BlockedFilenameError, DuplicateFilenameError, InvalidFilenameError, } from '../../../js/features/file-tree/errors' export const KeyedErrors = () => { return ( <> <ErrorMessage error="name-exists" /> <ErrorMessage error="too-many-files" /> <ErrorMessage error="remote-service-error" /> <ErrorMessage error="rate-limit-hit" /> {/* <ErrorMessage error="not-logged-in" /> */} <ErrorMessage error="something-else" /> </> ) } KeyedErrors.decorators = [createFileModalDecorator()] export const FetchStatusErrors = () => { return ( <> <ErrorMessage error={ new FetchError( 'There was an error', '/story', {}, new Response(null, { status: 400 }) ) } /> <ErrorMessage error={ new FetchError( 'There was an error', '/story', {}, new Response(null, { status: 403 }) ) } /> <ErrorMessage error={ new FetchError( 'There was an error', '/story', {}, new Response(null, { status: 429 }) ) } /> <ErrorMessage error={ new FetchError( 'There was an error', '/story', {}, new Response(null, { status: 500 }) ) } /> </> ) } export const FetchDataErrors = () => { return ( <> <ErrorMessage error={ new FetchError('Error', '/story', {}, new Response(), { message: 'There was an error!', }) } /> <ErrorMessage error={ new FetchError('Error', '/story', {}, new Response(), { message: { text: 'There was an error with some text!', }, }) } /> </> ) } export const SpecificClassErrors = () => { return ( <> <ErrorMessage error={new DuplicateFilenameError()} /> <ErrorMessage error={new InvalidFilenameError()} /> <ErrorMessage error={new BlockedFilenameError()} /> <ErrorMessage error={new Error()} /> </> ) } export default { title: 'Modals / Create File / Error Message', component: ErrorMessage, }
overleaf/web/frontend/stories/modals/create-file/error-message.stories.js/0
{ "file_path": "overleaf/web/frontend/stories/modals/create-file/error-message.stories.js", "repo_id": "overleaf", "token_count": 1220 }
542
/* v2 About Page */ .team { list-style: none; padding: 0; .team-member { display: block; float: left; margin-bottom: @margin-lg; width: 100%; h3 { margin: 0; } .team-pic { float: left; margin-right: @margin-sm; } .team-info { overflow: hidden; } .team-connect { list-style: none; margin-top: @margin-sm; padding: 0; li { display: inline-block; margin: 0 @margin-md 0 0; } } } }
overleaf/web/frontend/stylesheets/app/about.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/about.less", "repo_id": "overleaf", "token_count": 263 }
543
@changesListWidth: 250px; @changesListPadding: @line-height-computed / 2; @selector-padding-vertical: 10px; @selector-padding-horizontal: @line-height-computed / 2; @day-header-height: 24px; @range-bar-color: @link-color; @range-bar-selected-offset: 14px; @history-toolbar-height: 32px; #history { .upgrade-prompt { position: absolute; top: 0; bottom: 0; left: 0; right: 0; z-index: 100; background-color: rgba(128, 128, 128, 0.4); .message { margin: auto; margin-top: 100px; padding: (@line-height-computed / 2) @line-height-computed; width: 400px; background-color: white; border-radius: 8px; } .message-wider { width: 650px; margin-top: 60px; padding: 0; } .message-header { .modal-header; } .message-body { .modal-body; } } .diff-panel, .point-in-time-panel { .full-size; margin-right: @changesListWidth; } .diff { .full-size; .toolbar { padding: 3px; height: @history-toolbar-height; .name { color: #fff; float: left; padding: 3px @line-height-computed / 4; display: inline-block; } } .diff-editor-v2 { .full-size; } .diff-editor { .full-size; top: @history-toolbar-height; } .diff-deleted { padding: @line-height-computed; } .deleted-warning { background-color: @brand-danger; color: white; padding: @line-height-computed / 2; margin-right: @line-height-computed / 4; } &-binary { .alert { margin: @line-height-computed / 2; } } } aside.change-list { border-left: 1px solid @editor-border-color; height: 100%; width: @changesListWidth; position: absolute; right: 0; .loading { text-align: center; font-family: @font-family-serif; margin-top: (@line-height-computed / 2); } ul { li.change { position: relative; user-select: none; -ms-user-select: none; -moz-user-select: none; -webkit-user-select: none; .day { background-color: #fafafa; border-bottom: 1px solid @editor-border-color; padding: 4px; font-weight: bold; text-align: center; height: @day-header-height; font-size: 14px; line-height: 1; } .selectors { input { margin: 0; } position: absolute; left: @selector-padding-horizontal; top: 0; bottom: 0; width: 24px; .selector-from { position: absolute; bottom: @selector-padding-vertical; left: 0; opacity: 0.8; } .selector-to { position: absolute; top: @selector-padding-vertical; left: 0; opacity: 0.8; } .range { position: absolute; left: 5px; width: 4px; top: 0; bottom: 0; } } .description { padding: (@line-height-computed / 4); padding-left: 38px; min-height: 38px; border-bottom: 1px solid @editor-border-color; cursor: pointer; &:hover { background-color: @gray-lightest; } } .users { .user { font-size: 0.8rem; color: @gray; text-transform: capitalize; position: relative; padding-left: 16px; .color-square { height: 12px; width: 12px; border-radius: 3px; position: absolute; left: 0; bottom: 3px; } .name { width: 94%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } } } .time { float: right; color: @gray; display: inline-block; padding-right: (@line-height-computed / 2); font-size: 0.8rem; line-height: @line-height-computed; } .doc { font-size: 0.9rem; font-weight: bold; } .action { color: @gray; text-transform: uppercase; font-size: 0.7em; margin-bottom: -2px; margin-top: 2px; &-edited { margin-top: 0; } } } li.loading-changes, li.empty-message { padding: 6px; cursor: default; &:hover { background-color: inherit; } } li.selected { border-left: 4px solid @range-bar-color; .day { padding-left: 0; } .description { padding-left: 34px; } .selectors { left: @selector-padding-horizontal - 4px; .range { background-color: @range-bar-color; } } } li.selected-to { .selectors { .range { top: @range-bar-selected-offset; } .selector-to { opacity: 1; } } } li.selected-from { .selectors { .range { bottom: @range-bar-selected-offset; } .selector-from { opacity: 1; } } } li.first-in-day { .selectors { .selector-to { top: @day-header-height + @selector-padding-vertical; } } } li.first-in-day.selected-to { .selectors { .range { top: @day-header-height + @range-bar-selected-offset; } } } } ul.hover-state { li { .selectors { .range { background-color: transparent; top: 0; bottom: 0; } } } li.hover-selected { .selectors { .range { top: 0; background-color: @gray-light; } } } li.hover-selected-to { .selectors { .range { top: @range-bar-selected-offset; } .selector-to { opacity: 1; } } } li.hover-selected-from { .selectors { .range { bottom: @range-bar-selected-offset; } .selector-from { opacity: 1; } } } li.first-in-day.hover-selected-to { .selectors { .range { top: @day-header-height + @range-bar-selected-offset; } } } } } } .diff-deleted { padding-top: 15px; } .hide-ace-cursor { .ace_active-line, .ace_cursor-layer, .ace_bracket { display: none; } .ace_gutter-active-line { background-color: transparent; } } .editor-dark { #history { aside.change-list { border-color: @editor-dark-toolbar-border-color; ul li.change { .day { background-color: darken(@editor-dark-background-color, 10%); border-bottom: 1px solid @editor-dark-toolbar-border-color; } .description { border-bottom: 1px solid @editor-dark-toolbar-border-color; &:hover { background-color: black; } } } } } }
overleaf/web/frontend/stylesheets/app/editor/history.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/editor/history.less", "repo_id": "overleaf", "token_count": 4207 }
544
.long-form-features { h2 { margin-top: 0; margin-bottom: @line-height-computed; } img { border-radius: 3px; -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); max-width: 100%; height: auto; } h3 { margin: 0; } i { color: lighten(@blue, 15%); } }
overleaf/web/frontend/stylesheets/app/features.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/features.less", "repo_id": "overleaf", "token_count": 172 }
545
#publisher-hub { .recent-activity { .hub-big-number { text-align: right; padding-right: 15px; } } #templates-container { width: 100%; tr { border: 1px solid @ol-blue-gray-0; } td { padding: 15px; } td:last-child { text-align: right; } .title-cell { max-width: 300px; } .title-text { font-weight: bold; } .hub-big-number { width: 60%; padding-right: 10px; padding-top: 10px; text-align: right; } .hub-number-label, .since { width: 35%; float: right; @media screen and (max-width: 940px) { float: none; } } .hub-long-big-number { padding-right: 40px; } .created-on { color: @gray-light; font-style: italic; font-size: 14px; } } }
overleaf/web/frontend/stylesheets/app/publisher-hub.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/publisher-hub.less", "repo_id": "overleaf", "token_count": 442 }
546
// // Buttons // -------------------------------------------------- // Base styles // -------------------------------------------------- .btn { display: inline-block; margin-bottom: 0; // For input.btn font-weight: @btn-font-weight; text-align: center; vertical-align: middle; cursor: pointer; background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214 border: @btn-border-width solid transparent; border-bottom: @btn-border-bottom-width solid transparent; white-space: nowrap; .button-size( @padding-base-vertical; @padding-base-horizontal; @font-size-base; @line-height-base; @btn-border-radius-base ); .user-select(none); &, &:active, &.active { &:focus { .tab-focus(); } } &:hover, &:focus { color: @btn-default-color; text-decoration: none; } &:active, &.active { outline: 0; background-image: none; .box-shadow(inset 0 3px 5px rgba(0, 0, 0, 0.125)); } &.disabled, &[disabled], fieldset[disabled] & { cursor: not-allowed; pointer-events: none; // Future-proof disabling of clicks .opacity(0.65); .box-shadow(none); } } // Alternate buttons // -------------------------------------------------- .btn-default { .button-variant(@btn-default-color; @btn-default-bg; @btn-default-border); } .btn-default-outline { .button-outline-variant(@btn-default-bg); } .btn-primary { .button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border); } .btn-primary-on-primary-bg { .button-variant(@white; @ol-dark-green; @ol-dark-green); } // Success appears as green .btn-success { .button-variant(@btn-success-color; @btn-success-bg; @btn-success-border); } // Info appears as blue-green .btn-info { .button-variant(@btn-info-color; @btn-info-bg; @btn-info-border); } // Warning appears as orange .btn-warning { .button-variant(@btn-warning-color; @btn-warning-bg; @btn-warning-border); } // Danger and error appear as red .btn-danger { .button-variant(@btn-danger-color; @btn-danger-bg; @btn-danger-border); } .reset-btns { // reset all buttons back to their original colors .btn-danger { .btn-danger; } .btn-default { .btn-default; } .btn-default-outline { .btn-default-outline; } .btn-info { .btn-info; } .btn-primary { .btn-primary; } .btn-success { .btn-success; } .btn-warning { .btn-warning; } } // Link buttons // ------------------------- // Make a button look and behave like a link .btn-link { color: @link-color; font-weight: normal; cursor: pointer; border-radius: 0; &, &:active, &[disabled], fieldset[disabled] & { background-color: transparent; .box-shadow(none); } &, &:hover, &:focus, &:active { border-color: transparent; } &:hover, &:focus { color: @link-hover-color; text-decoration: underline; background-color: transparent; } &[disabled], fieldset[disabled] & { &:hover, &:focus { color: @btn-link-disabled-color; text-decoration: none; } } } .btn-inline-link { .btn-link(); padding: 0; font-size: inherit; vertical-align: inherit; } // Button Sizes // -------------------------------------------------- .btn-xl { .button-size( @padding-large-vertical; @padding-large-horizontal; @font-size-h2; @line-height-large; @btn-border-radius-large ); } .btn-lg { // line-height: ensure even-numbered height of button next to large input .button-size( @padding-large-vertical; @padding-large-horizontal; @font-size-large; @line-height-large; @btn-border-radius-large ); } .btn-sm { // line-height: ensure proper height of button next to small input .button-size( @padding-small-vertical; @padding-small-horizontal; @font-size-small; @line-height-small; @btn-border-radius-small ); } .btn-xs { .button-size( @padding-xs-vertical; @padding-xs-horizontal; @font-size-small; @line-height-small; @btn-border-radius-small ); } // Block button // -------------------------------------------------- .btn-block { display: block; width: 100%; padding-left: 0; padding-right: 0; } // Vertically space out multiple block buttons .btn-block + .btn-block { margin-top: 5px; } // Specificity overrides input[type='submit'], input[type='reset'], input[type='button'] { &.btn-block { width: 100%; } }
overleaf/web/frontend/stylesheets/components/buttons.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/buttons.less", "repo_id": "overleaf", "token_count": 1684 }
547
.infinite-scroll { overflow-y: auto; }
overleaf/web/frontend/stylesheets/components/infinite-scroll.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/infinite-scroll.less", "repo_id": "overleaf", "token_count": 17 }
548
// // Pager pagination // -------------------------------------------------- .pager { padding-left: 0; margin: @line-height-computed 0; list-style: none; text-align: center; &:extend(.clearfix all); li { display: inline; > a, > span { display: inline-block; padding: 5px 14px; background-color: @pager-bg; border: 1px solid @pager-border; border-radius: @pager-border-radius; } > a:hover, > a:focus { text-decoration: none; background-color: @pager-hover-bg; } } .next { > a, > span { float: right; } } .previous { > a, > span { float: left; } } .disabled { > a, > a:hover, > a:focus, > span { color: @pager-disabled-color; background-color: @pager-bg; cursor: not-allowed; } } }
overleaf/web/frontend/stylesheets/components/pager.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/pager.less", "repo_id": "overleaf", "token_count": 398 }
549
// // Mixins // -------------------------------------------------- // Utilities // ------------------------- // Clearfix // Source: http://nicolasgallagher.com/micro-clearfix-hack/ // // For modern browsers // 1. The space content is one way to avoid an Opera bug when the // contenteditable attribute is included anywhere else in the document. // Otherwise it causes space to appear at the top and bottom of elements // that are clearfixed. // 2. The use of `table` rather than `block` is only necessary if using // `:before` to contain the top-margins of child elements. .clearfix() { &:before, &:after { content: ' '; // 1 display: table; // 2 } &:after { clear: both; } } // WebKit-style focus .tab-focus() { // Default outline: thin dotted; // WebKit outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } // Center-align a block level element .center-block() { display: block; margin-left: auto; margin-right: auto; } // Sizing shortcuts .size(@width; @height) { width: @width; height: @height; } .square(@size) { .size(@size; @size); } // Placeholder text .placeholder(@color: @input-color-placeholder) { &::-moz-placeholder { color: @color; // Firefox opacity: 1; } // See https://github.com/twbs/bootstrap/pull/11526 &:-ms-input-placeholder { color: @color; } // Internet Explorer 10+ &::-webkit-input-placeholder { color: @color; } // Safari and Chrome } // Text overflow // Requires inline-block or block for proper styling .text-overflow() { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } // CSS image replacement // // Heads up! v3 launched with with only `.hide-text()`, but per our pattern for // mixins being reused as classes with the same name, this doesn't hold up. As // of v3.0.1 we have added `.text-hide()` and deprecated `.hide-text()`. Note // that we cannot chain the mixins together in Less, so they are repeated. // // Source: https://github.com/h5bp/html5-boilerplate/commit/aa0396eae757 // Deprecated as of v3.0.1 (will be removed in v4) .hide-text() { font: ~'0/0' a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } // New mixin to use as of v3.0.1 .text-hide() { .hide-text(); } // CSS3 PROPERTIES // -------------------------------------------------- // Single side border-radius .border-top-radius(@radius) { border-top-right-radius: @radius; border-top-left-radius: @radius; } .border-right-radius(@radius) { border-bottom-right-radius: @radius; border-top-right-radius: @radius; } .border-bottom-radius(@radius) { border-bottom-right-radius: @radius; border-bottom-left-radius: @radius; } .border-left-radius(@radius) { border-bottom-left-radius: @radius; border-top-left-radius: @radius; } // Drop shadows // // Note: Deprecated `.box-shadow()` as of v3.1.0 since all of Bootstrap's // supported browsers that have box shadow capabilities now support the // standard `box-shadow` property. .box-shadow(@shadow) { -webkit-box-shadow: @shadow; // iOS <4.3 & Android <4.1 box-shadow: @shadow; } // Transitions .transition(@transition) { -webkit-transition: @transition; transition: @transition; } .transition-property(@transition-property) { -webkit-transition-property: @transition-property; transition-property: @transition-property; } .transition-delay(@transition-delay) { -webkit-transition-delay: @transition-delay; transition-delay: @transition-delay; } .transition-duration(@transition-duration) { -webkit-transition-duration: @transition-duration; transition-duration: @transition-duration; } .transition-transform(@transition) { -webkit-transition: -webkit-transform @transition; -moz-transition: -moz-transform @transition; -o-transition: -o-transform @transition; transition: transform @transition; } // Transformations .rotate(@degrees) { -webkit-transform: rotate(@degrees); -ms-transform: rotate(@degrees); // IE9 only transform: rotate(@degrees); } .scale(@ratio; @ratio-y...) { -webkit-transform: scale(@ratio, @ratio-y); -ms-transform: scale(@ratio, @ratio-y); // IE9 only transform: scale(@ratio, @ratio-y); } .translate(@x; @y) { -webkit-transform: translate(@x, @y); -ms-transform: translate(@x, @y); // IE9 only transform: translate(@x, @y); } .skew(@x; @y) { -webkit-transform: skew(@x, @y); -ms-transform: skewX(@x) skewY(@y); // See https://github.com/twbs/bootstrap/issues/4885; IE9+ transform: skew(@x, @y); } .translate3d(@x; @y; @z) { -webkit-transform: translate3d(@x, @y, @z); transform: translate3d(@x, @y, @z); } .rotateX(@degrees) { -webkit-transform: rotateX(@degrees); -ms-transform: rotateX(@degrees); // IE9 only transform: rotateX(@degrees); } .rotateY(@degrees) { -webkit-transform: rotateY(@degrees); -ms-transform: rotateY(@degrees); // IE9 only transform: rotateY(@degrees); } .perspective(@perspective) { -webkit-perspective: @perspective; -moz-perspective: @perspective; perspective: @perspective; } .perspective-origin(@perspective) { -webkit-perspective-origin: @perspective; -moz-perspective-origin: @perspective; perspective-origin: @perspective; } .transform-origin(@origin) { -webkit-transform-origin: @origin; -moz-transform-origin: @origin; -ms-transform-origin: @origin; // IE9 only transform-origin: @origin; } // Animations .animation(@animation) { -webkit-animation: @animation; animation: @animation; } .animation-name(@name) { -webkit-animation-name: @name; animation-name: @name; } .animation-duration(@duration) { -webkit-animation-duration: @duration; animation-duration: @duration; } .animation-timing-function(@timing-function) { -webkit-animation-timing-function: @timing-function; animation-timing-function: @timing-function; } .animation-delay(@delay) { -webkit-animation-delay: @delay; animation-delay: @delay; } .animation-iteration-count(@iteration-count) { -webkit-animation-iteration-count: @iteration-count; animation-iteration-count: @iteration-count; } .animation-direction(@direction) { -webkit-animation-direction: @direction; animation-direction: @direction; } // Backface visibility // Prevent browsers from flickering when using CSS 3D transforms. // Default value is `visible`, but can be changed to `hidden` .backface-visibility(@visibility) { -webkit-backface-visibility: @visibility; -moz-backface-visibility: @visibility; backface-visibility: @visibility; } // Box sizing .box-sizing(@boxmodel) { -webkit-box-sizing: @boxmodel; -moz-box-sizing: @boxmodel; box-sizing: @boxmodel; } // User select // For selecting text on the page .user-select(@select) { -webkit-user-select: @select; -moz-user-select: @select; -ms-user-select: @select; // IE10+ user-select: @select; } // Resize anything .resizable(@direction) { resize: @direction; // Options: horizontal, vertical, both overflow: auto; // Safari fix } // CSS3 Content Columns .content-columns(@column-count; @column-gap: @grid-gutter-width) { -webkit-column-count: @column-count; -moz-column-count: @column-count; column-count: @column-count; -webkit-column-gap: @column-gap; -moz-column-gap: @column-gap; column-gap: @column-gap; } // Optional hyphenation .hyphens(@mode: auto) { word-wrap: break-word; -webkit-hyphens: @mode; -moz-hyphens: @mode; -ms-hyphens: @mode; // IE10+ -o-hyphens: @mode; hyphens: @mode; } // Opacity .opacity(@opacity) { opacity: @opacity; // IE8 filter @opacity-ie: (@opacity * 100); filter: ~'alpha(opacity=@{opacity-ie})'; } // GRADIENTS // -------------------------------------------------- #gradient { // Horizontal gradient, from left to right // // Creates two color stops, start and end, by specifying a color and position for each color stop. // Color stops are not available in IE9 and below. .horizontal(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent: 100%) { background-image: -webkit-linear-gradient( left, color-stop(@start-color @start-percent), color-stop(@end-color @end-percent) ); // Safari 5.1-6, Chrome 10+ background-image: linear-gradient( to right, @start-color @start-percent, @end-color @end-percent ); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+ background-repeat: repeat-x; filter: e( %( "progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)", argb(@start-color), argb(@end-color) ) ); // IE9 and down } // Vertical gradient, from top to bottom // // Creates two color stops, start and end, by specifying a color and position for each color stop. // Color stops are not available in IE9 and below. .vertical(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent: 100%) { background-image: -webkit-linear-gradient( top, @start-color @start-percent, @end-color @end-percent ); // Safari 5.1-6, Chrome 10+ background-image: linear-gradient( to bottom, @start-color @start-percent, @end-color @end-percent ); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+ background-repeat: repeat-x; filter: e( %( "progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)", argb(@start-color), argb(@end-color) ) ); // IE9 and down } .directional(@start-color: #555; @end-color: #333; @deg: 45deg) { background-repeat: repeat-x; background-image: -webkit-linear-gradient( @deg, @start-color, @end-color ); // Safari 5.1-6, Chrome 10+ background-image: linear-gradient( @deg, @start-color, @end-color ); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+ } .horizontal-three-colors(@start-color: #00b3ee; @mid-color: #7a43b6; @color-stop: 50%; @end-color: #c3325f) { background-image: -webkit-linear-gradient( left, @start-color, @mid-color @color-stop, @end-color ); background-image: linear-gradient( to right, @start-color, @mid-color @color-stop, @end-color ); background-repeat: no-repeat; filter: e( %( "progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)", argb(@start-color), argb(@end-color) ) ); // IE9 and down, gets no color-stop at all for proper fallback } .vertical-three-colors(@start-color: #00b3ee; @mid-color: #7a43b6; @color-stop: 50%; @end-color: #c3325f) { background-image: -webkit-linear-gradient( @start-color, @mid-color @color-stop, @end-color ); background-image: linear-gradient( @start-color, @mid-color @color-stop, @end-color ); background-repeat: no-repeat; filter: e( %( "progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)", argb(@start-color), argb(@end-color) ) ); // IE9 and down, gets no color-stop at all for proper fallback } .radial(@inner-color: #555; @outer-color: #333) { background-image: -webkit-radial-gradient( circle, @inner-color, @outer-color ); background-image: radial-gradient(circle, @inner-color, @outer-color); background-repeat: no-repeat; } .striped(@color: rgba(255,255,255,0.15); @angle: 45deg) { background-image: -webkit-linear-gradient( @angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent ); background-image: linear-gradient( @angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent ); } } // Reset filters for IE // // When you need to remove a gradient background, do not forget to use this to reset // the IE filter for IE9 and below. .reset-filter() { filter: e(%('progid:DXImageTransform.Microsoft.gradient(enabled = false)')); } // Retina images // // Short retina mixin for setting background-image and -size .img-retina(@file-1x; @file-2x; @width-1x; @height-1x) { background-image: url('@{file-1x}'); @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) { background-image: url('@{file-2x}'); background-size: @width-1x @height-1x; } } // Responsive image // // Keep images from scaling beyond the width of their parents. .img-responsive(@display: block) { display: @display; max-width: 100%; // Part 1: Set a maximum relative to the parent height: auto; // Part 2: Scale the height according to the width, otherwise you get stretching } // COMPONENT MIXINS // -------------------------------------------------- // Horizontal dividers // ------------------------- // Dividers (basically an hr) within dropdowns and nav lists .nav-divider(@color: #e5e5e5) { height: 1px; margin: @dropdown-divider-margin; overflow: hidden; background-color: @color; } // Panels // ------------------------- .panel-variant(@border; @heading-text-color; @heading-bg-color; @heading-border) { border-color: @border; & > .panel-heading { color: @heading-text-color; background-color: @heading-bg-color; border-color: @heading-border; + .panel-collapse .panel-body { border-top-color: @border; } } & > .panel-footer { + .panel-collapse .panel-body { border-bottom-color: @border; } } } // Alerts // ------------------------- .alert-variant(@background; @border; @text-color) { background-color: @background; border-color: @border; color: @text-color; hr { border-top-color: darken(@border, 5%); } .alert-link { color: darken(@text-color, 10%); } .alert-link-as-btn { display: inline-block; font-weight: bold; text-decoration: none; .btn-alert-variant(@background); .button-size( @padding-xs-vertical; @padding-small-horizontal; @font-size-small; @line-height-small; @btn-border-radius-small ); &:hover { text-decoration: none; } } small, .small { color: @text-color; } } .btn-alert-variant(@alert-bg) { .button-variant(#fff, shade(@alert-bg, 15%), transparent); border-radius: @btn-border-radius-base; } // Tables // ------------------------- .table-row-variant(@state; @background) { // Exact selectors below required to override `.table-striped` and prevent // inheritance to nested tables. .table > thead > tr, .table > tbody > tr, .table > tfoot > tr { > td.@{state}, > th.@{state}, &.@{state} > td, &.@{state} > th { background-color: @background; } } // Hover states for `.table-hover` // Note: this is not available for cells or rows within `thead` or `tfoot`. .table-hover > tbody > tr { > td.@{state}:hover, > th.@{state}:hover, &.@{state}:hover > td, &.@{state}:hover > th { background-color: darken(@background, 5%); } } } // List Groups // ------------------------- .list-group-item-variant(@state; @background; @color) { .list-group-item-@{state} { color: @color; background-color: @background; a& { color: @color; .list-group-item-heading { color: inherit; } &:hover, &:focus { color: @color; background-color: darken(@background, 5%); } &.active, &.active:hover, &.active:focus { color: #fff; background-color: @color; border-color: @color; } } } } // Button variants // ------------------------- // Easily pump out default styles, as well as :hover, :focus, :active, // and disabled options for all buttons .alert-btn(@background) { background-color: darken(@background, 16%); &:hover, &:focus, &:active, &.active, &.checked, .open .dropdown-toggle& { background-color: darken(@background, 24%); } } .button-variant(@color; @background; @border) { color: @color; background-color: @background; border-color: @border; .alert & { .alert-btn(@background); } &:hover, &:focus, &:active, &.active, &.checked, .open .dropdown-toggle& { color: @color; background-color: darken(@background, 8%); border-color: darken(@border, 12%); } &:active, &.active, .open .dropdown-toggle& { background-image: none; } &.disabled, &[disabled], fieldset[disabled] & { &, &:hover, &:focus, &:active, &.active { background-color: @background; border-color: @border; } } .badge { color: @background; background-color: @color; } } .button-outline-variant(@color) { color: @color; background-color: transparent; border-color: @color; .alert & { background-color: transparent; } &:hover, &:focus, &:active, &.active, &.checked, .open .dropdown-toggle& { color: @color; background-color: transparent; border-color: darken(@color, 12%); .alert & { background-color: transparent; } } &:active, &.active, .open .dropdown-toggle& { background-image: none; } &.disabled, &[disabled], fieldset[disabled] & { &, &:hover, &:focus, &:active, &.active { background-color: transparent; border-color: @color; } } .badge { color: transparent; background-color: @color; } } // Button sizes // ------------------------- .button-size(@padding-vertical; @padding-horizontal; @font-size; @line-height; @border-radius) { // Remove 1px to make up for the extra px of border-bottom we've added padding: @padding-vertical - 1 @padding-horizontal @padding-vertical; font-size: @font-size; line-height: @line-height; border-radius: @border-radius; } // Pagination // ------------------------- .pagination-size(@padding-vertical; @padding-horizontal; @font-size; @border-radius) { > li { > a, > span { padding: @padding-vertical @padding-horizontal; font-size: @font-size; } &:first-child { > a, > span { .border-left-radius(@border-radius); } } &:last-child { > a, > span { .border-right-radius(@border-radius); } } } } // Labels // ------------------------- .label-variant(@color) { background-color: @color; &[href] { &:hover, &:focus { background-color: darken(@color, 10%); } } } // Contextual backgrounds // ------------------------- .bg-variant(@color) { background-color: @color; a&:hover { background-color: darken(@color, 10%); } } // Typography // ------------------------- .text-emphasis-variant(@color) { color: @color; a&:hover { color: darken(@color, 10%); } } // Navbar vertical align // ------------------------- // Vertically center elements in the navbar. // Example: an element has a height of 30px, so write out `.navbar-vertical-align(30px);` to calculate the appropriate top margin. .navbar-vertical-align(@element-height) { margin-top: ((@navbar-height - @element-height) / 2); margin-bottom: ((@navbar-height - @element-height) / 2); } // Progress bars // ------------------------- .progress-bar-variant(@color) { background-color: @color; .progress-striped & { #gradient > .striped(); } } // Responsive utilities // ------------------------- // More easily include all the states for responsive-utilities.less. .responsive-visibility() { display: block !important; table& { display: table; } tr& { display: table-row !important; } th&, td& { display: table-cell !important; } } .responsive-invisibility() { display: none !important; } // Grid System // ----------- // Centered container element .container-fixed() { margin-right: auto; margin-left: auto; padding-left: (@grid-gutter-width / 2); padding-right: (@grid-gutter-width / 2); &:extend(.clearfix all); } // Creates a wrapper for a series of columns .make-row(@gutter: @grid-gutter-width) { margin-left: (@gutter / -2); margin-right: (@gutter / -2); &:extend(.clearfix all); } // Generate the extra small columns .make-xs-column(@columns; @gutter: @grid-gutter-width) { position: relative; float: left; width: percentage((@columns / @grid-columns)); min-height: 1px; padding-left: (@gutter / 2); padding-right: (@gutter / 2); } .make-xs-column-offset(@columns) { @media (min-width: @screen-xs-min) { margin-left: percentage((@columns / @grid-columns)); } } .make-xs-column-push(@columns) { @media (min-width: @screen-xs-min) { left: percentage((@columns / @grid-columns)); } } .make-xs-column-pull(@columns) { @media (min-width: @screen-xs-min) { right: percentage((@columns / @grid-columns)); } } // Generate the small columns .make-sm-column(@columns; @gutter: @grid-gutter-width) { position: relative; min-height: 1px; padding-left: (@gutter / 2); padding-right: (@gutter / 2); @media (min-width: @screen-sm-min) { float: left; width: percentage((@columns / @grid-columns)); } } .make-sm-column-offset(@columns) { @media (min-width: @screen-sm-min) { margin-left: percentage((@columns / @grid-columns)); } } .make-sm-column-push(@columns) { @media (min-width: @screen-sm-min) { left: percentage((@columns / @grid-columns)); } } .make-sm-column-pull(@columns) { @media (min-width: @screen-sm-min) { right: percentage((@columns / @grid-columns)); } } // Generate the medium columns .make-md-column(@columns; @gutter: @grid-gutter-width) { position: relative; min-height: 1px; padding-left: (@gutter / 2); padding-right: (@gutter / 2); @media (min-width: @screen-md-min) { float: left; width: percentage((@columns / @grid-columns)); } } .make-md-column-offset(@columns) { @media (min-width: @screen-md-min) { margin-left: percentage((@columns / @grid-columns)); } } .make-md-column-push(@columns) { @media (min-width: @screen-md-min) { left: percentage((@columns / @grid-columns)); } } .make-md-column-pull(@columns) { @media (min-width: @screen-md-min) { right: percentage((@columns / @grid-columns)); } } // Generate the large columns .make-lg-column(@columns; @gutter: @grid-gutter-width) { position: relative; min-height: 1px; padding-left: (@gutter / 2); padding-right: (@gutter / 2); @media (min-width: @screen-lg-min) { float: left; width: percentage((@columns / @grid-columns)); } } .make-lg-column-offset(@columns) { @media (min-width: @screen-lg-min) { margin-left: percentage((@columns / @grid-columns)); } } .make-lg-column-push(@columns) { @media (min-width: @screen-lg-min) { left: percentage((@columns / @grid-columns)); } } .make-lg-column-pull(@columns) { @media (min-width: @screen-lg-min) { right: percentage((@columns / @grid-columns)); } } // Framework grid generation // // Used only by Bootstrap to generate the correct number of grid classes given // any value of `@grid-columns`. .make-grid-columns() { // Common styles for all sizes of grid columns, widths 1-12 .col(@index) when (@index = 1) { // initial @item: ~'.col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}'; .col((@index + 1), @item); } .col(@index, @list) when (@index =< @grid-columns) { // general; "=<" isn't a typo @item: ~'.col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}'; .col((@index + 1), ~'@{list}, @{item}'); } .col(@index, @list) when (@index > @grid-columns) { // terminal @{list} { position: relative; // Prevent columns from collapsing when empty min-height: 1px; // Inner gutter via padding padding-left: (@grid-gutter-width / 2); padding-right: (@grid-gutter-width / 2); } } .col(1); // kickstart it } .float-grid-columns(@class) { .col(@index) when (@index = 1) { // initial @item: ~'.col-@{class}-@{index}'; .col((@index + 1), @item); } .col(@index, @list) when (@index =< @grid-columns) { // general @item: ~'.col-@{class}-@{index}'; .col((@index + 1), ~'@{list}, @{item}'); } .col(@index, @list) when (@index > @grid-columns) { // terminal @{list} { float: left; } } .col(1); // kickstart it } .calc-grid-column(@index, @class, @type) when (@type = width) and (@index > 0) { .col-@{class}-@{index} { width: percentage((@index / @grid-columns)); } } .calc-grid-column(@index, @class, @type) when (@type = push) { .col-@{class}-push-@{index} { left: percentage((@index / @grid-columns)); } } .calc-grid-column(@index, @class, @type) when (@type = pull) { .col-@{class}-pull-@{index} { right: percentage((@index / @grid-columns)); } } .calc-grid-column(@index, @class, @type) when (@type = offset) { .col-@{class}-offset-@{index} { margin-left: percentage((@index / @grid-columns)); } } // Basic looping in LESS .loop-grid-columns(@index, @class, @type) when (@index >= 0) { .calc-grid-column(@index, @class, @type); // next iteration .loop-grid-columns((@index - 1), @class, @type); } // Create grid for specific class .make-grid(@class) { .float-grid-columns(@class); .loop-grid-columns(@grid-columns, @class, width); .loop-grid-columns(@grid-columns, @class, pull); .loop-grid-columns(@grid-columns, @class, push); .loop-grid-columns(@grid-columns, @class, offset); } // Form validation states // // Used in forms.less to generate the form validation CSS for warnings, errors, // and successes. .form-control-validation(@text-color: #555; @border-color: #ccc; @background-color: #f5f5f5) { // Color the label and help text .help-block, .control-label, .radio, .checkbox, .radio-inline, .checkbox-inline { color: @text-color; } // Set the border and box shadow on specific inputs to match .form-control { border-color: @border-color; .box-shadow( inset 0 1px 1px rgba(0, 0, 0, 0.075) ); // Redeclare so transitions work &:focus { border-color: darken(@border-color, 10%); @shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px lighten(@border-color, 20%); .box-shadow(@shadow); } } // Set validation states also for addons .input-group-addon { color: @text-color; border-color: @border-color; background-color: @background-color; } // Optional feedback icon .form-control-feedback { color: @text-color; } } // Form control focus state // // Generate a customized focus state and for any input with the specified color, // which defaults to the `@input-focus-border` variable. // // We highly encourage you to not customize the default value, but instead use // this to tweak colors on an as-needed basis. This aesthetic change is based on // WebKit's default styles, but applicable to a wider range of browsers. Its // usability and accessibility should be taken into account with any change. // // Example usage: change the default blue border and shadow to white for better // contrast against a dark gray background. .form-control-focus(@color: @input-border-focus) { @color-rgba: rgba(red(@color), green(@color), blue(@color), 0.6); &:focus { border-color: @color; outline: 0; .box-shadow(~'inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px @{color-rgba}'); } } // Form control sizing // // Relative text size, padding, and border-radii changes for form controls. For // horizontal sizing, wrap controls in the predefined grid classes. `<select>` // element gets special love because it's special, and that's a fact! .input-size(@input-height; @padding-vertical; @padding-horizontal; @font-size; @line-height; @border-radius) { height: @input-height; padding: @padding-vertical @padding-horizontal; font-size: @font-size; line-height: @line-height; border-radius: @border-radius; select& { height: @input-height; line-height: @input-height; } textarea&, select[multiple]& { height: auto; } } .triangle(@_, @width, @height, @color) { position: absolute; border-color: transparent; border-style: solid; width: 0; height: 0; } .triangle(top, @width, @height, @color) { border-width: 0 @width / 2 @height @width / 2; border-bottom-color: @color; border-left-color: transparent; border-right-color: transparent; } .triangle(bottom, @width, @height, @color) { border-width: @height @width / 2 0 @width / 2; border-top-color: @color; border-left-color: transparent; border-right-color: transparent; } .triangle(right, @width, @height, @color) { border-width: @height / 2 0 @height / 2 @width; border-left-color: @color; border-top-color: transparent; border-bottom-color: transparent; } .triangle(left, @width, @height, @color) { border-width: @height / 2 @width @height / 2 0; border-right-color: @color; border-top-color: transparent; border-bottom-color: transparent; } .no-outline-ring-on-click { &:focus, &:focus:active { outline: 0; } }
overleaf/web/frontend/stylesheets/core/mixins.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/core/mixins.less", "repo_id": "overleaf", "token_count": 11379 }
550
.plv-annotations-layer { position: absolute; top: 0; left: 0; right: 0; bottom: 0; overflow: hidden; pointer-events: none; } .plv-annotations-layer > a { display: block; position: absolute; pointer-events: auto; }
overleaf/web/frontend/stylesheets/vendor/pdfListView/AnnotationsLayer.css/0
{ "file_path": "overleaf/web/frontend/stylesheets/vendor/pdfListView/AnnotationsLayer.css", "repo_id": "overleaf", "token_count": 90 }
551
{ "trash": "Cestino", "git": "Git", "yes_please": "Sì, grazie!", "ill_take_it": "Mi va bene!", "cancel_your_subscription": "Elimina il tuo account", "no_thanks_cancel_now": "No, grazie - Voglio ancora annullare", "cancel_my_account": "Elimina il mio account", "sure_you_want_to_cancel": "Sei sicuro di voler eliminare?", "i_want_to_stay": "Voglio rimanere", "have_more_days_to_try": "Hai altri <strong>__days__ giorni</strong> nel tuo Trial!", "interested_in_cheaper_plan": "Saresti interessato nel piano economico da <strong>__price__</strong> per studenti?", "session_expired_redirecting_to_login": "Sessione scaduta. Redirezione alla pagina di login fra __seconds__ secondi", "maximum_files_uploaded_together": "Massimo __max__ file caricati insieme", "too_many_files_uploaded_throttled_short_period": "Troppi file caricati, i tuoi caricamenti sono stati limitati per un breve periodo.", "compile_larger_projects": "Compila progetti più grandi", "upgrade_to_get_feature": "Esegui l'upgrade per avere __feature__, oltre a:", "new_group": "Nuovo Gruppo", "about_to_delete_groups": "Stai per cancellare i seguenti gruppi:", "removing": "Rimozione", "adding": "Aggiunta", "groups": "Gruppi", "rename_group": "Rinomina Gruppo", "renaming": "Ridenominazione", "create_group": "Crea Gruppo", "delete_group": "Elimina Gruppo", "delete_groups": "Elimina Gruppi", "your_groups": "I Tuoi Gruppi", "group_name": "Nome Gruppo", "no_groups": "Nessun Gruppo", "Subscription": "Iscrizione", "Documentation": "Documentazione", "Universities": "Università", "Account Settings": "Impostazioni Account", "Projects": "Progetti", "Account": "Account", "global": "globale", "Terms": "Termini", "Security": "Sicurezza", "About": "About", "editor_disconected_click_to_reconnect": "Editor disconnesso, clicca in qualsiasi punto per riconnettere.", "word_count": "Conteggio Parole", "please_compile_pdf_before_word_count": "Per favore, compila il tuo progetto prima di eseguire il conteggio parole", "total_words": "Parole Totali", "headers": "Intestazioni", "math_inline": "Formule In Linea", "math_display": "Formule Mostrate", "connected_users": "Utenti collegati", "projects": "Progetti", "upload_project": "Carica Progetto", "all_projects": "Tutti i progetti", "your_projects": "Tuoi Progetti", "shared_with_you": "Condiviso con te", "deleted_projects": "Progetti Eliminati", "templates": "Modelli", "new_folder": "Nuova Cartella", "create_your_first_project": "Crea il tuo primo progetto!", "complete": "Completo", "on_free_sl": "Stai utilizzando la versione gratuita di __appName__", "upgrade": "Upgrade", "or_unlock_features_bonus": "o sblocca alcune funzionalità bonus", "sharing_sl": "condividendo __appName__", "add_to_folder": "Aggiungi a cartella", "create_new_folder": "Crea Nuova Cartella", "more": "Più", "rename": "Rinomina", "make_copy": "Crea una copia", "restore": "Ripristina", "title": "Titolo", "last_modified": "Ultima Modifica", "no_projects": "Nessun progetto", "welcome_to_sl": "Benvenuto a __appName__!", "new_to_latex_look_at": "Nuovo in LaTeX? Inizia dando uno sguardo al nostro", "or": "o", "or_create_project_left": "o crea il tuo primo progetto a sinistra.", "thanks_settings_updated": "Grazie, le tue impostazioni sono state aggiornate.", "update_account_info": "Aggiorna Info Account", "must_be_email_address": "Deve essere un indirizzo email", "first_name": "Nome", "last_name": "Cognome", "update": "Aggiorna", "change_password": "Cambia Password", "current_password": "Password Attuale", "new_password": "Nuova Password", "confirm_new_password": "Conferma Nuova Password", "required": "richiesto", "doesnt_match": "Non corrisponde", "dropbox_integration": "Integrazione Dropbox", "learn_more": "Scopri di più", "dropbox_is_premium": "La sincronizzazione Dropbox è una funzionalità premium", "account_is_linked": "L'account è collegato", "unlink_dropbox": "Scollega Dropbox", "link_to_dropbox": "Collega a Dropbox", "newsletter_info_and_unsubscribe": "A intervalli di qualche mese inviamo una newsletter che ricapitola le nuove funzionalità disponibili. Se preferisci non ricevere questa email puoi cancellarti in ogni momento:", "unsubscribed": "Cancellato", "unsubscribing": "Cancellando", "unsubscribe": "Cancellati", "need_to_leave": "Vuoi andare via?", "delete_your_account": "Elimina il tuo account", "delete_account": "Elimina Account", "delete_account_warning_message": "Stai per <strong>eliminare per sempre tutti i tuoi dati</strong>, inclusi progetti e impostazioni. Per favore scrivi DELETE nel box sottostante per procedere.", "deleting": "Eliminando", "delete": "Elimina", "sl_benefits_plans": "__appName__ è l'editor più facile del mondo per usare LaTeX. Rimani aggiornato con i tuoi collaboratori, tieni traccia di tutti i cambiamenti al tuo lavoro, e usa il nostro ambiente LaTeX da qualsiasi parte nel mondo.", "monthly": "Mensile", "personal": "Personale", "free": "Gratis", "one_collaborator": "Solo un collaboratore", "collaborator": "Collaboratore", "collabs_per_proj": "__collabcount__ collaboratori per progetto", "full_doc_history": "Storia completa del documento", "sync_to_dropbox": "Sincronizzazione con Dropbox", "start_free_trial": "Inizia Trial Gratuito!", "professional": "Professionale", "unlimited_collabs": "Collaboratori illimitati", "name": "Nome", "student": "Studente", "university": "Università", "position": "Posizione", "choose_plan_works_for_you": "Scegli il piano che più gradisci con il nostro trial gratuito di __len__ giorni. Puoi annullare in ogni momento.", "interested_in_group_licence": "Interessato ad utilizzare __appName__ in un account di gruppo, team o dipartimento?", "get_in_touch_for_details": "Contattaci per i dettagli!", "group_plan_enquiry": "Richiesta di Piano di Gruppo", "enjoy_these_features": "Goditi tutte queste funzionalità gratuite", "create_unlimited_projects": "Crea tutti i progetti di cui hai bisogno.", "never_loose_work": "Non perdere mai niente, ci pensiamo noi.", "access_projects_anywhere": "Accedi ai tuoi progetti da ovunque.", "log_in": "Entra", "login": "Entra", "logging_in": "Entrata in corso", "forgot_your_password": "Password dimenticata", "password_reset": "Reimposta la Password", "password_reset_email_sent": "Ti abbiamo inviato una email per completare il reset della password.", "please_enter_email": "Per favore inserisci il tuo indirizzo email", "request_password_reset": "Richiedi reset della password", "reset_your_password": "Reimposta la tua password", "password_has_been_reset": "La tua password è stata reimpostata", "login_here": "Entra qui", "set_new_password": "Imposta nuova password", "user_wants_you_to_see_project": "__username__ vorrebbe che tu vedessi __projectname__", "join_sl_to_view_project": "Unisciti a __appName__ per vedere questo progetto", "register_to_edit_template": "Per favore registrati per modificare il modello __templateName__", "already_have_sl_account": "Hai già un account __appName__?", "register": "Registrati", "password": "Password", "registering": "Registrazione in corso", "planned_maintenance": "Manutenzione Pianificata", "no_planned_maintenance": "Non c'è nessuna manutenzione correntemente pianificata", "cant_find_page": "Spiacenti, non riusciamo a trovare la pagina che stai cercando.", "take_me_home": "Portami nella home!", "no_preview_available": "Spiacenti, non è disponibile nessuna anteprima.", "no_messages": "Nessun messaggio", "send_first_message": "Invia il tuo primo messaggio", "account_not_linked_to_dropbox": "Il tuo account non è collegato a Dropbox", "update_dropbox_settings": "Aggiorna Impostazioni Dropbox", "refresh_page_after_starting_free_trial": "Per favore aggiorna questa pagina dopo l'inizio del tuo trial gratuito.", "checking_dropbox_status": "controllando lo stato di Dropbox", "dismiss": "Rimuovi", "new_file": "Nuovo File", "upload_file": "Carica File", "create": "Crea", "creating": "Creazione", "upload_files": "Carica File(s)", "sure_you_want_to_delete": "Sei sicuro di voler eliminare per sempre <strong>&#123;&#123; entity.name &#125;&#125;</strong>?", "common": "Comune", "navigation": "Navigazione", "editing": "Modifica", "ok": "OK", "source": "Sorgente", "actions": "Azioni", "copy_project": "Copia Progetto", "publish_as_template": "Pubblica come Modello", "sync": "Sincronizza", "settings": "Impostazioni", "main_document": "Documento principale", "off": "Off", "auto_complete": "Auto-completamento", "theme": "Tema", "font_size": "Grandezza Font", "pdf_viewer": "Visualizzatore PDF", "built_in": "Built-In", "native": "nativo", "show_hotkeys": "Mostra Hotkeys", "new_name": "Nuovo Nome", "copying": "copia in corso", "copy": "Copia", "compiling": "Compilazione", "click_here_to_preview_pdf": "Clicca qui per visualizzare un'anteprima del tuo lavoro in PDF.", "server_error": "Errore Server", "somthing_went_wrong_compiling": "Spiacenti, qualcosa è andato storto e il tuo progetto non è stato compilato. Si prega di riprovare fra qualche momento.", "timedout": "Errore di time out", "proj_timed_out_reason": "Spiacenti, la tua compilazione ha impiegato troppo tempo. Ciò potrebbe essere dovuto ad un elevato numero di immagini ad alta risoluzione, o a molti diagrammi complicati.", "no_errors_good_job": "Nessun errore, bel lavoro!", "compile_error": "Errore di Compilazione", "generic_failed_compile_message": "Spiancenti, il tuo codice LaTeX non ha potuto essere compilato per qualche ragione. Per favore controlla qui sotto gli errori per i dettagli, o visualizza il log completo", "other_logs_and_files": "Altri log &amp; file", "view_raw_logs": "Visualizza Log Completi", "hide_raw_logs": "Nascondi Log Completi", "clear_cache": "Pulisci cache", "clear_cache_explanation": "Questo cancellerà tutti i file LaTeX nascosti (.aux, .bbl, ecc) dal nostro server per le compilazioni. In genere non hai bisogno di fare ciò a meno che non hai problemi con dei riferimenti.", "clear_cache_is_safe": "I file del tuo progetto non saranno eliminati o modificati.", "clearing": "Pulizia in corso", "template_description": "Descrizione del Modello", "project_last_published_at": "Il tuo progetto è stato pubblicato l'ultima volta alle", "problem_talking_to_publishing_service": "C'è un problema con il nostro servizio di pubblicazione, si prega di riprovare fra qualche minuto", "unpublishing": "Rimozione pubblicazione", "republish": "Ri-pubblica", "publishing": "Pubblicazione", "share_project": "Condividi Progetto", "this_project_is_private": "Questo progetto è privato e può essere acceduto solo dalle persone qui sotto.", "make_public": "Rendi Pubblico", "this_project_is_public": "Questo progetto è pubblico e può essere modificato da chiunque con la URL.", "make_private": "Rendi Privato", "can_edit": "Può Modificare", "share_with_your_collabs": "Condividi con i tuoi collaboratori", "share": "Condividi", "need_to_upgrade_for_more_collabs": "Devi eseguire l'upgrade dell'account per aggiungere più collaboratori", "make_project_public": "Rendi progetto pubblico", "make_project_public_consequences": "Se rendi il tuo progetto pubblico chiunque possieda la URL potrà accedervi.", "allow_public_editing": "Permetti modifica pubblica", "allow_public_read_only": "Permetti accesso pubblico in sola lettura", "make_project_private": "Rendi progetto privato", "make_project_private_consequences": "Se rendi il tuo progetto privato solo le persone con cui scegli di condividerlo potranno avere accesso.", "need_to_upgrade_for_history": "Devi eseguire l'upgrade dell'account per utilizzare la funzionalità della storia.", "ask_proj_owner_to_upgrade_for_history": "Per favore chiedi al proprietario del progetto di eseguire l'upgrade per poter utilizzare la funzionalità della storia.", "anonymous": "Anonimo", "generic_something_went_wrong": "Spiacenti, qualcosa è andato storto :(", "restoring": "Ripristinando", "restore_to_before_these_changes": "Ripristina prima di queste modifiche", "profile_complete_percentage": "Il tuo profilo è completo al __percentval__%", "file_has_been_deleted": "__filename__ è stato eliminato", "sure_you_want_to_restore_before": "Sei sicuro di voler ripristinare <0>__filename__</0> a prima delle modifiche del __date__?", "rename_project": "Rinomina Progetto", "about_to_delete_projects": "Stai per eliminare i seguenti progetti:", "about_to_leave_projects": "Stai per abbandonare i seguenti progetti:", "upload_zipped_project": "Carica Progetto Zip", "upload_a_zipped_project": "Carica un progetto zippato", "your_profile": "Tuo Profilo", "institution": "Istituzione", "role": "Ruolo", "folders": "Cartelle", "disconnected": "Disconnesso", "please_refresh": "Per favore, aggiorna la pagina per continuare.", "lost_connection": "Connessione Persa", "reconnecting_in_x_secs": "Riconnessione fra __seconds__ secondi", "try_now": "Prova Ora", "reconnecting": "Riconnessione", "saving_notification_with_seconds": "Salvataggio in corso di __docname__... (__seconds__ secondi di modifiche non salvate)", "help_us_spread_word": "Aiutaci a spargere la voce su __appName__", "share_sl_to_get_rewards": "Condividi __appName__ con amici e colleghi e sblocca i premi qui sotto", "post_on_facebook": "Condividi su Facebook", "share_us_on_googleplus": "Condividi su Google+", "email_us_to_your_friends": "Invia una email ai tuoi amici", "link_to_us": "Crea un collegamento dal tuo sito web", "direct_link": "Link Diretto", "sl_gives_you_free_stuff_see_progress_below": "Quando qualcuno inizia a usare __appName__ sotto tuo consiglio ti daremo <strong>funzionalità gratuite</strong> come ringraziamento! Controlla qui sotto i tuoi progressi.", "spread_the_word_and_fill_bar": "Spargi la voce e riempi questa barra", "one_free_collab": "Un collaboratore gratuito", "three_free_collab": "Tre collaboratori gratuiti", "free_dropbox_and_history": "Dropbox e storia gratuita", "you_not_introed_anyone_to_sl": "Non hai ancora presentato __appName__ a nessuno. Inizia a condividere!", "you_introed_small_number": " Hai presentato __appName__ a <0>__numberOfPeople__</0>. Bel lavoro, ma puoi trovarne altre?", "you_introed_high_number": " Hai presentato __appName__ a <0>__numberOfPeople__</0>. Bel lavoro!", "link_to_sl": "Collega a __appName__", "can_link_to_sl_with_html": "Puoi collegare a __appName__ con il seguente HTML:", "year": "anno", "month": "mese", "subscribe_to_this_plan": "Abbonati a questo piano", "your_plan": "Il tuo piano", "your_subscription": "Il tuo abbonamento", "on_free_trial_expiring_at": "Stai attualmente usando una versione di prova gratuita che scade il __expiresAt__.", "choose_a_plan_below": "Scegli uno dei piani qui sotto a cui abbonarti.", "currently_subscribed_to_plan": "Sei attualmente abbonato al piano <0>__planName__</0>.", "change_plan": "Modifica piano", "next_payment_of_x_collectected_on_y": "Il prossimo pagamento di <0>__paymentAmmount__</0> sarà riscosso il <1>__collectionDate__</1>", "update_your_billing_details": "Aggiorna Dettagli di Pagamento", "subscription_canceled_and_terminate_on_x": " Il tuo abbonamento è stato annullato e terminerà il <0>__terminateDate__</0>. Non saranno addebitati ulteriori costi.", "your_subscription_has_expired": "Il tuo abbonamento è scaduto.", "create_new_subscription": "Crea Nuovo Abbonamento", "problem_with_subscription_contact_us": "C'è un problema con il tuo abbonamento. Ti preghiamo di contattarci per altre informazioni.", "manage_group": "Gestisci Gruppo", "loading_billing_form": "Caricamento dettagli di addebito", "you_have_added_x_of_group_size_y": "Hai aggiunto <0>__addedUsersSize__</0> membri su <1>__groupSize__</1> disponibili.", "remove_from_group": "Rimuovi da gruppo", "group_account": "Account di Gruppo", "registered": "Registrato", "no_members": "Nessun membro", "add_more_members": "Aggiungi membri", "add": "Aggiungi", "thanks_for_subscribing": "Grazie per esserti abbonato!", "your_card_will_be_charged_soon": "La tua carta verrà addebitata a breve.", "if_you_dont_want_to_be_charged": "Se non vuoi altri addebiti ", "add_your_first_group_member_now": "Aggiungi ora i primi membri del gruppo", "thanks_for_subscribing_you_help_sl": "Grazie per esserti abbonato al piano __planName__. E' il supporto di persone come te che permettono a __appName__ di continuare a crescere e migliorare.", "back_to_your_projects": "Indietro ai tuoi progetti", "goes_straight_to_our_inboxes": "Finirà direttamente a entrambe le nostre email", "need_anything_contact_us_at": "Per qualsiasi bisogno puoi contattarci direttamente al", "regards": "Saluti", "about": "About", "comment": "Commento", "restricted_no_permission": "Vietato, ci dispiace ma non hai i permessi per caricare questa pagina.", "online_latex_editor": "Editor LaTeX online", "meet_team_behind_latex_editor": "Ecco il team che lavora al tuo editor LaTeX preferito.", "follow_me_on_twitter": "Seguimi su Twitter", "motivation": "Motivazione", "evolved": "Evoluto", "the_easy_online_collab_latex_editor": "L'editor LaTeX facile da usare, online, collaborativo", "get_started_now": "Inizia adesso", "sl_used_over_x_people_at": "__appName__ è utilizzato da più di __numberOfUsers__ studenti e accademici a:", "collaboration": "Collaborazione", "work_on_single_version": "Lavorate insieme su una singola versione", "view_collab_edits": "Visualizza le modifiche altrui ", "ease_of_use": " Facilità d'Uso", "no_complicated_latex_install": "Nessuna complicata installazione LaTeX", "all_packages_and_templates": "Tutti i pacchetti e <0>__templatesLink__</0> di cui hai bisogno", "document_history": "Storia dei documenti", "see_what_has_been": "Guarda cosa è stato ", "added": "aggiunto", "and": "e", "removed": "rimosso", "restore_to_any_older_version": "Ripristina a una versione precedente", "work_from_anywhere": "Lavora da ovunque", "acces_work_from_anywhere": "Accedi al tuo lavoro da qualsiasi parte del mondo", "work_offline_and_sync_with_dropbox": "Lavora offline e sincronizza i tuoi file da Dropbox e GitHub", "over": "su", "view_templates": "Visualizza modelli", "nothing_to_install_ready_to_go": "Non c'è niente di complicato o difficile da installare, e puoi <0>__start_now__</0>, anche se non l'hai mai visto prima. __appName__ è un ambiente LaTeX completo e pronto che viene eseguito sui nostri server.", "start_using_latex_now": "iniziare a usare LaTeX da subito", "get_same_latex_setup": "Con __appName__ hai le stesse impostazioni LaTeX dovunque tu sia. Lavorando con i tuoi colleghi e studenti su __appName__, sai che non avrai nessuna inconsistenza fra versioni o conflitti fra pacchetti.", "support_lots_of_features": "Supportiamo quasi tutte le funzionalità di LaTeX, inclusa l'aggiunta di immagini, bibliografie, equazioni e molto altro! Leggi di tutto ciò che puoi fare con __appName__ nelle nostre <0>__help_guides_link__</0>", "latex_guides": "guide a LaTeX", "reset_password": "Ripristino Password", "set_password": "Imposta Password", "updating_site": "Aggiornamento del Sito", "bonus_please_recommend_us": "Bonus - Per favore raccomandaci", "admin": "admin", "subscribe": "Abbonati", "update_billing_details": "Aggiorna Dettagli Pagamento", "group_admin": "Amministratore Gruppo", "all_templates": "Tutti i Modelli", "your_settings": "Tue impostazioni", "maintenance": "Manutenzione", "to_many_login_requests_2_mins": "Questo account ha ricevuto troppe richieste di login. Per favore, attendi 2 minuti prima di riprovare ad entrare", "email_or_password_wrong_try_again": "La tua email o password è errata.", "rate_limit_hit_wait": "Raggiunto limite massimo. Per favore, attendi un po' prima di riprovare", "problem_changing_email_address": "C'è stato un problema durante la modifica del tuo indirizzo email. Per favore, riprova fra qualche momento. Se il problema persiste non esitare a contattarci.", "single_version_easy_collab_blurb": "__appName__ fa sì che tu sia sempre aggiornato con i tuoi collaboratori e con ciò che fanno. Esiste una sola versione principale di ogni documento a cui ognuno ha accesso. E' impossibile fare modifiche conflittuali, e non dovrai aspettare che i tuoi colleghi ti inviino le ultime bozze prima che tu possa continuare a lavorare.", "can_see_collabs_type_blurb": "Non c'è problema se più persone vogliono lavorare su uno stesso documento in uno stesso momento. Puoi vedere dove i tuoi colleghi stanno scrivendo direttamente nell'editor, e le loro modifiche vengono mostrate immediatamente sul tuo schermo.", "work_directly_with_collabs": "Lavora direttamente con i tuoi collaboratori", "work_with_word_users": "Lavora con utenti Word", "work_with_word_users_blurb": "E' così facile iniziare con __appName__ che potrai invitare i tuoi colleghi che non usano LaTeX affinché contribuiscano direttamente ai tuoi documenti. Saranno produttivi dal primo giorno e potranno imparare un po' di LaTeX man mano che procedono.", "view_which_changes": "Visualizza quali modifiche sono state", "sl_included_history_of_changes_blurb": "__appName__ include una storia di tutte le tue modifiche così che tu possa esattamente vedere chi ha modificato cosa, e quando. Questo rende estremamente facile mantenersi aggiornati con tutti i progressi fatti dai tuoi collaboratori e permette di revisionare gli ultimi lavori.", "can_revert_back_blurb": "Sia in collaborazione che in proprio, si possono fare errori. Ritornare a versioni precedenti è semplice e rimuove il rischio di perdere lavoro o rimpiangere una modifica.", "start_using_sl_now": "Inizia a usare __appName__ adesso", "over_x_templates_easy_getting_started": "Esistono __over__ 400 __templates__ nella nostra galleria di modelli, ed è quindi molto facile iniziare, sia che tu stia scrivendo un articolo, una tesi, un CV o qualcos altro.", "done": "Fatto", "change": "Cambia", "page_not_found": "Pagina Non Trovata", "please_see_help_for_more_info": "Per favore, leggi la nostra guida di aiuto per più informazioni", "this_project_will_appear_in_your_dropbox_folder_at": "Questo progetto apparirà nella tua cartella Dropbox in ", "member_of_group_subscription": "Sei un membro di un abbonamento di gruppo gestito da __admin_email__. Per favore contattalo/la per gestire il tuo abbonamento. \n", "about_henry_oswald": "è un software engineer che vive a Londra. Ha costruito il prototipo originale di __appName__ ed è stato responsabile della realizzazione di una piattaforma stabile e scalabile. Henry è un forte sostenitore del Test Driven Development e fa in modo tale da mantenere il codice di __appName__ pulito e facile da manutenere.", "about_james_allen": "ha un PhD in fisica teorica ed è appassionato di LaTeX. Ha creato uno dei primi editor LaTeX online, ScribTeX, e ha preso parte nello sviluppo delle tecnologie che hanno reso possibile __appName__.", "two_strong_principles_behind_sl": "Ci sono due forti principi dietro il nostro lavoro con __appName__:", "want_to_improve_workflow_of_as_many_people_as_possible": "Vogliamo migliorare il lavoro del maggior numero possibile di persone.", "detail_on_improve_peoples_workflow": "LaTeX è notoriamente difficile da utilizzare, e la collaborazione è sempre difficile da coordinare. Crediamo di aver sviluppato delle importanti soluzioni per aiutare le persone che affrontano questi problemi, e vogliamo essere sicuri che __appName__ sia accessibile al maggior numero possibile di utenti. Abbiamo tentato di mantenere i nostri prezzi bassi, e abbiamo rilasciato gran parte di __appName__ come open source, così che ognuno possa eseguirlo su un proprio host.", "want_to_create_sustainable_lasting_legacy": "Vogliamo creare un lascito sostenibile e duraturo.", "details_on_legacy": "Lo sviluppo e la manutenzione di un prodotto come __appName__ richiedono molto tempo e lavoro, ed è quindi importante poter trovare un modello di business che supporti tutto ciò, sia adesso che nel lungo termine. Non vogliamo che __appName__ dipenda da finanziamenti esterni o che scompaia a causa di un modello di business fallimentare. Sono contento nel dire che, al momento, siamo in grado di gestire __appName__ in maniera profittevole e sostenibile, e ci aspettiamo di continuare a far questo nel lungo termine.", "get_in_touch": "Contattaci", "want_to_hear_from_you_email_us_at": "Ci piacerebbe parlare di __appName__ o di ciò che facciamo con chiunque utilizzi __appName__. Puoi contattarci a ", "cant_find_email": "Spiacenti, quell'indirizzo email non è registrato.", "plans_amper_pricing": "Piani &amp; Costi", "documentation": "Documentazione", "account": "Account", "subscription": "Abbonamento", "log_out": "Log Out", "en": "Inglese", "pt": "Portoghese", "es": "Spagnolo", "fr": "Francese", "de": "Tedesco", "it": "Italiano", "da": "Danese", "sv": "Svedese", "no": "Norvegese", "nl": "Olandese", "pl": "Polacco", "ru": "Russo", "uk": "Ucraino", "ro": "Rumeno", "click_here_to_view_sl_in_lng": "Clicca qui per usare __appName__ in <0>__lngName__</0>", "language": "Lingua", "upload": "Carica", "menu": "Menu", "full_screen": "Schermo intero", "logs_and_output_files": "Log e file di output", "download_pdf": "Scarica PDF", "split_screen": "Dividi schermo", "clear_cached_files": "Pulisci file in cache", "go_to_code_location_in_pdf": "Vai a riga in PDF", "please_compile_pdf_before_download": "Per favore, compila il progetto prima di scariare il PDF", "remove_collaborator": "Rimuovi collaboratore", "add_to_folders": "Aggiungi a cartelle", "download_zip_file": "Scarica file .zip", "price": "Costo", "close": "Chiudi", "keybindings": "Associazioni tasti", "restricted": "Limitato", "start_x_day_trial": "Inizia il Tuo Periodo di Prova Gratuita di __len__ Giorni Oggi!", "buy_now": "Compra Ora!", "cs": "Ceco", "view_all": "Visualizza Tutto", "terms": "Termini", "privacy": "Privacy", "contact": "Contatti", "change_to_this_plan": "Cambia a questo piano", "processing": "processamento", "sure_you_want_to_change_plan": "Sei sicuro di voler cambiare il piano a <0>__planName__</0>?", "move_to_annual_billing": "Cambia ad Addebitamento Annuale", "annual_billing_enabled": "Addebitamento annuale abilitato", "move_to_annual_billing_now": "Cambia ad addebitamento annuale subito", "change_to_annual_billing_and_save": "Ottieni uno sconto del <0>__percentage__</0> con l'addebitamento annuale. Se cambi adesso risparmierai <1>__yearlySaving__</1> all'anno.", "missing_template_question": "Modello Mancante?", "tell_us_about_the_template": "Se manca un modello puoi: Inviarci una copia del modello, un url __appName__ al modello, oppure puoi farci sapere dove possiamo trovarlo. Per favore, facci anche avere qualche informazione per la descrizione del modello.", "email_us": "Contatto email", "this_project_is_public_read_only": "Questo progetto è pubblico e può essere visualizzato, ma non modificato, da chiunque abbia la URL", "tr": "Turco", "select_files": "Seleziona file", "drag_files": "trascina file", "upload_failed_sorry": "Spiacenti, caricamento fallito :(", "inserting_files": "Inserimento del file...", "password_reset_token_expired": "Il tuo codice di password reset è scaduto. Per favore, richiedi una nuova password per email e segui il link che ti verrà fornito.", "merge_project_with_github": "Unisci Progetto con GitHub", "pull_github_changes_into_sharelatex": "Aggiorna da modifiche in GitHub verso __appName__", "push_sharelatex_changes_to_github": "Invia le modifiche __appName__ a GitHub", "features": "Caratteristiche", "commit": "Commit", "commiting": "Committing", "importing_and_merging_changes_in_github": "Importazione e unione modifiche in GitHub", "upgrade_for_faster_compiles": "Esegui l'upgrade per compilazioni più veloci e per aumentare il limite di timeout", "free_accounts_have_timeout_upgrade_to_increase": "Gli account gratuiti hanno un limite di timeout di un minuto. Esegui l'upgrade per aumentare il limite.", "learn_how_to_make_documents_compile_quickly": "Impara a rendere le tue compilazioni più veloci.", "zh-CN": "Cinese", "cn": "Cinese (Semplificato)", "sync_to_github": "Sincronizza con GitHub", "sync_to_dropbox_and_github": "Sincronizza con Dropbox e GitHub", "project_too_large": "Progetto troppo grande", "project_too_large_please_reduce": "Questo progetto contiene troppo testo, per favore prova a ridurlo.", "please_ask_the_project_owner_to_link_to_github": "Chiedi al proprietario del progetto di collegare questo progetto a un repository GitHub", "go_to_pdf_location_in_code": "Vai a locazione PDF in codice", "ko": "Coreano", "ja": "Giapponese", "about_brian_gough": "è uno sviluppatore software e un ex fisico teorico-energetico a Fermilab e a Los Alamos. Ha pubblicato per molti anni manuali software gratuiti scritti con TeX e LaTeX, ed è anche stato il manutentore della GNU Scientific Library.", "first_few_days_free": "Primi __trialLen__ giorni gratuiti", "every": "ogni", "credit_card": "Carta di Credito", "credit_card_number": "Numero Carta di Credito", "invalid": "Invalido", "expiry": "Data Scadenza", "january": "Gennaio", "february": "Febbraio", "march": "Marzo", "april": "Aprile", "may": "Maggio", "june": "Giugno", "july": "Luglio", "august": "Agosto", "september": "Settembre", "october": "Ottobre", "november": "Novembre", "december": "Dicembre", "zip_post_code": "CAP / Codice Postale", "city": "Città", "address": "Indirizzo", "coupon_code": "codice coupon", "country": "Nazione", "billing_address": "Indirizzo di Fatturazione", "upgrade_now": "Effettua l'Upgrade", "state": "Nazione", "vat_number": "Partita IVA", "you_have_joined": "Ti sei unito a __groupName__", "claim_premium_account": "Hai ottenuto un account premium fornito da __groupName__.", "you_are_invited_to_group": " Sei stato invitato ad unirti a __groupName__.", "you_can_claim_premium_account": "Puoi richiedere un account premium che sarà fornito da __groupName__ tramite verifica email", "not_now": "Non adesso", "verify_email_join_group": "Verifica email e unisciti al Gruppo", "check_email_to_complete_group": "Per favore, controlla la tua email per completare l'adesione al gruppo", "verify_email_address": "Verifica Indirizzo Email", "group_provides_you_with_premium_account": "__groupName__ ti fornisce un account premium. Verifica la tua email per eseguire l'upgrade del tuo account.", "check_email_to_complete_the_upgrade": "Per favore, controlla la tua email per completare l'upgrade", "email_link_expired": "Collegamento email scaduto, per favore richiedine un altro.", "services": "Servizi", "about_shane_kilkelly": "è uno sviluppatore software e vive a Edinburgo. Shane è un forte sostenitore di Programmazione Funzionale e Test Driven Development, e ci tiene molto a produrre software di qualità.", "this_is_your_template": "Questo è il template del tuo progetto", "links": "Link", "account_settings": "Impostazioni Account", "search_projects": "Cerca progetti", "clone_project": "Clona Progetto", "delete_project": "Elimina Progetto", "download_zip": "Scarica Zip", "new_project": "Nuovo Progetto", "blank_project": "Progetto Vuoto", "example_project": "Progetto di Esempio", "from_template": "Da Modello", "cv_or_resume": "CV o Resume", "cover_letter": "Lettera di Presentazione", "journal_article": "Articolo di Journal", "presentation": "Presentazione", "thesis": "Tesi", "bibliographies": "Bibliografie", "terms_of_service": "Termini di Servizio", "privacy_policy": "Privacy Policy", "plans_and_pricing": "Piani e Costi", "university_licences": "Licenze Universitarie", "security": "Sicurezza", "contact_us": "Contattaci", "thanks": "Grazie", "blog": "Blog", "latex_editor": "LaTeX Editor", "get_free_stuff": "Componenti gratuite", "chat": "Chat", "your_message": "Tuo Messaggio", "loading": "Caricamento", "connecting": "Connessione", "recompile": "Ricompila", "download": "Scarica", "email": "Email", "owner": "Proprietario", "read_and_write": "Leggi e Scrivi", "read_only": "Sola Lettura", "publish": "Pubblica", "view_in_template_gallery": "Visualizza nella galleria modelli", "unpublish": "De-pubblica", "hotkeys": "Scorciatoie", "saving": "Salvataggio", "cancel": "Annulla", "project_name": "Nome Progetto", "root_document": "Documento Radice", "spell_check": "Controllo Lingua", "compiler": "Compilatore", "private": "Privato", "public": "Pubblico", "delete_forever": "Elimina per sempre", "support_and_feedback": "Supporto e feedback", "help": "Aiuto", "latex_templates": "Modelli LaTeX", "info": "Info", "latex_help_guide": "Guida LaTeX", "choose_your_plan": "Scegli il tuo piano", "indvidual_plans": "Piani Individuali", "free_forever": "Gratis per sempre", "low_priority_compile": "Compilazione a bassa priorità", "unlimited_projects": "Progetti illimitati", "unlimited_compiles": "Compilazioni illimitate", "full_history_of_changes": "Storia completa delle modifiche", "highest_priority_compiling": "Compilazione a massima priorità", "dropbox_sync": "Sincronizzazione Dropbox", "beta": "Beta", "sign_up_now": "Registrati Ora", "annual": "Annuale", "half_price_student": "Piani a Metà Prezzo per Studenti", "about_us": "About Us", "loading_recent_github_commits": "Caricamento di commit recenti", "no_new_commits_in_github": "Nessun nuovo commit in GitHub dall'ultima unione.", "dropbox_sync_description": "Mantieni i tuoi progetti __appName__ in sincrono con il tuo Dropbox. Le modifiche in __appName__ saranno automaticamente inviate nel tuo Dropbox, e viceversa.", "github_sync_description": "Con GitHub Sync puoi collegare i tuoi progetti __appName__ a repository GitHub. Crea nuovi commit da __appName__ e unisci con commit fatti offline o su GitHub.", "github_import_description": "Con GitHub Sync puoi importare i tuoi repository GitHub in __appName__. Crea nuovi commit da __appName__ e unisci con commit fatti offline o su GitHub.", "link_to_github_description": "Devi autorizzare __appName__ ad accedere al tuo account GitHub per permetterci di sincronizzare i tuoi progetti.", "unlink": "Scollega", "unlink_github_warning": "Qualsiasi progetto sincronizzato con GitHub sarà disconnesso e non sarà più mantenuto sincronizzato con GitHub. Sei sicuro di voler scollegare il tuo account GitHub?", "github_account_successfully_linked": "Account GitHub Collegato con Successo!", "github_successfully_linked_description": "Grazie, abbiamo collegato con successo il tuo account GitHub a __appName__ . Adesso puoi esportare i progetti __appName__ in GitHub, o importarli dai tuoi repository GitHub.", "import_from_github": "Importa da GitHub", "github_sync_error": "Spiacenti, c'è stato un errore con la comunicazione con GitHub. Si prega di riprovare fra poco.", "loading_github_repositories": "Caricamento dei tuoi repository GitHub", "select_github_repository": "Seleziona un repository GitHub da importare in __appName__.", "import_to_sharelatex": "Importa in __appName__", "importing": "Importazione", "github_sync": "Sincronizzazione GitHub", "checking_project_github_status": "Controllo dello stato del progetto GitHub", "account_not_linked_to_github": "Il tuo account non è collegato a GitHub", "project_not_linked_to_github": "Questo progetto non è collegato ad un repository GitHub. Puoi creare un repository apposito in GitHub:", "create_project_in_github": "Crea un repository GitHub", "project_synced_with_git_repo_at": "Questo progetto è sincronizzato con il repository GitHub a", "recent_commits_in_github": "Commit recenti in GitHub", "sync_project_to_github": "Sincronizza progetto in GitHub", "sync_project_to_github_explanation": "Tutte le modifiche fatte in __appName__ saranno inviate e unite con tutti gli aggiornamenti in GitHub.", "github_merge_failed": "Le tue modifiche in __appName__ e GitHub non possono essere unite automaticamente. Per favore, unisci manualmente il branch <0>__sharelatex_branch__</0> con il branch <1>__master_branch__</1> in git. Clicca qui sotto per continuare dopo aver apportato le modifiche manuali.", "continue_github_merge": "Ho eseguito l'unione manuale. Continua", "export_project_to_github": "Esporta Progetto in GitHub", "github_validation_check": "Per favore, controlla che il nome del repository sia valido, e che tu abbia i permessi per crearlo.", "repository_name": "Nome Repository", "optional": "Opzionale", "github_public_description": "Chiunque può visualizzare il repository. Puoi scegliere chi può eseguire commit.", "github_commit_message_placeholder": "Messaggio di commit per le modifiche effettuate in __appName__...", "merge": "Unisci", "merging": "Unione", "github_account_is_linked": "Il tuo account GitHub è stato collegato con successo.", "unlink_github": "Scollega il tuo account GitHub", "link_to_github": "Collega il tuo account GitHub", "github_integration": "Integrazione GitHub", "github_is_premium": "La sincronizzazione GitHub è una funzionalità premium", "thank_you": "Grazie" }
overleaf/web/locales/it.json/0
{ "file_path": "overleaf/web/locales/it.json", "repo_id": "overleaf", "token_count": 14143 }
552
/* eslint-disable no-unused-vars */ const Helpers = require('./lib/helpers') exports.tags = ['server-ce', 'server-pro', 'saas'] const indexes = [ { key: { project_id: 1, }, name: 'project_id_1', }, ] exports.migrate = async client => { const { db } = client await Helpers.addIndexesToCollection(db.docHistoryIndex, indexes) } exports.rollback = async client => { const { db } = client try { await Helpers.dropIndexesFromCollection(db.docHistoryIndex, indexes) } catch (err) { console.error('Something went wrong rolling back the migrations', err) } }
overleaf/web/migrations/20190912145004_create_docHistoryIndex_indexes.js/0
{ "file_path": "overleaf/web/migrations/20190912145004_create_docHistoryIndex_indexes.js", "repo_id": "overleaf", "token_count": 222 }
553
/* eslint-disable no-unused-vars */ const Helpers = require('./lib/helpers') exports.tags = ['saas'] const indexes = [ { key: { project_id: 1, }, name: 'project_id_1', }, ] exports.migrate = async client => { const { db } = client await Helpers.addIndexesToCollection(db.projectHistoryMetaData, indexes) } exports.rollback = async client => { const { db } = client try { await Helpers.dropIndexesFromCollection(db.projectHistoryMetaData, indexes) } catch (err) { console.error('Something went wrong rolling back the migrations', err) } }
overleaf/web/migrations/20190912145020_create_projectHistoryMetaData_indexes.js/0
{ "file_path": "overleaf/web/migrations/20190912145020_create_projectHistoryMetaData_indexes.js", "repo_id": "overleaf", "token_count": 214 }
554
const Helpers = require('./lib/helpers') exports.tags = ['saas'] const indexes = [ { key: { brandVariationId: 1, }, name: 'brandVariationId_1', }, ] exports.migrate = async ({ db }) => { await Helpers.addIndexesToCollection(db.projects, indexes) } exports.rollback = async ({ db }) => { try { await Helpers.dropIndexesFromCollection(db.projects, indexes) } catch (err) { console.error('Something went wrong rolling back the migrations', err) } }
overleaf/web/migrations/20200110183327_brandVarationIdIndex.js/0
{ "file_path": "overleaf/web/migrations/20200110183327_brandVarationIdIndex.js", "repo_id": "overleaf", "token_count": 182 }
555
const runScript = require('../scripts/back_fill_doc_name_for_deleted_docs.js') exports.tags = ['server-ce', 'server-pro', 'saas'] exports.migrate = async client => { const options = { performCleanup: true, letUserDoubleCheckInputsFor: 10, } await runScript(options) } exports.rollback = async client => {}
overleaf/web/migrations/20210727150530_ce_sp_backfill_deleted_docs.js/0
{ "file_path": "overleaf/web/migrations/20210727150530_ce_sp_backfill_deleted_docs.js", "repo_id": "overleaf", "token_count": 115 }
556
const fs = require('fs') const path = require('path') const MODULES_PATH = path.join(__dirname, './') const entryPoints = [] if (fs.existsSync(MODULES_PATH)) { fs.readdirSync(MODULES_PATH).reduce((acc, module) => { const entryPath = path.join( MODULES_PATH, module, '/frontend/js/ide/index.js' ) if (fs.existsSync(entryPath)) { acc.push(entryPath) } return acc }, entryPoints) } module.exports = function () { return { code: entryPoints.map(entryPoint => `import '${entryPoint}'`).join('\n'), } }
overleaf/web/modules/modules-ide.js/0
{ "file_path": "overleaf/web/modules/modules-ide.js", "repo_id": "overleaf", "token_count": 233 }
557
const { batchedUpdate } = require('./helpers/batchedUpdate') const { promiseMapWithLimit, promisify } = require('../app/src/util/promises') const { db } = require('../app/src/infrastructure/mongodb') const sleep = promisify(setTimeout) const _ = require('lodash') async function main(options) { if (!options) { options = {} } _.defaults(options, { writeConcurrency: parseInt(process.env.WRITE_CONCURRENCY, 10) || 10, performCleanup: process.argv.includes('--perform-cleanup'), fixPartialInserts: process.argv.includes('--fix-partial-inserts'), letUserDoubleCheckInputsFor: parseInt( process.env.LET_USER_DOUBLE_CHECK_INPUTS_FOR || 10 * 1000, 10 ), }) await letUserDoubleCheckInputs(options) await batchedUpdate( 'projects', // array is not empty ~ array has one item { 'deletedFiles.0': { $exists: true } }, async (x, projects) => { await processBatch(x, projects, options) }, { _id: 1, deletedFiles: 1 } ) } async function processBatch(_, projects, options) { await promiseMapWithLimit( options.writeConcurrency, projects, async project => { await processProject(project, options) } ) } async function processProject(project, options) { await backFillFiles(project, options) if (options.performCleanup) { await cleanupProject(project) } } async function backFillFiles(project, options) { const projectId = project._id filterDuplicatesInPlace(project) project.deletedFiles.forEach(file => { file.projectId = projectId }) if (options.fixPartialInserts) { await fixPartialInserts(project) } else { await db.deletedFiles.insertMany(project.deletedFiles) } } function filterDuplicatesInPlace(project) { const fileIds = new Set() project.deletedFiles = project.deletedFiles.filter(file => { const id = file._id.toString() if (fileIds.has(id)) return false fileIds.add(id) return true }) } async function fixPartialInserts(project) { const seenFileIds = new Set( ( await db.deletedFiles .find( { _id: { $in: project.deletedFiles.map(file => file._id) } }, { projection: { _id: 1 } } ) .toArray() ).map(file => file._id.toString()) ) project.deletedFiles = project.deletedFiles.filter(file => { const id = file._id.toString() if (seenFileIds.has(id)) return false seenFileIds.add(id) return true }) if (project.deletedFiles.length > 0) { await db.deletedFiles.insertMany(project.deletedFiles) } } async function cleanupProject(project) { await db.projects.updateOne( { _id: project._id }, { $set: { deletedFiles: [] } } ) } async function letUserDoubleCheckInputs(options) { if (options.performCleanup) { console.error('BACK FILLING AND PERFORMING CLEANUP') } else { console.error( 'BACK FILLING ONLY - You will need to rerun with --perform-cleanup' ) } 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(() => { process.exit(0) }) .catch(error => { console.error({ error }) process.exit(1) }) }
overleaf/web/scripts/back_fill_deleted_files.js/0
{ "file_path": "overleaf/web/scripts/back_fill_deleted_files.js", "repo_id": "overleaf", "token_count": 1266 }
558
const { waitForDb } = require('../app/src/infrastructure/mongodb') const { User } = require('../app/src/models/User') const UserController = require('../app/src/Features/User/UserController') require('logger-sharelatex').logger.level('error') const pLimit = require('p-limit') const CONCURRENCY = 10 const failure = [] const success = [] console.log('Starting ensure affiliations') const query = { 'emails.affiliationUnchecked': true, } async function _handleEnsureAffiliation(user) { try { await UserController.promises.ensureAffiliation(user) console.log(`✔ ${user._id}`) success.push(user._id) } catch (error) { failure.push(user._id) console.log(`ERROR: ${user._id}`, error) } } async function getUsers() { return User.find(query, { emails: 1 }).exec() } async function run() { const limit = pLimit(CONCURRENCY) const users = await getUsers() console.log(`Found ${users.length} users`) await Promise.all( users.map(user => limit(() => _handleEnsureAffiliation(user))) ) console.log(`${success.length} successes`) console.log(`${failure.length} failures`) if (failure.length > 0) { console.log('Failed to update:', failure) } } waitForDb() .then(run) .then(() => { process.exit() }) .catch(error => { console.log(error) process.exit(1) })
overleaf/web/scripts/ensure_affiliations.js/0
{ "file_path": "overleaf/web/scripts/ensure_affiliations.js", "repo_id": "overleaf", "token_count": 479 }
559
const { Subscription } = require('../../app/src/models/Subscription') const RecurlyWrapper = require('../../app/src/Features/Subscription/RecurlyWrapper') const SubscriptionUpdater = require('../../app/src/Features/Subscription/SubscriptionUpdater') const async = require('async') const minimist = require('minimist') // make sure all `allMismatchReasons` are displayed in the output const util = require('util') util.inspect.defaultOptions.maxArrayLength = null const ScriptLogger = { checkedSubscriptionsCount: 0, mismatchSubscriptionsCount: 0, allMismatchReasons: {}, recordMismatch: (subscription, recurlySubscription) => { const mismatchReasons = {} if (subscription.planCode !== recurlySubscription.plan.plan_code) { mismatchReasons.recurlyPlan = recurlySubscription.plan.plan_code mismatchReasons.olPlan = subscription.planCode } if (recurlySubscription.state === 'expired') { mismatchReasons.state = 'expired' } if (!Object.keys(mismatchReasons).length) { return } ScriptLogger.mismatchSubscriptionsCount += 1 const mismatchReasonsString = JSON.stringify(mismatchReasons) if (ScriptLogger.allMismatchReasons[mismatchReasonsString]) { ScriptLogger.allMismatchReasons[mismatchReasonsString].push( subscription._id ) } else { ScriptLogger.allMismatchReasons[mismatchReasonsString] = [ subscription._id, ] } }, printProgress: () => { console.warn( `Subscriptions checked: ${ScriptLogger.checkedSubscriptionsCount}. Mismatches: ${ScriptLogger.mismatchSubscriptionsCount}` ) }, printSummary: () => { console.log('All Mismatch Reasons:', ScriptLogger.allMismatchReasons) console.log( 'Mismatch Subscriptions Count', ScriptLogger.mismatchSubscriptionsCount ) }, } const slowCallback = callback => setTimeout(callback, 80) const handleSyncSubscriptionError = (subscription, error, callback) => { console.warn(`Errors with subscription id=${subscription._id}:`, error) if (typeof error === 'string' && error.match(/429$/)) { return setTimeout(callback, 1000 * 60 * 5) } if (typeof error === 'string' && error.match(/5\d\d$/)) { return setTimeout(() => { syncSubscription(subscription, callback) }, 1000 * 60) } slowCallback(callback) } const syncSubscription = (subscription, callback) => { RecurlyWrapper.getSubscription( subscription.recurlySubscription_id, (error, recurlySubscription) => { if (error) { return handleSyncSubscriptionError(subscription, error, callback) } ScriptLogger.recordMismatch(subscription, recurlySubscription) if (!COMMIT) { return callback() } SubscriptionUpdater.updateSubscriptionFromRecurly( recurlySubscription, subscription, {}, error => { if (error) { return handleSyncSubscriptionError(subscription, error, callback) } slowCallback(callback) } ) } ) } const syncSubscriptions = (subscriptions, callback) => { async.eachLimit(subscriptions, ASYNC_LIMIT, syncSubscription, callback) } const loopForSubscriptions = (skip, callback) => { Subscription.find({ recurlySubscription_id: { $exists: true, $ne: '' }, }) .sort('_id') .skip(skip) .limit(FETCH_LIMIT) .exec((error, subscriptions) => { if (error) { return callback(error) } if (subscriptions.length === 0) { console.warn('DONE') return callback() } syncSubscriptions(subscriptions, error => { if (error) { return callback(error) } ScriptLogger.checkedSubscriptionsCount += subscriptions.length retryCounter = 0 ScriptLogger.printProgress() ScriptLogger.printSummary() loopForSubscriptions( MONGO_SKIP + ScriptLogger.checkedSubscriptionsCount, callback ) }) }) } let retryCounter = 0 const run = () => loopForSubscriptions( MONGO_SKIP + ScriptLogger.checkedSubscriptionsCount, error => { if (error) { if (retryCounter < 3) { console.error(error) retryCounter += 1 console.warn(`RETRYING IN 60 SECONDS. (${retryCounter}/3)`) return setTimeout(run, 60000) } 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`) } } setup() run()
overleaf/web/scripts/recurly/resync_subscriptions.js/0
{ "file_path": "overleaf/web/scripts/recurly/resync_subscriptions.js", "repo_id": "overleaf", "token_count": 1965 }
560
const fs = require('fs') const LANGUAGES = [ 'cs', 'da', 'de', 'en', 'es', 'fi', 'fr', 'it', 'ja', 'ko', 'nl', 'no', 'pl', 'pt', 'ru', 'sv', 'tr', 'zh-CN', ] const LOCALES = {} LANGUAGES.forEach(loadLocales) function loadLocales(language) { LOCALES[language] = require(`../../locales/${language}.json`) } function transformLocales(mapping, transformLocale) { Object.entries(LOCALES).forEach(([language, translatedLocales]) => { Object.entries(mapping).forEach(([localeKey, spec]) => { const locale = translatedLocales[localeKey] if (!locale) { // This locale is not translated yet. return } translatedLocales[localeKey] = transformLocale(locale, spec) }) fs.writeFileSync( `${__dirname}/../../locales/${language}.json`, JSON.stringify(translatedLocales, null, 2) + '\n' ) }) } module.exports = { transformLocales, }
overleaf/web/scripts/translations/transformLocales.js/0
{ "file_path": "overleaf/web/scripts/translations/transformLocales.js", "repo_id": "overleaf", "token_count": 401 }
561
const { expect } = require('chai') const async = require('async') const User = require('./helpers/User') describe('AdminEmails', function () { beforeEach(function (done) { this.timeout(5000) done() }) describe('an admin with an invalid email address', function () { before(function (done) { this.badUser = new User({ email: 'alice@evil.com' }) async.series( [ cb => this.badUser.ensureUserExists(cb), cb => this.badUser.ensureAdmin(cb), ], done ) }) it('should block the user', function (done) { this.badUser.login(err => { expect(err).to.not.exist this.badUser.getProjectListPage((err, statusCode) => { expect(err).to.exist done() }) }) }) }) describe('an admin with a valid email address', function () { before(function (done) { this.goodUser = new User({ email: 'alice@example.com' }) async.series( [ cb => this.goodUser.ensureUserExists(cb), cb => this.goodUser.ensureAdmin(cb), ], done ) }) it('should not block the user', function (done) { this.goodUser.login(err => { expect(err).to.not.exist this.goodUser.getProjectListPage((err, statusCode) => { expect(err).to.not.exist expect(statusCode).to.equal(200) done() }) }) }) }) })
overleaf/web/test/acceptance/src/AdminEmailTests.js/0
{ "file_path": "overleaf/web/test/acceptance/src/AdminEmailTests.js", "repo_id": "overleaf", "token_count": 654 }
562
require('./helpers/InitApp') const Features = require('../../../app/src/infrastructure/Features') const MockAnalyticsApi = require('./mocks/MockAnalyticsApi') const MockChatApi = require('./mocks/MockChatApi') const MockClsiApi = require('./mocks/MockClsiApi') const MockDocstoreApi = require('./mocks/MockDocstoreApi') const MockDocUpdaterApi = require('./mocks/MockDocUpdaterApi') const MockFilestoreApi = require('./mocks/MockFilestoreApi') const MockNotificationsApi = require('./mocks/MockNotificationsApi') const MockProjectHistoryApi = require('./mocks/MockProjectHistoryApi') const MockSpellingApi = require('./mocks/MockSpellingApi') const MockV1Api = require('./mocks/MockV1Api') const MockV1HistoryApi = require('./mocks/MockV1HistoryApi') const mockOpts = { debug: ['1', 'true', 'TRUE'].includes(process.env.DEBUG_MOCKS), } MockChatApi.initialize(3010, mockOpts) MockClsiApi.initialize(3013, mockOpts) MockDocstoreApi.initialize(3016, mockOpts) MockDocUpdaterApi.initialize(3003, mockOpts) MockFilestoreApi.initialize(3009, mockOpts) MockNotificationsApi.initialize(3042, mockOpts) MockSpellingApi.initialize(3005, mockOpts) if (Features.hasFeature('saas')) { MockAnalyticsApi.initialize(3050, mockOpts) MockProjectHistoryApi.initialize(3054, mockOpts) MockV1Api.initialize(5000, mockOpts) MockV1HistoryApi.initialize(3100, mockOpts) }
overleaf/web/test/acceptance/src/Init.js/0
{ "file_path": "overleaf/web/test/acceptance/src/Init.js", "repo_id": "overleaf", "token_count": 532 }
563
/* eslint-disable camelcase, 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 */ const { expect } = require('chai') const _ = require('underscore') const User = require('./helpers/User') const MockDocstoreApiClass = require('./mocks/MockDocstoreApi') const MockFilestoreApiClass = require('./mocks/MockFilestoreApi') let MockDocstoreApi, MockFilestoreApi before(function () { MockDocstoreApi = MockDocstoreApiClass.instance() MockFilestoreApi = MockFilestoreApiClass.instance() }) describe('RestoringFiles', function () { beforeEach(function (done) { this.owner = new User() return this.owner.login(error => { if (error != null) { throw error } return this.owner.createProject( 'example-project', { template: 'example' }, (error, project_id) => { this.project_id = project_id if (error != null) { throw error } return done() } ) }) }) describe('restoring a deleted doc', function () { beforeEach(function (done) { return this.owner.getProject(this.project_id, (error, project) => { if (error != null) { throw error } this.doc = _.find( project.rootFolder[0].docs, doc => doc.name === 'main.tex' ) return this.owner.request( { method: 'DELETE', url: `/project/${this.project_id}/doc/${this.doc._id}`, }, (error, response, body) => { if (error != null) { throw error } expect(response.statusCode).to.equal(204) return this.owner.request( { method: 'POST', url: `/project/${this.project_id}/doc/${this.doc._id}/restore`, json: { name: 'main.tex', }, }, (error, response, body) => { if (error != null) { throw error } expect(response.statusCode).to.equal(200) expect(body.doc_id).to.exist this.restored_doc_id = body.doc_id return done() } ) } ) }) }) it('should have restored the doc', function (done) { return this.owner.getProject(this.project_id, (error, project) => { if (error != null) { throw error } const restored_doc = _.find( project.rootFolder[0].docs, doc => doc.name === 'main.tex' ) expect(restored_doc._id.toString()).to.equal(this.restored_doc_id) expect(this.doc._id).to.not.equal(this.restored_doc_id) expect( MockDocstoreApi.docs[this.project_id][this.restored_doc_id].lines ).to.deep.equal( MockDocstoreApi.docs[this.project_id][this.doc._id].lines ) return done() }) }) }) })
overleaf/web/test/acceptance/src/RestoringFilesTest.js/0
{ "file_path": "overleaf/web/test/acceptance/src/RestoringFilesTest.js", "repo_id": "overleaf", "token_count": 1603 }
564
const { ObjectId } = require('mongodb') const PublisherModel = require('../../../../app/src/models/Publisher').Publisher let count = parseInt(Math.random() * 999999) class Publisher { constructor(options = {}) { this.slug = options.slug || `publisher-slug-${count}` this.managerIds = [] count += 1 } ensureExists(callback) { const filter = { slug: this.slug } const options = { upsert: true, new: true, setDefaultsOnInsert: true } PublisherModel.findOneAndUpdate(filter, {}, options, (error, publisher) => { this._id = publisher._id callback(error) }) } setManagerIds(managerIds, callback) { return PublisherModel.findOneAndUpdate( { _id: ObjectId(this._id) }, { managerIds: managerIds }, callback ) } } module.exports = Publisher
overleaf/web/test/acceptance/src/helpers/Publisher.js/0
{ "file_path": "overleaf/web/test/acceptance/src/helpers/Publisher.js", "repo_id": "overleaf", "token_count": 299 }
565
const { db, ObjectId } = require('../../../../app/src/infrastructure/mongodb') const AbstractMockApi = require('./AbstractMockApi') class MockDocstoreApi extends AbstractMockApi { reset() { this.docs = {} } createLegacyDeletedDoc(projectId, docId) { if (!this.docs[projectId]) { this.docs[projectId] = {} } this.docs[projectId][docId] = { lines: [], version: 1, ranges: {}, deleted: true, } } getDeletedDocs(projectId) { return Object.entries(this.docs[projectId] || {}) .filter(([_, doc]) => doc.deleted) .map(([docId, doc]) => { return { _id: docId, name: doc.name } }) } applyRoutes() { this.app.post('/project/:projectId/doc/:docId', (req, res) => { const { projectId, docId } = req.params const { lines, version, ranges } = req.body if (this.docs[projectId] == null) { this.docs[projectId] = {} } if (this.docs[projectId][docId] == null) { this.docs[projectId][docId] = {} } const { version: oldVersion, deleted } = this.docs[projectId][docId] this.docs[projectId][docId] = { lines, version, ranges, deleted } if (this.docs[projectId][docId].rev == null) { this.docs[projectId][docId].rev = 0 } this.docs[projectId][docId].rev += 1 this.docs[projectId][docId]._id = docId res.json({ modified: oldVersion !== version, rev: this.docs[projectId][docId].rev, }) }) this.app.get('/project/:projectId/doc', (req, res) => { res.json(Object.values(this.docs[req.params.projectId] || {})) }) this.app.get('/project/:projectId/doc-deleted', (req, res) => { res.json(this.getDeletedDocs(req.params.projectId)) }) this.app.get('/project/:projectId/doc/:docId', (req, res) => { const { projectId, docId } = req.params const doc = this.docs[projectId][docId] if (!doc || (doc.deleted && !req.query.include_deleted)) { res.sendStatus(404) } else { res.json(doc) } }) this.app.get('/project/:projectId/doc/:docId/deleted', (req, res) => { const { projectId, docId } = req.params if (!this.docs[projectId] || !this.docs[projectId][docId]) { res.sendStatus(404) } else { res.json({ deleted: Boolean(this.docs[projectId][docId].deleted) }) } }) this.app.patch('/project/:projectId/doc/:docId', (req, res) => { const { projectId, docId } = req.params if (!this.docs[projectId]) { res.sendStatus(404) } else if (!this.docs[projectId][docId]) { res.sendStatus(404) } else { Object.assign(this.docs[projectId][docId], req.body) res.sendStatus(204) } }) this.app.post('/project/:projectId/destroy', async (req, res) => { const { projectId } = req.params delete this.docs[projectId] await db.docs.deleteMany({ project_id: ObjectId(projectId) }) res.sendStatus(204) }) } } module.exports = MockDocstoreApi // type hint for the inherited `instance` method /** * @function instance * @memberOf MockDocstoreApi * @static * @returns {MockDocstoreApi} */
overleaf/web/test/acceptance/src/mocks/MockDocstoreApi.js/0
{ "file_path": "overleaf/web/test/acceptance/src/mocks/MockDocstoreApi.js", "repo_id": "overleaf", "token_count": 1408 }
566
import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { expect } from 'chai' import CloneProjectModal from '../../../../../frontend/js/features/clone-project-modal/components/clone-project-modal' import sinon from 'sinon' import fetchMock from 'fetch-mock' describe('<CloneProjectModal />', function () { afterEach(function () { fetchMock.reset() }) const modalProps = { handleHide: sinon.stub(), projectId: 'project-1', projectName: 'Test Project', openProject: sinon.stub(), show: true, } it('renders the translated modal title', async function () { render(<CloneProjectModal {...modalProps} />) await screen.findByText('Copy Project') }) it('posts the generated project name', async function () { fetchMock.post( 'express:/project/:projectId/clone', { status: 200, body: { project_id: modalProps.projectId }, }, { delay: 10 } ) const openProject = sinon.stub() render(<CloneProjectModal {...modalProps} openProject={openProject} />) const cancelButton = await screen.findByRole('button', { name: 'Cancel' }) expect(cancelButton.disabled).to.be.false const submitButton = await screen.findByRole('button', { name: 'Copy' }) expect(submitButton.disabled).to.be.false const input = await screen.getByLabelText('New Name') fireEvent.change(input, { target: { value: '' }, }) expect(submitButton.disabled).to.be.true fireEvent.change(input, { target: { value: 'A Cloned Project' }, }) expect(submitButton.disabled).to.be.false fireEvent.click(submitButton) expect(submitButton.disabled).to.be.true await fetchMock.flush(true) expect(fetchMock.done()).to.be.true const [url, options] = fetchMock.lastCall( 'express:/project/:projectId/clone' ) expect(url).to.equal('/project/project-1/clone') expect(JSON.parse(options.body)).to.deep.equal({ projectName: 'A Cloned Project', }) expect(openProject).to.be.calledOnce const errorMessage = screen.queryByText('Sorry, something went wrong') expect(errorMessage).to.be.null await waitFor(() => { expect(submitButton.disabled).to.be.false expect(cancelButton.disabled).to.be.false }) }) it('handles a generic error response', async function () { const matcher = 'express:/project/:projectId/clone' fetchMock.postOnce(matcher, { status: 500, body: 'There was an error!', }) const openProject = sinon.stub() render(<CloneProjectModal {...modalProps} openProject={openProject} />) const button = await screen.findByRole('button', { name: 'Copy' }) expect(button.disabled).to.be.false const cancelButton = await screen.findByRole('button', { name: 'Cancel' }) expect(cancelButton.disabled).to.be.false fireEvent.click(button) expect(fetchMock.done(matcher)).to.be.true expect(openProject).not.to.be.called await screen.findByText('Sorry, something went wrong') expect(button.disabled).to.be.false expect(cancelButton.disabled).to.be.false }) it('handles a specific error response', async function () { const matcher = 'express:/project/:projectId/clone' fetchMock.postOnce(matcher, { status: 400, body: 'There was an error!', }) const openProject = sinon.stub() render(<CloneProjectModal {...modalProps} openProject={openProject} />) const button = await screen.findByRole('button', { name: 'Copy' }) expect(button.disabled).to.be.false const cancelButton = await screen.findByRole('button', { name: 'Cancel' }) expect(cancelButton.disabled).to.be.false fireEvent.click(button) await fetchMock.flush(true) expect(fetchMock.done(matcher)).to.be.true expect(openProject).not.to.be.called await screen.findByText('There was an error!') expect(button.disabled).to.be.false expect(cancelButton.disabled).to.be.false }) })
overleaf/web/test/frontend/features/clone-project-modal/components/clone-project-modal.test.js/0
{ "file_path": "overleaf/web/test/frontend/features/clone-project-modal/components/clone-project-modal.test.js", "repo_id": "overleaf", "token_count": 1476 }
567
import { expect } from 'chai' import sinon from 'sinon' import { screen, fireEvent } from '@testing-library/react' import { renderWithEditorContext, cleanUpContext, } from '../../../helpers/render-with-context' import FileTreeRoot from '../../../../../frontend/js/features/file-tree/components/file-tree-root' describe('FileTree Context Menu Flow', function () { const onSelect = sinon.stub() const onInit = sinon.stub() afterEach(function () { onSelect.reset() onInit.reset() cleanUpContext() }) it('opens on contextMenu event', async 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} rootDocId="456def" onSelect={onSelect} onInit={onInit} isConnected /> ) const treeitem = screen.getByRole('button', { name: 'main.tex' }) expect(screen.queryByRole('menu')).to.be.null fireEvent.contextMenu(treeitem) screen.getByRole('menu') }) it("doesn't open in read only mode", async function () { const rootFolder = [ { _id: 'root-folder-id', docs: [{ _id: '456def', name: 'main.tex' }], folders: [], fileRefs: [], }, ] renderWithEditorContext( <FileTreeRoot rootFolder={rootFolder} projectId="123abc" hasWritePermissions={false} userHasFeature={() => true} refProviders={{}} reindexReferences={() => null} setRefProviderEnabled={() => null} setStartedFreeTrial={() => null} rootDocId="456def" onSelect={onSelect} onInit={onInit} isConnected /> ) const treeitem = screen.getByRole('button', { name: 'main.tex' }) fireEvent.contextMenu(treeitem) expect(screen.queryByRole('menu')).to.not.exist }) })
overleaf/web/test/frontend/features/file-tree/flows/context-menu.test.js/0
{ "file_path": "overleaf/web/test/frontend/features/file-tree/flows/context-menu.test.js", "repo_id": "overleaf", "token_count": 959 }
568
import { expect } from 'chai' import { screen, render } from '@testing-library/react' import PreviewDownloadButton from '../../../../../frontend/js/features/preview/components/preview-download-button' describe('<PreviewDownloadButton />', function () { const projectId = 'projectId123' const pdfDownloadUrl = `/download/project/${projectId}/build/17523aaafdf-1ad9063af140f004/output/output.pdf?compileGroup=priority&popupDownload=true` function renderPreviewDownloadButton( isCompiling, outputFiles, pdfDownloadUrl, showText ) { if (isCompiling === undefined) isCompiling = false if (showText === undefined) showText = true render( <PreviewDownloadButton isCompiling={isCompiling} outputFiles={outputFiles || []} pdfDownloadUrl={pdfDownloadUrl} showText={showText} /> ) } it('should disable the button and dropdown toggle when compiling', function () { const isCompiling = true const outputFiles = undefined renderPreviewDownloadButton(isCompiling, outputFiles) expect( screen.getByText('Download PDF').closest('a').getAttribute('disabled') ).to.exist const buttons = screen.getAllByRole('button') expect(buttons.length).to.equal(1) // the dropdown toggle expect(buttons[0].getAttribute('disabled')).to.exist expect(buttons[0].getAttribute('aria-label')).to.equal( 'Toggle output files list' ) }) it('should disable the PDF button when there is no PDF', function () { const isCompiling = false const outputFiles = [] renderPreviewDownloadButton(isCompiling, outputFiles) expect( screen.getByText('Download PDF').closest('a').getAttribute('disabled') ).to.exist }) it('should enable the PDF button when there is a main PDF', function () { const isCompiling = false const outputFiles = [] renderPreviewDownloadButton(isCompiling, outputFiles, pdfDownloadUrl) expect( screen.getByText('Download PDF').closest('a').getAttribute('href') ).to.equal(pdfDownloadUrl) expect( screen.getByText('Download PDF').closest('a').getAttribute('disabled') ).to.not.exist }) it('should enable the dropdown when not compiling', function () { const isCompiling = false const outputFiles = [] renderPreviewDownloadButton(isCompiling, outputFiles, pdfDownloadUrl) const buttons = screen.getAllByRole('button') expect(buttons[0]).to.exist expect(buttons[0].getAttribute('disabled')).to.not.exist }) it('should show the button text when prop showText=true', function () { const isCompiling = false const showText = true renderPreviewDownloadButton(isCompiling, [], pdfDownloadUrl, showText) expect(screen.getByText('Download PDF').getAttribute('style')).to.be.null }) it('should not show the button text when prop showText=false', function () { const isCompiling = false const showText = false renderPreviewDownloadButton(isCompiling, [], pdfDownloadUrl, showText) expect(screen.getByText('Download PDF').getAttribute('style')).to.equal( 'position: absolute; right: -100vw;' ) }) })
overleaf/web/test/frontend/features/preview/components/preview-download-button.test.js/0
{ "file_path": "overleaf/web/test/frontend/features/preview/components/preview-download-button.test.js", "repo_id": "overleaf", "token_count": 1057 }
569
import { expect } from 'chai' import { screen, render } from '@testing-library/react' import Icon from '../../../../frontend/js/shared/components/icon' describe('<Icon />', function () { it('renders basic fa classes', function () { const { container } = render(<Icon type="angle-down" />) const element = container.querySelector('i.fa.fa-angle-down') expect(element).to.exist }) it('renders with aria-hidden', function () { const { container } = render(<Icon type="angle-down" />) const element = container.querySelector('i[aria-hidden="true"]') expect(element).to.exist }) it('renders accessible label', function () { render(<Icon type="angle-down" accessibilityLabel="Accessible Foo" />) screen.getByText('Accessible Foo') }) it('renders with spin', function () { const { container } = render(<Icon type="angle-down" spin />) const element = container.querySelector('i.fa.fa-angle-down.fa-spin') expect(element).to.exist }) it('renders with modifier', function () { const { container } = render(<Icon type="angle-down" modifier="2x" />) const element = container.querySelector('i.fa.fa-angle-down.fa-2x') expect(element).to.exist }) it('renders with custom clases', function () { const { container } = render( <Icon type="angle-down" classes={{ icon: 'custom-icon-class' }} /> ) const element = container.querySelector( 'i.fa.fa-angle-down.custom-icon-class' ) expect(element).to.exist }) it('renders children', function () { const { container } = render( <Icon type="angle-down"> <Icon type="angle-up" /> </Icon> ) const element = container.querySelector( 'i.fa.fa-angle-down > i.fa.fa-angle-up' ) expect(element).to.exist }) })
overleaf/web/test/frontend/shared/components/icon.test.js/0
{ "file_path": "overleaf/web/test/frontend/shared/components/icon.test.js", "repo_id": "overleaf", "token_count": 651 }
570
const ANGULAR_PROJECT_CONTROLLER_REGEX = /controller="ProjectPageController"/ const TITLE_REGEX = /<title>Your Projects - .*, Online LaTeX Editor<\/title>/ async function run({ request, assertHasStatusCode }) { const response = await request('/project') assertHasStatusCode(response, 200) if (!TITLE_REGEX.test(response.body)) { throw new Error('body does not have correct title') } if (!ANGULAR_PROJECT_CONTROLLER_REGEX.test(response.body)) { throw new Error('body does not have correct angular controller') } } module.exports = { run }
overleaf/web/test/smoke/src/steps/100_loadProjectDashboard.js/0
{ "file_path": "overleaf/web/test/smoke/src/steps/100_loadProjectDashboard.js", "repo_id": "overleaf", "token_count": 180 }
571
/* 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 { expect } = require('chai') 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/BrandVariations/BrandVariationsHandler' ) describe('BrandVariationsHandler', function () { beforeEach(function () { this.settings = { apis: { v1: { url: 'http://overleaf.example.com', }, }, modules: { sanitize: { options: { allowedTags: ['br', 'strong'], allowedAttributes: { strong: ['style'], }, }, }, }, } this.V1Api = { request: sinon.stub() } this.BrandVariationsHandler = SandboxedModule.require(modulePath, { requires: { '@overleaf/settings': this.settings, '../V1/V1Api': this.V1Api, }, }) return (this.mockedBrandVariationDetails = { id: '12', active: true, brand_name: 'The journal', logo_url: 'http://my.cdn.tld/journal-logo.png', journal_cover_url: 'http://my.cdn.tld/journal-cover.jpg', home_url: 'http://www.thejournal.com/', publish_menu_link_html: 'Submit your paper to the <em>The Journal</em>', }) }) describe('getBrandVariationById', function () { it('should call the callback with an error when the branding variation id is not provided', function (done) { return this.BrandVariationsHandler.getBrandVariationById( null, (err, brandVariationDetails) => { expect(err).to.be.instanceof(Error) return done() } ) }) it('should call the callback with an error when the request errors', function (done) { this.V1Api.request.callsArgWith(1, new Error()) return this.BrandVariationsHandler.getBrandVariationById( '12', (err, brandVariationDetails) => { expect(err).to.be.instanceof(Error) return done() } ) }) it('should call the callback with branding details when request succeeds', function (done) { this.V1Api.request.callsArgWith( 1, null, { statusCode: 200 }, this.mockedBrandVariationDetails ) return this.BrandVariationsHandler.getBrandVariationById( '12', (err, brandVariationDetails) => { expect(err).to.not.exist expect(brandVariationDetails).to.deep.equal( this.mockedBrandVariationDetails ) return done() } ) }) it('should transform relative URLs in v1 absolute ones', function (done) { this.mockedBrandVariationDetails.logo_url = '/journal-logo.png' this.V1Api.request.callsArgWith( 1, null, { statusCode: 200 }, this.mockedBrandVariationDetails ) return this.BrandVariationsHandler.getBrandVariationById( '12', (err, brandVariationDetails) => { expect( brandVariationDetails.logo_url.startsWith(this.settings.apis.v1.url) ).to.be.true return done() } ) }) it("should sanitize 'submit_button_html'", function (done) { this.mockedBrandVariationDetails.submit_button_html = '<br class="break"/><strong style="color:#B39500">AGU Journal</strong><iframe>hello</iframe>' this.V1Api.request.callsArgWith( 1, null, { statusCode: 200 }, this.mockedBrandVariationDetails ) return this.BrandVariationsHandler.getBrandVariationById( '12', (err, brandVariationDetails) => { expect(brandVariationDetails.submit_button_html).to.equal( '<br /><strong style="color:#B39500">AGU Journal</strong>hello' ) return done() } ) }) }) })
overleaf/web/test/unit/src/BrandVariations/BrandVariationsHandlerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/BrandVariations/BrandVariationsHandlerTests.js", "repo_id": "overleaf", "token_count": 1875 }
572
/* 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 sinon = require('sinon') const modulePath = '../../../../app/src/Features/Contacts/ContactManager' const SandboxedModule = require('sandboxed-module') describe('ContactManager', function () { beforeEach(function () { this.ContactManager = SandboxedModule.require(modulePath, { requires: { request: (this.request = sinon.stub()), '@overleaf/settings': (this.settings = { apis: { contacts: { url: 'contacts.sharelatex.com', }, }, }), }, }) this.user_id = 'user-id-123' this.contact_id = 'contact-id-123' return (this.callback = sinon.stub()) }) describe('getContacts', function () { describe('with a successful response code', function () { beforeEach(function () { this.request.get = sinon .stub() .callsArgWith( 1, null, { statusCode: 204 }, { contact_ids: (this.contact_ids = ['mock', 'contact_ids']) } ) return this.ContactManager.getContactIds( this.user_id, { limit: 42 }, this.callback ) }) it('should get the contacts from the contacts api', function () { return this.request.get .calledWith({ url: `${this.settings.apis.contacts.url}/user/${this.user_id}/contacts`, qs: { limit: 42 }, json: true, jar: false, }) .should.equal(true) }) it('should call the callback with the contatcs', function () { return this.callback .calledWith(null, this.contact_ids) .should.equal(true) }) }) describe('with a failed response code', function () { beforeEach(function () { this.request.get = sinon .stub() .callsArgWith(1, null, { statusCode: 500 }, null) return this.ContactManager.getContactIds( this.user_id, { limit: 42 }, this.callback ) }) it('should call the callback with an error', function () { return this.callback .calledWith( sinon.match .instanceOf(Error) .and( sinon.match.has( 'message', 'contacts api responded with non-success code: 500' ) ) ) .should.equal(true) }) }) }) describe('addContact', function () { describe('with a successful response code', function () { beforeEach(function () { this.request.post = sinon .stub() .callsArgWith(1, null, { statusCode: 200 }, null) return this.ContactManager.addContact( this.user_id, this.contact_id, this.callback ) }) it('should add the contacts for the user in the contacts api', function () { return this.request.post .calledWith({ url: `${this.settings.apis.contacts.url}/user/${this.user_id}/contacts`, json: { contact_id: this.contact_id, }, jar: false, }) .should.equal(true) }) it('should call the callback', function () { return this.callback.called.should.equal(true) }) }) describe('with a failed response code', function () { beforeEach(function () { this.request.post = sinon .stub() .callsArgWith(1, null, { statusCode: 500 }, null) return this.ContactManager.addContact( this.user_id, this.contact_id, this.callback ) }) it('should call the callback with an error', function () { return this.callback .calledWith( sinon.match .instanceOf(Error) .and( sinon.match.has( 'message', 'contacts api responded with non-success code: 500' ) ) ) .should.equal(true) }) }) }) })
overleaf/web/test/unit/src/Contact/ContactManagerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Contact/ContactManagerTests.js", "repo_id": "overleaf", "token_count": 2162 }
573
const path = require('path') const modulePath = path.join( __dirname, '../../../../app/src/Features/Email/SpamSafe' ) const SpamSafe = require(modulePath) const { expect } = require('chai') describe('SpamSafe', function () { it('should reject spammy names', function () { expect(SpamSafe.isSafeUserName('Charline Wałęsa')).to.equal(true) expect( SpamSafe.isSafeUserName( "hey come buy this product im selling it's really good for you and it'll make your latex 10x guaranteed" ) ).to.equal(false) expect(SpamSafe.isSafeUserName('隆太郎 宮本')).to.equal(true) expect(SpamSafe.isSafeUserName('Visit haxx0red.com')).to.equal(false) expect( SpamSafe.isSafeUserName( '加美汝VX:hihi661,金沙2001005com the first deposit will be _100%_' ) ).to.equal(false) expect( SpamSafe.isSafeProjectName( 'Neural Networks: good for your health and will solve all your problems' ) ).to.equal(false) expect( SpamSafe.isSafeProjectName( 'An analysis of the questions of the universe!' ) ).to.equal(true) expect(SpamSafe.isSafeProjectName("A'p'o's't'r'o'p'h'e gallore")).to.equal( true ) expect( SpamSafe.isSafeProjectName( 'come buy this => http://www.dopeproduct.com/search/?q=user123' ) ).to.equal(false) expect( SpamSafe.isSafeEmail('realistic-email+1@domain.sub-hyphen.com') ).to.equal(true) expect(SpamSafe.isSafeEmail('notquiteRight@evil$.com')).to.equal(false) expect(SpamSafe.safeUserName('Tammy Weinstįen', 'A User')).to.equal( 'Tammy Weinstįen' ) expect(SpamSafe.safeUserName('haxx0red.com', 'A User')).to.equal('A User') expect(SpamSafe.safeUserName('What$ Upp', 'A User')).to.equal('A User') expect(SpamSafe.safeProjectName('Math-ematics!', 'A Project')).to.equal( 'Math-ematics!' ) expect( SpamSafe.safeProjectName( `A Very long title for a very long book that will never be read${'a'.repeat( 250 )}`, 'A Project' ) ).to.equal('A Project') expect( SpamSafe.safeEmail('safe-ëmail@domain.com', 'A collaborator') ).to.equal('safe-ëmail@domain.com') expect( SpamSafe.safeEmail('Բարեւ@another.domain', 'A collaborator') ).to.equal('Բարեւ@another.domain') expect( SpamSafe.safeEmail(`me+${'a'.repeat(40)}@googoole.con`, 'A collaborator') ).to.equal('A collaborator') expect( SpamSafe.safeEmail('sendME$$$@iAmAprince.com', 'A collaborator') ).to.equal('A collaborator') }) })
overleaf/web/test/unit/src/Email/SpamSafeTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Email/SpamSafeTests.js", "repo_id": "overleaf", "token_count": 1144 }
574
const { expect } = require('chai') const SandboxedModule = require('sandboxed-module') const path = require('path') const sinon = require('sinon') const modulePath = path.join( __dirname, '../../../../app/src/Features/Institutions/InstitutionsAPI' ) const Errors = require('../../../../app/src/Features/Errors/Errors') describe('InstitutionsAPI', function () { beforeEach(function () { this.settings = { apis: { v1: { url: 'v1.url', user: '', pass: '' } } } this.request = sinon.stub() this.ipMatcherNotification = { read: (this.markAsReadIpMatcher = sinon.stub().callsArgWith(1, null)), } this.InstitutionsAPI = SandboxedModule.require(modulePath, { requires: { '@overleaf/metrics': { timeAsyncMethod: sinon.stub(), }, '@overleaf/settings': this.settings, request: this.request, '../Notifications/NotificationsBuilder': { ipMatcherAffiliation: sinon .stub() .returns(this.ipMatcherNotification), }, }, }) this.stubbedUser = { _id: '3131231', name: 'bob', email: 'hello@world.com', } this.newEmail = 'bob@bob.com' }) describe('getInstitutionAffiliations', function () { it('get affiliations', function (done) { this.institutionId = 123 const responseBody = ['123abc', '456def'] this.request.yields(null, { statusCode: 200 }, responseBody) this.InstitutionsAPI.getInstitutionAffiliations( this.institutionId, (err, body) => { expect(err).not.to.exist this.request.calledOnce.should.equal(true) const requestOptions = this.request.lastCall.args[0] const expectedUrl = `v1.url/api/v2/institutions/${this.institutionId}/affiliations` requestOptions.url.should.equal(expectedUrl) requestOptions.method.should.equal('GET') expect(requestOptions.body).not.to.exist body.should.equal(responseBody) done() } ) }) it('handle empty response', function (done) { this.settings.apis.v1.url = '' this.InstitutionsAPI.getInstitutionAffiliations( this.institutionId, (err, body) => { expect(err).not.to.exist expect(body).to.be.a('Array') body.length.should.equal(0) done() } ) }) }) describe('getInstitutionLicences', function () { it('get licences', function (done) { this.institutionId = 123 const responseBody = { lag: 'monthly', data: [{ key: 'users', values: [{ x: '2018-01-01', y: 1 }] }], } this.request.yields(null, { statusCode: 200 }, responseBody) const startDate = '1417392000' const endDate = '1420848000' this.InstitutionsAPI.getInstitutionLicences( this.institutionId, startDate, endDate, 'monthly', (err, body) => { expect(err).not.to.exist this.request.calledOnce.should.equal(true) const requestOptions = this.request.lastCall.args[0] const expectedUrl = `v1.url/api/v2/institutions/${this.institutionId}/institution_licences` requestOptions.url.should.equal(expectedUrl) requestOptions.method.should.equal('GET') requestOptions.body.start_date.should.equal(startDate) requestOptions.body.end_date.should.equal(endDate) requestOptions.body.lag.should.equal('monthly') body.should.equal(responseBody) done() } ) }) }) describe('getLicencesForAnalytics', function () { const lag = 'daily' const queryDate = '2017-01-07:00:00.000Z' it('should send the request to v1', function (done) { const v1Result = { lag: 'daily', date: queryDate, data: { user_counts: { total: [], new: [] }, max_confirmation_months: [], }, } this.request.callsArgWith(1, null, { statusCode: 201 }, v1Result) this.InstitutionsAPI.getLicencesForAnalytics( lag, queryDate, (error, result) => { expect(error).not.to.exist const requestOptions = this.request.lastCall.args[0] expect(requestOptions.body.query_date).to.equal(queryDate) expect(requestOptions.body.lag).to.equal(lag) requestOptions.method.should.equal('GET') done() } ) }) it('should handle errors', function (done) { this.request.callsArgWith(1, null, { statusCode: 500 }) this.InstitutionsAPI.getLicencesForAnalytics( lag, queryDate, (error, result) => { expect(error).to.be.instanceof(Errors.V1ConnectionError) done() } ) }) }) describe('getUserAffiliations', function () { it('get affiliations', function (done) { const responseBody = [{ foo: 'bar' }] this.request.callsArgWith(1, null, { statusCode: 201 }, responseBody) this.InstitutionsAPI.getUserAffiliations( this.stubbedUser._id, (err, body) => { expect(err).not.to.exist this.request.calledOnce.should.equal(true) const requestOptions = this.request.lastCall.args[0] const expectedUrl = `v1.url/api/v2/users/${this.stubbedUser._id}/affiliations` requestOptions.url.should.equal(expectedUrl) requestOptions.method.should.equal('GET') expect(requestOptions.body).not.to.exist body.should.equal(responseBody) done() } ) }) it('handle error', function (done) { const body = { errors: 'affiliation error message' } this.request.callsArgWith(1, null, { statusCode: 503 }, body) this.InstitutionsAPI.getUserAffiliations(this.stubbedUser._id, err => { expect(err).to.be.instanceof(Errors.V1ConnectionError) done() }) }) it('handle empty response', function (done) { this.settings.apis.v1.url = '' this.InstitutionsAPI.getUserAffiliations( this.stubbedUser._id, (err, body) => { expect(err).not.to.exist expect(body).to.be.a('Array') body.length.should.equal(0) done() } ) }) }) describe('getUsersNeedingReconfirmationsLapsedProcessed', function () { it('get the list of users', function (done) { this.request.callsArgWith(1, null, { statusCode: 200 }) this.InstitutionsAPI.getUsersNeedingReconfirmationsLapsedProcessed( error => { expect(error).not.to.exist this.request.calledOnce.should.equal(true) const requestOptions = this.request.lastCall.args[0] const expectedUrl = `v1.url/api/v2/institutions/need_reconfirmation_lapsed_processed` requestOptions.url.should.equal(expectedUrl) requestOptions.method.should.equal('GET') done() } ) }) it('handle error', function (done) { this.request.callsArgWith(1, null, { statusCode: 500 }) this.InstitutionsAPI.getUsersNeedingReconfirmationsLapsedProcessed( error => { expect(error).to.exist done() } ) }) }) describe('addAffiliation', function () { beforeEach(function () { this.request.callsArgWith(1, null, { statusCode: 201 }) }) it('add affiliation', function (done) { const affiliationOptions = { university: { id: 1 }, role: 'Prof', department: 'Math', confirmedAt: new Date(), entitlement: true, } this.InstitutionsAPI.addAffiliation( this.stubbedUser._id, this.newEmail, affiliationOptions, err => { expect(err).not.to.exist this.request.calledOnce.should.equal(true) const requestOptions = this.request.lastCall.args[0] const expectedUrl = `v1.url/api/v2/users/${this.stubbedUser._id}/affiliations` requestOptions.url.should.equal(expectedUrl) requestOptions.method.should.equal('POST') const { body } = requestOptions Object.keys(body).length.should.equal(7) body.email.should.equal(this.newEmail) body.university.should.equal(affiliationOptions.university) body.department.should.equal(affiliationOptions.department) body.role.should.equal(affiliationOptions.role) body.confirmedAt.should.equal(affiliationOptions.confirmedAt) body.entitlement.should.equal(affiliationOptions.entitlement) this.markAsReadIpMatcher.calledOnce.should.equal(true) done() } ) }) it('handle error', function (done) { const body = { errors: 'affiliation error message' } this.request.callsArgWith(1, null, { statusCode: 422 }, body) this.InstitutionsAPI.addAffiliation( this.stubbedUser._id, this.newEmail, {}, err => { expect(err).to.exist err.message.should.have.string(422) err.message.should.have.string(body.errors) done() } ) }) }) describe('removeAffiliation', function () { beforeEach(function () { this.request.callsArgWith(1, null, { statusCode: 404 }) }) it('remove affiliation', function (done) { this.InstitutionsAPI.removeAffiliation( this.stubbedUser._id, this.newEmail, err => { expect(err).not.to.exist this.request.calledOnce.should.equal(true) const requestOptions = this.request.lastCall.args[0] const expectedUrl = `v1.url/api/v2/users/${this.stubbedUser._id}/affiliations/remove` requestOptions.url.should.equal(expectedUrl) requestOptions.method.should.equal('POST') expect(requestOptions.body).to.deep.equal({ email: this.newEmail }) done() } ) }) it('handle error', function (done) { this.request.callsArgWith(1, null, { statusCode: 500 }) this.InstitutionsAPI.removeAffiliation( this.stubbedUser._id, this.newEmail, err => { expect(err).to.exist err.message.should.exist done() } ) }) }) describe('deleteAffiliations', function () { it('delete affiliations', function (done) { this.request.callsArgWith(1, null, { statusCode: 200 }) this.InstitutionsAPI.deleteAffiliations(this.stubbedUser._id, err => { expect(err).not.to.exist this.request.calledOnce.should.equal(true) const requestOptions = this.request.lastCall.args[0] const expectedUrl = `v1.url/api/v2/users/${this.stubbedUser._id}/affiliations` requestOptions.url.should.equal(expectedUrl) requestOptions.method.should.equal('DELETE') done() }) }) it('handle error', function (done) { const body = { errors: 'affiliation error message' } this.request.callsArgWith(1, null, { statusCode: 518 }, body) this.InstitutionsAPI.deleteAffiliations(this.stubbedUser._id, err => { expect(err).to.be.instanceof(Errors.V1ConnectionError) done() }) }) }) describe('endorseAffiliation', function () { beforeEach(function () { this.request.callsArgWith(1, null, { statusCode: 204 }) }) it('endorse affiliation', function (done) { this.InstitutionsAPI.endorseAffiliation( this.stubbedUser._id, this.newEmail, 'Student', 'Physics', err => { expect(err).not.to.exist this.request.calledOnce.should.equal(true) const requestOptions = this.request.lastCall.args[0] const expectedUrl = `v1.url/api/v2/users/${this.stubbedUser._id}/affiliations/endorse` requestOptions.url.should.equal(expectedUrl) requestOptions.method.should.equal('POST') const { body } = requestOptions Object.keys(body).length.should.equal(3) body.email.should.equal(this.newEmail) body.role.should.equal('Student') body.department.should.equal('Physics') done() } ) }) }) describe('sendUsersWithReconfirmationsLapsedProcessed', function () { const users = ['abc123', 'def456'] it('sends the list of users', function (done) { this.request.callsArgWith(1, null, { statusCode: 200 }) this.InstitutionsAPI.sendUsersWithReconfirmationsLapsedProcessed( users, error => { expect(error).not.to.exist this.request.calledOnce.should.equal(true) const requestOptions = this.request.lastCall.args[0] const expectedUrl = 'v1.url/api/v2/institutions/reconfirmation_lapsed_processed' requestOptions.url.should.equal(expectedUrl) requestOptions.method.should.equal('POST') expect(requestOptions.body).to.deep.equal({ users }) done() } ) }) it('handle error', function (done) { this.request.callsArgWith(1, null, { statusCode: 500 }) this.InstitutionsAPI.sendUsersWithReconfirmationsLapsedProcessed( users, error => { expect(error).to.exist done() } ) }) }) })
overleaf/web/test/unit/src/Institutions/InstitutionsAPITests.js/0
{ "file_path": "overleaf/web/test/unit/src/Institutions/InstitutionsAPITests.js", "repo_id": "overleaf", "token_count": 5924 }
575
const sinon = require('sinon') const { expect } = require('chai') const { ObjectId } = require('mongodb') const SandboxedModule = require('sandboxed-module') const { Project } = require('../helpers/models/Project') const MODULE_PATH = '../../../../app/src/Features/Project/ProjectAuditLogHandler' describe('ProjectAuditLogHandler', function () { beforeEach(function () { this.projectId = ObjectId() this.userId = ObjectId() this.ProjectMock = sinon.mock(Project) this.ProjectAuditLogHandler = SandboxedModule.require(MODULE_PATH, { requires: { '../../models/Project': { Project }, }, }) }) afterEach(function () { this.ProjectMock.restore() }) describe('addEntry', function () { describe('success', function () { beforeEach(async function () { this.dbUpdate = this.ProjectMock.expects('updateOne').withArgs( { _id: this.projectId }, { $push: { auditLog: { $each: [ { operation: 'translate', initiatorId: this.userId, info: { destinationLanguage: 'tagalog' }, timestamp: sinon.match.typeOf('date'), }, ], $slice: -200, }, }, } ) this.dbUpdate.chain('exec').resolves({ nModified: 1 }) this.operationId = await this.ProjectAuditLogHandler.promises.addEntry( this.projectId, 'translate', this.userId, { destinationLanguage: 'tagalog' } ) }) it('writes a log', async function () { this.ProjectMock.verify() }) }) describe('when the project does not exist', function () { beforeEach(function () { this.ProjectMock.expects('updateOne') .chain('exec') .resolves({ nModified: 0 }) }) it('throws an error', async function () { await expect( this.ProjectAuditLogHandler.promises.addEntry( this.projectId, 'translate', this.userId, { destinationLanguage: 'tagalog' } ) ).to.be.rejected }) }) }) })
overleaf/web/test/unit/src/Project/ProjectAuditLogHandlerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Project/ProjectAuditLogHandlerTests.js", "repo_id": "overleaf", "token_count": 1073 }
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 sinon = require('sinon') const modulePath = '../../../../app/src/Features/Project/ProjectUpdateHandler.js' const SandboxedModule = require('sandboxed-module') describe('ProjectUpdateHandler', function () { beforeEach(function () { this.fakeTime = new Date() this.clock = sinon.useFakeTimers(this.fakeTime.getTime()) }) beforeEach(function () { let Project this.ProjectModel = Project = class Project {} this.ProjectModel.updateOne = sinon.stub().callsArg(3) return (this.handler = SandboxedModule.require(modulePath, { requires: { '../../models/Project': { Project: this.ProjectModel }, }, })) }) describe('marking a project as recently updated', function () { beforeEach(function () { this.project_id = 'project_id' this.lastUpdatedAt = 987654321 return (this.lastUpdatedBy = 'fake-last-updater-id') }) it('should send an update to mongo', function (done) { return this.handler.markAsUpdated( this.project_id, this.lastUpdatedAt, this.lastUpdatedBy, err => { sinon.assert.calledWith( this.ProjectModel.updateOne, { _id: this.project_id, lastUpdated: { $lt: this.lastUpdatedAt }, }, { lastUpdated: this.lastUpdatedAt, lastUpdatedBy: this.lastUpdatedBy, } ) return done() } ) }) it('should set smart fallbacks', function (done) { return this.handler.markAsUpdated(this.project_id, null, null, err => { sinon.assert.calledWithMatch( this.ProjectModel.updateOne, { _id: this.project_id, lastUpdated: { $lt: this.fakeTime }, }, { lastUpdated: this.fakeTime, lastUpdatedBy: null, } ) return done() }) }) }) describe('markAsOpened', function () { it('should send an update to mongo', function (done) { const project_id = 'project_id' return this.handler.markAsOpened(project_id, err => { const args = this.ProjectModel.updateOne.args[0] args[0]._id.should.equal(project_id) const date = args[1].lastOpened + '' const now = Date.now() + '' date.substring(0, 5).should.equal(now.substring(0, 5)) return done() }) }) }) describe('markAsInactive', function () { it('should send an update to mongo', function (done) { const project_id = 'project_id' return this.handler.markAsInactive(project_id, err => { const args = this.ProjectModel.updateOne.args[0] args[0]._id.should.equal(project_id) args[1].active.should.equal(false) return done() }) }) }) describe('markAsActive', function () { it('should send an update to mongo', function (done) { const project_id = 'project_id' return this.handler.markAsActive(project_id, err => { const args = this.ProjectModel.updateOne.args[0] args[0]._id.should.equal(project_id) args[1].active.should.equal(true) return done() }) }) }) })
overleaf/web/test/unit/src/Project/ProjectUpdateHandlerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Project/ProjectUpdateHandlerTests.js", "repo_id": "overleaf", "token_count": 1556 }
577
const chai = require('chai') const { expect } = chai function clearSettingsCache() { delete require.cache[ require.resolve('../../../../config/settings.defaults.js') ] const settingsDeps = Object.keys(require.cache).filter(x => x.includes('/@overleaf/settings/') ) settingsDeps.forEach(dep => delete require.cache[dep]) } describe('settings.defaults', function () { it('additional text extensions can be added via config', function () { clearSettingsCache() process.env.ADDITIONAL_TEXT_EXTENSIONS = 'abc, xyz' const settings = require('@overleaf/settings') expect(settings.textExtensions).to.include('tex') // from the default list expect(settings.textExtensions).to.include('abc') expect(settings.textExtensions).to.include('xyz') }) })
overleaf/web/test/unit/src/Settings/SettingsTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Settings/SettingsTests.js", "repo_id": "overleaf", "token_count": 258 }
578
const SandboxedModule = require('sandboxed-module') const sinon = require('sinon') const { expect } = require('chai') const modulePath = '../../../../app/src/Features/Subscription/TeamInvitesHandler' const { ObjectId } = require('mongodb') const Errors = require('../../../../app/src/Features/Errors/Errors') describe('TeamInvitesHandler', function () { beforeEach(function () { this.manager = { _id: '666666', first_name: 'Daenerys', last_name: 'Targaryen', email: 'daenerys@example.com', emails: [{ email: 'daenerys@example.com' }], } this.token = 'aaaaaaaaaaaaaaaaaaaaaa' this.teamInvite = { email: 'jorah@example.com', token: this.token, } this.subscription = { id: '55153a8014829a865bbf700d', _id: new ObjectId('55153a8014829a865bbf700d'), admin_id: this.manager._id, groupPlan: true, member_ids: [], teamInvites: [this.teamInvite], save: sinon.stub().yields(null), } this.SubscriptionLocator = { getUsersSubscription: sinon.stub(), getSubscription: sinon.stub().yields(null, this.subscription), } this.UserGetter = { getUser: sinon.stub().yields(), getUserByAnyEmail: sinon.stub().yields(), } this.SubscriptionUpdater = { addUserToGroup: sinon.stub().yields(), } this.LimitationsManager = { teamHasReachedMemberLimit: sinon.stub().returns(false), } this.Subscription = { findOne: sinon.stub().yields(), updateOne: sinon.stub().yields(), } this.EmailHandler = { sendEmail: sinon.stub().yields(null), } this.newToken = 'bbbbbbbbb' this.crypto = { randomBytes: () => { return { toString: sinon.stub().returns(this.newToken) } }, } this.UserGetter.getUser .withArgs(this.manager._id) .yields(null, this.manager) this.UserGetter.getUserByAnyEmail .withArgs(this.manager.email) .yields(null, this.manager) this.SubscriptionLocator.getUsersSubscription.yields( null, this.subscription ) this.Subscription.findOne.yields(null, this.subscription) this.TeamInvitesHandler = SandboxedModule.require(modulePath, { requires: { mongodb: { ObjectId }, crypto: this.crypto, '@overleaf/settings': { siteUrl: 'http://example.com' }, '../../models/TeamInvite': { TeamInvite: (this.TeamInvite = {}) }, '../../models/Subscription': { Subscription: this.Subscription }, '../User/UserGetter': this.UserGetter, './SubscriptionLocator': this.SubscriptionLocator, './SubscriptionUpdater': this.SubscriptionUpdater, './LimitationsManager': this.LimitationsManager, '../Email/EmailHandler': this.EmailHandler, }, }) }) describe('getInvite', function () { it("returns the invite if there's one", function (done) { this.TeamInvitesHandler.getInvite( this.token, (err, invite, subscription) => { expect(err).to.eq(null) expect(invite).to.deep.eq(this.teamInvite) expect(subscription).to.deep.eq(this.subscription) done() } ) }) it("returns teamNotFound if there's none", function (done) { this.Subscription.findOne = sinon.stub().yields(null, null) this.TeamInvitesHandler.getInvite( this.token, (err, invite, subscription) => { expect(err).to.be.instanceof(Errors.NotFoundError) done() } ) }) }) describe('createInvite', function () { it('adds the team invite to the subscription', function (done) { this.TeamInvitesHandler.createInvite( this.manager._id, this.subscription, 'John.Snow@example.com', (err, invite) => { expect(err).to.eq(null) expect(invite.token).to.eq(this.newToken) expect(invite.email).to.eq('john.snow@example.com') expect(invite.inviterName).to.eq( 'Daenerys Targaryen (daenerys@example.com)' ) expect(invite.invite).to.be.true expect(this.subscription.teamInvites).to.deep.include(invite) done() } ) }) it('sends an email', function (done) { this.TeamInvitesHandler.createInvite( this.manager._id, this.subscription, 'John.Snow@example.com', (err, invite) => { this.EmailHandler.sendEmail .calledWith( 'verifyEmailToJoinTeam', sinon.match({ to: 'john.snow@example.com', inviter: this.manager, acceptInviteUrl: `http://example.com/subscription/invites/${this.newToken}/`, }) ) .should.equal(true) done(err) } ) }) it('refreshes the existing invite if the email has already been invited', function (done) { const originalInvite = Object.assign({}, this.teamInvite) this.TeamInvitesHandler.createInvite( this.manager._id, this.subscription, originalInvite.email, (err, invite) => { expect(err).to.eq(null) expect(invite).to.exist expect(this.subscription.teamInvites.length).to.eq(1) expect(this.subscription.teamInvites).to.deep.include(invite) expect(invite.email).to.eq(originalInvite.email) this.subscription.save.calledOnce.should.eq(true) done() } ) }) it('removes any legacy invite from the subscription', function (done) { this.TeamInvitesHandler.createInvite( this.manager._id, this.subscription, 'John.Snow@example.com', (err, invite) => { this.Subscription.updateOne .calledWith( { _id: new ObjectId('55153a8014829a865bbf700d') }, { $pull: { invited_emails: 'john.snow@example.com' } } ) .should.eq(true) done(err) } ) }) it('add user to subscription if inviting self', function (done) { this.TeamInvitesHandler.createInvite( this.manager._id, this.subscription, this.manager.email, (err, invite) => { sinon.assert.calledWith( this.SubscriptionUpdater.addUserToGroup, this.subscription._id, this.manager._id ) sinon.assert.notCalled(this.subscription.save) expect(invite.token).to.not.exist expect(invite.email).to.eq(this.manager.email) expect(invite.first_name).to.eq(this.manager.first_name) expect(invite.last_name).to.eq(this.manager.last_name) expect(invite.invite).to.be.false done(err) } ) }) }) describe('importInvite', function () { beforeEach(function () { this.sentAt = new Date() }) it('can imports an invite from v1', function () { this.TeamInvitesHandler.importInvite( this.subscription, 'A-Team', 'hannibal@a-team.org', 'secret', this.sentAt, error => { expect(error).not.to.exist this.subscription.save.calledOnce.should.eq(true) const invite = this.subscription.teamInvites.find( i => i.email === 'hannibal@a-team.org' ) expect(invite.token).to.eq('secret') expect(invite.sentAt).to.eq(this.sentAt) } ) }) }) describe('acceptInvite', function () { beforeEach(function () { this.user = { id: '123456789', first_name: 'Tyrion', last_name: 'Lannister', email: 'tyrion@example.com', } this.UserGetter.getUserByAnyEmail .withArgs(this.user.email) .yields(null, this.user) this.subscription.teamInvites.push({ email: 'john.snow@example.com', token: 'dddddddd', inviterName: 'Daenerys Targaryen (daenerys@example.com)', }) }) it('adds the user to the team', function (done) { this.TeamInvitesHandler.acceptInvite('dddddddd', this.user.id, () => { this.SubscriptionUpdater.addUserToGroup .calledWith(this.subscription._id, this.user.id) .should.eq(true) done() }) }) it('removes the invite from the subscription', function (done) { this.TeamInvitesHandler.acceptInvite('dddddddd', this.user.id, () => { this.Subscription.updateOne .calledWith( { _id: new ObjectId('55153a8014829a865bbf700d') }, { $pull: { teamInvites: { email: 'john.snow@example.com' } } } ) .should.eq(true) done() }) }) }) describe('revokeInvite', function () { it('removes the team invite from the subscription', function (done) { this.TeamInvitesHandler.revokeInvite( this.manager._id, this.subscription, 'jorah@example.com', () => { this.Subscription.updateOne .calledWith( { _id: new ObjectId('55153a8014829a865bbf700d') }, { $pull: { teamInvites: { email: 'jorah@example.com' } } } ) .should.eq(true) this.Subscription.updateOne .calledWith( { _id: new ObjectId('55153a8014829a865bbf700d') }, { $pull: { invited_emails: 'jorah@example.com' } } ) .should.eq(true) done() } ) }) }) describe('createTeamInvitesForLegacyInvitedEmail', function (done) { beforeEach(function () { this.subscription.invited_emails = [ 'eddard@example.com', 'robert@example.com', ] this.TeamInvitesHandler.createInvite = sinon.stub().yields(null) this.SubscriptionLocator.getGroupsWithEmailInvite = sinon .stub() .yields(null, [this.subscription]) }) it('sends an invitation email to addresses in the legacy invited_emails field', function (done) { this.TeamInvitesHandler.createTeamInvitesForLegacyInvitedEmail( 'eddard@example.com', (err, invite) => { expect(err).not.to.exist this.TeamInvitesHandler.createInvite .calledWith( this.subscription.admin_id, this.subscription, 'eddard@example.com' ) .should.eq(true) this.TeamInvitesHandler.createInvite.callCount.should.eq(1) done() } ) }) }) describe('validation', function () { it("doesn't create an invite if the team limit has been reached", function (done) { this.LimitationsManager.teamHasReachedMemberLimit = sinon .stub() .returns(true) this.TeamInvitesHandler.createInvite( this.manager._id, this.subscription, 'John.Snow@example.com', (err, invite) => { expect(err).to.deep.equal({ limitReached: true }) done() } ) }) it("doesn't create an invite if the subscription is not in a group plan", function (done) { this.subscription.groupPlan = false this.TeamInvitesHandler.createInvite( this.manager._id, this.subscription, 'John.Snow@example.com', (err, invite) => { expect(err).to.deep.equal({ wrongPlan: true }) done() } ) }) it("doesn't create an invite if the user is already part of the team", function (done) { const member = { id: '1a2b', _id: '1a2b', email: 'tyrion@example.com', } this.subscription.member_ids = [member.id] this.UserGetter.getUserByAnyEmail .withArgs(member.email) .yields(null, member) this.TeamInvitesHandler.createInvite( this.manager._id, this.subscription, 'tyrion@example.com', (err, invite) => { expect(err).to.deep.equal({ alreadyInTeam: true }) expect(invite).not.to.exist done() } ) }) }) })
overleaf/web/test/unit/src/Subscription/TeamInvitesHandlerTests.js/0
{ "file_path": "overleaf/web/test/unit/src/Subscription/TeamInvitesHandlerTests.js", "repo_id": "overleaf", "token_count": 5718 }
579